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.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
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_LOCKED_USER;
81 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83 import static android.content.pm.PackageManager.PERMISSION_DENIED;
84 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86 import static android.content.pm.PackageParser.isApkFile;
87 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88 import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89 import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90 import static android.system.OsConstants.O_CREAT;
91 import static android.system.OsConstants.O_RDWR;
93 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97 import static com.android.internal.util.ArrayUtils.appendInt;
98 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
109 import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
111 import android.Manifest;
112 import android.annotation.IntDef;
113 import android.annotation.NonNull;
114 import android.annotation.Nullable;
115 import android.app.ActivityManager;
116 import android.app.AppOpsManager;
117 import android.app.IActivityManager;
118 import android.app.ResourcesManager;
119 import android.app.admin.IDevicePolicyManager;
120 import android.app.admin.SecurityLog;
121 import android.app.backup.IBackupManager;
122 import android.content.BroadcastReceiver;
123 import android.content.ComponentName;
124 import android.content.ContentResolver;
125 import android.content.Context;
126 import android.content.IIntentReceiver;
127 import android.content.Intent;
128 import android.content.IntentFilter;
129 import android.content.IntentSender;
130 import android.content.IntentSender.SendIntentException;
131 import android.content.ServiceConnection;
132 import android.content.pm.ActivityInfo;
133 import android.content.pm.ApplicationInfo;
134 import android.content.pm.AppsQueryHelper;
135 import android.content.pm.AuxiliaryResolveInfo;
136 import android.content.pm.ChangedPackages;
137 import android.content.pm.ComponentInfo;
138 import android.content.pm.FallbackCategoryProvider;
139 import android.content.pm.FeatureInfo;
140 import android.content.pm.IDexModuleRegisterCallback;
141 import android.content.pm.IOnPermissionsChangeListener;
142 import android.content.pm.IPackageDataObserver;
143 import android.content.pm.IPackageDeleteObserver;
144 import android.content.pm.IPackageDeleteObserver2;
145 import android.content.pm.IPackageInstallObserver2;
146 import android.content.pm.IPackageInstaller;
147 import android.content.pm.IPackageManager;
148 import android.content.pm.IPackageManagerNative;
149 import android.content.pm.IPackageMoveObserver;
150 import android.content.pm.IPackageStatsObserver;
151 import android.content.pm.InstantAppInfo;
152 import android.content.pm.InstantAppRequest;
153 import android.content.pm.InstantAppResolveInfo;
154 import android.content.pm.InstrumentationInfo;
155 import android.content.pm.IntentFilterVerificationInfo;
156 import android.content.pm.KeySet;
157 import android.content.pm.PackageCleanItem;
158 import android.content.pm.PackageInfo;
159 import android.content.pm.PackageInfoLite;
160 import android.content.pm.PackageInstaller;
161 import android.content.pm.PackageManager;
162 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163 import android.content.pm.PackageManagerInternal;
164 import android.content.pm.PackageParser;
165 import android.content.pm.PackageParser.ActivityIntentInfo;
166 import android.content.pm.PackageParser.PackageLite;
167 import android.content.pm.PackageParser.PackageParserException;
168 import android.content.pm.PackageStats;
169 import android.content.pm.PackageUserState;
170 import android.content.pm.ParceledListSlice;
171 import android.content.pm.PermissionGroupInfo;
172 import android.content.pm.PermissionInfo;
173 import android.content.pm.ProviderInfo;
174 import android.content.pm.ResolveInfo;
175 import android.content.pm.ServiceInfo;
176 import android.content.pm.SharedLibraryInfo;
177 import android.content.pm.Signature;
178 import android.content.pm.UserInfo;
179 import android.content.pm.VerifierDeviceIdentity;
180 import android.content.pm.VerifierInfo;
181 import android.content.pm.VersionedPackage;
182 import android.content.res.Resources;
183 import android.database.ContentObserver;
184 import android.graphics.Bitmap;
185 import android.hardware.display.DisplayManager;
186 import android.net.Uri;
187 import android.os.Binder;
188 import android.os.Build;
189 import android.os.Bundle;
190 import android.os.Debug;
191 import android.os.Environment;
192 import android.os.Environment.UserEnvironment;
193 import android.os.FileUtils;
194 import android.os.Handler;
195 import android.os.IBinder;
196 import android.os.Looper;
197 import android.os.Message;
198 import android.os.Parcel;
199 import android.os.ParcelFileDescriptor;
200 import android.os.PatternMatcher;
201 import android.os.Process;
202 import android.os.RemoteCallbackList;
203 import android.os.RemoteException;
204 import android.os.ResultReceiver;
205 import android.os.SELinux;
206 import android.os.ServiceManager;
207 import android.os.ShellCallback;
208 import android.os.SystemClock;
209 import android.os.SystemProperties;
210 import android.os.Trace;
211 import android.os.UserHandle;
212 import android.os.UserManager;
213 import android.os.UserManagerInternal;
214 import android.os.storage.IStorageManager;
215 import android.os.storage.StorageEventListener;
216 import android.os.storage.StorageManager;
217 import android.os.storage.StorageManagerInternal;
218 import android.os.storage.VolumeInfo;
219 import android.os.storage.VolumeRecord;
220 import android.provider.Settings.Global;
221 import android.provider.Settings.Secure;
222 import android.security.KeyStore;
223 import android.security.SystemKeyStore;
224 import android.service.pm.PackageServiceDumpProto;
225 import android.system.ErrnoException;
226 import android.system.Os;
227 import android.text.TextUtils;
228 import android.text.format.DateUtils;
229 import android.util.ArrayMap;
230 import android.util.ArraySet;
231 import android.util.Base64;
232 import android.util.TimingsTraceLog;
233 import android.util.DisplayMetrics;
234 import android.util.EventLog;
235 import android.util.ExceptionUtils;
236 import android.util.Log;
237 import android.util.LogPrinter;
238 import android.util.MathUtils;
239 import android.util.PackageUtils;
240 import android.util.Pair;
241 import android.util.PrintStreamPrinter;
242 import android.util.Slog;
243 import android.util.SparseArray;
244 import android.util.SparseBooleanArray;
245 import android.util.SparseIntArray;
246 import android.util.Xml;
247 import android.util.jar.StrictJarFile;
248 import android.util.proto.ProtoOutputStream;
249 import android.view.Display;
251 import com.android.internal.R;
252 import com.android.internal.annotations.GuardedBy;
253 import com.android.internal.app.IMediaContainerService;
254 import com.android.internal.app.ResolverActivity;
255 import com.android.internal.content.NativeLibraryHelper;
256 import com.android.internal.content.PackageHelper;
257 import com.android.internal.logging.MetricsLogger;
258 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259 import com.android.internal.os.IParcelFileDescriptorFactory;
260 import com.android.internal.os.RoSystemProperties;
261 import com.android.internal.os.SomeArgs;
262 import com.android.internal.os.Zygote;
263 import com.android.internal.telephony.CarrierAppUtils;
264 import com.android.internal.util.ArrayUtils;
265 import com.android.internal.util.ConcurrentUtils;
266 import com.android.internal.util.DumpUtils;
267 import com.android.internal.util.FastPrintWriter;
268 import com.android.internal.util.FastXmlSerializer;
269 import com.android.internal.util.IndentingPrintWriter;
270 import com.android.internal.util.Preconditions;
271 import com.android.internal.util.XmlUtils;
272 import com.android.server.AttributeCache;
273 import com.android.server.DeviceIdleController;
274 import com.android.server.EventLogTags;
275 import com.android.server.FgThread;
276 import com.android.server.IntentResolver;
277 import com.android.server.LocalServices;
278 import com.android.server.LockGuard;
279 import com.android.server.ServiceThread;
280 import com.android.server.SystemConfig;
281 import com.android.server.SystemServerInitThreadPool;
282 import com.android.server.Watchdog;
283 import com.android.server.net.NetworkPolicyManagerInternal;
284 import com.android.server.pm.Installer.InstallerException;
285 import com.android.server.pm.PermissionsState.PermissionState;
286 import com.android.server.pm.Settings.DatabaseVersion;
287 import com.android.server.pm.Settings.VersionInfo;
288 import com.android.server.pm.dex.DexManager;
289 import com.android.server.pm.dex.DexoptOptions;
290 import com.android.server.pm.dex.PackageDexUsage;
291 import com.android.server.storage.DeviceStorageMonitorInternal;
293 import dalvik.system.CloseGuard;
294 import dalvik.system.DexFile;
295 import dalvik.system.VMRuntime;
297 import libcore.io.IoUtils;
298 import libcore.io.Streams;
299 import libcore.util.EmptyArray;
301 import org.xmlpull.v1.XmlPullParser;
302 import org.xmlpull.v1.XmlPullParserException;
303 import org.xmlpull.v1.XmlSerializer;
305 import java.io.BufferedOutputStream;
306 import java.io.BufferedReader;
307 import java.io.ByteArrayInputStream;
308 import java.io.ByteArrayOutputStream;
310 import java.io.FileDescriptor;
311 import java.io.FileInputStream;
312 import java.io.FileOutputStream;
313 import java.io.FileReader;
314 import java.io.FilenameFilter;
315 import java.io.IOException;
316 import java.io.InputStream;
317 import java.io.OutputStream;
318 import java.io.PrintWriter;
319 import java.lang.annotation.Retention;
320 import java.lang.annotation.RetentionPolicy;
321 import java.nio.charset.StandardCharsets;
322 import java.security.DigestInputStream;
323 import java.security.MessageDigest;
324 import java.security.NoSuchAlgorithmException;
325 import java.security.PublicKey;
326 import java.security.SecureRandom;
327 import java.security.cert.Certificate;
328 import java.security.cert.CertificateEncodingException;
329 import java.security.cert.CertificateException;
330 import java.text.SimpleDateFormat;
331 import java.util.ArrayList;
332 import java.util.Arrays;
333 import java.util.Collection;
334 import java.util.Collections;
335 import java.util.Comparator;
336 import java.util.Date;
337 import java.util.HashMap;
338 import java.util.HashSet;
339 import java.util.Iterator;
340 import java.util.List;
341 import java.util.Map;
342 import java.util.Objects;
343 import java.util.Set;
344 import java.util.concurrent.CountDownLatch;
345 import java.util.concurrent.Future;
346 import java.util.concurrent.TimeUnit;
347 import java.util.concurrent.atomic.AtomicBoolean;
348 import java.util.concurrent.atomic.AtomicInteger;
349 import java.util.zip.GZIPInputStream;
352 * Keep track of all those APKs everywhere.
354 * Internally there are two important locks:
356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
357 * and other related state. It is a fine-grained lock that should only be held
358 * momentarily, as it's one of the most contended locks in the system.
359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
360 * operations typically involve heavy lifting of application data on disk. Since
361 * {@code installd} is single-threaded, and it's operations can often be slow,
362 * this lock should never be acquired while already holding {@link #mPackages}.
363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
364 * holding {@link #mInstallLock}.
366 * Many internal methods rely on the caller to hold the appropriate locks, and
367 * this contract is expressed through method name suffixes:
369 * <li>fooLI(): the caller must hold {@link #mInstallLock}
370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
371 * being modified must be frozen
372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
376 * Because this class is very central to the platform's security; please run all
377 * CTS and unit tests whenever making modifications:
380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
384 public class PackageManagerService extends IPackageManager.Stub
385 implements PackageSender {
386 static final String TAG = "PackageManager";
387 static final boolean DEBUG_SETTINGS = false;
388 static final boolean DEBUG_PREFERRED = false;
389 static final boolean DEBUG_UPGRADE = false;
390 static final boolean DEBUG_DOMAIN_VERIFICATION = false;
391 private static final boolean DEBUG_BACKUP = false;
392 private static final boolean DEBUG_INSTALL = false;
393 private static final boolean DEBUG_REMOVE = false;
394 private static final boolean DEBUG_BROADCASTS = false;
395 private static final boolean DEBUG_SHOW_INFO = false;
396 private static final boolean DEBUG_PACKAGE_INFO = false;
397 private static final boolean DEBUG_INTENT_MATCHING = false;
398 private static final boolean DEBUG_PACKAGE_SCANNING = false;
399 private static final boolean DEBUG_VERIFY = false;
400 private static final boolean DEBUG_FILTERS = false;
401 private static final boolean DEBUG_PERMISSIONS = false;
402 private static final boolean DEBUG_SHARED_LIBRARIES = false;
403 private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
405 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
406 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
407 // user, but by default initialize to this.
408 public static final boolean DEBUG_DEXOPT = false;
410 private static final boolean DEBUG_ABI_SELECTION = false;
411 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
412 private static final boolean DEBUG_TRIAGED_MISSING = false;
413 private static final boolean DEBUG_APP_DATA = false;
415 /** REMOVE. According to Svet, this was only used to reset permissions during development. */
416 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
418 private static final boolean HIDE_EPHEMERAL_APIS = false;
420 private static final boolean ENABLE_FREE_CACHE_V2 =
421 SystemProperties.getBoolean("fw.free_cache_v2", true);
423 private static final int RADIO_UID = Process.PHONE_UID;
424 private static final int LOG_UID = Process.LOG_UID;
425 private static final int NFC_UID = Process.NFC_UID;
426 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
427 private static final int SHELL_UID = Process.SHELL_UID;
429 // Cap the size of permission trees that 3rd party apps can define
430 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text
432 // Suffix used during package installation when copying/moving
433 // package apks to install directory.
434 private static final String INSTALL_PACKAGE_SUFFIX = "-";
436 static final int SCAN_NO_DEX = 1<<1;
437 static final int SCAN_FORCE_DEX = 1<<2;
438 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
439 static final int SCAN_NEW_INSTALL = 1<<4;
440 static final int SCAN_UPDATE_TIME = 1<<5;
441 static final int SCAN_BOOTING = 1<<6;
442 static final int SCAN_TRUSTED_OVERLAY = 1<<7;
443 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
444 static final int SCAN_REPLACING = 1<<9;
445 static final int SCAN_REQUIRE_KNOWN = 1<<10;
446 static final int SCAN_MOVE = 1<<11;
447 static final int SCAN_INITIAL = 1<<12;
448 static final int SCAN_CHECK_ONLY = 1<<13;
449 static final int SCAN_DONT_KILL_APP = 1<<14;
450 static final int SCAN_IGNORE_FROZEN = 1<<15;
451 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
452 static final int SCAN_AS_INSTANT_APP = 1<<17;
453 static final int SCAN_AS_FULL_APP = 1<<18;
454 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
455 /** Should not be with the scan flags */
456 static final int FLAGS_REMOVE_CHATTY = 1<<31;
458 private static final String STATIC_SHARED_LIB_DELIMITER = "_";
459 /** Extension of the compressed packages */
460 private final static String COMPRESSED_EXTENSION = ".gz";
461 /** Suffix of stub packages on the system partition */
462 private final static String STUB_SUFFIX = "-Stub";
464 private static final int[] EMPTY_INT_ARRAY = new int[0];
466 private static final int TYPE_UNKNOWN = 0;
467 private static final int TYPE_ACTIVITY = 1;
468 private static final int TYPE_RECEIVER = 2;
469 private static final int TYPE_SERVICE = 3;
470 private static final int TYPE_PROVIDER = 4;
471 @IntDef(prefix = { "TYPE_" }, value = {
478 @Retention(RetentionPolicy.SOURCE)
479 public @interface ComponentType {}
482 * Timeout (in milliseconds) after which the watchdog should declare that
483 * our handler thread is wedged. The usual default for such things is one
484 * minute but we sometimes do very lengthy I/O operations on this thread,
485 * such as installing multi-gigabyte applications, so ours needs to be longer.
487 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes
490 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
491 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
492 * settings entry if available, otherwise we use the hardcoded default. If it's been
493 * more than this long since the last fstrim, we force one during the boot sequence.
495 * This backstops other fstrim scheduling: if the device is alive at midnight+idle,
496 * one gets run at the next available charging+idle time. This final mandatory
497 * no-fstrim check kicks in only of the other scheduling criteria is never met.
499 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
502 * Whether verification is enabled by default.
504 private static final boolean DEFAULT_VERIFY_ENABLE = true;
507 * The default maximum time to wait for the verification agent to return in
510 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
513 * The default response for package verification timeout.
515 * This can be either PackageManager.VERIFICATION_ALLOW or
516 * PackageManager.VERIFICATION_REJECT.
518 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
520 static final String PLATFORM_PACKAGE_NAME = "android";
522 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
524 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
525 DEFAULT_CONTAINER_PACKAGE,
526 "com.android.defcontainer.DefaultContainerService");
528 private static final String KILL_APP_REASON_GIDS_CHANGED =
529 "permission grant or revoke changed gids";
531 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
532 "permissions revoked";
534 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
536 private static final String PACKAGE_SCHEME = "package";
538 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
540 /** Permission grant: not grant the permission. */
541 private static final int GRANT_DENIED = 1;
543 /** Permission grant: grant the permission as an install permission. */
544 private static final int GRANT_INSTALL = 2;
546 /** Permission grant: grant the permission as a runtime one. */
547 private static final int GRANT_RUNTIME = 3;
549 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
550 private static final int GRANT_UPGRADE = 4;
552 /** Canonical intent used to identify what counts as a "web browser" app */
553 private static final Intent sBrowserIntent;
555 sBrowserIntent = new Intent();
556 sBrowserIntent.setAction(Intent.ACTION_VIEW);
557 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
558 sBrowserIntent.setData(Uri.parse("http:"));
562 * The set of all protected actions [i.e. those actions for which a high priority
563 * intent filter is disallowed].
565 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
567 PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
568 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
569 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
570 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
573 // Compilation reasons.
574 public static final int REASON_FIRST_BOOT = 0;
575 public static final int REASON_BOOT = 1;
576 public static final int REASON_INSTALL = 2;
577 public static final int REASON_BACKGROUND_DEXOPT = 3;
578 public static final int REASON_AB_OTA = 4;
579 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
580 public static final int REASON_SHARED = 6;
582 public static final int REASON_LAST = REASON_SHARED;
584 /** All dangerous permission names in the same order as the events in MetricsEvent */
585 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
586 Manifest.permission.READ_CALENDAR,
587 Manifest.permission.WRITE_CALENDAR,
588 Manifest.permission.CAMERA,
589 Manifest.permission.READ_CONTACTS,
590 Manifest.permission.WRITE_CONTACTS,
591 Manifest.permission.GET_ACCOUNTS,
592 Manifest.permission.ACCESS_FINE_LOCATION,
593 Manifest.permission.ACCESS_COARSE_LOCATION,
594 Manifest.permission.RECORD_AUDIO,
595 Manifest.permission.READ_PHONE_STATE,
596 Manifest.permission.CALL_PHONE,
597 Manifest.permission.READ_CALL_LOG,
598 Manifest.permission.WRITE_CALL_LOG,
599 Manifest.permission.ADD_VOICEMAIL,
600 Manifest.permission.USE_SIP,
601 Manifest.permission.PROCESS_OUTGOING_CALLS,
602 Manifest.permission.READ_CELL_BROADCASTS,
603 Manifest.permission.BODY_SENSORS,
604 Manifest.permission.SEND_SMS,
605 Manifest.permission.RECEIVE_SMS,
606 Manifest.permission.READ_SMS,
607 Manifest.permission.RECEIVE_WAP_PUSH,
608 Manifest.permission.RECEIVE_MMS,
609 Manifest.permission.READ_EXTERNAL_STORAGE,
610 Manifest.permission.WRITE_EXTERNAL_STORAGE,
611 Manifest.permission.READ_PHONE_NUMBERS,
612 Manifest.permission.ANSWER_PHONE_CALLS);
616 * Version number for the package parser cache. Increment this whenever the format or
617 * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619 private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
622 * Whether the package parser cache is enabled.
624 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626 final ServiceThread mHandlerThread;
628 final PackageHandler mHandler;
630 private final ProcessLoggingHandler mProcessLoggingHandler;
633 * Messages for {@link #mHandler} that need to wait for system ready before
636 private ArrayList<Message> mPostSystemReadyMessages;
638 final int mSdkVersion = Build.VERSION.SDK_INT;
640 final Context mContext;
641 final boolean mFactoryTest;
642 final boolean mOnlyCore;
643 final DisplayMetrics mMetrics;
644 final int mDefParseFlags;
645 final String[] mSeparateProcesses;
646 final boolean mIsUpgrade;
647 final boolean mIsPreNUpgrade;
648 final boolean mIsPreNMR1Upgrade;
650 // Have we told the Activity Manager to whitelist the default container service by uid yet?
651 @GuardedBy("mPackages")
652 boolean mDefaultContainerWhitelisted = false;
654 @GuardedBy("mPackages")
655 private boolean mDexOptDialogShown;
657 /** The location for ASEC container files on internal storage. */
658 final String mAsecInternalPath;
660 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
661 // LOCK HELD. Can be called with mInstallLock held.
662 @GuardedBy("mInstallLock")
663 final Installer mInstaller;
665 /** Directory where installed third-party apps stored */
666 final File mAppInstallDir;
669 * Directory to which applications installed internally have their
670 * 32 bit native libraries copied.
672 private File mAppLib32InstallDir;
674 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
676 final File mDrmAppPrivateInstallDir;
678 // ----------------------------------------------------------------
680 // Lock for state used when installing and doing other long running
681 // operations. Methods that must be called with this lock held have
683 final Object mInstallLock = new Object();
685 // ----------------------------------------------------------------
687 // Keys are String (package name), values are Package. This also serves
688 // as the lock for the global state. Methods that must be called with
689 // this lock held have the prefix "LP".
690 @GuardedBy("mPackages")
691 final ArrayMap<String, PackageParser.Package> mPackages =
692 new ArrayMap<String, PackageParser.Package>();
694 final ArrayMap<String, Set<String>> mKnownCodebase =
695 new ArrayMap<String, Set<String>>();
697 // Keys are isolated uids and values are the uid of the application
698 // that created the isolated proccess.
699 @GuardedBy("mPackages")
700 final SparseIntArray mIsolatedOwners = new SparseIntArray();
703 * Tracks new system packages [received in an OTA] that we expect to
704 * find updated user-installed versions. Keys are package name, values
705 * are package location.
707 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709 * Tracks high priority intent filters for protected actions. During boot, certain
710 * filter actions are protected and should never be allowed to have a high priority
711 * intent filter for them. However, there is one, and only one exception -- the
712 * setup wizard. It must be able to define a high priority intent filter for these
713 * actions to ensure there are no escapes from the wizard. We need to delay processing
714 * of these during boot as we need to look at all of the system packages in order
715 * to know which component is the setup wizard.
717 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719 * Whether or not processing protected filters should be deferred.
721 private boolean mDeferProtectedFilters = true;
724 * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728 * Whether or not system app permissions should be promoted from install to runtime.
730 boolean mPromoteSystemApps;
732 @GuardedBy("mPackages")
733 final Settings mSettings;
736 * Set of package names that are currently "frozen", which means active
737 * surgery is being done on the code/data for that package. The platform
738 * will refuse to launch frozen packages to avoid race conditions.
740 * @see PackageFreezer
742 @GuardedBy("mPackages")
743 final ArraySet<String> mFrozenPackages = new ArraySet<>();
745 final ProtectedPackages mProtectedPackages;
747 @GuardedBy("mLoadedVolumes")
748 final ArraySet<String> mLoadedVolumes = new ArraySet<>();
752 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754 // System configuration read by SystemConfig.
755 final int[] mGlobalGids;
756 final SparseArray<ArraySet<String>> mSystemPermissions;
757 @GuardedBy("mAvailableFeatures")
758 final ArrayMap<String, FeatureInfo> mAvailableFeatures;
760 // If mac_permissions.xml was found for seinfo labeling.
761 boolean mFoundPolicyFile;
763 private final InstantAppRegistry mInstantAppRegistry;
765 @GuardedBy("mPackages")
766 int mChangedPackagesSequenceNumber;
768 * List of changed [installed, removed or updated] packages.
769 * mapping from user id -> sequence number -> package name
771 @GuardedBy("mPackages")
772 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
774 * The sequence number of the last change to a package.
775 * mapping from user id -> package name -> sequence number
777 @GuardedBy("mPackages")
778 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
780 class PackageParserCallback implements PackageParser.Callback {
781 @Override public final boolean hasFeature(String feature) {
782 return PackageManagerService.this.hasSystemFeature(feature, 0);
785 final List<PackageParser.Package> getStaticOverlayPackagesLocked(
786 Collection<PackageParser.Package> allPackages, String targetPackageName) {
787 List<PackageParser.Package> overlayPackages = null;
788 for (PackageParser.Package p : allPackages) {
789 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
790 if (overlayPackages == null) {
791 overlayPackages = new ArrayList<PackageParser.Package>();
793 overlayPackages.add(p);
796 if (overlayPackages != null) {
797 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
798 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
799 return p1.mOverlayPriority - p2.mOverlayPriority;
802 Collections.sort(overlayPackages, cmp);
804 return overlayPackages;
807 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
808 String targetPackageName, String targetPath) {
809 if ("android".equals(targetPackageName)) {
810 // Static RROs targeting to "android", ie framework-res.apk, are already applied by
811 // native AssetManager.
814 List<PackageParser.Package> overlayPackages =
815 getStaticOverlayPackagesLocked(allPackages, targetPackageName);
816 if (overlayPackages == null || overlayPackages.isEmpty()) {
819 List<String> overlayPathList = null;
820 for (PackageParser.Package overlayPackage : overlayPackages) {
821 if (targetPath == null) {
822 if (overlayPathList == null) {
823 overlayPathList = new ArrayList<String>();
825 overlayPathList.add(overlayPackage.baseCodePath);
830 // Creates idmaps for system to parse correctly the Android manifest of the
833 // OverlayManagerService will update each of them with a correct gid from its
834 // target package app id.
835 mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
836 UserHandle.getSharedAppGid(
837 UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
838 if (overlayPathList == null) {
839 overlayPathList = new ArrayList<String>();
841 overlayPathList.add(overlayPackage.baseCodePath);
842 } catch (InstallerException e) {
843 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
844 overlayPackage.baseCodePath);
847 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
850 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
851 synchronized (mPackages) {
852 return getStaticOverlayPathsLocked(
853 mPackages.values(), targetPackageName, targetPath);
857 @Override public final String[] getOverlayApks(String targetPackageName) {
858 return getStaticOverlayPaths(targetPackageName, null);
861 @Override public final String[] getOverlayPaths(String targetPackageName,
863 return getStaticOverlayPaths(targetPackageName, targetPath);
867 class ParallelPackageParserCallback extends PackageParserCallback {
868 List<PackageParser.Package> mOverlayPackages = null;
870 void findStaticOverlayPackages() {
871 synchronized (mPackages) {
872 for (PackageParser.Package p : mPackages.values()) {
873 if (p.mIsStaticOverlay) {
874 if (mOverlayPackages == null) {
875 mOverlayPackages = new ArrayList<PackageParser.Package>();
877 mOverlayPackages.add(p);
884 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
885 // We can trust mOverlayPackages without holding mPackages because package uninstall
886 // can't happen while running parallel parsing.
887 // Moreover holding mPackages on each parsing thread causes dead-lock.
888 return mOverlayPackages == null ? null :
889 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
893 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
894 final ParallelPackageParserCallback mParallelPackageParserCallback =
895 new ParallelPackageParserCallback();
897 public static final class SharedLibraryEntry {
898 public final @Nullable String path;
899 public final @Nullable String apk;
900 public final @NonNull SharedLibraryInfo info;
902 SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
903 String declaringPackageName, int declaringPackageVersionCode) {
906 info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
907 declaringPackageName, declaringPackageVersionCode), null);
911 // Currently known shared libraries.
912 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
913 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
916 // All available activities, for your resolving pleasure.
917 final ActivityIntentResolver mActivities =
918 new ActivityIntentResolver();
920 // All available receivers, for your resolving pleasure.
921 final ActivityIntentResolver mReceivers =
922 new ActivityIntentResolver();
924 // All available services, for your resolving pleasure.
925 final ServiceIntentResolver mServices = new ServiceIntentResolver();
927 // All available providers, for your resolving pleasure.
928 final ProviderIntentResolver mProviders = new ProviderIntentResolver();
930 // Mapping from provider base names (first directory in content URI codePath)
931 // to the provider information.
932 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
933 new ArrayMap<String, PackageParser.Provider>();
935 // Mapping from instrumentation class names to info about them.
936 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
937 new ArrayMap<ComponentName, PackageParser.Instrumentation>();
939 // Mapping from permission names to info about them.
940 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
941 new ArrayMap<String, PackageParser.PermissionGroup>();
943 // Packages whose data we have transfered into another package, thus
944 // should no longer exist.
945 final ArraySet<String> mTransferedPackages = new ArraySet<String>();
947 // Broadcast actions that are only available to the system.
948 @GuardedBy("mProtectedBroadcasts")
949 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
951 /** List of packages waiting for verification. */
952 final SparseArray<PackageVerificationState> mPendingVerification
953 = new SparseArray<PackageVerificationState>();
955 /** Set of packages associated with each app op permission. */
956 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
958 final PackageInstallerService mInstallerService;
960 private final PackageDexOptimizer mPackageDexOptimizer;
961 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
962 // is used by other apps).
963 private final DexManager mDexManager;
965 private AtomicInteger mNextMoveId = new AtomicInteger();
966 private final MoveCallbacks mMoveCallbacks;
968 private final OnPermissionChangeListeners mOnPermissionChangeListeners;
970 // Cache of users who need badging.
971 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
973 /** Token for keys in mPendingVerification. */
974 private int mPendingVerificationToken = 0;
976 volatile boolean mSystemReady;
977 volatile boolean mSafeMode;
978 volatile boolean mHasSystemUidErrors;
979 private volatile boolean mEphemeralAppsDisabled;
981 ApplicationInfo mAndroidApplication;
982 final ActivityInfo mResolveActivity = new ActivityInfo();
983 final ResolveInfo mResolveInfo = new ResolveInfo();
984 ComponentName mResolveComponentName;
985 PackageParser.Package mPlatformPackage;
986 ComponentName mCustomResolverComponentName;
988 boolean mResolverReplaced = false;
990 private final @Nullable ComponentName mIntentFilterVerifierComponent;
991 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
993 private int mIntentFilterVerificationToken = 0;
995 /** The service connection to the ephemeral resolver */
996 final EphemeralResolverConnection mInstantAppResolverConnection;
997 /** Component used to show resolver settings for Instant Apps */
998 final ComponentName mInstantAppResolverSettingsComponent;
1000 /** Activity used to install instant applications */
1001 ActivityInfo mInstantAppInstallerActivity;
1002 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1004 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1005 = new SparseArray<IntentFilterVerificationState>();
1007 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1009 // List of packages names to keep cached, even if they are uninstalled for all users
1010 private List<String> mKeepUninstalledPackages;
1012 private UserManagerInternal mUserManagerInternal;
1014 private DeviceIdleController.LocalService mDeviceIdleController;
1016 private File mCacheDir;
1018 private ArraySet<String> mPrivappPermissionsViolations;
1020 private Future<?> mPrepareAppDataFuture;
1022 private static class IFVerificationParams {
1023 PackageParser.Package pkg;
1028 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1029 int _userId, int _verifierUid) {
1031 replacing = _replacing;
1033 replacing = _replacing;
1034 verifierUid = _verifierUid;
1038 private interface IntentFilterVerifier<T extends IntentFilter> {
1039 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1040 T filter, String packageName);
1041 void startVerifications(int userId);
1042 void receiveVerificationResponse(int verificationId);
1045 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1046 private Context mContext;
1047 private ComponentName mIntentFilterVerifierComponent;
1048 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1050 public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1052 mIntentFilterVerifierComponent = verifierComponent;
1055 private String getDefaultScheme() {
1056 return IntentFilter.SCHEME_HTTPS;
1060 public void startVerifications(int userId) {
1061 // Launch verifications requests
1062 int count = mCurrentIntentFilterVerifications.size();
1063 for (int n=0; n<count; n++) {
1064 int verificationId = mCurrentIntentFilterVerifications.get(n);
1065 final IntentFilterVerificationState ivs =
1066 mIntentFilterVerificationStates.get(verificationId);
1068 String packageName = ivs.getPackageName();
1070 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1071 final int filterCount = filters.size();
1072 ArraySet<String> domainsSet = new ArraySet<>();
1073 for (int m=0; m<filterCount; m++) {
1074 PackageParser.ActivityIntentInfo filter = filters.get(m);
1075 domainsSet.addAll(filter.getHostsList());
1077 synchronized (mPackages) {
1078 if (mSettings.createIntentFilterVerificationIfNeededLPw(
1079 packageName, domainsSet) != null) {
1080 scheduleWriteSettingsLocked();
1083 sendVerificationRequest(verificationId, ivs);
1085 mCurrentIntentFilterVerifications.clear();
1088 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1089 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1090 verificationIntent.putExtra(
1091 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1093 verificationIntent.putExtra(
1094 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1095 getDefaultScheme());
1096 verificationIntent.putExtra(
1097 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1098 ivs.getHostsString());
1099 verificationIntent.putExtra(
1100 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1101 ivs.getPackageName());
1102 verificationIntent.setComponent(mIntentFilterVerifierComponent);
1103 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1105 DeviceIdleController.LocalService idleController = getDeviceIdleController();
1106 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1107 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1108 UserHandle.USER_SYSTEM, true, "intent filter verifier");
1110 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1111 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1112 "Sending IntentFilter verification broadcast");
1115 public void receiveVerificationResponse(int verificationId) {
1116 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1118 final boolean verified = ivs.isVerified();
1120 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1121 final int count = filters.size();
1122 if (DEBUG_DOMAIN_VERIFICATION) {
1123 Slog.i(TAG, "Received verification response " + verificationId
1124 + " for " + count + " filters, verified=" + verified);
1126 for (int n=0; n<count; n++) {
1127 PackageParser.ActivityIntentInfo filter = filters.get(n);
1128 filter.setVerified(verified);
1130 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1131 + " verified with result:" + verified + " and hosts:"
1132 + ivs.getHostsString());
1135 mIntentFilterVerificationStates.remove(verificationId);
1137 final String packageName = ivs.getPackageName();
1138 IntentFilterVerificationInfo ivi = null;
1140 synchronized (mPackages) {
1141 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1144 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1145 + verificationId + " packageName:" + packageName);
1148 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1149 "Updating IntentFilterVerificationInfo for package " + packageName
1150 +" verificationId:" + verificationId);
1152 synchronized (mPackages) {
1154 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1156 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1158 scheduleWriteSettingsLocked();
1160 final int userId = ivs.getUserId();
1161 if (userId != UserHandle.USER_ALL) {
1162 final int userStatus =
1163 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1165 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1166 boolean needUpdate = false;
1168 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1169 // already been set by the User thru the Disambiguation dialog
1170 switch (userStatus) {
1171 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1173 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1180 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1182 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1192 mSettings.updateIntentFilterVerificationStatusLPw(
1193 packageName, updatedStatus, userId);
1194 scheduleWritePackageRestrictionsLocked(userId);
1201 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1202 ActivityIntentInfo filter, String packageName) {
1203 if (!hasValidDomains(filter)) {
1206 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1208 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1211 if (DEBUG_DOMAIN_VERIFICATION) {
1212 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1214 ivs.addFilter(filter);
1218 private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1219 int userId, int verificationId, String packageName) {
1220 IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1221 verifierUid, userId, packageName);
1222 ivs.setPendingState();
1223 synchronized (mPackages) {
1224 mIntentFilterVerificationStates.append(verificationId, ivs);
1225 mCurrentIntentFilterVerifications.add(verificationId);
1231 private static boolean hasValidDomains(ActivityIntentInfo filter) {
1232 return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1233 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1234 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1237 // Set of pending broadcasts for aggregating enable/disable of components.
1238 static class PendingPackageBroadcasts {
1239 // for each user id, a map of <package name -> components within that package>
1240 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1242 public PendingPackageBroadcasts() {
1243 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1246 public ArrayList<String> get(int userId, String packageName) {
1247 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248 return packages.get(packageName);
1251 public void put(int userId, String packageName, ArrayList<String> components) {
1252 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253 packages.put(packageName, components);
1256 public void remove(int userId, String packageName) {
1257 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1258 if (packages != null) {
1259 packages.remove(packageName);
1263 public void remove(int userId) {
1264 mUidMap.remove(userId);
1267 public int userIdCount() {
1268 return mUidMap.size();
1271 public int userIdAt(int n) {
1272 return mUidMap.keyAt(n);
1275 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1276 return mUidMap.get(userId);
1280 // total number of pending broadcast entries across all userIds
1282 for (int i = 0; i< mUidMap.size(); i++) {
1283 num += mUidMap.valueAt(i).size();
1288 public void clear() {
1292 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1293 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1295 map = new ArrayMap<String, ArrayList<String>>();
1296 mUidMap.put(userId, map);
1301 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1303 // Service Connection to remote media container service to copy
1304 // package uri's from external media onto secure containers
1305 // or internal storage.
1306 private IMediaContainerService mContainerService = null;
1308 static final int SEND_PENDING_BROADCAST = 1;
1309 static final int MCS_BOUND = 3;
1310 static final int END_COPY = 4;
1311 static final int INIT_COPY = 5;
1312 static final int MCS_UNBIND = 6;
1313 static final int START_CLEANING_PACKAGE = 7;
1314 static final int FIND_INSTALL_LOC = 8;
1315 static final int POST_INSTALL = 9;
1316 static final int MCS_RECONNECT = 10;
1317 static final int MCS_GIVE_UP = 11;
1318 static final int UPDATED_MEDIA_STATUS = 12;
1319 static final int WRITE_SETTINGS = 13;
1320 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1321 static final int PACKAGE_VERIFIED = 15;
1322 static final int CHECK_PENDING_VERIFICATION = 16;
1323 static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1324 static final int INTENT_FILTER_VERIFIED = 18;
1325 static final int WRITE_PACKAGE_LIST = 19;
1326 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1328 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
1330 // Delay time in millisecs
1331 static final int BROADCAST_DELAY = 10 * 1000;
1333 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1334 2 * 60 * 60 * 1000L; /* two hours */
1336 static UserManagerService sUserManager;
1338 // Stores a list of users whose package restrictions file needs to be updated
1339 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1341 final private DefaultContainerConnection mDefContainerConn =
1342 new DefaultContainerConnection();
1343 class DefaultContainerConnection implements ServiceConnection {
1344 public void onServiceConnected(ComponentName name, IBinder service) {
1345 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1346 final IMediaContainerService imcs = IMediaContainerService.Stub
1347 .asInterface(Binder.allowBlocking(service));
1348 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1351 public void onServiceDisconnected(ComponentName name) {
1352 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1356 // Recordkeeping of restore-after-install operations that are currently in flight
1357 // between the Package Manager and the Backup Manager
1358 static class PostInstallData {
1359 public InstallArgs args;
1360 public PackageInstalledInfo res;
1362 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1368 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1369 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
1371 // XML tags for backup/restore of various bits of state
1372 private static final String TAG_PREFERRED_BACKUP = "pa";
1373 private static final String TAG_DEFAULT_APPS = "da";
1374 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1376 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1377 private static final String TAG_ALL_GRANTS = "rt-grants";
1378 private static final String TAG_GRANT = "grant";
1379 private static final String ATTR_PACKAGE_NAME = "pkg";
1381 private static final String TAG_PERMISSION = "perm";
1382 private static final String ATTR_PERMISSION_NAME = "name";
1383 private static final String ATTR_IS_GRANTED = "g";
1384 private static final String ATTR_USER_SET = "set";
1385 private static final String ATTR_USER_FIXED = "fixed";
1386 private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1388 // System/policy permission grants are not backed up
1389 private static final int SYSTEM_RUNTIME_GRANT_MASK =
1390 FLAG_PERMISSION_POLICY_FIXED
1391 | FLAG_PERMISSION_SYSTEM_FIXED
1392 | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1394 // And we back up these user-adjusted states
1395 private static final int USER_RUNTIME_GRANT_MASK =
1396 FLAG_PERMISSION_USER_SET
1397 | FLAG_PERMISSION_USER_FIXED
1398 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1400 final @Nullable String mRequiredVerifierPackage;
1401 final @NonNull String mRequiredInstallerPackage;
1402 final @NonNull String mRequiredUninstallerPackage;
1403 final @Nullable String mSetupWizardPackage;
1404 final @Nullable String mStorageManagerPackage;
1405 final @NonNull String mServicesSystemSharedLibraryPackageName;
1406 final @NonNull String mSharedSystemSharedLibraryPackageName;
1408 final boolean mPermissionReviewRequired;
1410 private final PackageUsage mPackageUsage = new PackageUsage();
1411 private final CompilerStats mCompilerStats = new CompilerStats();
1413 class PackageHandler extends Handler {
1414 private boolean mBound = false;
1415 final ArrayList<HandlerParams> mPendingInstalls =
1416 new ArrayList<HandlerParams>();
1418 private boolean connectToService() {
1419 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1420 " DefaultContainerService");
1421 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1422 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423 if (mContext.bindServiceAsUser(service, mDefContainerConn,
1424 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1425 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433 private void disconnectService() {
1434 mContainerService = null;
1436 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1437 mContext.unbindService(mDefContainerConn);
1438 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441 PackageHandler(Looper looper) {
1445 public void handleMessage(Message msg) {
1447 doHandleMessage(msg);
1449 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1453 void doHandleMessage(Message msg) {
1456 HandlerParams params = (HandlerParams) msg.obj;
1457 int idx = mPendingInstalls.size();
1458 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1459 // If a bind was already initiated we dont really
1460 // need to do anything. The pending install
1461 // will be processed later on.
1463 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464 System.identityHashCode(mHandler));
1465 // If this is the only one pending we might
1466 // have to bind to the service again.
1467 if (!connectToService()) {
1468 Slog.e(TAG, "Failed to bind to media container service");
1469 params.serviceError();
1470 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471 System.identityHashCode(mHandler));
1472 if (params.traceMethod != null) {
1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1474 params.traceCookie);
1478 // Once we bind to the service, the first
1479 // pending request will be processed.
1480 mPendingInstalls.add(idx, params);
1483 mPendingInstalls.add(idx, params);
1484 // Already bound to the service. Just make
1485 // sure we trigger off processing the first request.
1487 mHandler.sendEmptyMessage(MCS_BOUND);
1493 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1494 if (msg.obj != null) {
1495 mContainerService = (IMediaContainerService) msg.obj;
1496 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1497 System.identityHashCode(mHandler));
1499 if (mContainerService == null) {
1501 // Something seriously wrong since we are not bound and we are not
1502 // waiting for connection. Bail out.
1503 Slog.e(TAG, "Cannot bind to media container service");
1504 for (HandlerParams params : mPendingInstalls) {
1505 // Indicate service bind error
1506 params.serviceError();
1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1508 System.identityHashCode(params));
1509 if (params.traceMethod != null) {
1510 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1511 params.traceMethod, params.traceCookie);
1515 mPendingInstalls.clear();
1517 Slog.w(TAG, "Waiting to connect to media container service");
1519 } else if (mPendingInstalls.size() > 0) {
1520 HandlerParams params = mPendingInstalls.get(0);
1521 if (params != null) {
1522 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1523 System.identityHashCode(params));
1524 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1525 if (params.startCopy()) {
1526 // We are done... look for more work or to
1528 if (DEBUG_SD_INSTALL) Log.i(TAG,
1529 "Checking for more work or unbind...");
1530 // Delete pending install
1531 if (mPendingInstalls.size() > 0) {
1532 mPendingInstalls.remove(0);
1534 if (mPendingInstalls.size() == 0) {
1536 if (DEBUG_SD_INSTALL) Log.i(TAG,
1537 "Posting delayed MCS_UNBIND");
1538 removeMessages(MCS_UNBIND);
1539 Message ubmsg = obtainMessage(MCS_UNBIND);
1540 // Unbind after a little delay, to avoid
1541 // continual thrashing.
1542 sendMessageDelayed(ubmsg, 10000);
1545 // There are more pending requests in queue.
1546 // Just post MCS_BOUND message to trigger processing
1547 // of next pending install.
1548 if (DEBUG_SD_INSTALL) Log.i(TAG,
1549 "Posting MCS_BOUND for next work");
1550 mHandler.sendEmptyMessage(MCS_BOUND);
1553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1556 // Should never happen ideally.
1557 Slog.w(TAG, "Empty queue");
1561 case MCS_RECONNECT: {
1562 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1563 if (mPendingInstalls.size() > 0) {
1565 disconnectService();
1567 if (!connectToService()) {
1568 Slog.e(TAG, "Failed to bind to media container service");
1569 for (HandlerParams params : mPendingInstalls) {
1570 // Indicate service bind error
1571 params.serviceError();
1572 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1573 System.identityHashCode(params));
1575 mPendingInstalls.clear();
1581 // If there is no actual work left, then time to unbind.
1582 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1584 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1586 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1588 disconnectService();
1590 } else if (mPendingInstalls.size() > 0) {
1591 // There are more pending requests in queue.
1592 // Just post MCS_BOUND message to trigger processing
1593 // of next pending install.
1594 mHandler.sendEmptyMessage(MCS_BOUND);
1600 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1601 HandlerParams params = mPendingInstalls.remove(0);
1602 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1603 System.identityHashCode(params));
1606 case SEND_PENDING_BROADCAST: {
1608 ArrayList<String> components[];
1611 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1612 synchronized (mPackages) {
1613 if (mPendingBroadcasts == null) {
1616 size = mPendingBroadcasts.size();
1618 // Nothing to be done. Just return
1621 packages = new String[size];
1622 components = new ArrayList[size];
1623 uids = new int[size];
1624 int i = 0; // filling out the above arrays
1626 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1627 int packageUserId = mPendingBroadcasts.userIdAt(n);
1628 Iterator<Map.Entry<String, ArrayList<String>>> it
1629 = mPendingBroadcasts.packagesForUserId(packageUserId)
1630 .entrySet().iterator();
1631 while (it.hasNext() && i < size) {
1632 Map.Entry<String, ArrayList<String>> ent = it.next();
1633 packages[i] = ent.getKey();
1634 components[i] = ent.getValue();
1635 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1636 uids[i] = (ps != null)
1637 ? UserHandle.getUid(packageUserId, ps.appId)
1643 mPendingBroadcasts.clear();
1646 for (int i = 0; i < size; i++) {
1647 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1649 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1652 case START_CLEANING_PACKAGE: {
1653 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1654 final String packageName = (String)msg.obj;
1655 final int userId = msg.arg1;
1656 final boolean andCode = msg.arg2 != 0;
1657 synchronized (mPackages) {
1658 if (userId == UserHandle.USER_ALL) {
1659 int[] users = sUserManager.getUserIds();
1660 for (int user : users) {
1661 mSettings.addPackageToCleanLPw(
1662 new PackageCleanItem(user, packageName, andCode));
1665 mSettings.addPackageToCleanLPw(
1666 new PackageCleanItem(userId, packageName, andCode));
1669 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670 startCleaningPackages();
1672 case POST_INSTALL: {
1673 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1675 PostInstallData data = mRunningInstalls.get(msg.arg1);
1676 final boolean didRestore = (msg.arg2 != 0);
1677 mRunningInstalls.delete(msg.arg1);
1680 InstallArgs args = data.args;
1681 PackageInstalledInfo parentRes = data.res;
1683 final boolean grantPermissions = (args.installFlags
1684 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1685 final boolean killApp = (args.installFlags
1686 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1687 final boolean virtualPreload = ((args.installFlags
1688 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1689 final String[] grantedPermissions = args.installGrantPermissions;
1691 // Handle the parent package
1692 handlePackagePostInstall(parentRes, grantPermissions, killApp,
1693 virtualPreload, grantedPermissions, didRestore,
1694 args.installerPackageName, args.observer);
1696 // Handle the child packages
1697 final int childCount = (parentRes.addedChildPackages != null)
1698 ? parentRes.addedChildPackages.size() : 0;
1699 for (int i = 0; i < childCount; i++) {
1700 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1701 handlePackagePostInstall(childRes, grantPermissions, killApp,
1702 virtualPreload, grantedPermissions, false /*didRestore*/,
1703 args.installerPackageName, args.observer);
1706 // Log tracing if needed
1707 if (args.traceMethod != null) {
1708 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1712 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1715 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1717 case UPDATED_MEDIA_STATUS: {
1718 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1719 boolean reportStatus = msg.arg1 == 1;
1720 boolean doGc = msg.arg2 == 1;
1721 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1723 // Force a gc to clear up stale containers.
1724 Runtime.getRuntime().gc();
1726 if (msg.obj != null) {
1727 @SuppressWarnings("unchecked")
1728 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1729 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1730 // Unload containers
1731 unloadAllContainers(args);
1735 if (DEBUG_SD_INSTALL) Log.i(TAG,
1736 "Invoking StorageManagerService call back");
1737 PackageHelper.getStorageManager().finishMediaUpdate();
1738 } catch (RemoteException e) {
1739 Log.e(TAG, "StorageManagerService not running?");
1743 case WRITE_SETTINGS: {
1744 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1745 synchronized (mPackages) {
1746 removeMessages(WRITE_SETTINGS);
1747 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1748 mSettings.writeLPr();
1749 mDirtyUsers.clear();
1751 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1753 case WRITE_PACKAGE_RESTRICTIONS: {
1754 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1755 synchronized (mPackages) {
1756 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1757 for (int userId : mDirtyUsers) {
1758 mSettings.writePackageRestrictionsLPr(userId);
1760 mDirtyUsers.clear();
1762 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1764 case WRITE_PACKAGE_LIST: {
1765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1766 synchronized (mPackages) {
1767 removeMessages(WRITE_PACKAGE_LIST);
1768 mSettings.writePackageListLPr(msg.arg1);
1770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1772 case CHECK_PENDING_VERIFICATION: {
1773 final int verificationId = msg.arg1;
1774 final PackageVerificationState state = mPendingVerification.get(verificationId);
1776 if ((state != null) && !state.timeoutExtended()) {
1777 final InstallArgs args = state.getInstallArgs();
1778 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1780 Slog.i(TAG, "Verification timed out for " + originUri);
1781 mPendingVerification.remove(verificationId);
1783 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1785 final UserHandle user = args.getUser();
1786 if (getDefaultVerificationResponse(user)
1787 == PackageManager.VERIFICATION_ALLOW) {
1788 Slog.i(TAG, "Continuing with installation of " + originUri);
1789 state.setVerifierResponse(Binder.getCallingUid(),
1790 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1791 broadcastPackageVerified(verificationId, originUri,
1792 PackageManager.VERIFICATION_ALLOW, user);
1794 ret = args.copyApk(mContainerService, true);
1795 } catch (RemoteException e) {
1796 Slog.e(TAG, "Could not contact the ContainerService");
1799 broadcastPackageVerified(verificationId, originUri,
1800 PackageManager.VERIFICATION_REJECT, user);
1803 Trace.asyncTraceEnd(
1804 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806 processPendingInstall(args, ret);
1807 mHandler.sendEmptyMessage(MCS_UNBIND);
1811 case PACKAGE_VERIFIED: {
1812 final int verificationId = msg.arg1;
1814 final PackageVerificationState state = mPendingVerification.get(verificationId);
1815 if (state == null) {
1816 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1820 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1822 state.setVerifierResponse(response.callerUid, response.code);
1824 if (state.isVerificationComplete()) {
1825 mPendingVerification.remove(verificationId);
1827 final InstallArgs args = state.getInstallArgs();
1828 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1831 if (state.isInstallAllowed()) {
1832 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1833 broadcastPackageVerified(verificationId, originUri,
1834 response.code, state.getInstallArgs().getUser());
1836 ret = args.copyApk(mContainerService, true);
1837 } catch (RemoteException e) {
1838 Slog.e(TAG, "Could not contact the ContainerService");
1841 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1844 Trace.asyncTraceEnd(
1845 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1847 processPendingInstall(args, ret);
1848 mHandler.sendEmptyMessage(MCS_UNBIND);
1853 case START_INTENT_FILTER_VERIFICATIONS: {
1854 IFVerificationParams params = (IFVerificationParams) msg.obj;
1855 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1856 params.replacing, params.pkg);
1859 case INTENT_FILTER_VERIFIED: {
1860 final int verificationId = msg.arg1;
1862 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1864 if (state == null) {
1865 Slog.w(TAG, "Invalid IntentFilter verification token "
1866 + verificationId + " received");
1870 final int userId = state.getUserId();
1872 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1873 "Processing IntentFilter verification with token:"
1874 + verificationId + " and userId:" + userId);
1876 final IntentFilterVerificationResponse response =
1877 (IntentFilterVerificationResponse) msg.obj;
1879 state.setVerifierResponse(response.callerUid, response.code);
1881 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1882 "IntentFilter verification with token:" + verificationId
1883 + " and userId:" + userId
1884 + " is settings verifier response with response code:"
1887 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1888 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1889 + response.getFailedDomainsString());
1892 if (state.isVerificationComplete()) {
1893 mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1895 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1896 "IntentFilter verification with token:" + verificationId
1897 + " was not said to be complete");
1902 case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1903 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1904 mInstantAppResolverConnection,
1905 (InstantAppRequest) msg.obj,
1906 mInstantAppInstallerActivity,
1913 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1914 boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1915 boolean launchedForRestore, String installerPackage,
1916 IPackageInstallObserver2 installObserver) {
1917 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1918 // Send the removed broadcasts
1919 if (res.removedInfo != null) {
1920 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1923 // Now that we successfully installed the package, grant runtime
1924 // permissions if requested before broadcasting the install. Also
1925 // for legacy apps in permission review mode we clear the permission
1926 // review flag which is used to emulate runtime permissions for
1928 if (grantPermissions) {
1929 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1932 final boolean update = res.removedInfo != null
1933 && res.removedInfo.removedPackage != null;
1934 final String installerPackageName =
1935 res.installerPackageName != null
1936 ? res.installerPackageName
1937 : res.removedInfo != null
1938 ? res.removedInfo.installerPackageName
1941 // If this is the first time we have child packages for a disabled privileged
1942 // app that had no children, we grant requested runtime permissions to the new
1943 // children if the parent on the system image had them already granted.
1944 if (res.pkg.parentPackage != null) {
1945 synchronized (mPackages) {
1946 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1950 synchronized (mPackages) {
1951 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1954 final String packageName = res.pkg.applicationInfo.packageName;
1956 // Determine the set of users who are adding this package for
1957 // the first time vs. those who are seeing an update.
1958 int[] firstUsers = EMPTY_INT_ARRAY;
1959 int[] updateUsers = EMPTY_INT_ARRAY;
1960 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1961 final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1962 for (int newUser : res.newUsers) {
1963 if (ps.getInstantApp(newUser)) {
1967 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1970 boolean isNew = true;
1971 for (int origUser : res.origUsers) {
1972 if (origUser == newUser) {
1978 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1980 updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1984 // Send installed broadcasts if the package is not a static shared lib.
1985 if (res.pkg.staticSharedLibName == null) {
1986 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1988 // Send added for users that see the package for the first time
1989 // sendPackageAddedForNewUsers also deals with system apps
1990 int appId = UserHandle.getAppId(res.uid);
1991 boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1992 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1993 virtualPreload /*startReceiver*/, appId, firstUsers);
1995 // Send added for users that don't see the package for the first time
1996 Bundle extras = new Bundle(1);
1997 extras.putInt(Intent.EXTRA_UID, res.uid);
1999 extras.putBoolean(Intent.EXTRA_REPLACING, true);
2001 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2002 extras, 0 /*flags*/,
2003 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2004 if (installerPackageName != null) {
2005 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2006 extras, 0 /*flags*/,
2007 installerPackageName, null /*finishedReceiver*/, updateUsers);
2010 // Send replaced for users that don't see the package for the first time
2012 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2013 packageName, extras, 0 /*flags*/,
2014 null /*targetPackage*/, null /*finishedReceiver*/,
2016 if (installerPackageName != null) {
2017 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2018 extras, 0 /*flags*/,
2019 installerPackageName, null /*finishedReceiver*/, updateUsers);
2021 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2022 null /*package*/, null /*extras*/, 0 /*flags*/,
2023 packageName /*targetPackage*/,
2024 null /*finishedReceiver*/, updateUsers);
2025 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2026 // First-install and we did a restore, so we're responsible for the
2027 // first-launch broadcast.
2029 Slog.i(TAG, "Post-restore of " + packageName
2030 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2032 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2035 // Send broadcast package appeared if forward locked/external for all users
2036 // treat asec-hosted packages like removable media on upgrade
2037 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2038 if (DEBUG_INSTALL) {
2039 Slog.i(TAG, "upgrading pkg " + res.pkg
2040 + " is ASEC-hosted -> AVAILABLE");
2042 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2043 ArrayList<String> pkgList = new ArrayList<>(1);
2044 pkgList.add(packageName);
2045 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2049 // Work that needs to happen on first install within each user
2050 if (firstUsers != null && firstUsers.length > 0) {
2051 synchronized (mPackages) {
2052 for (int userId : firstUsers) {
2053 // If this app is a browser and it's newly-installed for some
2054 // users, clear any default-browser state in those users. The
2055 // app's nature doesn't depend on the user, so we can just check
2056 // its browser nature in any user and generalize.
2057 if (packageIsBrowser(packageName, userId)) {
2058 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2061 // We may also need to apply pending (restored) runtime
2062 // permission grants within these users.
2063 mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2068 // Log current value of "unknown sources" setting
2069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2070 getUnknownSourcesSettings());
2072 // Remove the replaced package's older resources safely now
2073 // We delete after a gc for applications on sdcard.
2074 if (res.removedInfo != null && res.removedInfo.args != null) {
2075 Runtime.getRuntime().gc();
2076 synchronized (mInstallLock) {
2077 res.removedInfo.args.doPostDeleteLI(true);
2080 // Force a gc to clear up things. Ask for a background one, it's fine to go on
2081 // and not block here.
2082 VMRuntime.getRuntime().requestConcurrentGC();
2085 // Notify DexManager that the package was installed for new users.
2086 // The updated users should already be indexed and the package code paths
2087 // should not change.
2088 // Don't notify the manager for ephemeral apps as they are not expected to
2089 // survive long enough to benefit of background optimizations.
2090 for (int userId : firstUsers) {
2091 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2092 // There's a race currently where some install events may interleave with an uninstall.
2093 // This can lead to package info being null (b/36642664).
2095 mDexManager.notifyPackageInstalled(info, userId);
2100 // If someone is watching installs - notify them
2101 if (installObserver != null) {
2103 Bundle extras = extrasForInstallResult(res);
2104 installObserver.onPackageInstalled(res.name, res.returnCode,
2105 res.returnMsg, extras);
2106 } catch (RemoteException e) {
2107 Slog.i(TAG, "Observer no longer exists.");
2112 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2113 PackageParser.Package pkg) {
2114 if (pkg.parentPackage == null) {
2117 if (pkg.requestedPermissions == null) {
2120 final PackageSetting disabledSysParentPs = mSettings
2121 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2122 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2123 || !disabledSysParentPs.isPrivileged()
2124 || (disabledSysParentPs.childPackageNames != null
2125 && !disabledSysParentPs.childPackageNames.isEmpty())) {
2128 final int[] allUserIds = sUserManager.getUserIds();
2129 final int permCount = pkg.requestedPermissions.size();
2130 for (int i = 0; i < permCount; i++) {
2131 String permission = pkg.requestedPermissions.get(i);
2132 BasePermission bp = mSettings.mPermissions.get(permission);
2133 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2136 for (int userId : allUserIds) {
2137 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2138 permission, userId)) {
2139 grantRuntimePermission(pkg.packageName, permission, userId);
2145 private StorageEventListener mStorageListener = new StorageEventListener() {
2147 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2148 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2149 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2150 final String volumeUuid = vol.getFsUuid();
2152 // Clean up any users or apps that were removed or recreated
2153 // while this volume was missing
2154 sUserManager.reconcileUsers(volumeUuid);
2155 reconcileApps(volumeUuid);
2157 // Clean up any install sessions that expired or were
2158 // cancelled while this volume was missing
2159 mInstallerService.onPrivateVolumeMounted(volumeUuid);
2161 loadPrivatePackages(vol);
2163 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2164 unloadPrivatePackages(vol);
2168 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2169 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2170 updateExternalMediaStatus(true, false);
2171 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2172 updateExternalMediaStatus(false, false);
2178 public void onVolumeForgotten(String fsUuid) {
2179 if (TextUtils.isEmpty(fsUuid)) {
2180 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2184 // Remove any apps installed on the forgotten volume
2185 synchronized (mPackages) {
2186 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2187 for (PackageSetting ps : packages) {
2188 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2189 deletePackageVersioned(new VersionedPackage(ps.name,
2190 PackageManager.VERSION_CODE_HIGHEST),
2191 new LegacyPackageDeleteObserver(null).getBinder(),
2192 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2193 // Try very hard to release any references to this package
2194 // so we don't risk the system server being killed due to
2196 AttributeCache.instance().removePackage(ps.name);
2199 mSettings.onVolumeForgotten(fsUuid);
2200 mSettings.writeLPr();
2205 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2206 String[] grantedPermissions) {
2207 for (int userId : userIds) {
2208 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2212 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2213 String[] grantedPermissions) {
2214 PackageSetting ps = (PackageSetting) pkg.mExtras;
2219 PermissionsState permissionsState = ps.getPermissionsState();
2221 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2222 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2224 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2225 >= Build.VERSION_CODES.M;
2227 final boolean instantApp = isInstantApp(pkg.packageName, userId);
2229 for (String permission : pkg.requestedPermissions) {
2230 final BasePermission bp;
2231 synchronized (mPackages) {
2232 bp = mSettings.mPermissions.get(permission);
2234 if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2235 && (!instantApp || bp.isInstant())
2236 && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2237 && (grantedPermissions == null
2238 || ArrayUtils.contains(grantedPermissions, permission))) {
2239 final int flags = permissionsState.getPermissionFlags(permission, userId);
2240 if (supportsRuntimePermissions) {
2241 // Installer cannot change immutable permissions.
2242 if ((flags & immutableFlags) == 0) {
2243 grantRuntimePermission(pkg.packageName, permission, userId);
2245 } else if (mPermissionReviewRequired) {
2246 // In permission review mode we clear the review flag when we
2247 // are asked to install the app with all permissions granted.
2248 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2249 updatePermissionFlags(permission, pkg.packageName,
2250 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2257 Bundle extrasForInstallResult(PackageInstalledInfo res) {
2258 Bundle extras = null;
2259 switch (res.returnCode) {
2260 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2261 extras = new Bundle();
2262 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2263 res.origPermission);
2264 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2268 case PackageManager.INSTALL_SUCCEEDED: {
2269 extras = new Bundle();
2270 extras.putBoolean(Intent.EXTRA_REPLACING,
2271 res.removedInfo != null && res.removedInfo.removedPackage != null);
2278 void scheduleWriteSettingsLocked() {
2279 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2280 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2284 void scheduleWritePackageListLocked(int userId) {
2285 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2286 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2288 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2292 void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2293 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2294 scheduleWritePackageRestrictionsLocked(userId);
2297 void scheduleWritePackageRestrictionsLocked(int userId) {
2298 final int[] userIds = (userId == UserHandle.USER_ALL)
2299 ? sUserManager.getUserIds() : new int[]{userId};
2300 for (int nextUserId : userIds) {
2301 if (!sUserManager.exists(nextUserId)) return;
2302 mDirtyUsers.add(nextUserId);
2303 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2304 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2309 public static PackageManagerService main(Context context, Installer installer,
2310 boolean factoryTest, boolean onlyCore) {
2311 // Self-check for initial settings.
2312 PackageManagerServiceCompilerMapping.checkProperties();
2314 PackageManagerService m = new PackageManagerService(context, installer,
2315 factoryTest, onlyCore);
2316 m.enableSystemUserPackages();
2317 ServiceManager.addService("package", m);
2318 final PackageManagerNative pmn = m.new PackageManagerNative();
2319 ServiceManager.addService("package_native", pmn);
2323 private void enableSystemUserPackages() {
2324 if (!UserManager.isSplitSystemUser()) {
2327 // For system user, enable apps based on the following conditions:
2328 // - app is whitelisted or belong to one of these groups:
2329 // -- system app which has no launcher icons
2330 // -- system app which has INTERACT_ACROSS_USERS permission
2331 // -- system IME app
2332 // - app is not in the blacklist
2333 AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2334 Set<String> enableApps = new ArraySet<>();
2335 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2336 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2337 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2338 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2339 enableApps.addAll(wlApps);
2340 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2341 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2342 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2343 enableApps.removeAll(blApps);
2344 Log.i(TAG, "Applications installed for system user: " + enableApps);
2345 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2347 final int allAppsSize = allAps.size();
2348 synchronized (mPackages) {
2349 for (int i = 0; i < allAppsSize; i++) {
2350 String pName = allAps.get(i);
2351 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2352 // Should not happen, but we shouldn't be failing if it does
2353 if (pkgSetting == null) {
2356 boolean install = enableApps.contains(pName);
2357 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2358 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2359 + " for system user");
2360 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2363 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2367 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2368 DisplayManager displayManager = (DisplayManager) context.getSystemService(
2369 Context.DISPLAY_SERVICE);
2370 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2374 * Requests that files preopted on a secondary system partition be copied to the data partition
2375 * if possible. Note that the actual copying of the files is accomplished by init for security
2376 * reasons. This simply requests that the copy takes place and awaits confirmation of its
2377 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2379 private static void requestCopyPreoptedFiles() {
2380 final int WAIT_TIME_MS = 100;
2381 final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2382 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2383 SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2384 // We will wait for up to 100 seconds.
2385 final long timeStart = SystemClock.uptimeMillis();
2386 final long timeEnd = timeStart + 100 * 1000;
2387 long timeNow = timeStart;
2388 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2390 Thread.sleep(WAIT_TIME_MS);
2391 } catch (InterruptedException e) {
2394 timeNow = SystemClock.uptimeMillis();
2395 if (timeNow > timeEnd) {
2396 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2397 Slog.wtf(TAG, "cppreopt did not finish!");
2402 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2406 public PackageManagerService(Context context, Installer installer,
2407 boolean factoryTest, boolean onlyCore) {
2408 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2409 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2410 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2411 SystemClock.uptimeMillis());
2413 if (mSdkVersion <= 0) {
2414 Slog.w(TAG, "**** ro.build.version.sdk not set!");
2419 mPermissionReviewRequired = context.getResources().getBoolean(
2420 R.bool.config_permissionReviewRequired);
2422 mFactoryTest = factoryTest;
2423 mOnlyCore = onlyCore;
2424 mMetrics = new DisplayMetrics();
2425 mSettings = new Settings(mPackages);
2426 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2427 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2429 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2431 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2433 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2435 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2437 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439 String separateProcesses = SystemProperties.get("debug.separate_processes");
2440 if (separateProcesses != null && separateProcesses.length() > 0) {
2441 if ("*".equals(separateProcesses)) {
2442 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2443 mSeparateProcesses = null;
2444 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2447 mSeparateProcesses = separateProcesses.split(",");
2448 Slog.w(TAG, "Running with debug.separate_processes: "
2449 + separateProcesses);
2453 mSeparateProcesses = null;
2456 mInstaller = installer;
2457 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2459 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2460 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2462 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2463 FgThread.get().getLooper());
2465 getDefaultDisplayMetrics(context, mMetrics);
2467 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2468 SystemConfig systemConfig = SystemConfig.getInstance();
2469 mGlobalGids = systemConfig.getGlobalGids();
2470 mSystemPermissions = systemConfig.getSystemPermissions();
2471 mAvailableFeatures = systemConfig.getAvailableFeatures();
2472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2474 mProtectedPackages = new ProtectedPackages(mContext);
2476 synchronized (mInstallLock) {
2478 synchronized (mPackages) {
2479 mHandlerThread = new ServiceThread(TAG,
2480 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2481 mHandlerThread.start();
2482 mHandler = new PackageHandler(mHandlerThread.getLooper());
2483 mProcessLoggingHandler = new ProcessLoggingHandler();
2484 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2486 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2487 mInstantAppRegistry = new InstantAppRegistry(this);
2489 File dataDir = Environment.getDataDirectory();
2490 mAppInstallDir = new File(dataDir, "app");
2491 mAppLib32InstallDir = new File(dataDir, "app-lib");
2492 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2493 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2494 sUserManager = new UserManagerService(context, this,
2495 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2497 // Propagate permission configuration in to package manager.
2498 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2499 = systemConfig.getPermissions();
2500 for (int i=0; i<permConfig.size(); i++) {
2501 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2502 BasePermission bp = mSettings.mPermissions.get(perm.name);
2504 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2505 mSettings.mPermissions.put(perm.name, bp);
2507 if (perm.gids != null) {
2508 bp.setGids(perm.gids, perm.perUser);
2512 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2513 final int builtInLibCount = libConfig.size();
2514 for (int i = 0; i < builtInLibCount; i++) {
2515 String name = libConfig.keyAt(i);
2516 String path = libConfig.valueAt(i);
2517 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2518 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2521 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2523 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2524 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2525 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2527 // Clean up orphaned packages for which the code path doesn't exist
2528 // and they are an update to a system app - caused by bug/32321269
2529 final int packageSettingCount = mSettings.mPackages.size();
2530 for (int i = packageSettingCount - 1; i >= 0; i--) {
2531 PackageSetting ps = mSettings.mPackages.valueAt(i);
2532 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2533 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2534 mSettings.mPackages.removeAt(i);
2535 mSettings.enableSystemPackageLPw(ps.name);
2540 requestCopyPreoptedFiles();
2543 String customResolverActivity = Resources.getSystem().getString(
2544 R.string.config_customResolverActivity);
2545 if (TextUtils.isEmpty(customResolverActivity)) {
2546 customResolverActivity = null;
2548 mCustomResolverComponentName = ComponentName.unflattenFromString(
2549 customResolverActivity);
2552 long startTime = SystemClock.uptimeMillis();
2554 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2557 final String bootClassPath = System.getenv("BOOTCLASSPATH");
2558 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2560 if (bootClassPath == null) {
2561 Slog.w(TAG, "No BOOTCLASSPATH found!");
2564 if (systemServerClassPath == null) {
2565 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2568 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2570 final VersionInfo ver = mSettings.getInternalVersion();
2571 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2573 logCriticalInfo(Log.INFO,
2574 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2577 // when upgrading from pre-M, promote system app permissions from install to runtime
2578 mPromoteSystemApps =
2579 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2581 // When upgrading from pre-N, we need to handle package extraction like first boot,
2582 // as there is no profiling data available.
2583 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2585 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2587 // save off the names of pre-existing system packages prior to scanning; we don't
2588 // want to automatically grant runtime permissions for new system apps
2589 if (mPromoteSystemApps) {
2590 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2591 while (pkgSettingIter.hasNext()) {
2592 PackageSetting ps = pkgSettingIter.next();
2593 if (isSystemApp(ps)) {
2594 mExistingSystemPackages.add(ps.name);
2599 mCacheDir = preparePackageParserCache(mIsUpgrade);
2601 // Set flag to monitor and not change apk file paths when
2602 // scanning install directories.
2603 int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2605 if (mIsUpgrade || mFirstBoot) {
2606 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2609 // Collect vendor overlay packages. (Do this before scanning any apps.)
2610 // For security and version matching reason, only consider
2611 // overlay packages if they reside in the right directory.
2612 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2613 | PackageParser.PARSE_IS_SYSTEM
2614 | PackageParser.PARSE_IS_SYSTEM_DIR
2615 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2617 mParallelPackageParserCallback.findStaticOverlayPackages();
2619 // Find base frameworks (resource packages without code).
2620 scanDirTracedLI(frameworkDir, mDefParseFlags
2621 | PackageParser.PARSE_IS_SYSTEM
2622 | PackageParser.PARSE_IS_SYSTEM_DIR
2623 | PackageParser.PARSE_IS_PRIVILEGED,
2624 scanFlags | SCAN_NO_DEX, 0);
2626 // Collected privileged system packages.
2627 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2628 scanDirTracedLI(privilegedAppDir, mDefParseFlags
2629 | PackageParser.PARSE_IS_SYSTEM
2630 | PackageParser.PARSE_IS_SYSTEM_DIR
2631 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2633 // Collect ordinary system packages.
2634 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2635 scanDirTracedLI(systemAppDir, mDefParseFlags
2636 | PackageParser.PARSE_IS_SYSTEM
2637 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2639 // Collect all vendor packages.
2640 File vendorAppDir = new File("/vendor/app");
2642 vendorAppDir = vendorAppDir.getCanonicalFile();
2643 } catch (IOException e) {
2644 // failed to look up canonical path, continue with original one
2646 scanDirTracedLI(vendorAppDir, mDefParseFlags
2647 | PackageParser.PARSE_IS_SYSTEM
2648 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2650 // Collect all OEM packages.
2651 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2652 scanDirTracedLI(oemAppDir, mDefParseFlags
2653 | PackageParser.PARSE_IS_SYSTEM
2654 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2656 // Prune any system packages that no longer exist.
2657 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2658 // Stub packages must either be replaced with full versions in the /data
2659 // partition or be disabled.
2660 final List<String> stubSystemApps = new ArrayList<>();
2662 // do this first before mucking with mPackages for the "expecting better" case
2663 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2664 while (pkgIterator.hasNext()) {
2665 final PackageParser.Package pkg = pkgIterator.next();
2667 stubSystemApps.add(pkg.packageName);
2671 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2672 while (psit.hasNext()) {
2673 PackageSetting ps = psit.next();
2676 * If this is not a system app, it can't be a
2677 * disable system app.
2679 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2684 * If the package is scanned, it's not erased.
2686 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2687 if (scannedPkg != null) {
2689 * If the system app is both scanned and in the
2690 * disabled packages list, then it must have been
2691 * added via OTA. Remove it from the currently
2692 * scanned package so the previously user-installed
2693 * application can be scanned.
2695 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2696 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2697 + ps.name + "; removing system app. Last known codePath="
2698 + ps.codePathString + ", installStatus=" + ps.installStatus
2699 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2700 + scannedPkg.mVersionCode);
2701 removePackageLI(scannedPkg, true);
2702 mExpectingBetter.put(ps.name, ps.codePath);
2708 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2710 logCriticalInfo(Log.WARN, "System package " + ps.name
2711 + " no longer exists; it's data will be wiped");
2712 // Actual deletion of code and data will be handled by later
2713 // reconciliation step
2715 // we still have a disabled system package, but, it still might have
2716 // been removed. check the code path still exists and check there's
2717 // still a package. the latter can happen if an OTA keeps the same
2718 // code path, but, changes the package name.
2719 final PackageSetting disabledPs =
2720 mSettings.getDisabledSystemPkgLPr(ps.name);
2721 if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2722 || disabledPs.pkg == null) {
2723 possiblyDeletedUpdatedSystemApps.add(ps.name);
2729 //look for any incomplete package installations
2730 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2731 for (int i = 0; i < deletePkgsList.size(); i++) {
2732 // Actual deletion of code and data will be handled by later
2733 // reconciliation step
2734 final String packageName = deletePkgsList.get(i).name;
2735 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2736 synchronized (mPackages) {
2737 mSettings.removePackageLPw(packageName);
2742 deleteTempPackageFiles();
2744 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2746 // Remove any shared userIDs that have no associated packages
2747 mSettings.pruneSharedUsersLPw();
2748 final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2749 final int systemPackagesCount = mPackages.size();
2750 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2751 + " ms, packageCount: " + systemPackagesCount
2752 + " , timePerPackage: "
2753 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2754 + " , cached: " + cachedSystemApps);
2755 if (mIsUpgrade && systemPackagesCount > 0) {
2756 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2757 ((int) systemScanTime) / systemPackagesCount);
2760 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2761 SystemClock.uptimeMillis());
2762 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2764 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2765 | PackageParser.PARSE_FORWARD_LOCK,
2766 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2768 // Remove disable package settings for updated system apps that were
2769 // removed via an OTA. If the update is no longer present, remove the
2770 // app completely. Otherwise, revoke their system privileges.
2771 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2772 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2773 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2776 if (deletedPkg == null) {
2777 // should have found an update, but, we didn't; remove everything
2778 msg = "Updated system package " + deletedAppName
2779 + " no longer exists; removing its data";
2780 // Actual deletion of code and data will be handled by later
2781 // reconciliation step
2783 // found an update; revoke system privileges
2784 msg = "Updated system package + " + deletedAppName
2785 + " no longer exists; revoking system privileges";
2787 // Don't do anything if a stub is removed from the system image. If
2788 // we were to remove the uncompressed version from the /data partition,
2789 // this is where it'd be done.
2791 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2792 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2793 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2795 logCriticalInfo(Log.WARN, msg);
2799 * Make sure all system apps that we expected to appear on
2800 * the userdata partition actually showed up. If they never
2801 * appeared, crawl back and revive the system version.
2803 for (int i = 0; i < mExpectingBetter.size(); i++) {
2804 final String packageName = mExpectingBetter.keyAt(i);
2805 if (!mPackages.containsKey(packageName)) {
2806 final File scanFile = mExpectingBetter.valueAt(i);
2808 logCriticalInfo(Log.WARN, "Expected better " + packageName
2809 + " but never showed up; reverting to system");
2811 int reparseFlags = mDefParseFlags;
2812 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2813 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2814 | PackageParser.PARSE_IS_SYSTEM_DIR
2815 | PackageParser.PARSE_IS_PRIVILEGED;
2816 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2817 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2818 | PackageParser.PARSE_IS_SYSTEM_DIR;
2819 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2820 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2821 | PackageParser.PARSE_IS_SYSTEM_DIR;
2822 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2823 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2824 | PackageParser.PARSE_IS_SYSTEM_DIR;
2826 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2830 mSettings.enableSystemPackageLPw(packageName);
2833 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2834 } catch (PackageManagerException e) {
2835 Slog.e(TAG, "Failed to parse original system package: "
2841 // Uncompress and install any stubbed system applications.
2842 // This must be done last to ensure all stubs are replaced or disabled.
2843 decompressSystemApplications(stubSystemApps, scanFlags);
2845 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2848 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2849 final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2850 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2851 + " ms, packageCount: " + dataPackagesCount
2852 + " , timePerPackage: "
2853 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2854 + " , cached: " + cachedNonSystemApps);
2855 if (mIsUpgrade && dataPackagesCount > 0) {
2856 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2857 ((int) dataScanTime) / dataPackagesCount);
2860 mExpectingBetter.clear();
2862 // Resolve the storage manager.
2863 mStorageManagerPackage = getStorageManagerPackageName();
2865 // Resolve protected action filters. Only the setup wizard is allowed to
2866 // have a high priority filter for these actions.
2867 mSetupWizardPackage = getSetupWizardPackageName();
2868 if (mProtectedFilters.size() > 0) {
2869 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2870 Slog.i(TAG, "No setup wizard;"
2871 + " All protected intents capped to priority 0");
2873 for (ActivityIntentInfo filter : mProtectedFilters) {
2874 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2875 if (DEBUG_FILTERS) {
2876 Slog.i(TAG, "Found setup wizard;"
2877 + " allow priority " + filter.getPriority() + ";"
2878 + " package: " + filter.activity.info.packageName
2879 + " activity: " + filter.activity.className
2880 + " priority: " + filter.getPriority());
2882 // skip setup wizard; allow it to keep the high priority filter
2885 if (DEBUG_FILTERS) {
2886 Slog.i(TAG, "Protected action; cap priority to 0;"
2887 + " package: " + filter.activity.info.packageName
2888 + " activity: " + filter.activity.className
2889 + " origPrio: " + filter.getPriority());
2891 filter.setPriority(0);
2894 mDeferProtectedFilters = false;
2895 mProtectedFilters.clear();
2897 // Now that we know all of the shared libraries, update all clients to have
2898 // the correct library paths.
2899 updateAllSharedLibrariesLPw(null);
2901 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2902 // NOTE: We ignore potential failures here during a system scan (like
2903 // the rest of the commands above) because there's precious little we
2904 // can do about it. A settings error is reported, though.
2905 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2908 // Now that we know all the packages we are keeping,
2909 // read and update their last usage times.
2910 mPackageUsage.read(mPackages);
2911 mCompilerStats.read();
2913 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2914 SystemClock.uptimeMillis());
2915 Slog.i(TAG, "Time to scan packages: "
2916 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2919 // If the platform SDK has changed since the last time we booted,
2920 // we need to re-grant app permission to catch any new ones that
2921 // appear. This is really a hack, and means that apps can in some
2922 // cases get permissions that the user didn't initially explicitly
2923 // allow... it would be nice to have some better way to handle
2925 int updateFlags = UPDATE_PERMISSIONS_ALL;
2926 if (ver.sdkVersion != mSdkVersion) {
2927 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2928 + mSdkVersion + "; regranting permissions for internal storage");
2929 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2931 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2932 ver.sdkVersion = mSdkVersion;
2934 // If this is the first boot or an update from pre-M, and it is a normal
2935 // boot, then we need to initialize the default preferred apps across
2936 // all defined users.
2937 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2938 for (UserInfo user : sUserManager.getUsers(true)) {
2939 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2940 applyFactoryDefaultBrowserLPw(user.id);
2941 primeDomainVerificationsLPw(user.id);
2945 // Prepare storage for system user really early during boot,
2946 // since core system apps like SettingsProvider and SystemUI
2947 // can't wait for user to start
2948 final int storageFlags;
2949 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2950 storageFlags = StorageManager.FLAG_STORAGE_DE;
2952 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2954 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2955 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2956 true /* onlyCoreApps */);
2957 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2958 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2959 Trace.TRACE_TAG_PACKAGE_MANAGER);
2960 traceLog.traceBegin("AppDataFixup");
2962 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2963 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2964 } catch (InstallerException e) {
2965 Slog.w(TAG, "Trouble fixing GIDs", e);
2967 traceLog.traceEnd();
2969 traceLog.traceBegin("AppDataPrepare");
2970 if (deferPackages == null || deferPackages.isEmpty()) {
2974 for (String pkgName : deferPackages) {
2975 PackageParser.Package pkg = null;
2976 synchronized (mPackages) {
2977 PackageSetting ps = mSettings.getPackageLPr(pkgName);
2978 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2983 synchronized (mInstallLock) {
2984 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2985 true /* maybeMigrateAppData */);
2990 traceLog.traceEnd();
2991 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2992 }, "prepareAppData");
2994 // If this is first boot after an OTA, and a normal boot, then
2995 // we need to clear code cache directories.
2996 // Note that we do *not* clear the application profiles. These remain valid
2997 // across OTAs and are used to drive profile verification (post OTA) and
2998 // profile compilation (without waiting to collect a fresh set of profiles).
2999 if (mIsUpgrade && !onlyCore) {
3000 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3001 for (int i = 0; i < mSettings.mPackages.size(); i++) {
3002 final PackageSetting ps = mSettings.mPackages.valueAt(i);
3003 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3004 // No apps are running this early, so no need to freeze
3005 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3006 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3007 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3010 ver.fingerprint = Build.FINGERPRINT;
3013 checkDefaultBrowser();
3015 // clear only after permissions and other defaults have been updated
3016 mExistingSystemPackages.clear();
3017 mPromoteSystemApps = false;
3019 // All the changes are done during package scanning.
3020 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3022 // can downgrade to reader
3023 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3024 mSettings.writeLPr();
3025 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3027 SystemClock.uptimeMillis());
3030 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3031 mRequiredInstallerPackage = getRequiredInstallerLPr();
3032 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3033 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3034 if (mIntentFilterVerifierComponent != null) {
3035 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3036 mIntentFilterVerifierComponent);
3038 mIntentFilterVerifier = null;
3040 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3041 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3042 SharedLibraryInfo.VERSION_UNDEFINED);
3043 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3044 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3045 SharedLibraryInfo.VERSION_UNDEFINED);
3047 mRequiredVerifierPackage = null;
3048 mRequiredInstallerPackage = null;
3049 mRequiredUninstallerPackage = null;
3050 mIntentFilterVerifierComponent = null;
3051 mIntentFilterVerifier = null;
3052 mServicesSystemSharedLibraryPackageName = null;
3053 mSharedSystemSharedLibraryPackageName = null;
3056 mInstallerService = new PackageInstallerService(context, this);
3057 final Pair<ComponentName, String> instantAppResolverComponent =
3058 getInstantAppResolverLPr();
3059 if (instantAppResolverComponent != null) {
3060 if (DEBUG_EPHEMERAL) {
3061 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3063 mInstantAppResolverConnection = new EphemeralResolverConnection(
3064 mContext, instantAppResolverComponent.first,
3065 instantAppResolverComponent.second);
3066 mInstantAppResolverSettingsComponent =
3067 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3069 mInstantAppResolverConnection = null;
3070 mInstantAppResolverSettingsComponent = null;
3072 updateInstantAppInstallerLocked(null);
3074 // Read and update the usage of dex files.
3075 // Do this at the end of PM init so that all the packages have their
3076 // data directory reconciled.
3077 // At this point we know the code paths of the packages, so we can validate
3078 // the disk file and build the internal cache.
3079 // The usage file is expected to be small so loading and verifying it
3080 // should take a fairly small time compare to the other activities (e.g. package
3082 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3083 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3084 for (int userId : currentUserIds) {
3085 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3087 mDexManager.load(userPackages);
3089 MetricsLogger.histogram(null, "ota_package_manager_init_time",
3090 (int) (SystemClock.uptimeMillis() - startTime));
3092 } // synchronized (mPackages)
3093 } // synchronized (mInstallLock)
3095 // Now after opening every single application zip, make sure they
3096 // are all flushed. Not really needed, but keeps things nice and
3098 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3099 Runtime.getRuntime().gc();
3100 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3102 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3103 FallbackCategoryProvider.loadFallbacks();
3104 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3106 // The initial scanning above does many calls into installd while
3107 // holding the mPackages lock, but we're mostly interested in yelling
3108 // once we have a booted system.
3109 mInstaller.setWarnIfHeld(mPackages);
3111 // Expose private service for system components to use.
3112 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3117 * Uncompress and install stub applications.
3118 * <p>In order to save space on the system partition, some applications are shipped in a
3119 * compressed form. In addition the compressed bits for the full application, the
3120 * system image contains a tiny stub comprised of only the Android manifest.
3121 * <p>During the first boot, attempt to uncompress and install the full application. If
3122 * the application can't be installed for any reason, disable the stub and prevent
3123 * uncompressing the full application during future boots.
3124 * <p>In order to forcefully attempt an installation of a full application, go to app
3125 * settings and enable the application.
3127 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3128 for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3129 final String pkgName = stubSystemApps.get(i);
3130 // skip if the system package is already disabled
3131 if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3132 stubSystemApps.remove(i);
3135 // skip if the package isn't installed (?!); this should never happen
3136 final PackageParser.Package pkg = mPackages.get(pkgName);
3138 stubSystemApps.remove(i);
3141 // skip if the package has been disabled by the user
3142 final PackageSetting ps = mSettings.mPackages.get(pkgName);
3144 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3145 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3146 stubSystemApps.remove(i);
3151 if (DEBUG_COMPRESSION) {
3152 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3155 // uncompress the binary to its eventual destination on /data
3156 final File scanFile = decompressPackage(pkg);
3157 if (scanFile == null) {
3161 // install the package to replace the stub on /system
3163 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3164 removePackageLI(pkg, true /*chatty*/);
3165 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3166 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3167 UserHandle.USER_SYSTEM, "android");
3168 stubSystemApps.remove(i);
3170 } catch (PackageManagerException e) {
3171 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3174 // any failed attempt to install the package will be cleaned up later
3177 // disable any stub still left; these failed to install the full application
3178 for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3179 final String pkgName = stubSystemApps.get(i);
3180 final PackageSetting ps = mSettings.mPackages.get(pkgName);
3181 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3182 UserHandle.USER_SYSTEM, "android");
3183 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3187 private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3188 if (DEBUG_COMPRESSION) {
3189 Slog.i(TAG, "Decompress file"
3190 + "; src: " + srcFile.getAbsolutePath()
3191 + ", dst: " + dstFile.getAbsolutePath());
3194 InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3195 OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3197 Streams.copy(fileIn, fileOut);
3198 Os.chmod(dstFile.getAbsolutePath(), 0644);
3199 return PackageManager.INSTALL_SUCCEEDED;
3200 } catch (IOException e) {
3201 logCriticalInfo(Log.ERROR, "Failed to decompress file"
3202 + "; src: " + srcFile.getAbsolutePath()
3203 + ", dst: " + dstFile.getAbsolutePath());
3205 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3208 private File[] getCompressedFiles(String codePath) {
3209 final File stubCodePath = new File(codePath);
3210 final String stubName = stubCodePath.getName();
3212 // The layout of a compressed package on a given partition is as follows :
3214 // Compressed artifacts:
3216 // /partition/ModuleName/foo.gz
3217 // /partation/ModuleName/bar.gz
3221 // /partition/ModuleName-Stub/ModuleName-Stub.apk
3223 // In other words, stub is on the same partition as the compressed artifacts
3224 // and in a directory that's suffixed with "-Stub".
3225 int idx = stubName.lastIndexOf(STUB_SUFFIX);
3226 if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3230 final File stubParentDir = stubCodePath.getParentFile();
3231 if (stubParentDir == null) {
3232 Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3236 final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3237 final File[] files = compressedPath.listFiles(new FilenameFilter() {
3239 public boolean accept(File dir, String name) {
3240 return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3244 if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3245 Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3251 private boolean compressedFileExists(String codePath) {
3252 final File[] compressedFiles = getCompressedFiles(codePath);
3253 return compressedFiles != null && compressedFiles.length > 0;
3257 * Decompresses the given package on the system image onto
3258 * the /data partition.
3259 * @return The directory the package was decompressed into. Otherwise, {@code null}.
3261 private File decompressPackage(PackageParser.Package pkg) {
3262 final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3263 if (compressedFiles == null || compressedFiles.length == 0) {
3264 if (DEBUG_COMPRESSION) {
3265 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3269 final File dstCodePath =
3270 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3271 int ret = PackageManager.INSTALL_SUCCEEDED;
3273 Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3274 Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3275 for (File srcFile : compressedFiles) {
3276 final String srcFileName = srcFile.getName();
3277 final String dstFileName = srcFileName.substring(
3278 0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3279 final File dstFile = new File(dstCodePath, dstFileName);
3280 ret = decompressFile(srcFile, dstFile);
3281 if (ret != PackageManager.INSTALL_SUCCEEDED) {
3282 logCriticalInfo(Log.ERROR, "Failed to decompress"
3283 + "; pkg: " + pkg.packageName
3284 + ", file: " + dstFileName);
3288 } catch (ErrnoException e) {
3289 logCriticalInfo(Log.ERROR, "Failed to decompress"
3290 + "; pkg: " + pkg.packageName
3291 + ", err: " + e.errno);
3293 if (ret == PackageManager.INSTALL_SUCCEEDED) {
3294 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3295 NativeLibraryHelper.Handle handle = null;
3297 handle = NativeLibraryHelper.Handle.create(dstCodePath);
3298 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3299 null /*abiOverride*/);
3300 } catch (IOException e) {
3301 logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3302 + "; pkg: " + pkg.packageName);
3303 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3305 IoUtils.closeQuietly(handle);
3308 if (ret != PackageManager.INSTALL_SUCCEEDED) {
3309 if (dstCodePath == null || !dstCodePath.exists()) {
3312 removeCodePathLI(dstCodePath);
3319 private void updateInstantAppInstallerLocked(String modifiedPackage) {
3320 // we're only interested in updating the installer appliction when 1) it's not
3321 // already set or 2) the modified package is the installer
3322 if (mInstantAppInstallerActivity != null
3323 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3324 .equals(modifiedPackage)) {
3327 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3330 private static File preparePackageParserCache(boolean isUpgrade) {
3331 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3335 // Disable package parsing on eng builds to allow for faster incremental development.
3340 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3341 Slog.i(TAG, "Disabling package parser cache due to system property.");
3345 // The base directory for the package parser cache lives under /data/system/.
3346 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3348 if (cacheBaseDir == null) {
3352 // If this is a system upgrade scenario, delete the contents of the package cache dir.
3353 // This also serves to "GC" unused entries when the package cache version changes (which
3354 // can only happen during upgrades).
3356 FileUtils.deleteContents(cacheBaseDir);
3360 // Return the versioned package cache directory. This is something like
3361 // "/data/system/package_cache/1"
3362 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3364 // The following is a workaround to aid development on non-numbered userdebug
3365 // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3366 // the system partition is newer.
3368 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3369 // that starts with "eng." to signify that this is an engineering build and not
3370 // destined for release.
3371 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3372 Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3374 // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3375 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3376 // in general and should not be used for production changes. In this specific case,
3377 // we know that they will work.
3378 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3379 if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3380 FileUtils.deleteContents(cacheBaseDir);
3381 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3389 public boolean isFirstBoot() {
3390 // allow instant applications
3395 public boolean isOnlyCoreApps() {
3396 // allow instant applications
3401 public boolean isUpgrade() {
3402 // allow instant applications
3406 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3407 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3409 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3410 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3411 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3412 if (matches.size() == 1) {
3413 return matches.get(0).getComponentInfo().packageName;
3414 } else if (matches.size() == 0) {
3415 Log.e(TAG, "There should probably be a verifier, but, none were found");
3418 throw new RuntimeException("There must be exactly one verifier; found " + matches);
3421 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3422 synchronized (mPackages) {
3423 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3424 if (libraryEntry == null) {
3425 throw new IllegalStateException("Missing required shared library:" + name);
3427 return libraryEntry.apk;
3431 private @NonNull String getRequiredInstallerLPr() {
3432 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3433 intent.addCategory(Intent.CATEGORY_DEFAULT);
3434 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3436 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3437 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3438 UserHandle.USER_SYSTEM);
3439 if (matches.size() == 1) {
3440 ResolveInfo resolveInfo = matches.get(0);
3441 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3442 throw new RuntimeException("The installer must be a privileged app");
3444 return matches.get(0).getComponentInfo().packageName;
3446 throw new RuntimeException("There must be exactly one installer; found " + matches);
3450 private @NonNull String getRequiredUninstallerLPr() {
3451 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3452 intent.addCategory(Intent.CATEGORY_DEFAULT);
3453 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3455 final ResolveInfo resolveInfo = resolveIntent(intent, null,
3456 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3457 UserHandle.USER_SYSTEM);
3458 if (resolveInfo == null ||
3459 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3460 throw new RuntimeException("There must be exactly one uninstaller; found "
3463 return resolveInfo.getComponentInfo().packageName;
3466 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3467 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3469 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3470 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3471 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3472 ResolveInfo best = null;
3473 final int N = matches.size();
3474 for (int i = 0; i < N; i++) {
3475 final ResolveInfo cur = matches.get(i);
3476 final String packageName = cur.getComponentInfo().packageName;
3477 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3478 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3482 if (best == null || cur.priority > best.priority) {
3488 return best.getComponentInfo().getComponentName();
3490 Slog.w(TAG, "Intent filter verifier not found");
3495 public @Nullable ComponentName getInstantAppResolverComponent() {
3496 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3499 synchronized (mPackages) {
3500 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3501 if (instantAppResolver == null) {
3504 return instantAppResolver.first;
3508 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3509 final String[] packageArray =
3510 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3511 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3512 if (DEBUG_EPHEMERAL) {
3513 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3518 final int callingUid = Binder.getCallingUid();
3519 final int resolveFlags =
3520 MATCH_DIRECT_BOOT_AWARE
3521 | MATCH_DIRECT_BOOT_UNAWARE
3522 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3523 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3524 final Intent resolverIntent = new Intent(actionName);
3525 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3526 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3527 // temporarily look for the old action
3528 if (resolvers.size() == 0) {
3529 if (DEBUG_EPHEMERAL) {
3530 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3532 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3533 resolverIntent.setAction(actionName);
3534 resolvers = queryIntentServicesInternal(resolverIntent, null,
3535 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3537 final int N = resolvers.size();
3539 if (DEBUG_EPHEMERAL) {
3540 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3545 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3546 for (int i = 0; i < N; i++) {
3547 final ResolveInfo info = resolvers.get(i);
3549 if (info.serviceInfo == null) {
3553 final String packageName = info.serviceInfo.packageName;
3554 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3555 if (DEBUG_EPHEMERAL) {
3556 Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3557 + " pkg: " + packageName + ", info:" + info);
3562 if (DEBUG_EPHEMERAL) {
3563 Slog.v(TAG, "Ephemeral resolver found;"
3564 + " pkg: " + packageName + ", info:" + info);
3566 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3568 if (DEBUG_EPHEMERAL) {
3569 Slog.v(TAG, "Ephemeral resolver NOT found");
3574 private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3575 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3576 intent.addCategory(Intent.CATEGORY_DEFAULT);
3577 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3579 final int resolveFlags =
3580 MATCH_DIRECT_BOOT_AWARE
3581 | MATCH_DIRECT_BOOT_UNAWARE
3582 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3583 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3584 resolveFlags, UserHandle.USER_SYSTEM);
3585 // temporarily look for the old action
3586 if (matches.isEmpty()) {
3587 if (DEBUG_EPHEMERAL) {
3588 Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3590 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3591 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3592 resolveFlags, UserHandle.USER_SYSTEM);
3594 Iterator<ResolveInfo> iter = matches.iterator();
3595 while (iter.hasNext()) {
3596 final ResolveInfo rInfo = iter.next();
3597 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3599 final PermissionsState permissionsState = ps.getPermissionsState();
3600 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3606 if (matches.size() == 0) {
3608 } else if (matches.size() == 1) {
3609 return (ActivityInfo) matches.get(0).getComponentInfo();
3611 throw new RuntimeException(
3612 "There must be at most one ephemeral installer; found " + matches);
3616 private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3617 @NonNull ComponentName resolver) {
3618 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3619 .addCategory(Intent.CATEGORY_DEFAULT)
3620 .setPackage(resolver.getPackageName());
3621 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3622 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3623 UserHandle.USER_SYSTEM);
3624 // temporarily look for the old action
3625 if (matches.isEmpty()) {
3626 if (DEBUG_EPHEMERAL) {
3627 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3629 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3630 matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3631 UserHandle.USER_SYSTEM);
3633 if (matches.isEmpty()) {
3636 return matches.get(0).getComponentInfo().getComponentName();
3639 private void primeDomainVerificationsLPw(int userId) {
3640 if (DEBUG_DOMAIN_VERIFICATION) {
3641 Slog.d(TAG, "Priming domain verifications in user " + userId);
3644 SystemConfig systemConfig = SystemConfig.getInstance();
3645 ArraySet<String> packages = systemConfig.getLinkedApps();
3647 for (String packageName : packages) {
3648 PackageParser.Package pkg = mPackages.get(packageName);
3650 if (!pkg.isSystemApp()) {
3651 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3655 ArraySet<String> domains = null;
3656 for (PackageParser.Activity a : pkg.activities) {
3657 for (ActivityIntentInfo filter : a.intents) {
3658 if (hasValidDomains(filter)) {
3659 if (domains == null) {
3660 domains = new ArraySet<String>();
3662 domains.addAll(filter.getHostsList());
3667 if (domains != null && domains.size() > 0) {
3668 if (DEBUG_DOMAIN_VERIFICATION) {
3669 Slog.v(TAG, " + " + packageName);
3671 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3672 // state w.r.t. the formal app-linkage "no verification attempted" state;
3673 // and then 'always' in the per-user state actually used for intent resolution.
3674 final IntentFilterVerificationInfo ivi;
3675 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3676 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3677 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3678 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3680 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3681 + "' does not handle web links");
3684 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3688 scheduleWritePackageRestrictionsLocked(userId);
3689 scheduleWriteSettingsLocked();
3692 private void applyFactoryDefaultBrowserLPw(int userId) {
3693 // The default browser app's package name is stored in a string resource,
3694 // with a product-specific overlay used for vendor customization.
3695 String browserPkg = mContext.getResources().getString(
3696 com.android.internal.R.string.default_browser);
3697 if (!TextUtils.isEmpty(browserPkg)) {
3698 // non-empty string => required to be a known package
3699 PackageSetting ps = mSettings.mPackages.get(browserPkg);
3701 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3704 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3708 // Nothing valid explicitly set? Make the factory-installed browser the explicit
3709 // default. If there's more than one, just leave everything alone.
3710 if (browserPkg == null) {
3711 calculateDefaultBrowserLPw(userId);
3715 private void calculateDefaultBrowserLPw(int userId) {
3716 List<String> allBrowsers = resolveAllBrowserApps(userId);
3717 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3718 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3721 private List<String> resolveAllBrowserApps(int userId) {
3722 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3723 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3724 PackageManager.MATCH_ALL, userId);
3726 final int count = list.size();
3727 List<String> result = new ArrayList<String>(count);
3728 for (int i=0; i<count; i++) {
3729 ResolveInfo info = list.get(i);
3730 if (info.activityInfo == null
3731 || !info.handleAllWebDataURI
3732 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3733 || result.contains(info.activityInfo.packageName)) {
3736 result.add(info.activityInfo.packageName);
3742 private boolean packageIsBrowser(String packageName, int userId) {
3743 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3744 PackageManager.MATCH_ALL, userId);
3745 final int N = list.size();
3746 for (int i = 0; i < N; i++) {
3747 ResolveInfo info = list.get(i);
3748 if (packageName.equals(info.activityInfo.packageName)) {
3755 private void checkDefaultBrowser() {
3756 final int myUserId = UserHandle.myUserId();
3757 final String packageName = getDefaultBrowserPackageName(myUserId);
3758 if (packageName != null) {
3759 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3761 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3762 synchronized (mPackages) {
3763 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
3770 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3771 throws RemoteException {
3773 return super.onTransact(code, data, reply, flags);
3774 } catch (RuntimeException e) {
3775 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3776 Slog.wtf(TAG, "Package Manager Crash", e);
3782 static int[] appendInts(int[] cur, int[] add) {
3783 if (add == null) return cur;
3784 if (cur == null) return add;
3785 final int N = add.length;
3786 for (int i=0; i<N; i++) {
3787 cur = appendInt(cur, add[i]);
3793 * Returns whether or not a full application can see an instant application.
3795 * Currently, there are three cases in which this can occur:
3797 * <li>The calling application is a "special" process. Special processes
3798 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3799 * <li>The calling application has the permission
3800 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3801 * <li>The calling application is the default launcher on the
3802 * system partition.</li>
3805 private boolean canViewInstantApps(int callingUid, int userId) {
3806 if (callingUid < Process.FIRST_APPLICATION_UID) {
3809 if (mContext.checkCallingOrSelfPermission(
3810 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3813 if (mContext.checkCallingOrSelfPermission(
3814 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3815 final ComponentName homeComponent = getDefaultHomeActivity(userId);
3816 if (homeComponent != null
3817 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3824 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3825 if (!sUserManager.exists(userId)) return null;
3829 PackageParser.Package p = ps.pkg;
3833 final int callingUid = Binder.getCallingUid();
3834 // Filter out ephemeral app metadata:
3835 // * The system/shell/root can see metadata for any app
3836 // * An installed app can see metadata for 1) other installed apps
3837 // and 2) ephemeral apps that have explicitly interacted with it
3838 // * Ephemeral apps can only see their own data and exposed installed apps
3839 // * Holding a signature permission allows seeing instant apps
3840 if (filterAppAccessLPr(ps, callingUid, userId)) {
3844 final PermissionsState permissionsState = ps.getPermissionsState();
3846 // Compute GIDs only if requested
3847 final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3848 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3849 // Compute granted permissions only if package has requested permissions
3850 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3851 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3852 final PackageUserState state = ps.readUserState(userId);
3854 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3856 flags |= MATCH_ANY_USER;
3859 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3860 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3862 if (packageInfo == null) {
3866 packageInfo.packageName = packageInfo.applicationInfo.packageName =
3867 resolveExternalPackageNameLPr(p);
3873 public void checkPackageStartable(String packageName, int userId) {
3874 final int callingUid = Binder.getCallingUid();
3875 if (getInstantAppPackageName(callingUid) != null) {
3876 throw new SecurityException("Instant applications don't have access to this method");
3878 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3879 synchronized (mPackages) {
3880 final PackageSetting ps = mSettings.mPackages.get(packageName);
3881 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3882 throw new SecurityException("Package " + packageName + " was not found!");
3885 if (!ps.getInstalled(userId)) {
3886 throw new SecurityException(
3887 "Package " + packageName + " was not installed for user " + userId + "!");
3890 if (mSafeMode && !ps.isSystem()) {
3891 throw new SecurityException("Package " + packageName + " not a system app!");
3894 if (mFrozenPackages.contains(packageName)) {
3895 throw new SecurityException("Package " + packageName + " is currently frozen!");
3898 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3899 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3905 public boolean isPackageAvailable(String packageName, int userId) {
3906 if (!sUserManager.exists(userId)) return false;
3907 final int callingUid = Binder.getCallingUid();
3908 enforceCrossUserPermission(callingUid, userId,
3909 false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3910 synchronized (mPackages) {
3911 PackageParser.Package p = mPackages.get(packageName);
3913 final PackageSetting ps = (PackageSetting) p.mExtras;
3914 if (filterAppAccessLPr(ps, callingUid, userId)) {
3918 final PackageUserState state = ps.readUserState(userId);
3919 if (state != null) {
3920 return PackageParser.isAvailable(state);
3929 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3930 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3931 flags, Binder.getCallingUid(), userId);
3935 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3936 int flags, int userId) {
3937 return getPackageInfoInternal(versionedPackage.getPackageName(),
3938 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3942 * Important: The provided filterCallingUid is used exclusively to filter out packages
3943 * that can be seen based on user state. It's typically the original caller uid prior
3944 * to clearing. Because it can only be provided by trusted code, it's value can be
3945 * trusted and will be used as-is; unlike userId which will be validated by this method.
3947 private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3948 int flags, int filterCallingUid, int userId) {
3949 if (!sUserManager.exists(userId)) return null;
3950 flags = updateFlagsForPackage(flags, userId, packageName);
3951 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3952 false /* requireFullPermission */, false /* checkShell */, "get package info");
3955 synchronized (mPackages) {
3956 // Normalize package name to handle renamed packages and static libs
3957 packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3959 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3960 if (matchFactoryOnly) {
3961 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3963 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3966 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3969 return generatePackageInfo(ps, flags, userId);
3973 PackageParser.Package p = mPackages.get(packageName);
3974 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3977 if (DEBUG_PACKAGE_INFO)
3978 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3980 final PackageSetting ps = (PackageSetting) p.mExtras;
3981 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3984 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3987 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3989 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3990 final PackageSetting ps = mSettings.mPackages.get(packageName);
3991 if (ps == null) return null;
3992 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3995 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3998 return generatePackageInfo(ps, flags, userId);
4004 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4005 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4008 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4011 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4017 private boolean isComponentVisibleToInstantApp(
4018 @Nullable ComponentName component, @ComponentType int type) {
4019 if (type == TYPE_ACTIVITY) {
4020 final PackageParser.Activity activity = mActivities.mActivities.get(component);
4021 return activity != null
4022 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4024 } else if (type == TYPE_RECEIVER) {
4025 final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4026 return activity != null
4027 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4029 } else if (type == TYPE_SERVICE) {
4030 final PackageParser.Service service = mServices.mServices.get(component);
4031 return service != null
4032 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4034 } else if (type == TYPE_PROVIDER) {
4035 final PackageParser.Provider provider = mProviders.mProviders.get(component);
4036 return provider != null
4037 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4039 } else if (type == TYPE_UNKNOWN) {
4040 return isComponentVisibleToInstantApp(component);
4046 * Returns whether or not access to the application should be filtered.
4048 * Access may be limited based upon whether the calling or target applications
4049 * are instant applications.
4051 * @see #canAccessInstantApps(int)
4053 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4054 @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4055 // if we're in an isolated process, get the real calling UID
4056 if (Process.isIsolated(callingUid)) {
4057 callingUid = mIsolatedOwners.get(callingUid);
4059 final String instantAppPkgName = getInstantAppPackageName(callingUid);
4060 final boolean callerIsInstantApp = instantAppPkgName != null;
4062 if (callerIsInstantApp) {
4063 // pretend the application exists, but, needs to be filtered
4068 // if the target and caller are the same application, don't filter
4069 if (isCallerSameApp(ps.name, callingUid)) {
4072 if (callerIsInstantApp) {
4073 // request for a specific component; if it hasn't been explicitly exposed, filter
4074 if (component != null) {
4075 return !isComponentVisibleToInstantApp(component, componentType);
4077 // request for application; if no components have been explicitly exposed, filter
4078 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4080 if (ps.getInstantApp(userId)) {
4081 // caller can see all components of all instant applications, don't filter
4082 if (canViewInstantApps(callingUid, userId)) {
4085 // request for a specific instant application component, filter
4086 if (component != null) {
4089 // request for an instant application; if the caller hasn't been granted access, filter
4090 return !mInstantAppRegistry.isInstantAccessGranted(
4091 userId, UserHandle.getAppId(callingUid), ps.appId);
4097 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4099 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4100 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4103 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4105 // Callers can access only the libs they depend on, otherwise they need to explicitly
4106 // ask for the shared libraries given the caller is allowed to access all static libs.
4107 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4108 // System/shell/root get to see all static libs
4109 final int appId = UserHandle.getAppId(uid);
4110 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4111 || appId == Process.ROOT_UID) {
4116 // No package means no static lib as it is always on internal storage
4117 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4121 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4122 ps.pkg.staticSharedLibVersion);
4123 if (libEntry == null) {
4127 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4128 final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4129 if (uidPackageNames == null) {
4133 for (String uidPackageName : uidPackageNames) {
4134 if (ps.name.equals(uidPackageName)) {
4137 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4138 if (uidPs != null) {
4139 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4140 libEntry.info.getName());
4144 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4153 public String[] currentToCanonicalPackageNames(String[] names) {
4154 final int callingUid = Binder.getCallingUid();
4155 if (getInstantAppPackageName(callingUid) != null) {
4158 final String[] out = new String[names.length];
4160 synchronized (mPackages) {
4161 final int callingUserId = UserHandle.getUserId(callingUid);
4162 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4163 for (int i=names.length-1; i>=0; i--) {
4164 final PackageSetting ps = mSettings.mPackages.get(names[i]);
4165 boolean translateName = false;
4166 if (ps != null && ps.realName != null) {
4167 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4168 translateName = !targetIsInstantApp
4169 || canViewInstantApps
4170 || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4171 UserHandle.getAppId(callingUid), ps.appId);
4173 out[i] = translateName ? ps.realName : names[i];
4180 public String[] canonicalToCurrentPackageNames(String[] names) {
4181 final int callingUid = Binder.getCallingUid();
4182 if (getInstantAppPackageName(callingUid) != null) {
4185 final String[] out = new String[names.length];
4187 synchronized (mPackages) {
4188 final int callingUserId = UserHandle.getUserId(callingUid);
4189 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4190 for (int i=names.length-1; i>=0; i--) {
4191 final String cur = mSettings.getRenamedPackageLPr(names[i]);
4192 boolean translateName = false;
4194 final PackageSetting ps = mSettings.mPackages.get(names[i]);
4195 final boolean targetIsInstantApp =
4196 ps != null && ps.getInstantApp(callingUserId);
4197 translateName = !targetIsInstantApp
4198 || canViewInstantApps
4199 || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4200 UserHandle.getAppId(callingUid), ps.appId);
4202 out[i] = translateName ? cur : names[i];
4209 public int getPackageUid(String packageName, int flags, int userId) {
4210 if (!sUserManager.exists(userId)) return -1;
4211 final int callingUid = Binder.getCallingUid();
4212 flags = updateFlagsForPackage(flags, userId, packageName);
4213 enforceCrossUserPermission(callingUid, userId,
4214 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4217 synchronized (mPackages) {
4218 final PackageParser.Package p = mPackages.get(packageName);
4219 if (p != null && p.isMatch(flags)) {
4220 PackageSetting ps = (PackageSetting) p.mExtras;
4221 if (filterAppAccessLPr(ps, callingUid, userId)) {
4224 return UserHandle.getUid(userId, p.applicationInfo.uid);
4226 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4227 final PackageSetting ps = mSettings.mPackages.get(packageName);
4228 if (ps != null && ps.isMatch(flags)
4229 && !filterAppAccessLPr(ps, callingUid, userId)) {
4230 return UserHandle.getUid(userId, ps.appId);
4239 public int[] getPackageGids(String packageName, int flags, int userId) {
4240 if (!sUserManager.exists(userId)) return null;
4241 final int callingUid = Binder.getCallingUid();
4242 flags = updateFlagsForPackage(flags, userId, packageName);
4243 enforceCrossUserPermission(callingUid, userId,
4244 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4247 synchronized (mPackages) {
4248 final PackageParser.Package p = mPackages.get(packageName);
4249 if (p != null && p.isMatch(flags)) {
4250 PackageSetting ps = (PackageSetting) p.mExtras;
4251 if (filterAppAccessLPr(ps, callingUid, userId)) {
4254 // TODO: Shouldn't this be checking for package installed state for userId and
4256 return ps.getPermissionsState().computeGids(userId);
4258 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4259 final PackageSetting ps = mSettings.mPackages.get(packageName);
4260 if (ps != null && ps.isMatch(flags)
4261 && !filterAppAccessLPr(ps, callingUid, userId)) {
4262 return ps.getPermissionsState().computeGids(userId);
4270 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4271 if (bp.perm != null) {
4272 return PackageParser.generatePermissionInfo(bp.perm, flags);
4274 PermissionInfo pi = new PermissionInfo();
4276 pi.packageName = bp.sourcePackage;
4277 pi.nonLocalizedLabel = bp.name;
4278 pi.protectionLevel = bp.protectionLevel;
4283 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4284 final int callingUid = Binder.getCallingUid();
4285 if (getInstantAppPackageName(callingUid) != null) {
4289 synchronized (mPackages) {
4290 final BasePermission p = mSettings.mPermissions.get(name);
4294 // If the caller is an app that targets pre 26 SDK drop protection flags.
4295 PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4296 if (permissionInfo != null) {
4297 final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4298 permissionInfo.protectionLevel, packageName, callingUid);
4299 if (permissionInfo.protectionLevel != protectionLevel) {
4300 // If we return different protection level, don't use the cached info
4301 if (p.perm != null && p.perm.info == permissionInfo) {
4302 permissionInfo = new PermissionInfo(permissionInfo);
4304 permissionInfo.protectionLevel = protectionLevel;
4307 return permissionInfo;
4311 private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4312 String packageName, int uid) {
4313 // Signature permission flags area always reported
4314 final int protectionLevelMasked = protectionLevel
4315 & (PermissionInfo.PROTECTION_NORMAL
4316 | PermissionInfo.PROTECTION_DANGEROUS
4317 | PermissionInfo.PROTECTION_SIGNATURE);
4318 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4319 return protectionLevel;
4322 // System sees all flags.
4323 final int appId = UserHandle.getAppId(uid);
4324 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4325 || appId == Process.SHELL_UID) {
4326 return protectionLevel;
4329 // Normalize package name to handle renamed packages and static libs
4330 packageName = resolveInternalPackageNameLPr(packageName,
4331 PackageManager.VERSION_CODE_HIGHEST);
4333 // Apps that target O see flags for all protection levels.
4334 final PackageSetting ps = mSettings.mPackages.get(packageName);
4336 return protectionLevel;
4338 if (ps.appId != appId) {
4339 return protectionLevel;
4342 final PackageParser.Package pkg = mPackages.get(packageName);
4344 return protectionLevel;
4346 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4347 return protectionLevelMasked;
4350 return protectionLevel;
4354 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4356 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4360 synchronized (mPackages) {
4361 if (group != null && !mPermissionGroups.containsKey(group)) {
4362 // This is thrown as NameNotFoundException
4366 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4367 for (BasePermission p : mSettings.mPermissions.values()) {
4368 if (group == null) {
4369 if (p.perm == null || p.perm.info.group == null) {
4370 out.add(generatePermissionInfo(p, flags));
4373 if (p.perm != null && group.equals(p.perm.info.group)) {
4374 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4378 return new ParceledListSlice<>(out);
4383 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4384 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4388 synchronized (mPackages) {
4389 return PackageParser.generatePermissionGroupInfo(
4390 mPermissionGroups.get(name), flags);
4395 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4396 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4397 return ParceledListSlice.emptyList();
4400 synchronized (mPackages) {
4401 final int N = mPermissionGroups.size();
4402 ArrayList<PermissionGroupInfo> out
4403 = new ArrayList<PermissionGroupInfo>(N);
4404 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4405 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4407 return new ParceledListSlice<>(out);
4411 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4412 int filterCallingUid, int userId) {
4413 if (!sUserManager.exists(userId)) return null;
4414 PackageSetting ps = mSettings.mPackages.get(packageName);
4416 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4419 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4422 if (ps.pkg == null) {
4423 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4424 if (pInfo != null) {
4425 return pInfo.applicationInfo;
4429 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4430 ps.readUserState(userId), userId);
4432 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4440 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4441 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4445 * Important: The provided filterCallingUid is used exclusively to filter out applications
4446 * that can be seen based on user state. It's typically the original caller uid prior
4447 * to clearing. Because it can only be provided by trusted code, it's value can be
4448 * trusted and will be used as-is; unlike userId which will be validated by this method.
4450 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4451 int filterCallingUid, int userId) {
4452 if (!sUserManager.exists(userId)) return null;
4453 flags = updateFlagsForApplication(flags, userId, packageName);
4454 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4455 false /* requireFullPermission */, false /* checkShell */, "get application info");
4458 synchronized (mPackages) {
4459 // Normalize package name to handle renamed packages and static libs
4460 packageName = resolveInternalPackageNameLPr(packageName,
4461 PackageManager.VERSION_CODE_HIGHEST);
4463 PackageParser.Package p = mPackages.get(packageName);
4464 if (DEBUG_PACKAGE_INFO) Log.v(
4465 TAG, "getApplicationInfo " + packageName
4468 PackageSetting ps = mSettings.mPackages.get(packageName);
4469 if (ps == null) return null;
4470 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4473 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4476 // Note: isEnabledLP() does not apply here - always return info
4477 ApplicationInfo ai = PackageParser.generateApplicationInfo(
4478 p, flags, ps.readUserState(userId), userId);
4480 ai.packageName = resolveExternalPackageNameLPr(p);
4484 if ("android".equals(packageName)||"system".equals(packageName)) {
4485 return mAndroidApplication;
4487 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4488 // Already generates the external package name
4489 return generateApplicationInfoFromSettingsLPw(packageName,
4490 flags, filterCallingUid, userId);
4496 private String normalizePackageNameLPr(String packageName) {
4497 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4498 return normalizedPackageName != null ? normalizedPackageName : packageName;
4502 public void deletePreloadsFileCache() {
4503 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4504 throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4506 File dir = Environment.getDataPreloadsFileCacheDirectory();
4507 Slog.i(TAG, "Deleting preloaded file cache " + dir);
4508 FileUtils.deleteContents(dir);
4512 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4513 final int storageFlags, final IPackageDataObserver observer) {
4514 mContext.enforceCallingOrSelfPermission(
4515 android.Manifest.permission.CLEAR_APP_CACHE, null);
4516 mHandler.post(() -> {
4517 boolean success = false;
4519 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4521 } catch (IOException e) {
4524 if (observer != null) {
4526 observer.onRemoveCompleted(null, success);
4527 } catch (RemoteException e) {
4535 public void freeStorage(final String volumeUuid, final long freeStorageSize,
4536 final int storageFlags, final IntentSender pi) {
4537 mContext.enforceCallingOrSelfPermission(
4538 android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4539 mHandler.post(() -> {
4540 boolean success = false;
4542 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4544 } catch (IOException e) {
4549 pi.sendIntent(null, success ? 1 : 0, null, null, null);
4550 } catch (SendIntentException e) {
4558 * Blocking call to clear various types of cached data across the system
4559 * until the requested bytes are available.
4561 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4562 final StorageManager storage = mContext.getSystemService(StorageManager.class);
4563 final File file = storage.findPathForUuid(volumeUuid);
4564 if (file.getUsableSpace() >= bytes) return;
4566 if (ENABLE_FREE_CACHE_V2) {
4567 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4569 final boolean aggressive = (storageFlags
4570 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4571 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4573 // 1. Pre-flight to determine if we have any chance to succeed
4574 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4575 if (internalVolume && (aggressive || SystemProperties
4576 .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4577 deletePreloadsFileCache();
4578 if (file.getUsableSpace() >= bytes) return;
4581 // 3. Consider parsed APK data (aggressive only)
4582 if (internalVolume && aggressive) {
4583 FileUtils.deleteContents(mCacheDir);
4584 if (file.getUsableSpace() >= bytes) return;
4587 // 4. Consider cached app data (above quotas)
4589 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4590 Installer.FLAG_FREE_CACHE_V2);
4591 } catch (InstallerException ignored) {
4593 if (file.getUsableSpace() >= bytes) return;
4595 // 5. Consider shared libraries with refcount=0 and age>min cache period
4596 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4597 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4598 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4599 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4603 // 6. Consider dexopt output (aggressive only)
4606 // 7. Consider installed instant apps unused longer than min cache period
4607 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4608 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4609 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4610 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4614 // 8. Consider cached app data (below quotas)
4616 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4617 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4618 } catch (InstallerException ignored) {
4620 if (file.getUsableSpace() >= bytes) return;
4622 // 9. Consider DropBox entries
4625 // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4626 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4627 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4628 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4629 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4634 mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4635 } catch (InstallerException ignored) {
4637 if (file.getUsableSpace() >= bytes) return;
4640 throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4643 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4644 throws IOException {
4645 final StorageManager storage = mContext.getSystemService(StorageManager.class);
4646 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4648 List<VersionedPackage> packagesToDelete = null;
4649 final long now = System.currentTimeMillis();
4651 synchronized (mPackages) {
4652 final int[] allUsers = sUserManager.getUserIds();
4653 final int libCount = mSharedLibraries.size();
4654 for (int i = 0; i < libCount; i++) {
4655 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4656 if (versionedLib == null) {
4659 final int versionCount = versionedLib.size();
4660 for (int j = 0; j < versionCount; j++) {
4661 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4662 // Skip packages that are not static shared libs.
4663 if (!libInfo.isStatic()) {
4666 // Important: We skip static shared libs used for some user since
4667 // in such a case we need to keep the APK on the device. The check for
4668 // a lib being used for any user is performed by the uninstall call.
4669 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4670 // Resolve the package name - we use synthetic package names internally
4671 final String internalPackageName = resolveInternalPackageNameLPr(
4672 declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4673 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4674 // Skip unused static shared libs cached less than the min period
4675 // to prevent pruning a lib needed by a subsequently installed package.
4676 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4679 if (packagesToDelete == null) {
4680 packagesToDelete = new ArrayList<>();
4682 packagesToDelete.add(new VersionedPackage(internalPackageName,
4683 declaringPackage.getVersionCode()));
4688 if (packagesToDelete != null) {
4689 final int packageCount = packagesToDelete.size();
4690 for (int i = 0; i < packageCount; i++) {
4691 final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4692 // Delete the package synchronously (will fail of the lib used for any user).
4693 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4694 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4695 == PackageManager.DELETE_SUCCEEDED) {
4696 if (volume.getUsableSpace() >= neededSpace) {
4707 * Update given flags based on encryption status of current user.
4709 private int updateFlags(int flags, int userId) {
4710 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4711 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4712 // Caller expressed an explicit opinion about what encryption
4713 // aware/unaware components they want to see, so fall through and
4714 // give them what they want
4716 // Caller expressed no opinion, so match based on user state
4717 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4718 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4720 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4726 private UserManagerInternal getUserManagerInternal() {
4727 if (mUserManagerInternal == null) {
4728 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4730 return mUserManagerInternal;
4733 private DeviceIdleController.LocalService getDeviceIdleController() {
4734 if (mDeviceIdleController == null) {
4735 mDeviceIdleController =
4736 LocalServices.getService(DeviceIdleController.LocalService.class);
4738 return mDeviceIdleController;
4742 * Update given flags when being used to request {@link PackageInfo}.
4744 private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4745 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4746 boolean triaged = true;
4747 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4748 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4749 // Caller is asking for component details, so they'd better be
4750 // asking for specific encryption matching behavior, or be triaged
4751 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4752 | PackageManager.MATCH_DIRECT_BOOT_AWARE
4753 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4757 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4758 | PackageManager.MATCH_SYSTEM_ONLY
4759 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4762 if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4763 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4764 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4765 + Debug.getCallers(5));
4766 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4767 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4768 // If the caller wants all packages and has a restricted profile associated with it,
4769 // then match all users. This is to make sure that launchers that need to access work
4770 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4771 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4772 flags |= PackageManager.MATCH_ANY_USER;
4774 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4775 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4776 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4778 return updateFlags(flags, userId);
4782 * Update given flags when being used to request {@link ApplicationInfo}.
4784 private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4785 return updateFlagsForPackage(flags, userId, cookie);
4789 * Update given flags when being used to request {@link ComponentInfo}.
4791 private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4792 if (cookie instanceof Intent) {
4793 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4794 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4798 boolean triaged = true;
4799 // Caller is asking for component details, so they'd better be
4800 // asking for specific encryption matching behavior, or be triaged
4801 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4802 | PackageManager.MATCH_DIRECT_BOOT_AWARE
4803 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4806 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4807 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4808 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4811 return updateFlags(flags, userId);
4815 * Update given intent when being used to request {@link ResolveInfo}.
4817 private Intent updateIntentForResolve(Intent intent) {
4818 if (intent.getSelector() != null) {
4819 intent = intent.getSelector();
4821 if (DEBUG_PREFERRED) {
4822 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4828 * Update given flags when being used to request {@link ResolveInfo}.
4829 * <p>Instant apps are resolved specially, depending upon context. Minimally,
4830 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4831 * flag set. However, this flag is only honoured in three circumstances:
4833 * <li>when called from a system process</li>
4834 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4835 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4836 * action and a {@code android.intent.category.BROWSABLE} category</li>
4839 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4840 return updateFlagsForResolve(flags, userId, intent, callingUid,
4841 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4843 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4844 boolean wantInstantApps) {
4845 return updateFlagsForResolve(flags, userId, intent, callingUid,
4846 wantInstantApps, false /*onlyExposedExplicitly*/);
4848 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4849 boolean wantInstantApps, boolean onlyExposedExplicitly) {
4850 // Safe mode means we shouldn't match any third-party components
4852 flags |= PackageManager.MATCH_SYSTEM_ONLY;
4854 if (getInstantAppPackageName(callingUid) != null) {
4855 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4856 if (onlyExposedExplicitly) {
4857 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4859 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4860 flags |= PackageManager.MATCH_INSTANT;
4862 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4863 final boolean allowMatchInstant =
4865 && Intent.ACTION_VIEW.equals(intent.getAction())
4866 && hasWebURI(intent))
4867 || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4868 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4869 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4870 if (!allowMatchInstant) {
4871 flags &= ~PackageManager.MATCH_INSTANT;
4874 return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4878 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4879 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4883 * Important: The provided filterCallingUid is used exclusively to filter out activities
4884 * that can be seen based on user state. It's typically the original caller uid prior
4885 * to clearing. Because it can only be provided by trusted code, it's value can be
4886 * trusted and will be used as-is; unlike userId which will be validated by this method.
4888 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4889 int filterCallingUid, int userId) {
4890 if (!sUserManager.exists(userId)) return null;
4891 flags = updateFlagsForComponent(flags, userId, component);
4892 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4893 false /* requireFullPermission */, false /* checkShell */, "get activity info");
4894 synchronized (mPackages) {
4895 PackageParser.Activity a = mActivities.mActivities.get(component);
4897 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4898 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4899 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4900 if (ps == null) return null;
4901 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4904 return PackageParser.generateActivityInfo(
4905 a, flags, ps.readUserState(userId), userId);
4907 if (mResolveComponentName.equals(component)) {
4908 return PackageParser.generateActivityInfo(
4909 mResolveActivity, flags, new PackageUserState(), userId);
4916 public boolean activitySupportsIntent(ComponentName component, Intent intent,
4917 String resolvedType) {
4918 synchronized (mPackages) {
4919 if (component.equals(mResolveComponentName)) {
4920 // The resolver supports EVERYTHING!
4923 final int callingUid = Binder.getCallingUid();
4924 final int callingUserId = UserHandle.getUserId(callingUid);
4925 PackageParser.Activity a = mActivities.mActivities.get(component);
4929 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4933 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4936 for (int i=0; i<a.intents.size(); i++) {
4937 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4938 intent.getData(), intent.getCategories(), TAG) >= 0) {
4947 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4948 if (!sUserManager.exists(userId)) return null;
4949 final int callingUid = Binder.getCallingUid();
4950 flags = updateFlagsForComponent(flags, userId, component);
4951 enforceCrossUserPermission(callingUid, userId,
4952 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4953 synchronized (mPackages) {
4954 PackageParser.Activity a = mReceivers.mActivities.get(component);
4955 if (DEBUG_PACKAGE_INFO) Log.v(
4956 TAG, "getReceiverInfo " + component + ": " + a);
4957 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4958 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4959 if (ps == null) return null;
4960 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4963 return PackageParser.generateActivityInfo(
4964 a, flags, ps.readUserState(userId), userId);
4971 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4972 int flags, int userId) {
4973 if (!sUserManager.exists(userId)) return null;
4974 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4975 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4979 flags = updateFlagsForPackage(flags, userId, null);
4981 final boolean canSeeStaticLibraries =
4982 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4983 == PERMISSION_GRANTED
4984 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4985 == PERMISSION_GRANTED
4986 || canRequestPackageInstallsInternal(packageName,
4987 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4988 false /* throwIfPermNotDeclared*/)
4989 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4990 == PERMISSION_GRANTED;
4992 synchronized (mPackages) {
4993 List<SharedLibraryInfo> result = null;
4995 final int libCount = mSharedLibraries.size();
4996 for (int i = 0; i < libCount; i++) {
4997 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4998 if (versionedLib == null) {
5002 final int versionCount = versionedLib.size();
5003 for (int j = 0; j < versionCount; j++) {
5004 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5005 if (!canSeeStaticLibraries && libInfo.isStatic()) {
5008 final long identity = Binder.clearCallingIdentity();
5010 PackageInfo packageInfo = getPackageInfoVersioned(
5011 libInfo.getDeclaringPackage(), flags
5012 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5013 if (packageInfo == null) {
5017 Binder.restoreCallingIdentity(identity);
5020 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5021 libInfo.getVersion(), libInfo.getType(),
5022 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5025 if (result == null) {
5026 result = new ArrayList<>();
5028 result.add(resLibInfo);
5032 return result != null ? new ParceledListSlice<>(result) : null;
5036 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5037 SharedLibraryInfo libInfo, int flags, int userId) {
5038 List<VersionedPackage> versionedPackages = null;
5039 final int packageCount = mSettings.mPackages.size();
5040 for (int i = 0; i < packageCount; i++) {
5041 PackageSetting ps = mSettings.mPackages.valueAt(i);
5047 if (!ps.getUserState().get(userId).isAvailable(flags)) {
5051 final String libName = libInfo.getName();
5052 if (libInfo.isStatic()) {
5053 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5057 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5060 if (versionedPackages == null) {
5061 versionedPackages = new ArrayList<>();
5063 // If the dependent is a static shared lib, use the public package name
5064 String dependentPackageName = ps.name;
5065 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5066 dependentPackageName = ps.pkg.manifestPackageName;
5068 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5069 } else if (ps.pkg != null) {
5070 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5071 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5072 if (versionedPackages == null) {
5073 versionedPackages = new ArrayList<>();
5075 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5080 return versionedPackages;
5084 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5085 if (!sUserManager.exists(userId)) return null;
5086 final int callingUid = Binder.getCallingUid();
5087 flags = updateFlagsForComponent(flags, userId, component);
5088 enforceCrossUserPermission(callingUid, userId,
5089 false /* requireFullPermission */, false /* checkShell */, "get service info");
5090 synchronized (mPackages) {
5091 PackageParser.Service s = mServices.mServices.get(component);
5092 if (DEBUG_PACKAGE_INFO) Log.v(
5093 TAG, "getServiceInfo " + component + ": " + s);
5094 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5095 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5096 if (ps == null) return null;
5097 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5100 return PackageParser.generateServiceInfo(
5101 s, flags, ps.readUserState(userId), userId);
5108 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5109 if (!sUserManager.exists(userId)) return null;
5110 final int callingUid = Binder.getCallingUid();
5111 flags = updateFlagsForComponent(flags, userId, component);
5112 enforceCrossUserPermission(callingUid, userId,
5113 false /* requireFullPermission */, false /* checkShell */, "get provider info");
5114 synchronized (mPackages) {
5115 PackageParser.Provider p = mProviders.mProviders.get(component);
5116 if (DEBUG_PACKAGE_INFO) Log.v(
5117 TAG, "getProviderInfo " + component + ": " + p);
5118 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5119 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5120 if (ps == null) return null;
5121 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5124 return PackageParser.generateProviderInfo(
5125 p, flags, ps.readUserState(userId), userId);
5132 public String[] getSystemSharedLibraryNames() {
5133 // allow instant applications
5134 synchronized (mPackages) {
5135 Set<String> libs = null;
5136 final int libCount = mSharedLibraries.size();
5137 for (int i = 0; i < libCount; i++) {
5138 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5139 if (versionedLib == null) {
5142 final int versionCount = versionedLib.size();
5143 for (int j = 0; j < versionCount; j++) {
5144 SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5145 if (!libEntry.info.isStatic()) {
5147 libs = new ArraySet<>();
5149 libs.add(libEntry.info.getName());
5152 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5153 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5154 UserHandle.getUserId(Binder.getCallingUid()),
5155 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5157 libs = new ArraySet<>();
5159 libs.add(libEntry.info.getName());
5166 String[] libsArray = new String[libs.size()];
5167 libs.toArray(libsArray);
5176 public @NonNull String getServicesSystemSharedLibraryPackageName() {
5177 // allow instant applications
5178 synchronized (mPackages) {
5179 return mServicesSystemSharedLibraryPackageName;
5184 public @NonNull String getSharedSystemSharedLibraryPackageName() {
5185 // allow instant applications
5186 synchronized (mPackages) {
5187 return mSharedSystemSharedLibraryPackageName;
5191 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5192 for (int i = userList.length - 1; i >= 0; --i) {
5193 final int userId = userList[i];
5194 // don't add instant app to the list of updates
5195 if (pkgSetting.getInstantApp(userId)) {
5198 SparseArray<String> changedPackages = mChangedPackages.get(userId);
5199 if (changedPackages == null) {
5200 changedPackages = new SparseArray<>();
5201 mChangedPackages.put(userId, changedPackages);
5203 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5204 if (sequenceNumbers == null) {
5205 sequenceNumbers = new HashMap<>();
5206 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5208 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5209 if (sequenceNumber != null) {
5210 changedPackages.remove(sequenceNumber);
5212 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5213 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5215 mChangedPackagesSequenceNumber++;
5219 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5220 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5223 synchronized (mPackages) {
5224 if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5227 final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5228 if (changedPackages == null) {
5231 final List<String> packageNames =
5232 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5233 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5234 final String packageName = changedPackages.get(i);
5235 if (packageName != null) {
5236 packageNames.add(packageName);
5239 return packageNames.isEmpty()
5240 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5245 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5246 // allow instant applications
5247 ArrayList<FeatureInfo> res;
5248 synchronized (mAvailableFeatures) {
5249 res = new ArrayList<>(mAvailableFeatures.size() + 1);
5250 res.addAll(mAvailableFeatures.values());
5252 final FeatureInfo fi = new FeatureInfo();
5253 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5254 FeatureInfo.GL_ES_VERSION_UNDEFINED);
5257 return new ParceledListSlice<>(res);
5261 public boolean hasSystemFeature(String name, int version) {
5262 // allow instant applications
5263 synchronized (mAvailableFeatures) {
5264 final FeatureInfo feat = mAvailableFeatures.get(name);
5268 return feat.version >= version;
5274 public int checkPermission(String permName, String pkgName, int userId) {
5275 if (!sUserManager.exists(userId)) {
5276 return PackageManager.PERMISSION_DENIED;
5278 final int callingUid = Binder.getCallingUid();
5280 synchronized (mPackages) {
5281 final PackageParser.Package p = mPackages.get(pkgName);
5282 if (p != null && p.mExtras != null) {
5283 final PackageSetting ps = (PackageSetting) p.mExtras;
5284 if (filterAppAccessLPr(ps, callingUid, userId)) {
5285 return PackageManager.PERMISSION_DENIED;
5287 final boolean instantApp = ps.getInstantApp(userId);
5288 final PermissionsState permissionsState = ps.getPermissionsState();
5289 if (permissionsState.hasPermission(permName, userId)) {
5291 BasePermission bp = mSettings.mPermissions.get(permName);
5292 if (bp != null && bp.isInstant()) {
5293 return PackageManager.PERMISSION_GRANTED;
5296 return PackageManager.PERMISSION_GRANTED;
5299 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5300 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5301 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5302 return PackageManager.PERMISSION_GRANTED;
5307 return PackageManager.PERMISSION_DENIED;
5311 public int checkUidPermission(String permName, int uid) {
5312 final int callingUid = Binder.getCallingUid();
5313 final int callingUserId = UserHandle.getUserId(callingUid);
5314 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5315 final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5316 final int userId = UserHandle.getUserId(uid);
5317 if (!sUserManager.exists(userId)) {
5318 return PackageManager.PERMISSION_DENIED;
5321 synchronized (mPackages) {
5322 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5324 if (obj instanceof SharedUserSetting) {
5325 if (isCallerInstantApp) {
5326 return PackageManager.PERMISSION_DENIED;
5328 } else if (obj instanceof PackageSetting) {
5329 final PackageSetting ps = (PackageSetting) obj;
5330 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5331 return PackageManager.PERMISSION_DENIED;
5334 final SettingBase settingBase = (SettingBase) obj;
5335 final PermissionsState permissionsState = settingBase.getPermissionsState();
5336 if (permissionsState.hasPermission(permName, userId)) {
5337 if (isUidInstantApp) {
5338 BasePermission bp = mSettings.mPermissions.get(permName);
5339 if (bp != null && bp.isInstant()) {
5340 return PackageManager.PERMISSION_GRANTED;
5343 return PackageManager.PERMISSION_GRANTED;
5346 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5347 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5348 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5349 return PackageManager.PERMISSION_GRANTED;
5352 ArraySet<String> perms = mSystemPermissions.get(uid);
5353 if (perms != null) {
5354 if (perms.contains(permName)) {
5355 return PackageManager.PERMISSION_GRANTED;
5357 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5358 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5359 return PackageManager.PERMISSION_GRANTED;
5365 return PackageManager.PERMISSION_DENIED;
5369 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5370 if (UserHandle.getCallingUserId() != userId) {
5371 mContext.enforceCallingPermission(
5372 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5373 "isPermissionRevokedByPolicy for user " + userId);
5376 if (checkPermission(permission, packageName, userId)
5377 == PackageManager.PERMISSION_GRANTED) {
5381 final int callingUid = Binder.getCallingUid();
5382 if (getInstantAppPackageName(callingUid) != null) {
5383 if (!isCallerSameApp(packageName, callingUid)) {
5387 if (isInstantApp(packageName, userId)) {
5392 final long identity = Binder.clearCallingIdentity();
5394 final int flags = getPermissionFlags(permission, packageName, userId);
5395 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5397 Binder.restoreCallingIdentity(identity);
5402 public String getPermissionControllerPackageName() {
5403 synchronized (mPackages) {
5404 return mRequiredInstallerPackage;
5409 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5410 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5411 * @param checkShell whether to prevent shell from access if there's a debugging restriction
5412 * @param message the message to log on security exception
5414 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5415 boolean checkShell, String message) {
5417 throw new IllegalArgumentException("Invalid userId " + userId);
5420 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5422 if (userId == UserHandle.getUserId(callingUid)) return;
5423 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5424 if (requireFullPermission) {
5425 mContext.enforceCallingOrSelfPermission(
5426 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5429 mContext.enforceCallingOrSelfPermission(
5430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5431 } catch (SecurityException se) {
5432 mContext.enforceCallingOrSelfPermission(
5433 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5439 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5440 if (callingUid == Process.SHELL_UID) {
5442 && sUserManager.hasUserRestriction(restriction, userHandle)) {
5443 throw new SecurityException("Shell does not have permission to access user "
5445 } else if (userHandle < 0) {
5446 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5447 + Debug.getCallers(3));
5452 private BasePermission findPermissionTreeLP(String permName) {
5453 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5454 if (permName.startsWith(bp.name) &&
5455 permName.length() > bp.name.length() &&
5456 permName.charAt(bp.name.length()) == '.') {
5463 private BasePermission checkPermissionTreeLP(String permName) {
5464 if (permName != null) {
5465 BasePermission bp = findPermissionTreeLP(permName);
5467 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5470 throw new SecurityException("Calling uid "
5471 + Binder.getCallingUid()
5472 + " is not allowed to add to permission tree "
5473 + bp.name + " owned by uid " + bp.uid);
5476 throw new SecurityException("No permission tree found for " + permName);
5479 static boolean compareStrings(CharSequence s1, CharSequence s2) {
5486 if (s1.getClass() != s2.getClass()) {
5489 return s1.equals(s2);
5492 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5493 if (pi1.icon != pi2.icon) return false;
5494 if (pi1.logo != pi2.logo) return false;
5495 if (pi1.protectionLevel != pi2.protectionLevel) return false;
5496 if (!compareStrings(pi1.name, pi2.name)) return false;
5497 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5498 // We'll take care of setting this one.
5499 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5500 // These are not currently stored in settings.
5501 //if (!compareStrings(pi1.group, pi2.group)) return false;
5502 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5503 //if (pi1.labelRes != pi2.labelRes) return false;
5504 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5508 int permissionInfoFootprint(PermissionInfo info) {
5509 int size = info.name.length();
5510 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5511 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5515 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5517 for (BasePermission perm : mSettings.mPermissions.values()) {
5518 if (perm.uid == tree.uid) {
5519 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5525 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5526 // We calculate the max size of permissions defined by this uid and throw
5527 // if that plus the size of 'info' would exceed our stated maximum.
5528 if (tree.uid != Process.SYSTEM_UID) {
5529 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5530 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5531 throw new SecurityException("Permission tree size cap exceeded");
5536 boolean addPermissionLocked(PermissionInfo info, boolean async) {
5537 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5538 throw new SecurityException("Instant apps can't add permissions");
5540 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5541 throw new SecurityException("Label must be specified in permission");
5543 BasePermission tree = checkPermissionTreeLP(info.name);
5544 BasePermission bp = mSettings.mPermissions.get(info.name);
5545 boolean added = bp == null;
5546 boolean changed = true;
5547 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5549 enforcePermissionCapLocked(info, tree);
5550 bp = new BasePermission(info.name, tree.sourcePackage,
5551 BasePermission.TYPE_DYNAMIC);
5552 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5553 throw new SecurityException(
5554 "Not allowed to modify non-dynamic permission "
5557 if (bp.protectionLevel == fixedLevel
5558 && bp.perm.owner.equals(tree.perm.owner)
5559 && bp.uid == tree.uid
5560 && comparePermissionInfos(bp.perm.info, info)) {
5564 bp.protectionLevel = fixedLevel;
5565 info = new PermissionInfo(info);
5566 info.protectionLevel = fixedLevel;
5567 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5568 bp.perm.info.packageName = tree.perm.info.packageName;
5571 mSettings.mPermissions.put(info.name, bp);
5575 mSettings.writeLPr();
5577 scheduleWriteSettingsLocked();
5584 public boolean addPermission(PermissionInfo info) {
5585 synchronized (mPackages) {
5586 return addPermissionLocked(info, false);
5591 public boolean addPermissionAsync(PermissionInfo info) {
5592 synchronized (mPackages) {
5593 return addPermissionLocked(info, true);
5598 public void removePermission(String name) {
5599 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5600 throw new SecurityException("Instant applications don't have access to this method");
5602 synchronized (mPackages) {
5603 checkPermissionTreeLP(name);
5604 BasePermission bp = mSettings.mPermissions.get(name);
5606 if (bp.type != BasePermission.TYPE_DYNAMIC) {
5607 throw new SecurityException(
5608 "Not allowed to modify non-dynamic permission "
5611 mSettings.mPermissions.remove(name);
5612 mSettings.writeLPr();
5617 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5618 PackageParser.Package pkg, BasePermission bp) {
5619 int index = pkg.requestedPermissions.indexOf(bp.name);
5621 throw new SecurityException("Package " + pkg.packageName
5622 + " has not requested permission " + bp.name);
5624 if (!bp.isRuntime() && !bp.isDevelopment()) {
5625 throw new SecurityException("Permission " + bp.name
5626 + " is not a changeable permission type");
5631 public void grantRuntimePermission(String packageName, String name, final int userId) {
5632 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5635 private void grantRuntimePermission(String packageName, String name, final int userId,
5636 boolean overridePolicy) {
5637 if (!sUserManager.exists(userId)) {
5638 Log.e(TAG, "No such user:" + userId);
5641 final int callingUid = Binder.getCallingUid();
5643 mContext.enforceCallingOrSelfPermission(
5644 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5645 "grantRuntimePermission");
5647 enforceCrossUserPermission(callingUid, userId,
5648 true /* requireFullPermission */, true /* checkShell */,
5649 "grantRuntimePermission");
5652 final PackageSetting ps;
5654 synchronized (mPackages) {
5655 final PackageParser.Package pkg = mPackages.get(packageName);
5657 throw new IllegalArgumentException("Unknown package: " + packageName);
5659 final BasePermission bp = mSettings.mPermissions.get(name);
5661 throw new IllegalArgumentException("Unknown permission: " + name);
5663 ps = (PackageSetting) pkg.mExtras;
5665 || filterAppAccessLPr(ps, callingUid, userId)) {
5666 throw new IllegalArgumentException("Unknown package: " + packageName);
5669 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5671 // If a permission review is required for legacy apps we represent
5672 // their permissions as always granted runtime ones since we need
5673 // to keep the review required permission flag per user while an
5674 // install permission's state is shared across all users.
5675 if (mPermissionReviewRequired
5676 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5677 && bp.isRuntime()) {
5681 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5683 final PermissionsState permissionsState = ps.getPermissionsState();
5685 final int flags = permissionsState.getPermissionFlags(name, userId);
5686 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5687 throw new SecurityException("Cannot grant system fixed permission "
5688 + name + " for package " + packageName);
5690 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5691 throw new SecurityException("Cannot grant policy fixed permission "
5692 + name + " for package " + packageName);
5695 if (bp.isDevelopment()) {
5696 // Development permissions must be handled specially, since they are not
5697 // normal runtime permissions. For now they apply to all users.
5698 if (permissionsState.grantInstallPermission(bp) !=
5699 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5700 scheduleWriteSettingsLocked();
5705 if (ps.getInstantApp(userId) && !bp.isInstant()) {
5706 throw new SecurityException("Cannot grant non-ephemeral permission"
5707 + name + " for package " + packageName);
5710 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5711 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5715 final int result = permissionsState.grantRuntimePermission(bp, userId);
5717 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5721 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5722 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5723 mHandler.post(new Runnable() {
5726 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5733 if (bp.isRuntime()) {
5734 logPermissionGranted(mContext, name, packageName);
5737 mOnPermissionChangeListeners.onPermissionsChanged(uid);
5739 // Not critical if that is lost - app has to request again.
5740 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5743 // Only need to do this if user is initialized. Otherwise it's a new user
5744 // and there are no processes running as the user yet and there's no need
5745 // to make an expensive call to remount processes for the changed permissions.
5746 if (READ_EXTERNAL_STORAGE.equals(name)
5747 || WRITE_EXTERNAL_STORAGE.equals(name)) {
5748 final long token = Binder.clearCallingIdentity();
5750 if (sUserManager.isInitialized(userId)) {
5751 StorageManagerInternal storageManagerInternal = LocalServices.getService(
5752 StorageManagerInternal.class);
5753 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5756 Binder.restoreCallingIdentity(token);
5762 public void revokeRuntimePermission(String packageName, String name, int userId) {
5763 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5766 private void revokeRuntimePermission(String packageName, String name, int userId,
5767 boolean overridePolicy) {
5768 if (!sUserManager.exists(userId)) {
5769 Log.e(TAG, "No such user:" + userId);
5773 mContext.enforceCallingOrSelfPermission(
5774 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5775 "revokeRuntimePermission");
5777 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5778 true /* requireFullPermission */, true /* checkShell */,
5779 "revokeRuntimePermission");
5783 synchronized (mPackages) {
5784 final PackageParser.Package pkg = mPackages.get(packageName);
5786 throw new IllegalArgumentException("Unknown package: " + packageName);
5788 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5790 || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5791 throw new IllegalArgumentException("Unknown package: " + packageName);
5793 final BasePermission bp = mSettings.mPermissions.get(name);
5795 throw new IllegalArgumentException("Unknown permission: " + name);
5798 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5800 // If a permission review is required for legacy apps we represent
5801 // their permissions as always granted runtime ones since we need
5802 // to keep the review required permission flag per user while an
5803 // install permission's state is shared across all users.
5804 if (mPermissionReviewRequired
5805 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5806 && bp.isRuntime()) {
5810 final PermissionsState permissionsState = ps.getPermissionsState();
5812 final int flags = permissionsState.getPermissionFlags(name, userId);
5813 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5814 throw new SecurityException("Cannot revoke system fixed permission "
5815 + name + " for package " + packageName);
5817 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5818 throw new SecurityException("Cannot revoke policy fixed permission "
5819 + name + " for package " + packageName);
5822 if (bp.isDevelopment()) {
5823 // Development permissions must be handled specially, since they are not
5824 // normal runtime permissions. For now they apply to all users.
5825 if (permissionsState.revokeInstallPermission(bp) !=
5826 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5827 scheduleWriteSettingsLocked();
5832 if (permissionsState.revokeRuntimePermission(bp, userId) ==
5833 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5837 if (bp.isRuntime()) {
5838 logPermissionRevoked(mContext, name, packageName);
5841 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5843 // Critical, after this call app should never have the permission.
5844 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5846 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5849 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5853 * Get the first event id for the permission.
5855 * <p>There are four events for each permission: <ul>
5856 * <li>Request permission: first id + 0</li>
5857 * <li>Grant permission: first id + 1</li>
5858 * <li>Request for permission denied: first id + 2</li>
5859 * <li>Revoke permission: first id + 3</li>
5862 * @param name name of the permission
5864 * @return The first event id for the permission
5866 private static int getBaseEventId(@NonNull String name) {
5867 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5869 if (eventIdIndex == -1) {
5870 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5872 Log.i(TAG, "Unknown permission " + name);
5874 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5876 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5879 // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5880 // - metrics_constants.proto
5881 throw new IllegalStateException("Unknown permission " + name);
5885 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5889 * Log that a permission was revoked.
5891 * @param context Context of the caller
5892 * @param name name of the permission
5893 * @param packageName package permission if for
5895 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5896 @NonNull String packageName) {
5897 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5901 * Log that a permission request was granted.
5903 * @param context Context of the caller
5904 * @param name name of the permission
5905 * @param packageName package permission if for
5907 private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5908 @NonNull String packageName) {
5909 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5913 public void resetRuntimePermissions() {
5914 mContext.enforceCallingOrSelfPermission(
5915 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5916 "revokeRuntimePermission");
5918 int callingUid = Binder.getCallingUid();
5919 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5920 mContext.enforceCallingOrSelfPermission(
5921 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5922 "resetRuntimePermissions");
5925 synchronized (mPackages) {
5926 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5927 for (int userId : UserManagerService.getInstance().getUserIds()) {
5928 final int packageCount = mPackages.size();
5929 for (int i = 0; i < packageCount; i++) {
5930 PackageParser.Package pkg = mPackages.valueAt(i);
5931 if (!(pkg.mExtras instanceof PackageSetting)) {
5934 PackageSetting ps = (PackageSetting) pkg.mExtras;
5935 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5942 public int getPermissionFlags(String name, String packageName, int userId) {
5943 if (!sUserManager.exists(userId)) {
5947 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5949 final int callingUid = Binder.getCallingUid();
5950 enforceCrossUserPermission(callingUid, userId,
5951 true /* requireFullPermission */, false /* checkShell */,
5952 "getPermissionFlags");
5954 synchronized (mPackages) {
5955 final PackageParser.Package pkg = mPackages.get(packageName);
5959 final BasePermission bp = mSettings.mPermissions.get(name);
5963 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5965 || filterAppAccessLPr(ps, callingUid, userId)) {
5968 PermissionsState permissionsState = ps.getPermissionsState();
5969 return permissionsState.getPermissionFlags(name, userId);
5974 public void updatePermissionFlags(String name, String packageName, int flagMask,
5975 int flagValues, int userId) {
5976 if (!sUserManager.exists(userId)) {
5980 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5982 final int callingUid = Binder.getCallingUid();
5983 enforceCrossUserPermission(callingUid, userId,
5984 true /* requireFullPermission */, true /* checkShell */,
5985 "updatePermissionFlags");
5987 // Only the system can change these flags and nothing else.
5988 if (getCallingUid() != Process.SYSTEM_UID) {
5989 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5990 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5991 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5992 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5993 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5996 synchronized (mPackages) {
5997 final PackageParser.Package pkg = mPackages.get(packageName);
5999 throw new IllegalArgumentException("Unknown package: " + packageName);
6001 final PackageSetting ps = (PackageSetting) pkg.mExtras;
6003 || filterAppAccessLPr(ps, callingUid, userId)) {
6004 throw new IllegalArgumentException("Unknown package: " + packageName);
6007 final BasePermission bp = mSettings.mPermissions.get(name);
6009 throw new IllegalArgumentException("Unknown permission: " + name);
6012 PermissionsState permissionsState = ps.getPermissionsState();
6014 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6016 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6017 // Install and runtime permissions are stored in different places,
6018 // so figure out what permission changed and persist the change.
6019 if (permissionsState.getInstallPermissionState(name) != null) {
6020 scheduleWriteSettingsLocked();
6021 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6023 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6030 * Update the permission flags for all packages and runtime permissions of a user in order
6031 * to allow device or profile owner to remove POLICY_FIXED.
6034 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6035 if (!sUserManager.exists(userId)) {
6039 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6041 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6042 true /* requireFullPermission */, true /* checkShell */,
6043 "updatePermissionFlagsForAllApps");
6045 // Only the system can change system fixed flags.
6046 if (getCallingUid() != Process.SYSTEM_UID) {
6047 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6048 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6051 synchronized (mPackages) {
6052 boolean changed = false;
6053 final int packageCount = mPackages.size();
6054 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6055 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6056 final PackageSetting ps = (PackageSetting) pkg.mExtras;
6060 PermissionsState permissionsState = ps.getPermissionsState();
6061 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6062 userId, flagMask, flagValues);
6065 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6070 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6071 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6072 != PackageManager.PERMISSION_GRANTED
6073 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6074 != PackageManager.PERMISSION_GRANTED) {
6075 throw new SecurityException(message + " requires "
6076 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6077 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6082 public boolean shouldShowRequestPermissionRationale(String permissionName,
6083 String packageName, int userId) {
6084 if (UserHandle.getCallingUserId() != userId) {
6085 mContext.enforceCallingPermission(
6086 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6087 "canShowRequestPermissionRationale for user " + userId);
6090 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6091 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6095 if (checkPermission(permissionName, packageName, userId)
6096 == PackageManager.PERMISSION_GRANTED) {
6102 final long identity = Binder.clearCallingIdentity();
6104 flags = getPermissionFlags(permissionName,
6105 packageName, userId);
6107 Binder.restoreCallingIdentity(identity);
6110 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6111 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6112 | PackageManager.FLAG_PERMISSION_USER_FIXED;
6114 if ((flags & fixedFlags) != 0) {
6118 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6122 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6123 mContext.enforceCallingOrSelfPermission(
6124 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6125 "addOnPermissionsChangeListener");
6127 synchronized (mPackages) {
6128 mOnPermissionChangeListeners.addListenerLocked(listener);
6133 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6134 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6135 throw new SecurityException("Instant applications don't have access to this method");
6137 synchronized (mPackages) {
6138 mOnPermissionChangeListeners.removeListenerLocked(listener);
6143 public boolean isProtectedBroadcast(String actionName) {
6144 // allow instant applications
6145 synchronized (mProtectedBroadcasts) {
6146 if (mProtectedBroadcasts.contains(actionName)) {
6148 } else if (actionName != null) {
6149 // TODO: remove these terrible hacks
6150 if (actionName.startsWith("android.net.netmon.lingerExpired")
6151 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6152 || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6153 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6162 public int checkSignatures(String pkg1, String pkg2) {
6163 synchronized (mPackages) {
6164 final PackageParser.Package p1 = mPackages.get(pkg1);
6165 final PackageParser.Package p2 = mPackages.get(pkg2);
6166 if (p1 == null || p1.mExtras == null
6167 || p2 == null || p2.mExtras == null) {
6168 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6170 final int callingUid = Binder.getCallingUid();
6171 final int callingUserId = UserHandle.getUserId(callingUid);
6172 final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6173 final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6174 if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6175 || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6176 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6178 return compareSignatures(p1.mSignatures, p2.mSignatures);
6183 public int checkUidSignatures(int uid1, int uid2) {
6184 final int callingUid = Binder.getCallingUid();
6185 final int callingUserId = UserHandle.getUserId(callingUid);
6186 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6187 // Map to base uids.
6188 uid1 = UserHandle.getAppId(uid1);
6189 uid2 = UserHandle.getAppId(uid2);
6191 synchronized (mPackages) {
6194 Object obj = mSettings.getUserIdLPr(uid1);
6196 if (obj instanceof SharedUserSetting) {
6197 if (isCallerInstantApp) {
6198 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6200 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6201 } else if (obj instanceof PackageSetting) {
6202 final PackageSetting ps = (PackageSetting) obj;
6203 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6204 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6206 s1 = ps.signatures.mSignatures;
6208 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6211 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6213 obj = mSettings.getUserIdLPr(uid2);
6215 if (obj instanceof SharedUserSetting) {
6216 if (isCallerInstantApp) {
6217 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6219 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6220 } else if (obj instanceof PackageSetting) {
6221 final PackageSetting ps = (PackageSetting) obj;
6222 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6223 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6225 s2 = ps.signatures.mSignatures;
6227 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6230 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6232 return compareSignatures(s1, s2);
6237 * This method should typically only be used when granting or revoking
6238 * permissions, since the app may immediately restart after this call.
6240 * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6241 * guard your work against the app being relaunched.
6243 private void killUid(int appId, int userId, String reason) {
6244 final long identity = Binder.clearCallingIdentity();
6246 IActivityManager am = ActivityManager.getService();
6249 am.killUid(appId, userId, reason);
6250 } catch (RemoteException e) {
6251 /* ignore - same process */
6255 Binder.restoreCallingIdentity(identity);
6260 * Compares two sets of signatures. Returns:
6262 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6264 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6266 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6268 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6270 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6272 static int compareSignatures(Signature[] s1, Signature[] s2) {
6275 ? PackageManager.SIGNATURE_NEITHER_SIGNED
6276 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6280 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6283 if (s1.length != s2.length) {
6284 return PackageManager.SIGNATURE_NO_MATCH;
6287 // Since both signature sets are of size 1, we can compare without HashSets.
6288 if (s1.length == 1) {
6289 return s1[0].equals(s2[0]) ?
6290 PackageManager.SIGNATURE_MATCH :
6291 PackageManager.SIGNATURE_NO_MATCH;
6294 ArraySet<Signature> set1 = new ArraySet<Signature>();
6295 for (Signature sig : s1) {
6298 ArraySet<Signature> set2 = new ArraySet<Signature>();
6299 for (Signature sig : s2) {
6302 // Make sure s2 contains all signatures in s1.
6303 if (set1.equals(set2)) {
6304 return PackageManager.SIGNATURE_MATCH;
6306 return PackageManager.SIGNATURE_NO_MATCH;
6310 * If the database version for this type of package (internal storage or
6311 * external storage) is less than the version where package signatures
6312 * were updated, return true.
6314 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6315 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6316 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6320 * Used for backward compatibility to make sure any packages with
6321 * certificate chains get upgraded to the new style. {@code existingSigs}
6322 * will be in the old format (since they were stored on disk from before the
6323 * system upgrade) and {@code scannedSigs} will be in the newer format.
6325 private int compareSignaturesCompat(PackageSignatures existingSigs,
6326 PackageParser.Package scannedPkg) {
6327 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6328 return PackageManager.SIGNATURE_NO_MATCH;
6331 ArraySet<Signature> existingSet = new ArraySet<Signature>();
6332 for (Signature sig : existingSigs.mSignatures) {
6333 existingSet.add(sig);
6335 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6336 for (Signature sig : scannedPkg.mSignatures) {
6338 Signature[] chainSignatures = sig.getChainSignatures();
6339 for (Signature chainSig : chainSignatures) {
6340 scannedCompatSet.add(chainSig);
6342 } catch (CertificateEncodingException e) {
6343 scannedCompatSet.add(sig);
6347 * Make sure the expanded scanned set contains all signatures in the
6350 if (scannedCompatSet.equals(existingSet)) {
6351 // Migrate the old signatures to the new scheme.
6352 existingSigs.assignSignatures(scannedPkg.mSignatures);
6353 // The new KeySets will be re-added later in the scanning process.
6354 synchronized (mPackages) {
6355 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6357 return PackageManager.SIGNATURE_MATCH;
6359 return PackageManager.SIGNATURE_NO_MATCH;
6362 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6363 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6364 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6367 private int compareSignaturesRecover(PackageSignatures existingSigs,
6368 PackageParser.Package scannedPkg) {
6369 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6370 return PackageManager.SIGNATURE_NO_MATCH;
6375 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6376 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6377 + scannedPkg.packageName);
6378 return PackageManager.SIGNATURE_MATCH;
6380 } catch (CertificateException e) {
6381 msg = e.getMessage();
6384 logCriticalInfo(Log.INFO,
6385 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6386 return PackageManager.SIGNATURE_NO_MATCH;
6390 public List<String> getAllPackages() {
6391 final int callingUid = Binder.getCallingUid();
6392 final int callingUserId = UserHandle.getUserId(callingUid);
6393 synchronized (mPackages) {
6394 if (canViewInstantApps(callingUid, callingUserId)) {
6395 return new ArrayList<String>(mPackages.keySet());
6397 final String instantAppPkgName = getInstantAppPackageName(callingUid);
6398 final List<String> result = new ArrayList<>();
6399 if (instantAppPkgName != null) {
6400 // caller is an instant application; filter unexposed applications
6401 for (PackageParser.Package pkg : mPackages.values()) {
6402 if (!pkg.visibleToInstantApps) {
6405 result.add(pkg.packageName);
6408 // caller is a normal application; filter instant applications
6409 for (PackageParser.Package pkg : mPackages.values()) {
6410 final PackageSetting ps =
6411 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6413 && ps.getInstantApp(callingUserId)
6414 && !mInstantAppRegistry.isInstantAccessGranted(
6415 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6418 result.add(pkg.packageName);
6426 public String[] getPackagesForUid(int uid) {
6427 final int callingUid = Binder.getCallingUid();
6428 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6429 final int userId = UserHandle.getUserId(uid);
6430 uid = UserHandle.getAppId(uid);
6432 synchronized (mPackages) {
6433 Object obj = mSettings.getUserIdLPr(uid);
6434 if (obj instanceof SharedUserSetting) {
6435 if (isCallerInstantApp) {
6438 final SharedUserSetting sus = (SharedUserSetting) obj;
6439 final int N = sus.packages.size();
6440 String[] res = new String[N];
6441 final Iterator<PackageSetting> it = sus.packages.iterator();
6443 while (it.hasNext()) {
6444 PackageSetting ps = it.next();
6445 if (ps.getInstalled(userId)) {
6448 res = ArrayUtils.removeElement(String.class, res, res[i]);
6452 } else if (obj instanceof PackageSetting) {
6453 final PackageSetting ps = (PackageSetting) obj;
6454 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6455 return new String[]{ps.name};
6463 public String getNameForUid(int uid) {
6464 final int callingUid = Binder.getCallingUid();
6465 if (getInstantAppPackageName(callingUid) != null) {
6468 synchronized (mPackages) {
6469 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6470 if (obj instanceof SharedUserSetting) {
6471 final SharedUserSetting sus = (SharedUserSetting) obj;
6472 return sus.name + ":" + sus.userId;
6473 } else if (obj instanceof PackageSetting) {
6474 final PackageSetting ps = (PackageSetting) obj;
6475 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6485 public String[] getNamesForUids(int[] uids) {
6486 if (uids == null || uids.length == 0) {
6489 final int callingUid = Binder.getCallingUid();
6490 if (getInstantAppPackageName(callingUid) != null) {
6493 final String[] names = new String[uids.length];
6494 synchronized (mPackages) {
6495 for (int i = uids.length - 1; i >= 0; i--) {
6496 final int uid = uids[i];
6497 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6498 if (obj instanceof SharedUserSetting) {
6499 final SharedUserSetting sus = (SharedUserSetting) obj;
6500 names[i] = "shared:" + sus.name;
6501 } else if (obj instanceof PackageSetting) {
6502 final PackageSetting ps = (PackageSetting) obj;
6503 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6517 public int getUidForSharedUser(String sharedUserName) {
6518 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6521 if (sharedUserName == null) {
6525 synchronized (mPackages) {
6526 SharedUserSetting suid;
6528 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6532 } catch (PackageManagerException ignore) {
6533 // can't happen, but, still need to catch it
6540 public int getFlagsForUid(int uid) {
6541 final int callingUid = Binder.getCallingUid();
6542 if (getInstantAppPackageName(callingUid) != null) {
6545 synchronized (mPackages) {
6546 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6547 if (obj instanceof SharedUserSetting) {
6548 final SharedUserSetting sus = (SharedUserSetting) obj;
6549 return sus.pkgFlags;
6550 } else if (obj instanceof PackageSetting) {
6551 final PackageSetting ps = (PackageSetting) obj;
6552 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6562 public int getPrivateFlagsForUid(int uid) {
6563 final int callingUid = Binder.getCallingUid();
6564 if (getInstantAppPackageName(callingUid) != null) {
6567 synchronized (mPackages) {
6568 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6569 if (obj instanceof SharedUserSetting) {
6570 final SharedUserSetting sus = (SharedUserSetting) obj;
6571 return sus.pkgPrivateFlags;
6572 } else if (obj instanceof PackageSetting) {
6573 final PackageSetting ps = (PackageSetting) obj;
6574 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6577 return ps.pkgPrivateFlags;
6584 public boolean isUidPrivileged(int uid) {
6585 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6588 uid = UserHandle.getAppId(uid);
6590 synchronized (mPackages) {
6591 Object obj = mSettings.getUserIdLPr(uid);
6592 if (obj instanceof SharedUserSetting) {
6593 final SharedUserSetting sus = (SharedUserSetting) obj;
6594 final Iterator<PackageSetting> it = sus.packages.iterator();
6595 while (it.hasNext()) {
6596 if (it.next().isPrivileged()) {
6600 } else if (obj instanceof PackageSetting) {
6601 final PackageSetting ps = (PackageSetting) obj;
6602 return ps.isPrivileged();
6609 public String[] getAppOpPermissionPackages(String permissionName) {
6610 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6613 synchronized (mPackages) {
6614 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6618 return pkgs.toArray(new String[pkgs.size()]);
6623 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6624 int flags, int userId) {
6625 return resolveIntentInternal(
6626 intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6629 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6630 int flags, int userId, boolean resolveForStart) {
6632 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6634 if (!sUserManager.exists(userId)) return null;
6635 final int callingUid = Binder.getCallingUid();
6636 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6637 enforceCrossUserPermission(callingUid, userId,
6638 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6640 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6641 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6642 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6643 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6645 final ResolveInfo bestChoice =
6646 chooseBestActivity(intent, resolvedType, flags, query, userId);
6649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6654 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6655 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6656 throw new SecurityException(
6657 "findPersistentPreferredActivity can only be run by the system");
6659 if (!sUserManager.exists(userId)) {
6662 final int callingUid = Binder.getCallingUid();
6663 intent = updateIntentForResolve(intent);
6664 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6665 final int flags = updateFlagsForResolve(
6666 0, userId, intent, callingUid, false /*includeInstantApps*/);
6667 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6669 synchronized (mPackages) {
6670 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6676 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6677 IntentFilter filter, int match, ComponentName activity) {
6678 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6681 final int userId = UserHandle.getCallingUserId();
6682 if (DEBUG_PREFERRED) {
6683 Log.v(TAG, "setLastChosenActivity intent=" + intent
6684 + " resolvedType=" + resolvedType
6686 + " filter=" + filter
6688 + " activity=" + activity);
6689 filter.dump(new PrintStreamPrinter(System.out), " ");
6691 intent.setComponent(null);
6692 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6694 // Find any earlier preferred or last chosen entries and nuke them
6695 findPreferredActivity(intent, resolvedType,
6696 flags, query, 0, false, true, false, userId);
6697 // Add the new activity as the last chosen for this filter
6698 addPreferredActivityInternal(filter, match, null, activity, false, userId,
6699 "Setting last chosen");
6703 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6704 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6707 final int userId = UserHandle.getCallingUserId();
6708 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6709 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6711 return findPreferredActivity(intent, resolvedType, flags, query, 0,
6712 false, false, false, userId);
6716 * Returns whether or not instant apps have been disabled remotely.
6718 private boolean isEphemeralDisabled() {
6719 return mEphemeralAppsDisabled;
6722 private boolean isInstantAppAllowed(
6723 Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6724 boolean skipPackageCheck) {
6725 if (mInstantAppResolverConnection == null) {
6728 if (mInstantAppInstallerActivity == null) {
6731 if (intent.getComponent() != null) {
6734 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6737 if (!skipPackageCheck && intent.getPackage() != null) {
6740 final boolean isWebUri = hasWebURI(intent);
6741 if (!isWebUri || intent.getData().getHost() == null) {
6744 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6745 // Or if there's already an ephemeral app installed that handles the action
6746 synchronized (mPackages) {
6747 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6748 for (int n = 0; n < count; n++) {
6749 final ResolveInfo info = resolvedActivities.get(n);
6750 final String packageName = info.activityInfo.packageName;
6751 final PackageSetting ps = mSettings.mPackages.get(packageName);
6753 // only check domain verification status if the app is not a browser
6754 if (!info.handleAllWebDataURI) {
6755 // Try to get the status from User settings first
6756 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6757 final int status = (int) (packedStatus >> 32);
6758 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6759 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6760 if (DEBUG_EPHEMERAL) {
6761 Slog.v(TAG, "DENY instant app;"
6762 + " pkg: " + packageName + ", status: " + status);
6767 if (ps.getInstantApp(userId)) {
6768 if (DEBUG_EPHEMERAL) {
6769 Slog.v(TAG, "DENY instant app installed;"
6770 + " pkg: " + packageName);
6777 // We've exhausted all ways to deny ephemeral application; let the system look for them.
6781 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6782 Intent origIntent, String resolvedType, String callingPackage,
6783 Bundle verificationBundle, int userId) {
6784 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6785 new InstantAppRequest(responseObj, origIntent, resolvedType,
6786 callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6787 mHandler.sendMessage(msg);
6790 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6791 int flags, List<ResolveInfo> query, int userId) {
6792 if (query != null) {
6793 final int N = query.size();
6795 return query.get(0);
6797 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6798 // If there is more than one activity with the same priority,
6799 // then let the user decide between them.
6800 ResolveInfo r0 = query.get(0);
6801 ResolveInfo r1 = query.get(1);
6802 if (DEBUG_INTENT_MATCHING || debug) {
6803 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6804 + r1.activityInfo.name + "=" + r1.priority);
6806 // If the first activity has a higher priority, or a different
6807 // default, then it is always desirable to pick it.
6808 if (r0.priority != r1.priority
6809 || r0.preferredOrder != r1.preferredOrder
6810 || r0.isDefault != r1.isDefault) {
6811 return query.get(0);
6813 // If we have saved a preference for a preferred activity for
6814 // this Intent, use that.
6815 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6816 flags, query, r0.priority, true, false, debug, userId);
6820 // If we have an ephemeral app, use it
6821 for (int i = 0; i < N; i++) {
6823 if (ri.activityInfo.applicationInfo.isInstantApp()) {
6824 final String packageName = ri.activityInfo.packageName;
6825 final PackageSetting ps = mSettings.mPackages.get(packageName);
6826 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6827 final int status = (int)(packedStatus >> 32);
6828 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6833 ri = new ResolveInfo(mResolveInfo);
6834 ri.activityInfo = new ActivityInfo(ri.activityInfo);
6835 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6836 // If all of the options come from the same package, show the application's
6837 // label and icon instead of the generic resolver's.
6838 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6839 // and then throw away the ResolveInfo itself, meaning that the caller loses
6840 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6841 // a fallback for this case; we only set the target package's resources on
6842 // the ResolveInfo, not the ActivityInfo.
6843 final String intentPackage = intent.getPackage();
6844 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6845 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6846 ri.resolvePackageName = intentPackage;
6847 if (userNeedsBadging(userId)) {
6848 ri.noResourceId = true;
6850 ri.icon = appi.icon;
6852 ri.iconResourceId = appi.icon;
6853 ri.labelRes = appi.labelRes;
6855 ri.activityInfo.applicationInfo = new ApplicationInfo(
6856 ri.activityInfo.applicationInfo);
6858 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6859 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6861 // Make sure that the resolver is displayable in car mode
6862 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6863 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6871 * Return true if the given list is not empty and all of its contents have
6872 * an activityInfo with the given package name.
6874 private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6875 if (ArrayUtils.isEmpty(list)) {
6878 for (int i = 0, N = list.size(); i < N; i++) {
6879 final ResolveInfo ri = list.get(i);
6880 final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6881 if (ai == null || !packageName.equals(ai.packageName)) {
6888 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6889 int flags, List<ResolveInfo> query, boolean debug, int userId) {
6890 final int N = query.size();
6891 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6893 // Get the list of persistent preferred activities that handle the intent
6894 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6895 List<PersistentPreferredActivity> pprefs = ppir != null
6896 ? ppir.queryIntent(intent, resolvedType,
6897 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6900 if (pprefs != null && pprefs.size() > 0) {
6901 final int M = pprefs.size();
6902 for (int i=0; i<M; i++) {
6903 final PersistentPreferredActivity ppa = pprefs.get(i);
6904 if (DEBUG_PREFERRED || debug) {
6905 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6906 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6907 + "\n component=" + ppa.mComponent);
6908 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6910 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6911 flags | MATCH_DISABLED_COMPONENTS, userId);
6912 if (DEBUG_PREFERRED || debug) {
6913 Slog.v(TAG, "Found persistent preferred activity:");
6915 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6917 Slog.v(TAG, " null");
6921 // This previously registered persistent preferred activity
6922 // component is no longer known. Ignore it and do NOT remove it.
6925 for (int j=0; j<N; j++) {
6926 final ResolveInfo ri = query.get(j);
6927 if (!ri.activityInfo.applicationInfo.packageName
6928 .equals(ai.applicationInfo.packageName)) {
6931 if (!ri.activityInfo.name.equals(ai.name)) {
6934 // Found a persistent preference that can handle the intent.
6935 if (DEBUG_PREFERRED || debug) {
6936 Slog.v(TAG, "Returning persistent preferred activity: " +
6937 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6946 // TODO: handle preferred activities missing while user has amnesia
6947 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6948 List<ResolveInfo> query, int priority, boolean always,
6949 boolean removeMatches, boolean debug, int userId) {
6950 if (!sUserManager.exists(userId)) return null;
6951 final int callingUid = Binder.getCallingUid();
6952 flags = updateFlagsForResolve(
6953 flags, userId, intent, callingUid, false /*includeInstantApps*/);
6954 intent = updateIntentForResolve(intent);
6956 synchronized (mPackages) {
6957 // Try to find a matching persistent preferred activity.
6958 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6961 // If a persistent preferred activity matched, use it.
6966 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6967 // Get the list of preferred activities that handle the intent
6968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6969 List<PreferredActivity> prefs = pir != null
6970 ? pir.queryIntent(intent, resolvedType,
6971 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6974 if (prefs != null && prefs.size() > 0) {
6975 boolean changed = false;
6977 // First figure out how good the original match set is.
6978 // We will only allow preferred activities that came
6979 // from the same match quality.
6982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6984 final int N = query.size();
6985 for (int j=0; j<N; j++) {
6986 final ResolveInfo ri = query.get(j);
6987 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6988 + ": 0x" + Integer.toHexString(match));
6989 if (ri.match > match) {
6994 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6995 + Integer.toHexString(match));
6997 match &= IntentFilter.MATCH_CATEGORY_MASK;
6998 final int M = prefs.size();
6999 for (int i=0; i<M; i++) {
7000 final PreferredActivity pa = prefs.get(i);
7001 if (DEBUG_PREFERRED || debug) {
7002 Slog.v(TAG, "Checking PreferredActivity ds="
7003 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7004 + "\n component=" + pa.mPref.mComponent);
7005 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
7007 if (pa.mPref.mMatch != match) {
7008 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7009 + Integer.toHexString(pa.mPref.mMatch));
7012 // If it's not an "always" type preferred activity and that's what we're
7013 // looking for, skip it.
7014 if (always && !pa.mPref.mAlways) {
7015 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7018 final ActivityInfo ai = getActivityInfo(
7019 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7020 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7022 if (DEBUG_PREFERRED || debug) {
7023 Slog.v(TAG, "Found preferred activity:");
7025 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
7027 Slog.v(TAG, " null");
7031 // This previously registered preferred activity
7032 // component is no longer known. Most likely an update
7033 // to the app was installed and in the new version this
7034 // component no longer exists. Clean it up by removing
7035 // it from the preferred activities list, and skip it.
7036 Slog.w(TAG, "Removing dangling preferred activity: "
7037 + pa.mPref.mComponent);
7038 pir.removeFilter(pa);
7042 for (int j=0; j<N; j++) {
7043 final ResolveInfo ri = query.get(j);
7044 if (!ri.activityInfo.applicationInfo.packageName
7045 .equals(ai.applicationInfo.packageName)) {
7048 if (!ri.activityInfo.name.equals(ai.name)) {
7052 if (removeMatches) {
7053 pir.removeFilter(pa);
7055 if (DEBUG_PREFERRED) {
7056 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7061 // Okay we found a previously set preferred or last chosen app.
7062 // If the result set is different from when this
7063 // was created, and is not a subset of the preferred set, we need to
7064 // clear it and re-ask the user their preference, if we're looking for
7065 // an "always" type entry.
7066 if (always && !pa.mPref.sameSet(query)) {
7067 if (pa.mPref.isSuperset(query)) {
7068 // some components of the set are no longer present in
7069 // the query, but the preferred activity can still be reused
7070 if (DEBUG_PREFERRED) {
7071 Slog.i(TAG, "Result set changed, but PreferredActivity is"
7072 + " still valid as only non-preferred components"
7073 + " were removed for " + intent + " type "
7076 // remove obsolete components and re-add the up-to-date filter
7077 PreferredActivity freshPa = new PreferredActivity(pa,
7079 pa.mPref.discardObsoleteComponents(query),
7080 pa.mPref.mComponent,
7082 pir.removeFilter(pa);
7083 pir.addFilter(freshPa);
7087 "Result set changed, dropping preferred activity for "
7088 + intent + " type " + resolvedType);
7089 if (DEBUG_PREFERRED) {
7090 Slog.v(TAG, "Removing preferred activity since set changed "
7091 + pa.mPref.mComponent);
7093 pir.removeFilter(pa);
7094 // Re-add the filter as a "last chosen" entry (!always)
7095 PreferredActivity lastChosen = new PreferredActivity(
7096 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7097 pir.addFilter(lastChosen);
7103 // Yay! Either the set matched or we're looking for the last chosen
7104 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7105 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7111 if (DEBUG_PREFERRED) {
7112 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7114 scheduleWritePackageRestrictionsLocked(userId);
7119 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7124 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7127 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7129 mContext.enforceCallingOrSelfPermission(
7130 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7131 List<CrossProfileIntentFilter> matches =
7132 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7133 if (matches != null) {
7134 int size = matches.size();
7135 for (int i = 0; i < size; i++) {
7136 if (matches.get(i).getTargetUserId() == targetUserId) return true;
7139 if (hasWebURI(intent)) {
7140 // cross-profile app linking works only towards the parent.
7141 final int callingUid = Binder.getCallingUid();
7142 final UserInfo parent = getProfileParent(sourceUserId);
7143 synchronized(mPackages) {
7144 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7145 false /*includeInstantApps*/);
7146 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7147 intent, resolvedType, flags, sourceUserId, parent.id);
7148 return xpDomainInfo != null;
7154 private UserInfo getProfileParent(int userId) {
7155 final long identity = Binder.clearCallingIdentity();
7157 return sUserManager.getProfileParent(userId);
7159 Binder.restoreCallingIdentity(identity);
7163 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7164 String resolvedType, int userId) {
7165 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7166 if (resolver != null) {
7167 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7173 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7174 String resolvedType, int flags, int userId) {
7176 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7178 return new ParceledListSlice<>(
7179 queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7181 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7186 * Returns the package name of the calling Uid if it's an instant app. If it isn't
7187 * instant, returns {@code null}.
7189 private String getInstantAppPackageName(int callingUid) {
7190 synchronized (mPackages) {
7191 // If the caller is an isolated app use the owner's uid for the lookup.
7192 if (Process.isIsolated(callingUid)) {
7193 callingUid = mIsolatedOwners.get(callingUid);
7195 final int appId = UserHandle.getAppId(callingUid);
7196 final Object obj = mSettings.getUserIdLPr(appId);
7197 if (obj instanceof PackageSetting) {
7198 final PackageSetting ps = (PackageSetting) obj;
7199 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7200 return isInstantApp ? ps.pkg.packageName : null;
7206 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7207 String resolvedType, int flags, int userId) {
7208 return queryIntentActivitiesInternal(
7209 intent, resolvedType, flags, Binder.getCallingUid(), userId,
7210 false /*resolveForStart*/, true /*allowDynamicSplits*/);
7213 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7214 String resolvedType, int flags, int filterCallingUid, int userId,
7215 boolean resolveForStart, boolean allowDynamicSplits) {
7216 if (!sUserManager.exists(userId)) return Collections.emptyList();
7217 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7218 enforceCrossUserPermission(Binder.getCallingUid(), userId,
7219 false /* requireFullPermission */, false /* checkShell */,
7220 "query intent activities");
7221 final String pkgName = intent.getPackage();
7222 ComponentName comp = intent.getComponent();
7224 if (intent.getSelector() != null) {
7225 intent = intent.getSelector();
7226 comp = intent.getComponent();
7230 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7231 comp != null || pkgName != null /*onlyExposedExplicitly*/);
7233 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7234 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7236 // When specifying an explicit component, we prevent the activity from being
7237 // used when either 1) the calling package is normal and the activity is within
7238 // an ephemeral application or 2) the calling package is ephemeral and the
7239 // activity is not visible to ephemeral applications.
7240 final boolean matchInstantApp =
7241 (flags & PackageManager.MATCH_INSTANT) != 0;
7242 final boolean matchVisibleToInstantAppOnly =
7243 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7244 final boolean matchExplicitlyVisibleOnly =
7245 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7246 final boolean isCallerInstantApp =
7247 instantAppPkgName != null;
7248 final boolean isTargetSameInstantApp =
7249 comp.getPackageName().equals(instantAppPkgName);
7250 final boolean isTargetInstantApp =
7251 (ai.applicationInfo.privateFlags
7252 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7253 final boolean isTargetVisibleToInstantApp =
7254 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7255 final boolean isTargetExplicitlyVisibleToInstantApp =
7256 isTargetVisibleToInstantApp
7257 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7258 final boolean isTargetHiddenFromInstantApp =
7259 !isTargetVisibleToInstantApp
7260 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7261 final boolean blockResolution =
7262 !isTargetSameInstantApp
7263 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7264 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7265 && isTargetHiddenFromInstantApp));
7266 if (!blockResolution) {
7267 final ResolveInfo ri = new ResolveInfo();
7268 ri.activityInfo = ai;
7272 return applyPostResolutionFilter(
7273 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7277 boolean sortResult = false;
7278 boolean addEphemeral = false;
7279 List<ResolveInfo> result;
7280 final boolean ephemeralDisabled = isEphemeralDisabled();
7281 synchronized (mPackages) {
7282 if (pkgName == null) {
7283 List<CrossProfileIntentFilter> matchingFilters =
7284 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7285 // Check for results that need to skip the current profile.
7286 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
7287 resolvedType, flags, userId);
7288 if (xpResolveInfo != null) {
7289 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7290 xpResult.add(xpResolveInfo);
7291 return applyPostResolutionFilter(
7292 filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7293 allowDynamicSplits, filterCallingUid, userId);
7296 // Check for results in the current profile.
7297 result = filterIfNotSystemUser(mActivities.queryIntent(
7298 intent, resolvedType, flags, userId), userId);
7299 addEphemeral = !ephemeralDisabled
7300 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7301 // Check for cross profile results.
7302 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7303 xpResolveInfo = queryCrossProfileIntents(
7304 matchingFilters, intent, resolvedType, flags, userId,
7305 hasNonNegativePriorityResult);
7306 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7307 boolean isVisibleToUser = filterIfNotSystemUser(
7308 Collections.singletonList(xpResolveInfo), userId).size() > 0;
7309 if (isVisibleToUser) {
7310 result.add(xpResolveInfo);
7314 if (hasWebURI(intent)) {
7315 CrossProfileDomainInfo xpDomainInfo = null;
7316 final UserInfo parent = getProfileParent(userId);
7317 if (parent != null) {
7318 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7319 flags, userId, parent.id);
7321 if (xpDomainInfo != null) {
7322 if (xpResolveInfo != null) {
7323 // If we didn't remove it, the cross-profile ResolveInfo would be twice
7325 result.remove(xpResolveInfo);
7327 if (result.size() == 0 && !addEphemeral) {
7328 // No result in current profile, but found candidate in parent user.
7329 // And we are not going to add emphemeral app, so we can return the
7330 // result straight away.
7331 result.add(xpDomainInfo.resolveInfo);
7332 return applyPostResolutionFilter(result, instantAppPkgName,
7333 allowDynamicSplits, filterCallingUid, userId);
7335 } else if (result.size() <= 1 && !addEphemeral) {
7336 // No result in parent user and <= 1 result in current profile, and we
7337 // are not going to add emphemeral app, so we can return the result without
7338 // further processing.
7339 return applyPostResolutionFilter(result, instantAppPkgName,
7340 allowDynamicSplits, filterCallingUid, userId);
7342 // We have more than one candidate (combining results from current and parent
7343 // profile), so we need filtering and sorting.
7344 result = filterCandidatesWithDomainPreferredActivitiesLPr(
7345 intent, flags, result, xpDomainInfo, userId);
7349 final PackageParser.Package pkg = mPackages.get(pkgName);
7352 result = filterIfNotSystemUser(
7353 mActivities.queryIntentForPackage(
7354 intent, resolvedType, flags, pkg.activities, userId),
7357 if (result == null || result.size() == 0) {
7358 // the caller wants to resolve for a particular package; however, there
7359 // were no installed results, so, try to find an ephemeral result
7360 addEphemeral = !ephemeralDisabled
7361 && isInstantAppAllowed(
7362 intent, null /*result*/, userId, true /*skipPackageCheck*/);
7363 if (result == null) {
7364 result = new ArrayList<>();
7370 result = maybeAddInstantAppInstaller(
7371 result, intent, resolvedType, flags, userId, resolveForStart);
7374 Collections.sort(result, mResolvePrioritySorter);
7376 return applyPostResolutionFilter(
7377 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7380 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7381 String resolvedType, int flags, int userId, boolean resolveForStart) {
7382 // first, check to see if we've got an instant app already installed
7383 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7384 ResolveInfo localInstantApp = null;
7385 boolean blockResolution = false;
7386 if (!alreadyResolvedLocally) {
7387 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7389 | PackageManager.GET_RESOLVED_FILTER
7390 | PackageManager.MATCH_INSTANT
7391 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7393 for (int i = instantApps.size() - 1; i >= 0; --i) {
7394 final ResolveInfo info = instantApps.get(i);
7395 final String packageName = info.activityInfo.packageName;
7396 final PackageSetting ps = mSettings.mPackages.get(packageName);
7397 if (ps.getInstantApp(userId)) {
7398 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7399 final int status = (int)(packedStatus >> 32);
7400 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7401 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7402 // there's a local instant application installed, but, the user has
7403 // chosen to never use it; skip resolution and don't acknowledge
7404 // an instant application is even available
7405 if (DEBUG_EPHEMERAL) {
7406 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7408 blockResolution = true;
7411 // we have a locally installed instant application; skip resolution
7412 // but acknowledge there's an instant application available
7413 if (DEBUG_EPHEMERAL) {
7414 Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7416 localInstantApp = info;
7422 // no app installed, let's see if one's available
7423 AuxiliaryResolveInfo auxiliaryResponse = null;
7424 if (!blockResolution) {
7425 if (localInstantApp == null) {
7426 // we don't have an instant app locally, resolve externally
7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7428 final InstantAppRequest requestObject = new InstantAppRequest(
7429 null /*responseObj*/, intent /*origIntent*/, resolvedType,
7430 null /*callingPackage*/, userId, null /*verificationBundle*/,
7433 InstantAppResolver.doInstantAppResolutionPhaseOne(
7434 mContext, mInstantAppResolverConnection, requestObject);
7435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7437 // we have an instant application locally, but, we can't admit that since
7438 // callers shouldn't be able to determine prior browsing. create a dummy
7439 // auxiliary response so the downstream code behaves as if there's an
7440 // instant application available externally. when it comes time to start
7441 // the instant application, we'll do the right thing.
7442 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7443 auxiliaryResponse = new AuxiliaryResolveInfo(
7444 ai.packageName, null /*splitName*/, null /*failureActivity*/,
7445 ai.versionCode, null /*failureIntent*/);
7448 if (auxiliaryResponse != null) {
7449 if (DEBUG_EPHEMERAL) {
7450 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7452 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7453 final PackageSetting ps =
7454 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7456 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7457 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7458 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7459 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7460 // make sure this resolver is the default
7461 ephemeralInstaller.isDefault = true;
7462 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7463 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7464 // add a non-generic filter
7465 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7466 ephemeralInstaller.filter.addDataPath(
7467 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7468 ephemeralInstaller.isInstantAppAvailable = true;
7469 result.add(ephemeralInstaller);
7475 private static class CrossProfileDomainInfo {
7476 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7477 ResolveInfo resolveInfo;
7478 /* Best domain verification status of the activities found in the other profile */
7479 int bestDomainVerificationStatus;
7482 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7483 String resolvedType, int flags, int sourceUserId, int parentUserId) {
7484 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7488 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7489 resolvedType, flags, parentUserId);
7491 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7494 CrossProfileDomainInfo result = null;
7495 int size = resultTargetUser.size();
7496 for (int i = 0; i < size; i++) {
7497 ResolveInfo riTargetUser = resultTargetUser.get(i);
7498 // Intent filter verification is only for filters that specify a host. So don't return
7499 // those that handle all web uris.
7500 if (riTargetUser.handleAllWebDataURI) {
7503 String packageName = riTargetUser.activityInfo.packageName;
7504 PackageSetting ps = mSettings.mPackages.get(packageName);
7508 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7509 int status = (int)(verificationState >> 32);
7510 if (result == null) {
7511 result = new CrossProfileDomainInfo();
7512 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7513 sourceUserId, parentUserId);
7514 result.bestDomainVerificationStatus = status;
7516 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7517 result.bestDomainVerificationStatus);
7520 // Don't consider matches with status NEVER across profiles.
7521 if (result != null && result.bestDomainVerificationStatus
7522 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7529 * Verification statuses are ordered from the worse to the best, except for
7530 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7532 private int bestDomainVerificationStatus(int status1, int status2) {
7533 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7536 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7539 return (int) MathUtils.max(status1, status2);
7542 private boolean isUserEnabled(int userId) {
7543 long callingId = Binder.clearCallingIdentity();
7545 UserInfo userInfo = sUserManager.getUserInfo(userId);
7546 return userInfo != null && userInfo.isEnabled();
7548 Binder.restoreCallingIdentity(callingId);
7553 * Filter out activities with systemUserOnly flag set, when current user is not System.
7555 * @return filtered list
7557 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7558 if (userId == UserHandle.USER_SYSTEM) {
7559 return resolveInfos;
7561 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7562 ResolveInfo info = resolveInfos.get(i);
7563 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7564 resolveInfos.remove(i);
7567 return resolveInfos;
7571 * Filters out ephemeral activities.
7572 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7573 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7575 * @param resolveInfos The pre-filtered list of resolved activities
7576 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7578 * @return A filtered list of resolved activities.
7580 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7581 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7582 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7583 final ResolveInfo info = resolveInfos.get(i);
7584 // allow activities that are defined in the provided package
7585 if (allowDynamicSplits
7586 && info.activityInfo.splitName != null
7587 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7588 info.activityInfo.splitName)) {
7589 if (mInstantAppInstallerInfo == null) {
7590 if (DEBUG_INSTALL) {
7591 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
7593 resolveInfos.remove(i);
7596 // requested activity is defined in a split that hasn't been installed yet.
7597 // add the installer to the resolve list
7598 if (DEBUG_INSTALL) {
7599 Slog.v(TAG, "Adding installer to the ResolveInfo list");
7601 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7602 final ComponentName installFailureActivity = findInstallFailureActivity(
7603 info.activityInfo.packageName, filterCallingUid, userId);
7604 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7605 info.activityInfo.packageName, info.activityInfo.splitName,
7606 installFailureActivity,
7607 info.activityInfo.applicationInfo.versionCode,
7608 null /*failureIntent*/);
7609 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7610 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7611 // add a non-generic filter
7612 installerInfo.filter = new IntentFilter();
7614 // This resolve info may appear in the chooser UI, so let us make it
7615 // look as the one it replaces as far as the user is concerned which
7616 // requires loading the correct label and icon for the resolve info.
7617 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7618 installerInfo.labelRes = info.resolveLabelResId();
7619 installerInfo.icon = info.resolveIconResId();
7621 // propagate priority/preferred order/default
7622 installerInfo.priority = info.priority;
7623 installerInfo.preferredOrder = info.preferredOrder;
7624 installerInfo.isDefault = info.isDefault;
7625 resolveInfos.set(i, installerInfo);
7628 // caller is a full app, don't need to apply any other filtering
7629 if (ephemeralPkgName == null) {
7631 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7632 // caller is same app; don't need to apply any other filtering
7635 // allow activities that have been explicitly exposed to ephemeral apps
7636 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7638 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7641 resolveInfos.remove(i);
7643 return resolveInfos;
7647 * Returns the activity component that can handle install failures.
7648 * <p>By default, the instant application installer handles failures. However, an
7649 * application may want to handle failures on its own. Applications do this by
7650 * creating an activity with an intent filter that handles the action
7651 * {@link Intent#ACTION_INSTALL_FAILURE}.
7653 private @Nullable ComponentName findInstallFailureActivity(
7654 String packageName, int filterCallingUid, int userId) {
7655 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7656 failureActivityIntent.setPackage(packageName);
7657 // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7658 final List<ResolveInfo> result = queryIntentActivitiesInternal(
7659 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7660 false /*resolveForStart*/, false /*allowDynamicSplits*/);
7661 final int NR = result.size();
7663 for (int i = 0; i < NR; i++) {
7664 final ResolveInfo info = result.get(i);
7665 if (info.activityInfo.splitName != null) {
7668 return new ComponentName(packageName, info.activityInfo.name);
7675 * @param resolveInfos list of resolve infos in descending priority order
7676 * @return if the list contains a resolve info with non-negative priority
7678 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7679 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7682 private static boolean hasWebURI(Intent intent) {
7683 if (intent.getData() == null) {
7686 final String scheme = intent.getScheme();
7687 if (TextUtils.isEmpty(scheme)) {
7690 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7693 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7694 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7696 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7698 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7699 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7703 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7704 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7705 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7706 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7707 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7708 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7710 synchronized (mPackages) {
7711 final int count = candidates.size();
7712 // First, try to use linked apps. Partition the candidates into four lists:
7713 // one for the final results, one for the "do not use ever", one for "undefined status"
7714 // and finally one for "browser app type".
7715 for (int n=0; n<count; n++) {
7716 ResolveInfo info = candidates.get(n);
7717 String packageName = info.activityInfo.packageName;
7718 PackageSetting ps = mSettings.mPackages.get(packageName);
7720 // Add to the special match all list (Browser use case)
7721 if (info.handleAllWebDataURI) {
7722 matchAllList.add(info);
7725 // Try to get the status from User settings first
7726 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7727 int status = (int)(packedStatus >> 32);
7728 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7729 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7730 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7731 Slog.i(TAG, " + always: " + info.activityInfo.packageName
7732 + " : linkgen=" + linkGeneration);
7734 // Use link-enabled generation as preferredOrder, i.e.
7735 // prefer newly-enabled over earlier-enabled.
7736 info.preferredOrder = linkGeneration;
7737 alwaysList.add(info);
7738 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7739 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7740 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
7742 neverList.add(info);
7743 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7744 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7745 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
7747 alwaysAskList.add(info);
7748 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7749 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7750 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7751 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
7753 undefinedList.add(info);
7758 // We'll want to include browser possibilities in a few cases
7759 boolean includeBrowser = false;
7761 // First try to add the "always" resolution(s) for the current user, if any
7762 if (alwaysList.size() > 0) {
7763 result.addAll(alwaysList);
7765 // Add all undefined apps as we want them to appear in the disambiguation dialog.
7766 result.addAll(undefinedList);
7767 // Maybe add one for the other profile.
7768 if (xpDomainInfo != null && (
7769 xpDomainInfo.bestDomainVerificationStatus
7770 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7771 result.add(xpDomainInfo.resolveInfo);
7773 includeBrowser = true;
7776 // The presence of any 'always ask' alternatives means we'll also offer browsers.
7777 // If there were 'always' entries their preferred order has been set, so we also
7778 // back that off to make the alternatives equivalent
7779 if (alwaysAskList.size() > 0) {
7780 for (ResolveInfo i : result) {
7781 i.preferredOrder = 0;
7783 result.addAll(alwaysAskList);
7784 includeBrowser = true;
7787 if (includeBrowser) {
7788 // Also add browsers (all of them or only the default one)
7789 if (DEBUG_DOMAIN_VERIFICATION) {
7790 Slog.v(TAG, " ...including browsers in candidate set");
7792 if ((matchFlags & MATCH_ALL) != 0) {
7793 result.addAll(matchAllList);
7795 // Browser/generic handling case. If there's a default browser, go straight
7796 // to that (but only if there is no other higher-priority match).
7797 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7798 int maxMatchPrio = 0;
7799 ResolveInfo defaultBrowserMatch = null;
7800 final int numCandidates = matchAllList.size();
7801 for (int n = 0; n < numCandidates; n++) {
7802 ResolveInfo info = matchAllList.get(n);
7803 // track the highest overall match priority...
7804 if (info.priority > maxMatchPrio) {
7805 maxMatchPrio = info.priority;
7807 // ...and the highest-priority default browser match
7808 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7809 if (defaultBrowserMatch == null
7810 || (defaultBrowserMatch.priority < info.priority)) {
7812 Slog.v(TAG, "Considering default browser match " + info);
7814 defaultBrowserMatch = info;
7818 if (defaultBrowserMatch != null
7819 && defaultBrowserMatch.priority >= maxMatchPrio
7820 && !TextUtils.isEmpty(defaultBrowserPackageName))
7823 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7825 result.add(defaultBrowserMatch);
7827 result.addAll(matchAllList);
7831 // If there is nothing selected, add all candidates and remove the ones that the user
7832 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7833 if (result.size() == 0) {
7834 result.addAll(candidates);
7835 result.removeAll(neverList);
7839 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7840 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7842 for (ResolveInfo info : result) {
7843 Slog.v(TAG, " + " + info.activityInfo);
7849 // Returns a packed value as a long:
7851 // high 'int'-sized word: link status: undefined/ask/never/always.
7852 // low 'int'-sized word: relative priority among 'always' results.
7853 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7854 long result = ps.getDomainVerificationStatusForUser(userId);
7855 // if none available, get the master status
7856 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7857 if (ps.getIntentFilterVerificationInfo() != null) {
7858 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7864 private ResolveInfo querySkipCurrentProfileIntents(
7865 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7866 int flags, int sourceUserId) {
7867 if (matchingFilters != null) {
7868 int size = matchingFilters.size();
7869 for (int i = 0; i < size; i ++) {
7870 CrossProfileIntentFilter filter = matchingFilters.get(i);
7871 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7872 // Checking if there are activities in the target user that can handle the
7874 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7875 resolvedType, flags, sourceUserId);
7876 if (resolveInfo != null) {
7885 // Return matching ResolveInfo in target user if any.
7886 private ResolveInfo queryCrossProfileIntents(
7887 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7888 int flags, int sourceUserId, boolean matchInCurrentProfile) {
7889 if (matchingFilters != null) {
7890 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7891 // match the same intent. For performance reasons, it is better not to
7892 // run queryIntent twice for the same userId
7893 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7894 int size = matchingFilters.size();
7895 for (int i = 0; i < size; i++) {
7896 CrossProfileIntentFilter filter = matchingFilters.get(i);
7897 int targetUserId = filter.getTargetUserId();
7898 boolean skipCurrentProfile =
7899 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7900 boolean skipCurrentProfileIfNoMatchFound =
7901 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7902 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7903 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7904 // Checking if there are activities in the target user that can handle the
7906 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7907 resolvedType, flags, sourceUserId);
7908 if (resolveInfo != null) return resolveInfo;
7909 alreadyTriedUserIds.put(targetUserId, true);
7917 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7918 * will forward the intent to the filter's target user.
7919 * Otherwise, returns null.
7921 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7922 String resolvedType, int flags, int sourceUserId) {
7923 int targetUserId = filter.getTargetUserId();
7924 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7925 resolvedType, flags, targetUserId);
7926 if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7927 // If all the matches in the target profile are suspended, return null.
7928 for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7929 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7930 & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7931 return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7939 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7940 int sourceUserId, int targetUserId) {
7941 ResolveInfo forwardingResolveInfo = new ResolveInfo();
7942 long ident = Binder.clearCallingIdentity();
7943 boolean targetIsProfile;
7945 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7947 Binder.restoreCallingIdentity(ident);
7950 if (targetIsProfile) {
7951 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7953 className = FORWARD_INTENT_TO_PARENT;
7955 ComponentName forwardingActivityComponentName = new ComponentName(
7956 mAndroidApplication.packageName, className);
7957 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7959 if (!targetIsProfile) {
7960 forwardingActivityInfo.showUserIcon = targetUserId;
7961 forwardingResolveInfo.noResourceId = true;
7963 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7964 forwardingResolveInfo.priority = 0;
7965 forwardingResolveInfo.preferredOrder = 0;
7966 forwardingResolveInfo.match = 0;
7967 forwardingResolveInfo.isDefault = true;
7968 forwardingResolveInfo.filter = filter;
7969 forwardingResolveInfo.targetUserId = targetUserId;
7970 return forwardingResolveInfo;
7974 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7975 Intent[] specifics, String[] specificTypes, Intent intent,
7976 String resolvedType, int flags, int userId) {
7977 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7978 specificTypes, intent, resolvedType, flags, userId));
7981 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7982 Intent[] specifics, String[] specificTypes, Intent intent,
7983 String resolvedType, int flags, int userId) {
7984 if (!sUserManager.exists(userId)) return Collections.emptyList();
7985 final int callingUid = Binder.getCallingUid();
7986 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7987 false /*includeInstantApps*/);
7988 enforceCrossUserPermission(callingUid, userId,
7989 false /*requireFullPermission*/, false /*checkShell*/,
7990 "query intent activity options");
7991 final String resultsAction = intent.getAction();
7993 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7994 | PackageManager.GET_RESOLVED_FILTER, userId);
7996 if (DEBUG_INTENT_MATCHING) {
7997 Log.v(TAG, "Query " + intent + ": " + results);
8000 int specificsPos = 0;
8003 // todo: note that the algorithm used here is O(N^2). This
8004 // isn't a problem in our current environment, but if we start running
8005 // into situations where we have more than 5 or 10 matches then this
8006 // should probably be changed to something smarter...
8008 // First we go through and resolve each of the specific items
8009 // that were supplied, taking care of removing any corresponding
8010 // duplicate items in the generic resolve list.
8011 if (specifics != null) {
8012 for (int i=0; i<specifics.length; i++) {
8013 final Intent sintent = specifics[i];
8014 if (sintent == null) {
8018 if (DEBUG_INTENT_MATCHING) {
8019 Log.v(TAG, "Specific #" + i + ": " + sintent);
8022 String action = sintent.getAction();
8023 if (resultsAction != null && resultsAction.equals(action)) {
8024 // If this action was explicitly requested, then don't
8025 // remove things that have it.
8029 ResolveInfo ri = null;
8030 ActivityInfo ai = null;
8032 ComponentName comp = sintent.getComponent();
8036 specificTypes != null ? specificTypes[i] : null,
8041 if (ri == mResolveInfo) {
8042 // ACK! Must do something better with this.
8044 ai = ri.activityInfo;
8045 comp = new ComponentName(ai.applicationInfo.packageName,
8048 ai = getActivityInfo(comp, flags, userId);
8054 // Look for any generic query activities that are duplicates
8055 // of this specific one, and remove them from the results.
8056 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8059 for (j=specificsPos; j<N; j++) {
8060 ResolveInfo sri = results.get(j);
8061 if ((sri.activityInfo.name.equals(comp.getClassName())
8062 && sri.activityInfo.applicationInfo.packageName.equals(
8063 comp.getPackageName()))
8064 || (action != null && sri.filter.matchAction(action))) {
8066 if (DEBUG_INTENT_MATCHING) Log.v(
8067 TAG, "Removing duplicate item from " + j
8068 + " due to specific " + specificsPos);
8077 // Add this specific item to its proper place.
8079 ri = new ResolveInfo();
8080 ri.activityInfo = ai;
8082 results.add(specificsPos, ri);
8083 ri.specificIndex = i;
8088 // Now we go through the remaining generic results and remove any
8089 // duplicate actions that are found here.
8091 for (int i=specificsPos; i<N-1; i++) {
8092 final ResolveInfo rii = results.get(i);
8093 if (rii.filter == null) {
8097 // Iterate over all of the actions of this result's intent
8098 // filter... typically this should be just one.
8099 final Iterator<String> it = rii.filter.actionsIterator();
8103 while (it.hasNext()) {
8104 final String action = it.next();
8105 if (resultsAction != null && resultsAction.equals(action)) {
8106 // If this action was explicitly requested, then don't
8107 // remove things that have it.
8110 for (int j=i+1; j<N; j++) {
8111 final ResolveInfo rij = results.get(j);
8112 if (rij.filter != null && rij.filter.hasAction(action)) {
8114 if (DEBUG_INTENT_MATCHING) Log.v(
8115 TAG, "Removing duplicate item from " + j
8116 + " due to action " + action + " at " + i);
8123 // If the caller didn't request filter information, drop it now
8124 // so we don't have to marshall/unmarshall it.
8125 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8130 // Filter out the caller activity if so requested.
8131 if (caller != null) {
8133 for (int i=0; i<N; i++) {
8134 ActivityInfo ainfo = results.get(i).activityInfo;
8135 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8136 && caller.getClassName().equals(ainfo.name)) {
8143 // If the caller didn't request filter information,
8144 // drop them now so we don't have to
8145 // marshall/unmarshall it.
8146 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8148 for (int i=0; i<N; i++) {
8149 results.get(i).filter = null;
8153 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8158 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8159 String resolvedType, int flags, int userId) {
8160 return new ParceledListSlice<>(
8161 queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8162 false /*allowDynamicSplits*/));
8165 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8166 String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8167 if (!sUserManager.exists(userId)) return Collections.emptyList();
8168 final int callingUid = Binder.getCallingUid();
8169 enforceCrossUserPermission(callingUid, userId,
8170 false /*requireFullPermission*/, false /*checkShell*/,
8171 "query intent receivers");
8172 final String instantAppPkgName = getInstantAppPackageName(callingUid);
8173 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8174 false /*includeInstantApps*/);
8175 ComponentName comp = intent.getComponent();
8177 if (intent.getSelector() != null) {
8178 intent = intent.getSelector();
8179 comp = intent.getComponent();
8183 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8184 final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8186 // When specifying an explicit component, we prevent the activity from being
8187 // used when either 1) the calling package is normal and the activity is within
8188 // an instant application or 2) the calling package is ephemeral and the
8189 // activity is not visible to instant applications.
8190 final boolean matchInstantApp =
8191 (flags & PackageManager.MATCH_INSTANT) != 0;
8192 final boolean matchVisibleToInstantAppOnly =
8193 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8194 final boolean matchExplicitlyVisibleOnly =
8195 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8196 final boolean isCallerInstantApp =
8197 instantAppPkgName != null;
8198 final boolean isTargetSameInstantApp =
8199 comp.getPackageName().equals(instantAppPkgName);
8200 final boolean isTargetInstantApp =
8201 (ai.applicationInfo.privateFlags
8202 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8203 final boolean isTargetVisibleToInstantApp =
8204 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8205 final boolean isTargetExplicitlyVisibleToInstantApp =
8206 isTargetVisibleToInstantApp
8207 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8208 final boolean isTargetHiddenFromInstantApp =
8209 !isTargetVisibleToInstantApp
8210 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8211 final boolean blockResolution =
8212 !isTargetSameInstantApp
8213 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8214 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8215 && isTargetHiddenFromInstantApp));
8216 if (!blockResolution) {
8217 ResolveInfo ri = new ResolveInfo();
8218 ri.activityInfo = ai;
8222 return applyPostResolutionFilter(
8223 list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8227 synchronized (mPackages) {
8228 String pkgName = intent.getPackage();
8229 if (pkgName == null) {
8230 final List<ResolveInfo> result =
8231 mReceivers.queryIntent(intent, resolvedType, flags, userId);
8232 return applyPostResolutionFilter(
8233 result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8235 final PackageParser.Package pkg = mPackages.get(pkgName);
8237 final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8238 intent, resolvedType, flags, pkg.receivers, userId);
8239 return applyPostResolutionFilter(
8240 result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8242 return Collections.emptyList();
8247 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8248 final int callingUid = Binder.getCallingUid();
8249 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8252 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8253 int userId, int callingUid) {
8254 if (!sUserManager.exists(userId)) return null;
8255 flags = updateFlagsForResolve(
8256 flags, userId, intent, callingUid, false /*includeInstantApps*/);
8257 List<ResolveInfo> query = queryIntentServicesInternal(
8258 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8259 if (query != null) {
8260 if (query.size() >= 1) {
8261 // If there is more than one service with the same priority,
8262 // just arbitrarily pick the first one.
8263 return query.get(0);
8270 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8271 String resolvedType, int flags, int userId) {
8272 final int callingUid = Binder.getCallingUid();
8273 return new ParceledListSlice<>(queryIntentServicesInternal(
8274 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8277 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8278 String resolvedType, int flags, int userId, int callingUid,
8279 boolean includeInstantApps) {
8280 if (!sUserManager.exists(userId)) return Collections.emptyList();
8281 enforceCrossUserPermission(callingUid, userId,
8282 false /*requireFullPermission*/, false /*checkShell*/,
8283 "query intent receivers");
8284 final String instantAppPkgName = getInstantAppPackageName(callingUid);
8285 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8286 ComponentName comp = intent.getComponent();
8288 if (intent.getSelector() != null) {
8289 intent = intent.getSelector();
8290 comp = intent.getComponent();
8294 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8295 final ServiceInfo si = getServiceInfo(comp, flags, userId);
8297 // When specifying an explicit component, we prevent the service from being
8298 // used when either 1) the service is in an instant application and the
8299 // caller is not the same instant application or 2) the calling package is
8300 // ephemeral and the activity is not visible to ephemeral applications.
8301 final boolean matchInstantApp =
8302 (flags & PackageManager.MATCH_INSTANT) != 0;
8303 final boolean matchVisibleToInstantAppOnly =
8304 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8305 final boolean isCallerInstantApp =
8306 instantAppPkgName != null;
8307 final boolean isTargetSameInstantApp =
8308 comp.getPackageName().equals(instantAppPkgName);
8309 final boolean isTargetInstantApp =
8310 (si.applicationInfo.privateFlags
8311 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8312 final boolean isTargetHiddenFromInstantApp =
8313 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8314 final boolean blockResolution =
8315 !isTargetSameInstantApp
8316 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8317 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8318 && isTargetHiddenFromInstantApp));
8319 if (!blockResolution) {
8320 final ResolveInfo ri = new ResolveInfo();
8321 ri.serviceInfo = si;
8329 synchronized (mPackages) {
8330 String pkgName = intent.getPackage();
8331 if (pkgName == null) {
8332 return applyPostServiceResolutionFilter(
8333 mServices.queryIntent(intent, resolvedType, flags, userId),
8336 final PackageParser.Package pkg = mPackages.get(pkgName);
8338 return applyPostServiceResolutionFilter(
8339 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8343 return Collections.emptyList();
8347 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8348 String instantAppPkgName) {
8349 if (instantAppPkgName == null) {
8350 return resolveInfos;
8352 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8353 final ResolveInfo info = resolveInfos.get(i);
8354 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8355 // allow services that are defined in the provided package
8356 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8357 if (info.serviceInfo.splitName != null
8358 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8359 info.serviceInfo.splitName)) {
8360 // requested service is defined in a split that hasn't been installed yet.
8361 // add the installer to the resolve list
8362 if (DEBUG_EPHEMERAL) {
8363 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8365 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8366 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8367 info.serviceInfo.packageName, info.serviceInfo.splitName,
8368 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8369 null /*failureIntent*/);
8370 // make sure this resolver is the default
8371 installerInfo.isDefault = true;
8372 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8373 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8374 // add a non-generic filter
8375 installerInfo.filter = new IntentFilter();
8376 // load resources from the correct package
8377 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8378 resolveInfos.set(i, installerInfo);
8382 // allow services that have been explicitly exposed to ephemeral apps
8384 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8387 resolveInfos.remove(i);
8389 return resolveInfos;
8393 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8394 String resolvedType, int flags, int userId) {
8395 return new ParceledListSlice<>(
8396 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8399 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8400 Intent intent, String resolvedType, int flags, int userId) {
8401 if (!sUserManager.exists(userId)) return Collections.emptyList();
8402 final int callingUid = Binder.getCallingUid();
8403 final String instantAppPkgName = getInstantAppPackageName(callingUid);
8404 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8405 false /*includeInstantApps*/);
8406 ComponentName comp = intent.getComponent();
8408 if (intent.getSelector() != null) {
8409 intent = intent.getSelector();
8410 comp = intent.getComponent();
8414 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8415 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8417 // When specifying an explicit component, we prevent the provider from being
8418 // used when either 1) the provider is in an instant application and the
8419 // caller is not the same instant application or 2) the calling package is an
8420 // instant application and the provider is not visible to instant applications.
8421 final boolean matchInstantApp =
8422 (flags & PackageManager.MATCH_INSTANT) != 0;
8423 final boolean matchVisibleToInstantAppOnly =
8424 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8425 final boolean isCallerInstantApp =
8426 instantAppPkgName != null;
8427 final boolean isTargetSameInstantApp =
8428 comp.getPackageName().equals(instantAppPkgName);
8429 final boolean isTargetInstantApp =
8430 (pi.applicationInfo.privateFlags
8431 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8432 final boolean isTargetHiddenFromInstantApp =
8433 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8434 final boolean blockResolution =
8435 !isTargetSameInstantApp
8436 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8437 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8438 && isTargetHiddenFromInstantApp));
8439 if (!blockResolution) {
8440 final ResolveInfo ri = new ResolveInfo();
8441 ri.providerInfo = pi;
8449 synchronized (mPackages) {
8450 String pkgName = intent.getPackage();
8451 if (pkgName == null) {
8452 return applyPostContentProviderResolutionFilter(
8453 mProviders.queryIntent(intent, resolvedType, flags, userId),
8456 final PackageParser.Package pkg = mPackages.get(pkgName);
8458 return applyPostContentProviderResolutionFilter(
8459 mProviders.queryIntentForPackage(
8460 intent, resolvedType, flags, pkg.providers, userId),
8463 return Collections.emptyList();
8467 private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8468 List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8469 if (instantAppPkgName == null) {
8470 return resolveInfos;
8472 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8473 final ResolveInfo info = resolveInfos.get(i);
8474 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8475 // allow providers that are defined in the provided package
8476 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8477 if (info.providerInfo.splitName != null
8478 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8479 info.providerInfo.splitName)) {
8480 // requested provider is defined in a split that hasn't been installed yet.
8481 // add the installer to the resolve list
8482 if (DEBUG_EPHEMERAL) {
8483 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8485 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8486 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8487 info.providerInfo.packageName, info.providerInfo.splitName,
8488 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8489 null /*failureIntent*/);
8490 // make sure this resolver is the default
8491 installerInfo.isDefault = true;
8492 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8493 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8494 // add a non-generic filter
8495 installerInfo.filter = new IntentFilter();
8496 // load resources from the correct package
8497 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8498 resolveInfos.set(i, installerInfo);
8502 // allow providers that have been explicitly exposed to instant applications
8504 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8507 resolveInfos.remove(i);
8509 return resolveInfos;
8513 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8514 final int callingUid = Binder.getCallingUid();
8515 if (getInstantAppPackageName(callingUid) != null) {
8516 return ParceledListSlice.emptyList();
8518 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8519 flags = updateFlagsForPackage(flags, userId, null);
8520 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8521 enforceCrossUserPermission(callingUid, userId,
8522 true /* requireFullPermission */, false /* checkShell */,
8523 "get installed packages");
8526 synchronized (mPackages) {
8527 ArrayList<PackageInfo> list;
8528 if (listUninstalled) {
8529 list = new ArrayList<>(mSettings.mPackages.size());
8530 for (PackageSetting ps : mSettings.mPackages.values()) {
8531 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8534 if (filterAppAccessLPr(ps, callingUid, userId)) {
8537 final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8543 list = new ArrayList<>(mPackages.size());
8544 for (PackageParser.Package p : mPackages.values()) {
8545 final PackageSetting ps = (PackageSetting) p.mExtras;
8546 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8549 if (filterAppAccessLPr(ps, callingUid, userId)) {
8552 final PackageInfo pi = generatePackageInfo((PackageSetting)
8553 p.mExtras, flags, userId);
8560 return new ParceledListSlice<>(list);
8564 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8565 String[] permissions, boolean[] tmp, int flags, int userId) {
8567 final PermissionsState permissionsState = ps.getPermissionsState();
8568 for (int i=0; i<permissions.length; i++) {
8569 final String permission = permissions[i];
8570 if (permissionsState.hasPermission(permission, userId)) {
8577 if (numMatch == 0) {
8580 final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8582 // The above might return null in cases of uninstalled apps or install-state
8583 // skew across users/profiles.
8585 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8586 if (numMatch == permissions.length) {
8587 pi.requestedPermissions = permissions;
8589 pi.requestedPermissions = new String[numMatch];
8591 for (int i=0; i<permissions.length; i++) {
8593 pi.requestedPermissions[numMatch] = permissions[i];
8604 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8605 String[] permissions, int flags, int userId) {
8606 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8607 flags = updateFlagsForPackage(flags, userId, permissions);
8608 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8609 true /* requireFullPermission */, false /* checkShell */,
8610 "get packages holding permissions");
8611 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8614 synchronized (mPackages) {
8615 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8616 boolean[] tmpBools = new boolean[permissions.length];
8617 if (listUninstalled) {
8618 for (PackageSetting ps : mSettings.mPackages.values()) {
8619 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8623 for (PackageParser.Package pkg : mPackages.values()) {
8624 PackageSetting ps = (PackageSetting)pkg.mExtras;
8626 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8632 return new ParceledListSlice<PackageInfo>(list);
8637 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8638 final int callingUid = Binder.getCallingUid();
8639 if (getInstantAppPackageName(callingUid) != null) {
8640 return ParceledListSlice.emptyList();
8642 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8643 flags = updateFlagsForApplication(flags, userId, null);
8644 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8647 synchronized (mPackages) {
8648 ArrayList<ApplicationInfo> list;
8649 if (listUninstalled) {
8650 list = new ArrayList<>(mSettings.mPackages.size());
8651 for (PackageSetting ps : mSettings.mPackages.values()) {
8653 int effectiveFlags = flags;
8654 if (ps.isSystem()) {
8655 effectiveFlags |= PackageManager.MATCH_ANY_USER;
8657 if (ps.pkg != null) {
8658 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8661 if (filterAppAccessLPr(ps, callingUid, userId)) {
8664 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8665 ps.readUserState(userId), userId);
8667 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8670 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8671 // and already converts to externally visible package name
8672 ai = generateApplicationInfoFromSettingsLPw(ps.name,
8673 callingUid, effectiveFlags, userId);
8680 list = new ArrayList<>(mPackages.size());
8681 for (PackageParser.Package p : mPackages.values()) {
8682 if (p.mExtras != null) {
8683 PackageSetting ps = (PackageSetting) p.mExtras;
8684 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8687 if (filterAppAccessLPr(ps, callingUid, userId)) {
8690 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8691 ps.readUserState(userId), userId);
8693 ai.packageName = resolveExternalPackageNameLPr(p);
8700 return new ParceledListSlice<>(list);
8705 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8706 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8709 if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8710 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8711 "getEphemeralApplications");
8713 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8714 true /* requireFullPermission */, false /* checkShell */,
8715 "getEphemeralApplications");
8716 synchronized (mPackages) {
8717 List<InstantAppInfo> instantApps = mInstantAppRegistry
8718 .getInstantAppsLPr(userId);
8719 if (instantApps != null) {
8720 return new ParceledListSlice<>(instantApps);
8727 public boolean isInstantApp(String packageName, int userId) {
8728 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8729 true /* requireFullPermission */, false /* checkShell */,
8731 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8735 synchronized (mPackages) {
8736 int callingUid = Binder.getCallingUid();
8737 if (Process.isIsolated(callingUid)) {
8738 callingUid = mIsolatedOwners.get(callingUid);
8740 final PackageSetting ps = mSettings.mPackages.get(packageName);
8741 PackageParser.Package pkg = mPackages.get(packageName);
8742 final boolean returnAllowed =
8744 && (isCallerSameApp(packageName, callingUid)
8745 || canViewInstantApps(callingUid, userId)
8746 || mInstantAppRegistry.isInstantAccessGranted(
8747 userId, UserHandle.getAppId(callingUid), ps.appId));
8748 if (returnAllowed) {
8749 return ps.getInstantApp(userId);
8756 public byte[] getInstantAppCookie(String packageName, int userId) {
8757 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8761 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8762 true /* requireFullPermission */, false /* checkShell */,
8763 "getInstantAppCookie");
8764 if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8767 synchronized (mPackages) {
8768 return mInstantAppRegistry.getInstantAppCookieLPw(
8769 packageName, userId);
8774 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8775 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8779 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8780 true /* requireFullPermission */, true /* checkShell */,
8781 "setInstantAppCookie");
8782 if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8785 synchronized (mPackages) {
8786 return mInstantAppRegistry.setInstantAppCookieLPw(
8787 packageName, cookie, userId);
8792 public Bitmap getInstantAppIcon(String packageName, int userId) {
8793 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8797 if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8798 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8799 "getInstantAppIcon");
8801 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8802 true /* requireFullPermission */, false /* checkShell */,
8803 "getInstantAppIcon");
8805 synchronized (mPackages) {
8806 return mInstantAppRegistry.getInstantAppIconLPw(
8807 packageName, userId);
8811 private boolean isCallerSameApp(String packageName, int uid) {
8812 PackageParser.Package pkg = mPackages.get(packageName);
8814 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8818 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8819 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8820 return ParceledListSlice.emptyList();
8822 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8825 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8826 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8829 synchronized (mPackages) {
8830 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8831 final int userId = UserHandle.getCallingUserId();
8832 while (i.hasNext()) {
8833 final PackageParser.Package p = i.next();
8834 if (p.applicationInfo == null) continue;
8836 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8837 && !p.applicationInfo.isDirectBootAware();
8838 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8839 && p.applicationInfo.isDirectBootAware();
8841 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8842 && (!mSafeMode || isSystemApp(p))
8843 && (matchesUnaware || matchesAware)) {
8844 PackageSetting ps = mSettings.mPackages.get(p.packageName);
8846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8847 ps.readUserState(userId), userId);
8860 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8861 if (!sUserManager.exists(userId)) return null;
8862 flags = updateFlagsForComponent(flags, userId, name);
8863 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8865 synchronized (mPackages) {
8866 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8867 PackageSetting ps = provider != null
8868 ? mSettings.mPackages.get(provider.owner.packageName)
8871 final boolean isInstantApp = ps.getInstantApp(userId);
8872 // normal application; filter out instant application provider
8873 if (instantAppPkgName == null && isInstantApp) {
8876 // instant application; filter out other instant applications
8877 if (instantAppPkgName != null
8879 && !provider.owner.packageName.equals(instantAppPkgName)) {
8882 // instant application; filter out non-exposed provider
8883 if (instantAppPkgName != null
8885 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8888 // provider not enabled
8889 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8892 return PackageParser.generateProviderInfo(
8893 provider, flags, ps.readUserState(userId), userId);
8903 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8904 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8908 synchronized (mPackages) {
8909 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8910 .entrySet().iterator();
8911 final int userId = UserHandle.getCallingUserId();
8912 while (i.hasNext()) {
8913 Map.Entry<String, PackageParser.Provider> entry = i.next();
8914 PackageParser.Provider p = entry.getValue();
8915 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8917 if (ps != null && p.syncable
8918 && (!mSafeMode || (p.info.applicationInfo.flags
8919 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8920 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8921 ps.readUserState(userId), userId);
8923 outNames.add(entry.getKey());
8932 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8933 int uid, int flags, String metaDataKey) {
8934 final int callingUid = Binder.getCallingUid();
8935 final int userId = processName != null ? UserHandle.getUserId(uid)
8936 : UserHandle.getCallingUserId();
8937 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8938 flags = updateFlagsForComponent(flags, userId, processName);
8939 ArrayList<ProviderInfo> finalList = null;
8941 synchronized (mPackages) {
8942 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8943 while (i.hasNext()) {
8944 final PackageParser.Provider p = i.next();
8945 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8946 if (ps != null && p.info.authority != null
8947 && (processName == null
8948 || (p.info.processName.equals(processName)
8949 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8950 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8952 // See PM.queryContentProviders()'s javadoc for why we have the metaData
8954 if (metaDataKey != null
8955 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8958 final ComponentName component =
8959 new ComponentName(p.info.packageName, p.info.name);
8960 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8963 if (finalList == null) {
8964 finalList = new ArrayList<ProviderInfo>(3);
8966 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8967 ps.readUserState(userId), userId);
8969 finalList.add(info);
8975 if (finalList != null) {
8976 Collections.sort(finalList, mProviderInitOrderSorter);
8977 return new ParceledListSlice<ProviderInfo>(finalList);
8980 return ParceledListSlice.emptyList();
8984 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8986 synchronized (mPackages) {
8987 final int callingUid = Binder.getCallingUid();
8988 final int callingUserId = UserHandle.getUserId(callingUid);
8989 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8990 if (ps == null) return null;
8991 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8994 final PackageParser.Instrumentation i = mInstrumentation.get(component);
8995 return PackageParser.generateInstrumentationInfo(i, flags);
9000 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
9001 String targetPackage, int flags) {
9002 final int callingUid = Binder.getCallingUid();
9003 final int callingUserId = UserHandle.getUserId(callingUid);
9004 final PackageSetting ps = mSettings.mPackages.get(targetPackage);
9005 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
9006 return ParceledListSlice.emptyList();
9008 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9011 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9013 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9016 synchronized (mPackages) {
9017 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9018 while (i.hasNext()) {
9019 final PackageParser.Instrumentation p = i.next();
9020 if (targetPackage == null
9021 || targetPackage.equals(p.info.targetPackage)) {
9022 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9034 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9035 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9037 scanDirLI(dir, parseFlags, scanFlags, currentTime);
9039 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9043 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9044 final File[] files = dir.listFiles();
9045 if (ArrayUtils.isEmpty(files)) {
9046 Log.d(TAG, "No files in app dir " + dir);
9050 if (DEBUG_PACKAGE_SCANNING) {
9051 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9052 + " flags=0x" + Integer.toHexString(parseFlags));
9054 ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9055 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9056 mParallelPackageParserCallback);
9058 // Submit files for parsing in parallel
9060 for (File file : files) {
9061 final boolean isPackage = (isApkFile(file) || file.isDirectory())
9062 && !PackageInstallerService.isStageName(file.getName());
9064 // Ignore entries which are not packages
9067 parallelPackageParser.submit(file, parseFlags);
9071 // Process results one by one
9072 for (; fileCount > 0; fileCount--) {
9073 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9074 Throwable throwable = parseResult.throwable;
9075 int errorCode = PackageManager.INSTALL_SUCCEEDED;
9077 if (throwable == null) {
9078 // Static shared libraries have synthetic package names
9079 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9080 renameStaticSharedLibraryPackage(parseResult.pkg);
9083 if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9084 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9087 } catch (PackageManagerException e) {
9088 errorCode = e.error;
9089 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9091 } else if (throwable instanceof PackageParser.PackageParserException) {
9092 PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9094 errorCode = e.error;
9095 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9097 throw new IllegalStateException("Unexpected exception occurred while parsing "
9098 + parseResult.scanFile, throwable);
9101 // Delete invalid userdata apps
9102 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9103 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9104 logCriticalInfo(Log.WARN,
9105 "Deleting invalid package at " + parseResult.scanFile);
9106 removeCodePathLI(parseResult.scanFile);
9109 parallelPackageParser.close();
9112 private static File getSettingsProblemFile() {
9113 File dataDir = Environment.getDataDirectory();
9114 File systemDir = new File(dataDir, "system");
9115 File fname = new File(systemDir, "uiderrors.txt");
9119 static void reportSettingsProblem(int priority, String msg) {
9120 logCriticalInfo(priority, msg);
9123 public static void logCriticalInfo(int priority, String msg) {
9124 Slog.println(priority, TAG, msg);
9125 EventLogTags.writePmCriticalInfo(msg);
9127 File fname = getSettingsProblemFile();
9128 FileOutputStream out = new FileOutputStream(fname, true);
9129 PrintWriter pw = new FastPrintWriter(out);
9130 SimpleDateFormat formatter = new SimpleDateFormat();
9131 String dateString = formatter.format(new Date(System.currentTimeMillis()));
9132 pw.println(dateString + ": " + msg);
9134 FileUtils.setPermissions(
9136 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9138 } catch (java.io.IOException e) {
9142 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9143 if (srcFile.isDirectory()) {
9144 final File baseFile = new File(pkg.baseCodePath);
9145 long maxModifiedTime = baseFile.lastModified();
9146 if (pkg.splitCodePaths != null) {
9147 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9148 final File splitFile = new File(pkg.splitCodePaths[i]);
9149 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9152 return maxModifiedTime;
9154 return srcFile.lastModified();
9157 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9158 final int policyFlags) throws PackageManagerException {
9159 // When upgrading from pre-N MR1, verify the package time stamp using the package
9160 // directory and not the APK file.
9161 final long lastModifiedTime = mIsPreNMR1Upgrade
9162 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9164 && ps.codePath.equals(srcFile)
9165 && ps.timeStamp == lastModifiedTime
9166 && !isCompatSignatureUpdateNeeded(pkg)
9167 && !isRecoverSignatureUpdateNeeded(pkg)) {
9168 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9169 KeySetManagerService ksms = mSettings.mKeySetManagerService;
9170 ArraySet<PublicKey> signingKs;
9171 synchronized (mPackages) {
9172 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9174 if (ps.signatures.mSignatures != null
9175 && ps.signatures.mSignatures.length != 0
9176 && signingKs != null) {
9177 // Optimization: reuse the existing cached certificates
9178 // if the package appears to be unchanged.
9179 pkg.mSignatures = ps.signatures.mSignatures;
9180 pkg.mSigningKeys = signingKs;
9184 Slog.w(TAG, "PackageSetting for " + ps.name
9185 + " is missing signatures. Collecting certs again to recover them.");
9187 Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9191 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9192 PackageParser.collectCertificates(pkg, policyFlags);
9193 } catch (PackageParserException e) {
9194 throw PackageManagerException.from(e);
9196 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9201 * Traces a package scan.
9202 * @see #scanPackageLI(File, int, int, long, UserHandle)
9204 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9205 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9206 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9208 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9215 * Scans a package and returns the newly parsed package.
9216 * Returns {@code null} in case of errors and the error code is stored in mLastScanError
9218 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9219 long currentTime, UserHandle user) throws PackageManagerException {
9220 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9221 PackageParser pp = new PackageParser();
9222 pp.setSeparateProcesses(mSeparateProcesses);
9223 pp.setOnlyCoreApps(mOnlyCore);
9224 pp.setDisplayMetrics(mMetrics);
9225 pp.setCallback(mPackageParserCallback);
9227 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9228 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9232 final PackageParser.Package pkg;
9234 pkg = pp.parsePackage(scanFile, parseFlags);
9235 } catch (PackageParserException e) {
9236 throw PackageManagerException.from(e);
9238 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9241 // Static shared libraries have synthetic package names
9242 if (pkg.applicationInfo.isStaticSharedLibrary()) {
9243 renameStaticSharedLibraryPackage(pkg);
9246 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9250 * Scans a package and returns the newly parsed package.
9251 * @throws PackageManagerException on a parse error.
9253 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9254 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9255 throws PackageManagerException {
9256 // If the package has children and this is the first dive in the function
9257 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9258 // packages (parent and children) would be successfully scanned before the
9259 // actual scan since scanning mutates internal state and we want to atomically
9260 // install the package and its children.
9261 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9262 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9263 scanFlags |= SCAN_CHECK_ONLY;
9266 scanFlags &= ~SCAN_CHECK_ONLY;
9270 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9271 scanFlags, currentTime, user);
9273 // Scan the children
9274 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9275 for (int i = 0; i < childCount; i++) {
9276 PackageParser.Package childPackage = pkg.childPackages.get(i);
9277 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9282 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9283 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9290 * Scans a package and returns the newly parsed package.
9291 * @throws PackageManagerException on a parse error.
9293 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9294 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9295 throws PackageManagerException {
9296 PackageSetting ps = null;
9297 PackageSetting updatedPkg;
9299 synchronized (mPackages) {
9300 // Look to see if we already know about this package.
9301 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9302 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9303 // This package has been renamed to its original name. Let's
9305 ps = mSettings.getPackageLPr(oldName);
9307 // If there was no original package, see one for the real package name.
9309 ps = mSettings.getPackageLPr(pkg.packageName);
9311 // Check to see if this package could be hiding/updating a system
9312 // package. Must look for it either under the original or real
9313 // package name depending on our state.
9314 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9315 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9317 // If this is a package we don't know about on the system partition, we
9318 // may need to remove disabled child packages on the system partition
9319 // or may need to not add child packages if the parent apk is updated
9320 // on the data partition and no longer defines this child package.
9321 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9322 // If this is a parent package for an updated system app and this system
9323 // app got an OTA update which no longer defines some of the child packages
9324 // we have to prune them from the disabled system packages.
9325 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9326 if (disabledPs != null) {
9327 final int scannedChildCount = (pkg.childPackages != null)
9328 ? pkg.childPackages.size() : 0;
9329 final int disabledChildCount = disabledPs.childPackageNames != null
9330 ? disabledPs.childPackageNames.size() : 0;
9331 for (int i = 0; i < disabledChildCount; i++) {
9332 String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9333 boolean disabledPackageAvailable = false;
9334 for (int j = 0; j < scannedChildCount; j++) {
9335 PackageParser.Package childPkg = pkg.childPackages.get(j);
9336 if (childPkg.packageName.equals(disabledChildPackageName)) {
9337 disabledPackageAvailable = true;
9341 if (!disabledPackageAvailable) {
9342 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9349 final boolean isUpdatedPkg = updatedPkg != null;
9350 final boolean isUpdatedSystemPkg = isUpdatedPkg
9351 && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9352 boolean isUpdatedPkgBetter = false;
9353 // First check if this is a system package that may involve an update
9354 if (isUpdatedSystemPkg) {
9355 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9356 // it needs to drop FLAG_PRIVILEGED.
9357 if (locationIsPrivileged(scanFile)) {
9358 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9360 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9363 if (ps != null && !ps.codePath.equals(scanFile)) {
9364 // The path has changed from what was last scanned... check the
9365 // version of the new path against what we have stored to determine
9367 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9368 if (pkg.mVersionCode <= ps.versionCode) {
9369 // The system package has been updated and the code path does not match
9370 // Ignore entry. Skip it.
9371 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9372 + " ignored: updated version " + ps.versionCode
9373 + " better than this " + pkg.mVersionCode);
9374 if (!updatedPkg.codePath.equals(scanFile)) {
9375 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9376 + ps.name + " changing from " + updatedPkg.codePathString
9377 + " to " + scanFile);
9378 updatedPkg.codePath = scanFile;
9379 updatedPkg.codePathString = scanFile.toString();
9380 updatedPkg.resourcePath = scanFile;
9381 updatedPkg.resourcePathString = scanFile.toString();
9383 updatedPkg.pkg = pkg;
9384 updatedPkg.versionCode = pkg.mVersionCode;
9386 // Update the disabled system child packages to point to the package too.
9387 final int childCount = updatedPkg.childPackageNames != null
9388 ? updatedPkg.childPackageNames.size() : 0;
9389 for (int i = 0; i < childCount; i++) {
9390 String childPackageName = updatedPkg.childPackageNames.get(i);
9391 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9393 if (updatedChildPkg != null) {
9394 updatedChildPkg.pkg = pkg;
9395 updatedChildPkg.versionCode = pkg.mVersionCode;
9399 // The current app on the system partition is better than
9400 // what we have updated to on the data partition; switch
9401 // back to the system partition version.
9402 // At this point, its safely assumed that package installation for
9403 // apps in system partition will go through. If not there won't be a working
9404 // version of the app
9406 synchronized (mPackages) {
9407 // Just remove the loaded entries from package lists.
9408 mPackages.remove(ps.name);
9411 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9412 + " reverting from " + ps.codePathString
9413 + ": new version " + pkg.mVersionCode
9414 + " better than installed " + ps.versionCode);
9416 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9417 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9418 synchronized (mInstallLock) {
9419 args.cleanUpResourcesLI();
9421 synchronized (mPackages) {
9422 mSettings.enableSystemPackageLPw(ps.name);
9424 isUpdatedPkgBetter = true;
9429 String resourcePath = null;
9430 String baseResourcePath = null;
9431 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9432 if (ps != null && ps.resourcePathString != null) {
9433 resourcePath = ps.resourcePathString;
9434 baseResourcePath = ps.resourcePathString;
9436 // Should not happen at all. Just log an error.
9437 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9440 resourcePath = pkg.codePath;
9441 baseResourcePath = pkg.baseCodePath;
9444 // Set application objects path explicitly.
9445 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9446 pkg.setApplicationInfoCodePath(pkg.codePath);
9447 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9448 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9449 pkg.setApplicationInfoResourcePath(resourcePath);
9450 pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9451 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9453 // throw an exception if we have an update to a system application, but, it's not more
9454 // recent than the package we've already scanned
9455 if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9456 // Set CPU Abis to application info.
9457 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9458 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9459 derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9461 pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9462 pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9465 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9466 + scanFile + " ignored: updated version " + ps.versionCode
9467 + " better than this " + pkg.mVersionCode);
9471 // An updated system app will not have the PARSE_IS_SYSTEM flag set
9473 policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9475 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9476 // flag set initially
9477 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9478 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9482 // Verify certificates against what was last scanned
9483 collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9486 * A new system app appeared, but we already had a non-system one of the
9487 * same name installed earlier.
9489 boolean shouldHideSystemApp = false;
9490 if (!isUpdatedPkg && ps != null
9491 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9493 * Check to make sure the signatures match first. If they don't,
9494 * wipe the installed application and its data.
9496 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9497 != PackageManager.SIGNATURE_MATCH) {
9498 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9499 + " signatures don't match existing userdata copy; removing");
9500 try (PackageFreezer freezer = freezePackage(pkg.packageName,
9501 "scanPackageInternalLI")) {
9502 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9507 * If the newly-added system app is an older version than the
9508 * already installed version, hide it. It will be scanned later
9509 * and re-added like an update.
9511 if (pkg.mVersionCode <= ps.versionCode) {
9512 shouldHideSystemApp = true;
9513 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9514 + " but new version " + pkg.mVersionCode + " better than installed "
9515 + ps.versionCode + "; hiding system");
9518 * The newly found system app is a newer version that the
9519 * one previously installed. Simply remove the
9520 * already-installed application and replace it with our own
9521 * while keeping the application data.
9523 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9524 + " reverting from " + ps.codePathString + ": new version "
9525 + pkg.mVersionCode + " better than installed " + ps.versionCode);
9526 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9527 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9528 synchronized (mInstallLock) {
9529 args.cleanUpResourcesLI();
9535 // The apk is forward locked (not public) if its code and resources
9536 // are kept in different files. (except for app in either system or
9538 // TODO grab this value from PackageSettings
9539 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9540 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9541 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9545 final int userId = ((user == null) ? 0 : user.getIdentifier());
9546 if (ps != null && ps.getInstantApp(userId)) {
9547 scanFlags |= SCAN_AS_INSTANT_APP;
9549 if (ps != null && ps.getVirtulalPreload(userId)) {
9550 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9553 // Note that we invoke the following method only if we are about to unpack an application
9554 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9555 | SCAN_UPDATE_SIGNATURE, currentTime, user);
9558 * If the system app should be overridden by a previously installed
9559 * data, hide the system app now and let the /data/app scan pick it up
9562 if (shouldHideSystemApp) {
9563 synchronized (mPackages) {
9564 mSettings.disableSystemPackageLPw(pkg.packageName, true);
9571 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9572 // Derive the new package synthetic package name
9573 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9574 + pkg.staticSharedLibVersion);
9577 private static String fixProcessName(String defProcessName,
9578 String processName) {
9579 if (processName == null) {
9580 return defProcessName;
9585 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9586 throws PackageManagerException {
9587 if (pkgSetting.signatures.mSignatures != null) {
9588 // Already existing package. Make sure signatures match
9589 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9590 == PackageManager.SIGNATURE_MATCH;
9592 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9593 == PackageManager.SIGNATURE_MATCH;
9596 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9597 == PackageManager.SIGNATURE_MATCH;
9600 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9601 + pkg.packageName + " signatures do not match the "
9602 + "previously installed version; ignoring!");
9606 // Check for shared user signatures
9607 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9608 // Already existing package. Make sure signatures match
9609 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9610 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9612 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9613 == PackageManager.SIGNATURE_MATCH;
9616 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9617 == PackageManager.SIGNATURE_MATCH;
9620 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9621 "Package " + pkg.packageName
9622 + " has no signatures that match those in shared user "
9623 + pkgSetting.sharedUser.name + "; ignoring!");
9629 * Enforces that only the system UID or root's UID can call a method exposed
9632 * @param message used as message if SecurityException is thrown
9633 * @throws SecurityException if the caller is not system or root
9635 private static final void enforceSystemOrRoot(String message) {
9636 final int uid = Binder.getCallingUid();
9637 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9638 throw new SecurityException(message);
9643 public void performFstrimIfNeeded() {
9644 enforceSystemOrRoot("Only the system can request fstrim");
9646 // Before everything else, see whether we need to fstrim.
9648 IStorageManager sm = PackageHelper.getStorageManager();
9650 boolean doTrim = false;
9651 final long interval = android.provider.Settings.Global.getLong(
9652 mContext.getContentResolver(),
9653 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9654 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9656 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9657 if (timeSinceLast > interval) {
9659 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9660 + "; running immediately");
9664 final boolean dexOptDialogShown;
9665 synchronized (mPackages) {
9666 dexOptDialogShown = mDexOptDialogShown;
9668 if (!isFirstBoot() && dexOptDialogShown) {
9670 ActivityManager.getService().showBootMessage(
9671 mContext.getResources().getString(
9672 R.string.android_upgrading_fstrim), true);
9673 } catch (RemoteException e) {
9676 sm.runMaintenance();
9679 Slog.e(TAG, "storageManager service unavailable!");
9681 } catch (RemoteException e) {
9682 // Can't happen; StorageManagerService is local
9687 public void updatePackagesIfNeeded() {
9688 enforceSystemOrRoot("Only the system can request package update");
9690 // We need to re-extract after an OTA.
9691 boolean causeUpgrade = isUpgrade();
9693 // First boot or factory reset.
9694 // Note: we also handle devices that are upgrading to N right now as if it is their
9695 // first boot, as they do not have profile data.
9696 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9698 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9699 boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9701 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9705 List<PackageParser.Package> pkgs;
9706 synchronized (mPackages) {
9707 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9710 final long startTime = System.nanoTime();
9711 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9712 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9713 false /* bootComplete */);
9715 final int elapsedTimeSeconds =
9716 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9718 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9719 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9720 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9721 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9722 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9726 * Return the prebuilt profile path given a package base code path.
9728 private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9729 return pkg.baseCodePath + ".prof";
9733 * Performs dexopt on the set of packages in {@code packages} and returns an int array
9734 * containing statistics about the invocation. The array consists of three elements,
9735 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9736 * and {@code numberOfPackagesFailed}.
9738 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9739 final String compilerFilter, boolean bootComplete) {
9741 int numberOfPackagesVisited = 0;
9742 int numberOfPackagesOptimized = 0;
9743 int numberOfPackagesSkipped = 0;
9744 int numberOfPackagesFailed = 0;
9745 final int numberOfPackagesToDexopt = pkgs.size();
9747 for (PackageParser.Package pkg : pkgs) {
9748 numberOfPackagesVisited++;
9750 boolean useProfileForDexopt = false;
9752 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9753 // Copy over initial preopt profiles since we won't get any JIT samples for methods
9754 // that are already compiled.
9755 File profileFile = new File(getPrebuildProfilePath(pkg));
9756 // Copy profile if it exists.
9757 if (profileFile.exists()) {
9759 // We could also do this lazily before calling dexopt in
9760 // PackageDexOptimizer to prevent this happening on first boot. The issue
9761 // is that we don't have a good way to say "do this only once".
9762 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9763 pkg.applicationInfo.uid, pkg.packageName)) {
9764 Log.e(TAG, "Installer failed to copy system profile!");
9766 // Disabled as this causes speed-profile compilation during first boot
9767 // even if things are already compiled.
9768 // useProfileForDexopt = true;
9770 } catch (Exception e) {
9771 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9775 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9776 // Handle compressed APKs in this path. Only do this for stubs with profiles to
9777 // minimize the number off apps being speed-profile compiled during first boot.
9778 // The other paths will not change the filter.
9779 if (disabledPs != null && disabledPs.pkg.isStub) {
9780 // The package is the stub one, remove the stub suffix to get the normal
9781 // package and APK names.
9782 String systemProfilePath =
9783 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9784 profileFile = new File(systemProfilePath);
9785 // If we have a profile for a compressed APK, copy it to the reference
9787 // Note that copying the profile here will cause it to override the
9788 // reference profile every OTA even though the existing reference profile
9789 // may have more data. We can't copy during decompression since the
9790 // directories are not set up at that point.
9791 if (profileFile.exists()) {
9793 // We could also do this lazily before calling dexopt in
9794 // PackageDexOptimizer to prevent this happening on first boot. The
9795 // issue is that we don't have a good way to say "do this only
9797 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9798 pkg.applicationInfo.uid, pkg.packageName)) {
9799 Log.e(TAG, "Failed to copy system profile for stub package!");
9801 useProfileForDexopt = true;
9803 } catch (Exception e) {
9804 Log.e(TAG, "Failed to copy profile " +
9805 profileFile.getAbsolutePath() + " ", e);
9812 if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9814 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9816 numberOfPackagesSkipped++;
9821 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9822 numberOfPackagesToDexopt + ": " + pkg.packageName);
9827 ActivityManager.getService().showBootMessage(
9828 mContext.getResources().getString(R.string.android_upgrading_apk,
9829 numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9830 } catch (RemoteException e) {
9832 synchronized (mPackages) {
9833 mDexOptDialogShown = true;
9837 String pkgCompilerFilter = compilerFilter;
9838 if (useProfileForDexopt) {
9839 // Use background dexopt mode to try and use the profile. Note that this does not
9840 // guarantee usage of the profile.
9842 PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9843 PackageManagerService.REASON_BACKGROUND_DEXOPT);
9846 // checkProfiles is false to avoid merging profiles during boot which
9847 // might interfere with background compilation (b/28612421).
9848 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9849 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9850 // trade-off worth doing to save boot time work.
9851 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9852 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9857 switch (primaryDexOptStaus) {
9858 case PackageDexOptimizer.DEX_OPT_PERFORMED:
9859 numberOfPackagesOptimized++;
9861 case PackageDexOptimizer.DEX_OPT_SKIPPED:
9862 numberOfPackagesSkipped++;
9864 case PackageDexOptimizer.DEX_OPT_FAILED:
9865 numberOfPackagesFailed++;
9868 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9873 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9874 numberOfPackagesFailed };
9878 public void notifyPackageUse(String packageName, int reason) {
9879 synchronized (mPackages) {
9880 final int callingUid = Binder.getCallingUid();
9881 final int callingUserId = UserHandle.getUserId(callingUid);
9882 if (getInstantAppPackageName(callingUid) != null) {
9883 if (!isCallerSameApp(packageName, callingUid)) {
9887 if (isInstantApp(packageName, callingUserId)) {
9891 notifyPackageUseLocked(packageName, reason);
9895 private void notifyPackageUseLocked(String packageName, int reason) {
9896 final PackageParser.Package p = mPackages.get(packageName);
9900 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9904 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9905 List<String> classPaths, String loaderIsa) {
9906 int userId = UserHandle.getCallingUserId();
9907 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9909 Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9910 + loadingPackageName + ", user=" + userId);
9913 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9917 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9918 IDexModuleRegisterCallback callback) {
9919 int userId = UserHandle.getCallingUserId();
9920 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9921 DexManager.RegisterDexModuleResult result;
9923 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9924 " calling user. package=" + packageName + ", user=" + userId);
9925 result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9927 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9930 if (callback != null) {
9931 mHandler.post(() -> {
9933 callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9934 } catch (RemoteException e) {
9935 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9942 * Ask the package manager to perform a dex-opt with the given compiler filter.
9944 * Note: exposed only for the shell command to allow moving packages explicitly to a
9948 public boolean performDexOptMode(String packageName,
9949 boolean checkProfiles, String targetCompilerFilter, boolean force,
9950 boolean bootComplete, String splitName) {
9951 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9952 (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9953 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9954 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9959 * Ask the package manager to perform a dex-opt with the given compiler filter on the
9960 * secondary dex files belonging to the given package.
9962 * Note: exposed only for the shell command to allow moving packages explicitly to a
9966 public boolean performDexOptSecondary(String packageName, String compilerFilter,
9968 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9969 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9970 DexoptOptions.DEXOPT_BOOT_COMPLETE |
9971 (force ? DexoptOptions.DEXOPT_FORCE : 0);
9972 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9975 /*package*/ boolean performDexOpt(DexoptOptions options) {
9976 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9978 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9982 if (options.isDexoptOnlySecondaryDex()) {
9983 return mDexManager.dexoptSecondaryDex(options);
9985 int dexoptStatus = performDexOptWithStatus(options);
9986 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9991 * Perform dexopt on the given package and return one of following result:
9992 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9993 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9994 * {@link PackageDexOptimizer#DEX_OPT_FAILED}
9996 /* package */ int performDexOptWithStatus(DexoptOptions options) {
9997 return performDexOptTraced(options);
10000 private int performDexOptTraced(DexoptOptions options) {
10001 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10003 return performDexOptInternal(options);
10005 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10009 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
10010 // if the package can now be considered up to date for the given filter.
10011 private int performDexOptInternal(DexoptOptions options) {
10012 PackageParser.Package p;
10013 synchronized (mPackages) {
10014 p = mPackages.get(options.getPackageName());
10016 // Package could not be found. Report failure.
10017 return PackageDexOptimizer.DEX_OPT_FAILED;
10019 mPackageUsage.maybeWriteAsync(mPackages);
10020 mCompilerStats.maybeWriteAsync();
10022 long callingId = Binder.clearCallingIdentity();
10024 synchronized (mInstallLock) {
10025 return performDexOptInternalWithDependenciesLI(p, options);
10028 Binder.restoreCallingIdentity(callingId);
10032 public ArraySet<String> getOptimizablePackages() {
10033 ArraySet<String> pkgs = new ArraySet<String>();
10034 synchronized (mPackages) {
10035 for (PackageParser.Package p : mPackages.values()) {
10036 if (PackageDexOptimizer.canOptimizePackage(p)) {
10037 pkgs.add(p.packageName);
10044 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10045 DexoptOptions options) {
10046 // Select the dex optimizer based on the force parameter.
10047 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10048 // allocate an object here.
10049 PackageDexOptimizer pdo = options.isForce()
10050 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10051 : mPackageDexOptimizer;
10053 // Dexopt all dependencies first. Note: we ignore the return value and march on
10055 // Note that we are going to call performDexOpt on those libraries as many times as
10056 // they are referenced in packages. When we do a batch of performDexOpt (for example
10057 // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10058 // and the first package that uses the library will dexopt it. The
10059 // others will see that the compiled code for the library is up to date.
10060 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10061 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10062 if (!deps.isEmpty()) {
10063 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10064 options.getCompilerFilter(), options.getSplitName(),
10065 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10066 for (PackageParser.Package depPackage : deps) {
10067 // TODO: Analyze and investigate if we (should) profile libraries.
10068 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10069 getOrCreateCompilerPackageStats(depPackage),
10070 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10073 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10074 getOrCreateCompilerPackageStats(p),
10075 mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10079 * Reconcile the information we have about the secondary dex files belonging to
10080 * {@code packagName} and the actual dex files. For all dex files that were
10081 * deleted, update the internal records and delete the generated oat files.
10084 public void reconcileSecondaryDexFiles(String packageName) {
10085 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10087 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10090 mDexManager.reconcileSecondaryDexFiles(packageName);
10093 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10094 // a reference there.
10095 /*package*/ DexManager getDexManager() {
10096 return mDexManager;
10100 * Execute the background dexopt job immediately.
10103 public boolean runBackgroundDexoptJob() {
10104 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10107 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10110 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10111 if (p.usesLibraries != null || p.usesOptionalLibraries != null
10112 || p.usesStaticLibraries != null) {
10113 ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10114 Set<String> collectedNames = new HashSet<>();
10115 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10117 retValue.remove(p);
10121 return Collections.emptyList();
10125 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10126 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10127 if (!collectedNames.contains(p.packageName)) {
10128 collectedNames.add(p.packageName);
10131 if (p.usesLibraries != null) {
10132 findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10133 null, collected, collectedNames);
10135 if (p.usesOptionalLibraries != null) {
10136 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10137 null, collected, collectedNames);
10139 if (p.usesStaticLibraries != null) {
10140 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10141 p.usesStaticLibrariesVersions, collected, collectedNames);
10146 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10147 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10148 final int libNameCount = libs.size();
10149 for (int i = 0; i < libNameCount; i++) {
10150 String libName = libs.get(i);
10151 int version = (versions != null && versions.length == libNameCount)
10152 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10153 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10154 if (libPkg != null) {
10155 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10160 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10161 synchronized (mPackages) {
10162 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10163 if (libEntry != null) {
10164 return mPackages.get(libEntry.apk);
10170 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10171 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10172 if (versionedLib == null) {
10175 return versionedLib.get(version);
10178 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10179 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10180 pkg.staticSharedLibName);
10181 if (versionedLib == null) {
10184 int previousLibVersion = -1;
10185 final int versionCount = versionedLib.size();
10186 for (int i = 0; i < versionCount; i++) {
10187 final int libVersion = versionedLib.keyAt(i);
10188 if (libVersion < pkg.staticSharedLibVersion) {
10189 previousLibVersion = Math.max(previousLibVersion, libVersion);
10192 if (previousLibVersion >= 0) {
10193 return versionedLib.get(previousLibVersion);
10198 public void shutdown() {
10199 mPackageUsage.writeNow(mPackages);
10200 mCompilerStats.writeNow();
10201 mDexManager.writePackageDexUsageNow();
10205 public void dumpProfiles(String packageName) {
10206 PackageParser.Package pkg;
10207 synchronized (mPackages) {
10208 pkg = mPackages.get(packageName);
10210 throw new IllegalArgumentException("Unknown package: " + packageName);
10213 /* Only the shell, root, or the app user should be able to dump profiles. */
10214 int callingUid = Binder.getCallingUid();
10215 if (callingUid != Process.SHELL_UID &&
10216 callingUid != Process.ROOT_UID &&
10217 callingUid != pkg.applicationInfo.uid) {
10218 throw new SecurityException("dumpProfiles");
10221 synchronized (mInstallLock) {
10222 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10223 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10225 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10226 String codePaths = TextUtils.join(";", allCodePaths);
10227 mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10228 } catch (InstallerException e) {
10229 Slog.w(TAG, "Failed to dump profiles", e);
10231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10236 public void forceDexOpt(String packageName) {
10237 enforceSystemOrRoot("forceDexOpt");
10239 PackageParser.Package pkg;
10240 synchronized (mPackages) {
10241 pkg = mPackages.get(packageName);
10243 throw new IllegalArgumentException("Unknown package: " + packageName);
10247 synchronized (mInstallLock) {
10248 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10250 // Whoever is calling forceDexOpt wants a compiled package.
10251 // Don't use profiles since that may cause compilation to be skipped.
10252 final int res = performDexOptInternalWithDependenciesLI(
10254 new DexoptOptions(packageName,
10255 getDefaultCompilerFilter(),
10256 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10259 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10260 throw new IllegalStateException("Failed to dexopt: " + res);
10265 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10266 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10267 Slog.w(TAG, "Unable to update from " + oldPkg.name
10268 + " to " + newPkg.packageName
10269 + ": old package not in system partition");
10271 } else if (mPackages.get(oldPkg.name) != null) {
10272 Slog.w(TAG, "Unable to update from " + oldPkg.name
10273 + " to " + newPkg.packageName
10274 + ": old package still exists");
10280 void removeCodePathLI(File codePath) {
10281 if (codePath.isDirectory()) {
10283 mInstaller.rmPackageDir(codePath.getAbsolutePath());
10284 } catch (InstallerException e) {
10285 Slog.w(TAG, "Failed to remove code path", e);
10292 private int[] resolveUserIds(int userId) {
10293 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10296 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10298 Slog.wtf(TAG, "Package was null!", new Throwable());
10301 clearAppDataLeafLIF(pkg, userId, flags);
10302 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10303 for (int i = 0; i < childCount; i++) {
10304 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10308 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10309 final PackageSetting ps;
10310 synchronized (mPackages) {
10311 ps = mSettings.mPackages.get(pkg.packageName);
10313 for (int realUserId : resolveUserIds(userId)) {
10314 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10316 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10318 } catch (InstallerException e) {
10319 Slog.w(TAG, String.valueOf(e));
10324 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10326 Slog.wtf(TAG, "Package was null!", new Throwable());
10329 destroyAppDataLeafLIF(pkg, userId, flags);
10330 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10331 for (int i = 0; i < childCount; i++) {
10332 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10336 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10337 final PackageSetting ps;
10338 synchronized (mPackages) {
10339 ps = mSettings.mPackages.get(pkg.packageName);
10341 for (int realUserId : resolveUserIds(userId)) {
10342 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10344 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10346 } catch (InstallerException e) {
10347 Slog.w(TAG, String.valueOf(e));
10349 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10353 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10355 Slog.wtf(TAG, "Package was null!", new Throwable());
10358 destroyAppProfilesLeafLIF(pkg);
10359 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10360 for (int i = 0; i < childCount; i++) {
10361 destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10365 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10367 mInstaller.destroyAppProfiles(pkg.packageName);
10368 } catch (InstallerException e) {
10369 Slog.w(TAG, String.valueOf(e));
10373 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10375 Slog.wtf(TAG, "Package was null!", new Throwable());
10378 clearAppProfilesLeafLIF(pkg);
10379 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10380 for (int i = 0; i < childCount; i++) {
10381 clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10385 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10387 mInstaller.clearAppProfiles(pkg.packageName);
10388 } catch (InstallerException e) {
10389 Slog.w(TAG, String.valueOf(e));
10393 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10394 long lastUpdateTime) {
10395 // Set parent install/update time
10396 PackageSetting ps = (PackageSetting) pkg.mExtras;
10398 ps.firstInstallTime = firstInstallTime;
10399 ps.lastUpdateTime = lastUpdateTime;
10401 // Set children install/update time
10402 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10403 for (int i = 0; i < childCount; i++) {
10404 PackageParser.Package childPkg = pkg.childPackages.get(i);
10405 ps = (PackageSetting) childPkg.mExtras;
10407 ps.firstInstallTime = firstInstallTime;
10408 ps.lastUpdateTime = lastUpdateTime;
10413 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10414 PackageParser.Package changingLib) {
10415 if (file.path != null) {
10416 usesLibraryFiles.add(file.path);
10419 PackageParser.Package p = mPackages.get(file.apk);
10420 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10421 // If we are doing this while in the middle of updating a library apk,
10422 // then we need to make sure to use that new apk for determining the
10423 // dependencies here. (We haven't yet finished committing the new apk
10424 // to the package manager state.)
10425 if (p == null || p.packageName.equals(changingLib.packageName)) {
10430 usesLibraryFiles.addAll(p.getAllCodePaths());
10431 if (p.usesLibraryFiles != null) {
10432 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10437 private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10438 PackageParser.Package changingLib) throws PackageManagerException {
10442 ArraySet<String> usesLibraryFiles = null;
10443 if (pkg.usesLibraries != null) {
10444 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10445 null, null, pkg.packageName, changingLib, true,
10446 pkg.applicationInfo.targetSdkVersion, null);
10448 if (pkg.usesStaticLibraries != null) {
10449 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10450 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10451 pkg.packageName, changingLib, true,
10452 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10454 if (pkg.usesOptionalLibraries != null) {
10455 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10456 null, null, pkg.packageName, changingLib, false,
10457 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10459 if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10460 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10462 pkg.usesLibraryFiles = null;
10466 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10467 @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10468 @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10469 boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10470 throws PackageManagerException {
10471 final int libCount = requestedLibraries.size();
10472 for (int i = 0; i < libCount; i++) {
10473 final String libName = requestedLibraries.get(i);
10474 final int libVersion = requiredVersions != null ? requiredVersions[i]
10475 : SharedLibraryInfo.VERSION_UNDEFINED;
10476 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10477 if (libEntry == null) {
10479 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10480 "Package " + packageName + " requires unavailable shared library "
10481 + libName + "; failing!");
10482 } else if (DEBUG_SHARED_LIBRARIES) {
10483 Slog.i(TAG, "Package " + packageName
10484 + " desires unavailable shared library "
10485 + libName + "; ignoring!");
10488 if (requiredVersions != null && requiredCertDigests != null) {
10489 if (libEntry.info.getVersion() != requiredVersions[i]) {
10490 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10491 "Package " + packageName + " requires unavailable static shared"
10492 + " library " + libName + " version "
10493 + libEntry.info.getVersion() + "; failing!");
10496 PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10497 if (libPkg == null) {
10498 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10499 "Package " + packageName + " requires unavailable static shared"
10500 + " library; failing!");
10503 final String[] expectedCertDigests = requiredCertDigests[i];
10504 // For apps targeting O MR1 we require explicit enumeration of all certs.
10505 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10506 ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10507 : PackageUtils.computeSignaturesSha256Digests(
10508 new Signature[]{libPkg.mSignatures[0]});
10510 // Take a shortcut if sizes don't match. Note that if an app doesn't
10511 // target O we don't parse the "additional-certificate" tags similarly
10512 // how we only consider all certs only for apps targeting O (see above).
10513 // Therefore, the size check is safe to make.
10514 if (expectedCertDigests.length != libCertDigests.length) {
10515 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10516 "Package " + packageName + " requires differently signed" +
10517 " static sDexLoadReporter.java:45.19hared library; failing!");
10520 // Use a predictable order as signature order may vary
10521 Arrays.sort(libCertDigests);
10522 Arrays.sort(expectedCertDigests);
10524 final int certCount = libCertDigests.length;
10525 for (int j = 0; j < certCount; j++) {
10526 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10527 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10528 "Package " + packageName + " requires differently signed" +
10529 " static shared library; failing!");
10534 if (outUsedLibraries == null) {
10535 outUsedLibraries = new ArraySet<>();
10537 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10540 return outUsedLibraries;
10543 private static boolean hasString(List<String> list, List<String> which) {
10544 if (list == null) {
10547 for (int i=list.size()-1; i>=0; i--) {
10548 for (int j=which.size()-1; j>=0; j--) {
10549 if (which.get(j).equals(list.get(i))) {
10557 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10558 PackageParser.Package changingPkg) {
10559 ArrayList<PackageParser.Package> res = null;
10560 for (PackageParser.Package pkg : mPackages.values()) {
10561 if (changingPkg != null
10562 && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10563 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10564 && !ArrayUtils.contains(pkg.usesStaticLibraries,
10565 changingPkg.staticSharedLibName)) {
10569 res = new ArrayList<>();
10573 updateSharedLibrariesLPr(pkg, changingPkg);
10574 } catch (PackageManagerException e) {
10575 // If a system app update or an app and a required lib missing we
10576 // delete the package and for updated system apps keep the data as
10577 // it is better for the user to reinstall than to be in an limbo
10578 // state. Also libs disappearing under an app should never happen
10580 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10581 final int flags = pkg.isUpdatedSystemApp()
10582 ? PackageManager.DELETE_KEEP_DATA : 0;
10583 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10584 flags , null, true, null);
10586 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10593 * Derive the value of the {@code cpuAbiOverride} based on the provided
10594 * value and an optional stored value from the package settings.
10596 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10597 String cpuAbiOverride = null;
10599 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10600 cpuAbiOverride = null;
10601 } else if (abiOverride != null) {
10602 cpuAbiOverride = abiOverride;
10603 } else if (settings != null) {
10604 cpuAbiOverride = settings.cpuAbiOverrideString;
10607 return cpuAbiOverride;
10610 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10611 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10612 throws PackageManagerException {
10613 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10614 // If the package has children and this is the first dive in the function
10615 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10616 // whether all packages (parent and children) would be successfully scanned
10617 // before the actual scan since scanning mutates internal state and we want
10618 // to atomically install the package and its children.
10619 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10620 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10621 scanFlags |= SCAN_CHECK_ONLY;
10624 scanFlags &= ~SCAN_CHECK_ONLY;
10627 final PackageParser.Package scannedPkg;
10630 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10631 // Scan the children
10632 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10633 for (int i = 0; i < childCount; i++) {
10634 PackageParser.Package childPkg = pkg.childPackages.get(i);
10635 scanPackageLI(childPkg, policyFlags,
10636 scanFlags, currentTime, user);
10639 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10642 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10643 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10649 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10650 int scanFlags, long currentTime, @Nullable UserHandle user)
10651 throws PackageManagerException {
10652 boolean success = false;
10654 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10655 currentTime, user);
10659 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10660 // DELETE_DATA_ON_FAILURES is only used by frozen paths
10661 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10662 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10663 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10669 * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10671 private static boolean apkHasCode(String fileName) {
10672 StrictJarFile jarFile = null;
10674 jarFile = new StrictJarFile(fileName,
10675 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10676 return jarFile.findEntry("classes.dex") != null;
10677 } catch (IOException ignore) {
10680 if (jarFile != null) {
10683 } catch (IOException ignore) {}
10689 * Enforces code policy for the package. This ensures that if an APK has
10690 * declared hasCode="true" in its manifest that the APK actually contains
10693 * @throws PackageManagerException If bytecode could not be found when it should exist
10695 private static void assertCodePolicy(PackageParser.Package pkg)
10696 throws PackageManagerException {
10697 final boolean shouldHaveCode =
10698 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10699 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10700 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10701 "Package " + pkg.baseCodePath + " code is missing");
10704 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10705 for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10706 final boolean splitShouldHaveCode =
10707 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10708 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10709 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10710 "Package " + pkg.splitCodePaths[i] + " code is missing");
10716 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10717 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10718 throws PackageManagerException {
10719 if (DEBUG_PACKAGE_SCANNING) {
10720 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10721 Log.d(TAG, "Scanning package " + pkg.packageName);
10724 applyPolicy(pkg, policyFlags);
10726 assertPackageIsValid(pkg, policyFlags, scanFlags);
10728 // Initialize package source and resource directories
10729 final File scanFile = new File(pkg.codePath);
10730 final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10731 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10733 SharedUserSetting suid = null;
10734 PackageSetting pkgSetting = null;
10736 // Getting the package setting may have a side-effect, so if we
10737 // are only checking if scan would succeed, stash a copy of the
10738 // old setting to restore at the end.
10739 PackageSetting nonMutatedPs = null;
10741 // We keep references to the derived CPU Abis from settings in oder to reuse
10742 // them in the case where we're not upgrading or booting for the first time.
10743 String primaryCpuAbiFromSettings = null;
10744 String secondaryCpuAbiFromSettings = null;
10747 synchronized (mPackages) {
10748 if (pkg.mSharedUserId != null) {
10749 // SIDE EFFECTS; may potentially allocate a new shared user
10750 suid = mSettings.getSharedUserLPw(
10751 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10752 if (DEBUG_PACKAGE_SCANNING) {
10753 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10754 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10755 + "): packages=" + suid.packages);
10759 // Check if we are renaming from an original package name.
10760 PackageSetting origPackage = null;
10761 String realName = null;
10762 if (pkg.mOriginalPackages != null) {
10763 // This package may need to be renamed to a previously
10764 // installed name. Let's check on that...
10765 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10766 if (pkg.mOriginalPackages.contains(renamed)) {
10767 // This package had originally been installed as the
10768 // original name, and we have already taken care of
10769 // transitioning to the new one. Just update the new
10770 // one to continue using the old name.
10771 realName = pkg.mRealPackage;
10772 if (!pkg.packageName.equals(renamed)) {
10773 // Callers into this function may have already taken
10774 // care of renaming the package; only do it here if
10775 // it is not already done.
10776 pkg.setPackageName(renamed);
10779 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10780 if ((origPackage = mSettings.getPackageLPr(
10781 pkg.mOriginalPackages.get(i))) != null) {
10782 // We do have the package already installed under its
10783 // original name... should we use it?
10784 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10785 // New package is not compatible with original.
10786 origPackage = null;
10788 } else if (origPackage.sharedUser != null) {
10789 // Make sure uid is compatible between packages.
10790 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10791 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10792 + " to " + pkg.packageName + ": old uid "
10793 + origPackage.sharedUser.name
10794 + " differs from " + pkg.mSharedUserId);
10795 origPackage = null;
10798 // TODO: Add case when shared user id is added [b/28144775]
10800 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10801 + pkg.packageName + " to old name " + origPackage.name);
10809 if (mTransferedPackages.contains(pkg.packageName)) {
10810 Slog.w(TAG, "Package " + pkg.packageName
10811 + " was transferred to another, but its .apk remains");
10814 // See comments in nonMutatedPs declaration
10815 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10816 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10817 if (foundPs != null) {
10818 nonMutatedPs = new PackageSetting(foundPs);
10822 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10823 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10824 if (foundPs != null) {
10825 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10826 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10830 pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10831 if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10832 PackageManagerService.reportSettingsProblem(Log.WARN,
10833 "Package " + pkg.packageName + " shared user changed from "
10834 + (pkgSetting.sharedUser != null
10835 ? pkgSetting.sharedUser.name : "<nothing>")
10837 + (suid != null ? suid.name : "<nothing>")
10838 + "; replacing with new");
10841 final PackageSetting oldPkgSetting =
10842 pkgSetting == null ? null : new PackageSetting(pkgSetting);
10843 final PackageSetting disabledPkgSetting =
10844 mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10846 String[] usesStaticLibraries = null;
10847 if (pkg.usesStaticLibraries != null) {
10848 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10849 pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10852 if (pkgSetting == null) {
10853 final String parentPackageName = (pkg.parentPackage != null)
10854 ? pkg.parentPackage.packageName : null;
10855 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10856 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10857 // REMOVE SharedUserSetting from method; update in a separate call
10858 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10859 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10860 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10861 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10862 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10863 true /*allowInstall*/, instantApp, virtualPreload,
10864 parentPackageName, pkg.getChildPackageNames(),
10865 UserManagerService.getInstance(), usesStaticLibraries,
10866 pkg.usesStaticLibrariesVersions);
10867 // SIDE EFFECTS; updates system state; move elsewhere
10868 if (origPackage != null) {
10869 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10871 mSettings.addUserToSettingLPw(pkgSetting);
10873 // REMOVE SharedUserSetting from method; update in a separate call.
10875 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10876 // secondaryCpuAbi are not known at this point so we always update them
10877 // to null here, only to reset them at a later point.
10878 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10879 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10880 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10881 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10882 UserManagerService.getInstance(), usesStaticLibraries,
10883 pkg.usesStaticLibrariesVersions);
10885 // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10886 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10888 // SIDE EFFECTS; modifies system state; move elsewhere
10889 if (pkgSetting.origPackage != null) {
10890 // If we are first transitioning from an original package,
10891 // fix up the new package's name now. We need to do this after
10892 // looking up the package under its new name, so getPackageLP
10893 // can take care of fiddling things correctly.
10894 pkg.setPackageName(origPackage.name);
10896 // File a report about this.
10897 String msg = "New package " + pkgSetting.realName
10898 + " renamed to replace old package " + pkgSetting.name;
10899 reportSettingsProblem(Log.WARN, msg);
10901 // Make a note of it.
10902 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10903 mTransferedPackages.add(origPackage.name);
10906 // No longer need to retain this.
10907 pkgSetting.origPackage = null;
10910 // SIDE EFFECTS; modifies system state; move elsewhere
10911 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10912 // Make a note of it.
10913 mTransferedPackages.add(pkg.packageName);
10916 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10917 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10920 if ((scanFlags & SCAN_BOOTING) == 0
10921 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10922 // Check all shared libraries and map to their actual file path.
10923 // We only do this here for apps not on a system dir, because those
10924 // are the only ones that can fail an install due to this. We
10925 // will take care of the system apps by updating all of their
10926 // library paths after the scan is done. Also during the initial
10927 // scan don't update any libs as we do this wholesale after all
10928 // apps are scanned to avoid dependency based scanning.
10929 updateSharedLibrariesLPr(pkg, null);
10932 if (mFoundPolicyFile) {
10933 SELinuxMMAC.assignSeInfoValue(pkg);
10935 pkg.applicationInfo.uid = pkgSetting.appId;
10936 pkg.mExtras = pkgSetting;
10939 // Static shared libs have same package with different versions where
10940 // we internally use a synthetic package name to allow multiple versions
10941 // of the same package, therefore we need to compare signatures against
10942 // the package setting for the latest library version.
10943 PackageSetting signatureCheckPs = pkgSetting;
10944 if (pkg.applicationInfo.isStaticSharedLibrary()) {
10945 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10946 if (libraryEntry != null) {
10947 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10951 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10952 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10953 // We just determined the app is signed correctly, so bring
10954 // over the latest parsed certs.
10955 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10957 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10958 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10959 "Package " + pkg.packageName + " upgrade keys do not match the "
10960 + "previously installed version");
10962 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10963 String msg = "System package " + pkg.packageName
10964 + " signature changed; retaining data.";
10965 reportSettingsProblem(Log.WARN, msg);
10970 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10971 verifySignaturesLP(signatureCheckPs, pkg);
10972 // We just determined the app is signed correctly, so bring
10973 // over the latest parsed certs.
10974 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10975 } catch (PackageManagerException e) {
10976 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10979 // The signature has changed, but this package is in the system
10980 // image... let's recover!
10981 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10982 // However... if this package is part of a shared user, but it
10983 // doesn't match the signature of the shared user, let's fail.
10984 // What this means is that you can't change the signatures
10985 // associated with an overall shared user, which doesn't seem all
10986 // that unreasonable.
10987 if (signatureCheckPs.sharedUser != null) {
10988 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10989 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10990 throw new PackageManagerException(
10991 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10992 "Signature mismatch for shared user: "
10993 + pkgSetting.sharedUser);
10996 // File a report about this.
10997 String msg = "System package " + pkg.packageName
10998 + " signature changed; retaining data.";
10999 reportSettingsProblem(Log.WARN, msg);
11003 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11004 // This package wants to adopt ownership of permissions from
11005 // another package.
11006 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11007 final String origName = pkg.mAdoptPermissions.get(i);
11008 final PackageSetting orig = mSettings.getPackageLPr(origName);
11009 if (orig != null) {
11010 if (verifyPackageUpdateLPr(orig, pkg)) {
11011 Slog.i(TAG, "Adopting permissions from " + origName + " to "
11012 + pkg.packageName);
11013 // SIDE EFFECTS; updates permissions system state; move elsewhere
11014 mSettings.transferPermissionsLPw(origName, pkg.packageName);
11021 pkg.applicationInfo.processName = fixProcessName(
11022 pkg.applicationInfo.packageName,
11023 pkg.applicationInfo.processName);
11025 if (pkg != mPlatformPackage) {
11026 // Get all of our default paths setup
11027 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11030 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11032 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11033 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
11034 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11035 final boolean extractNativeLibs = !pkg.isLibrary();
11036 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11037 mAppLib32InstallDir);
11038 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11040 // Some system apps still use directory structure for native libraries
11041 // in which case we might end up not detecting abi solely based on apk
11042 // structure. Try to detect abi based on directory structure.
11043 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11044 pkg.applicationInfo.primaryCpuAbi == null) {
11045 setBundledAppAbisAndRoots(pkg, pkgSetting);
11046 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11049 // This is not a first boot or an upgrade, don't bother deriving the
11050 // ABI during the scan. Instead, trust the value that was stored in the
11051 // package setting.
11052 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11053 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11055 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11057 if (DEBUG_ABI_SELECTION) {
11058 Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11059 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11060 pkg.applicationInfo.secondaryCpuAbi);
11064 if ((scanFlags & SCAN_MOVE) != 0) {
11065 // We haven't run dex-opt for this move (since we've moved the compiled output too)
11066 // but we already have this packages package info in the PackageSetting. We just
11067 // use that and derive the native library path based on the new codepath.
11068 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11069 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11072 // Set native library paths again. For moves, the path will be updated based on the
11073 // ABIs we've determined above. For non-moves, the path will be updated based on the
11074 // ABIs we determined during compilation, but the path will depend on the final
11075 // package path (after the rename away from the stage path).
11076 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11079 // This is a special case for the "system" package, where the ABI is
11080 // dictated by the zygote configuration (and init.rc). We should keep track
11081 // of this ABI so that we can deal with "normal" applications that run under
11082 // the same UID correctly.
11083 if (mPlatformPackage == pkg) {
11084 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11085 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11088 // If there's a mismatch between the abi-override in the package setting
11089 // and the abiOverride specified for the install. Warn about this because we
11090 // would've already compiled the app without taking the package setting into
11092 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11093 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11094 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11095 " for package " + pkg.packageName);
11099 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11100 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11101 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11103 // Copy the derived override back to the parsed package, so that we can
11104 // update the package settings accordingly.
11105 pkg.cpuAbiOverride = cpuAbiOverride;
11107 if (DEBUG_ABI_SELECTION) {
11108 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11109 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11110 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11113 // Push the derived path down into PackageSettings so we know what to
11114 // clean up at uninstall time.
11115 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11117 if (DEBUG_ABI_SELECTION) {
11118 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11119 " primary=" + pkg.applicationInfo.primaryCpuAbi +
11120 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11123 // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11124 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11125 // We don't do this here during boot because we can do it all
11126 // at once after scanning all existing packages.
11128 // We also do this *before* we perform dexopt on this package, so that
11129 // we can avoid redundant dexopts, and also to make sure we've got the
11130 // code and package path correct.
11131 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11134 if (mFactoryTest && pkg.requestedPermissions.contains(
11135 android.Manifest.permission.FACTORY_TEST)) {
11136 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11139 if (isSystemApp(pkg)) {
11140 pkgSetting.isOrphaned = true;
11143 // Take care of first install / last update times.
11144 final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11145 if (currentTime != 0) {
11146 if (pkgSetting.firstInstallTime == 0) {
11147 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11148 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11149 pkgSetting.lastUpdateTime = currentTime;
11151 } else if (pkgSetting.firstInstallTime == 0) {
11152 // We need *something*. Take time time stamp of the file.
11153 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11154 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11155 if (scanFileTime != pkgSetting.timeStamp) {
11156 // A package on the system image has changed; consider this
11157 // to be an update.
11158 pkgSetting.lastUpdateTime = scanFileTime;
11161 pkgSetting.setTimeStamp(scanFileTime);
11163 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11164 if (nonMutatedPs != null) {
11165 synchronized (mPackages) {
11166 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11170 final int userId = user == null ? 0 : user.getIdentifier();
11171 // Modify state for the given package setting
11172 commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11173 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11174 if (pkgSetting.getInstantApp(userId)) {
11175 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11182 * Applies policy to the parsed package based upon the given policy flags.
11183 * Ensures the package is in a good state.
11185 * Implementation detail: This method must NOT have any side effect. It would
11186 * ideally be static, but, it requires locks to read system state.
11188 private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11189 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11190 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11191 if (pkg.applicationInfo.isDirectBootAware()) {
11192 // we're direct boot aware; set for all components
11193 for (PackageParser.Service s : pkg.services) {
11194 s.info.encryptionAware = s.info.directBootAware = true;
11196 for (PackageParser.Provider p : pkg.providers) {
11197 p.info.encryptionAware = p.info.directBootAware = true;
11199 for (PackageParser.Activity a : pkg.activities) {
11200 a.info.encryptionAware = a.info.directBootAware = true;
11202 for (PackageParser.Activity r : pkg.receivers) {
11203 r.info.encryptionAware = r.info.directBootAware = true;
11206 if (compressedFileExists(pkg.codePath)) {
11210 // Only allow system apps to be flagged as core apps.
11211 pkg.coreApp = false;
11212 // clear flags not applicable to regular apps
11213 pkg.applicationInfo.privateFlags &=
11214 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11215 pkg.applicationInfo.privateFlags &=
11216 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11218 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11220 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11221 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11224 if (!isSystemApp(pkg)) {
11225 // Only system apps can use these features.
11226 pkg.mOriginalPackages = null;
11227 pkg.mRealPackage = null;
11228 pkg.mAdoptPermissions = null;
11233 * Asserts the parsed package is valid according to the given policy. If the
11234 * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11236 * Implementation detail: This method must NOT have any side effects. It would
11237 * ideally be static, but, it requires locks to read system state.
11239 * @throws PackageManagerException If the package fails any of the validation checks
11241 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11242 throws PackageManagerException {
11243 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11244 assertCodePolicy(pkg);
11247 if (pkg.applicationInfo.getCodePath() == null ||
11248 pkg.applicationInfo.getResourcePath() == null) {
11249 // Bail out. The resource and code paths haven't been set.
11250 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11251 "Code and resource paths haven't been set correctly");
11254 // Make sure we're not adding any bogus keyset info
11255 KeySetManagerService ksms = mSettings.mKeySetManagerService;
11256 ksms.assertScannedPackageValid(pkg);
11258 synchronized (mPackages) {
11259 // The special "android" package can only be defined once
11260 if (pkg.packageName.equals("android")) {
11261 if (mAndroidApplication != null) {
11262 Slog.w(TAG, "*************************************************");
11263 Slog.w(TAG, "Core android package being redefined. Skipping.");
11264 Slog.w(TAG, " codePath=" + pkg.codePath);
11265 Slog.w(TAG, "*************************************************");
11266 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11267 "Core android package being redefined. Skipping.");
11271 // A package name must be unique; don't allow duplicates
11272 if (mPackages.containsKey(pkg.packageName)) {
11273 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11274 "Application package " + pkg.packageName
11275 + " already installed. Skipping duplicate.");
11278 if (pkg.applicationInfo.isStaticSharedLibrary()) {
11279 // Static libs have a synthetic package name containing the version
11280 // but we still want the base name to be unique.
11281 if (mPackages.containsKey(pkg.manifestPackageName)) {
11282 throw new PackageManagerException(
11283 "Duplicate static shared lib provider package");
11286 // Static shared libraries should have at least O target SDK
11287 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11288 throw new PackageManagerException(
11289 "Packages declaring static-shared libs must target O SDK or higher");
11292 // Package declaring static a shared lib cannot be instant apps
11293 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11294 throw new PackageManagerException(
11295 "Packages declaring static-shared libs cannot be instant apps");
11298 // Package declaring static a shared lib cannot be renamed since the package
11299 // name is synthetic and apps can't code around package manager internals.
11300 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11301 throw new PackageManagerException(
11302 "Packages declaring static-shared libs cannot be renamed");
11305 // Package declaring static a shared lib cannot declare child packages
11306 if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11307 throw new PackageManagerException(
11308 "Packages declaring static-shared libs cannot have child packages");
11311 // Package declaring static a shared lib cannot declare dynamic libs
11312 if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11313 throw new PackageManagerException(
11314 "Packages declaring static-shared libs cannot declare dynamic libs");
11317 // Package declaring static a shared lib cannot declare shared users
11318 if (pkg.mSharedUserId != null) {
11319 throw new PackageManagerException(
11320 "Packages declaring static-shared libs cannot declare shared users");
11323 // Static shared libs cannot declare activities
11324 if (!pkg.activities.isEmpty()) {
11325 throw new PackageManagerException(
11326 "Static shared libs cannot declare activities");
11329 // Static shared libs cannot declare services
11330 if (!pkg.services.isEmpty()) {
11331 throw new PackageManagerException(
11332 "Static shared libs cannot declare services");
11335 // Static shared libs cannot declare providers
11336 if (!pkg.providers.isEmpty()) {
11337 throw new PackageManagerException(
11338 "Static shared libs cannot declare content providers");
11341 // Static shared libs cannot declare receivers
11342 if (!pkg.receivers.isEmpty()) {
11343 throw new PackageManagerException(
11344 "Static shared libs cannot declare broadcast receivers");
11347 // Static shared libs cannot declare permission groups
11348 if (!pkg.permissionGroups.isEmpty()) {
11349 throw new PackageManagerException(
11350 "Static shared libs cannot declare permission groups");
11353 // Static shared libs cannot declare permissions
11354 if (!pkg.permissions.isEmpty()) {
11355 throw new PackageManagerException(
11356 "Static shared libs cannot declare permissions");
11359 // Static shared libs cannot declare protected broadcasts
11360 if (pkg.protectedBroadcasts != null) {
11361 throw new PackageManagerException(
11362 "Static shared libs cannot declare protected broadcasts");
11365 // Static shared libs cannot be overlay targets
11366 if (pkg.mOverlayTarget != null) {
11367 throw new PackageManagerException(
11368 "Static shared libs cannot be overlay targets");
11371 // The version codes must be ordered as lib versions
11372 int minVersionCode = Integer.MIN_VALUE;
11373 int maxVersionCode = Integer.MAX_VALUE;
11375 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11376 pkg.staticSharedLibName);
11377 if (versionedLib != null) {
11378 final int versionCount = versionedLib.size();
11379 for (int i = 0; i < versionCount; i++) {
11380 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11381 final int libVersionCode = libInfo.getDeclaringPackage()
11383 if (libInfo.getVersion() < pkg.staticSharedLibVersion) {
11384 minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11385 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) {
11386 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11388 minVersionCode = maxVersionCode = libVersionCode;
11393 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11394 throw new PackageManagerException("Static shared"
11395 + " lib version codes must be ordered as lib versions");
11399 // Only privileged apps and updated privileged apps can add child packages.
11400 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11401 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11402 throw new PackageManagerException("Only privileged apps can add child "
11403 + "packages. Ignoring package " + pkg.packageName);
11405 final int childCount = pkg.childPackages.size();
11406 for (int i = 0; i < childCount; i++) {
11407 PackageParser.Package childPkg = pkg.childPackages.get(i);
11408 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11409 childPkg.packageName)) {
11410 throw new PackageManagerException("Can't override child of "
11411 + "another disabled app. Ignoring package " + pkg.packageName);
11416 // If we're only installing presumed-existing packages, require that the
11417 // scanned APK is both already known and at the path previously established
11418 // for it. Previously unknown packages we pick up normally, but if we have an
11419 // a priori expectation about this package's install presence, enforce it.
11420 // With a singular exception for new system packages. When an OTA contains
11421 // a new system package, we allow the codepath to change from a system location
11422 // to the user-installed location. If we don't allow this change, any newer,
11423 // user-installed version of the application will be ignored.
11424 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11425 if (mExpectingBetter.containsKey(pkg.packageName)) {
11426 logCriticalInfo(Log.WARN,
11427 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11429 PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11430 if (known != null) {
11431 if (DEBUG_PACKAGE_SCANNING) {
11432 Log.d(TAG, "Examining " + pkg.codePath
11433 + " and requiring known paths " + known.codePathString
11434 + " & " + known.resourcePathString);
11436 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11437 || !pkg.applicationInfo.getResourcePath().equals(
11438 known.resourcePathString)) {
11439 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11440 "Application package " + pkg.packageName
11441 + " found at " + pkg.applicationInfo.getCodePath()
11442 + " but expected at " + known.codePathString
11446 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11447 "Application package " + pkg.packageName
11448 + " not found; ignoring.");
11453 // Verify that this new package doesn't have any content providers
11454 // that conflict with existing packages. Only do this if the
11455 // package isn't already installed, since we don't want to break
11456 // things that are installed.
11457 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11458 final int N = pkg.providers.size();
11460 for (i=0; i<N; i++) {
11461 PackageParser.Provider p = pkg.providers.get(i);
11462 if (p.info.authority != null) {
11463 String names[] = p.info.authority.split(";");
11464 for (int j = 0; j < names.length; j++) {
11465 if (mProvidersByAuthority.containsKey(names[j])) {
11466 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11467 final String otherPackageName =
11468 ((other != null && other.getComponentName() != null) ?
11469 other.getComponentName().getPackageName() : "?");
11470 throw new PackageManagerException(
11471 INSTALL_FAILED_CONFLICTING_PROVIDER,
11472 "Can't install because provider name " + names[j]
11473 + " (in package " + pkg.applicationInfo.packageName
11474 + ") is already used by " + otherPackageName);
11483 private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11484 int type, String declaringPackageName, int declaringVersionCode) {
11485 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11486 if (versionedLib == null) {
11487 versionedLib = new SparseArray<>();
11488 mSharedLibraries.put(name, versionedLib);
11489 if (type == SharedLibraryInfo.TYPE_STATIC) {
11490 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11492 } else if (versionedLib.indexOfKey(version) >= 0) {
11495 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11496 version, type, declaringPackageName, declaringVersionCode);
11497 versionedLib.put(version, libEntry);
11501 private boolean removeSharedLibraryLPw(String name, int version) {
11502 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11503 if (versionedLib == null) {
11506 final int libIdx = versionedLib.indexOfKey(version);
11510 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11511 versionedLib.remove(version);
11512 if (versionedLib.size() <= 0) {
11513 mSharedLibraries.remove(name);
11514 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11515 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11516 .getPackageName());
11523 * Adds a scanned package to the system. When this method is finished, the package will
11524 * be available for query, resolution, etc...
11526 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11527 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11528 final String pkgName = pkg.packageName;
11529 if (mCustomResolverComponentName != null &&
11530 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11531 setUpCustomResolverActivity(pkg);
11534 if (pkg.packageName.equals("android")) {
11535 synchronized (mPackages) {
11536 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11537 // Set up information for our fall-back user intent resolution activity.
11538 mPlatformPackage = pkg;
11539 pkg.mVersionCode = mSdkVersion;
11540 mAndroidApplication = pkg.applicationInfo;
11541 if (!mResolverReplaced) {
11542 mResolveActivity.applicationInfo = mAndroidApplication;
11543 mResolveActivity.name = ResolverActivity.class.getName();
11544 mResolveActivity.packageName = mAndroidApplication.packageName;
11545 mResolveActivity.processName = "system:ui";
11546 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11547 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11548 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11549 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11550 mResolveActivity.exported = true;
11551 mResolveActivity.enabled = true;
11552 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11553 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11554 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11555 | ActivityInfo.CONFIG_SCREEN_LAYOUT
11556 | ActivityInfo.CONFIG_ORIENTATION
11557 | ActivityInfo.CONFIG_KEYBOARD
11558 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11559 mResolveInfo.activityInfo = mResolveActivity;
11560 mResolveInfo.priority = 0;
11561 mResolveInfo.preferredOrder = 0;
11562 mResolveInfo.match = 0;
11563 mResolveComponentName = new ComponentName(
11564 mAndroidApplication.packageName, mResolveActivity.name);
11570 ArrayList<PackageParser.Package> clientLibPkgs = null;
11572 synchronized (mPackages) {
11573 boolean hasStaticSharedLibs = false;
11575 // Any app can add new static shared libraries
11576 if (pkg.staticSharedLibName != null) {
11577 // Static shared libs don't allow renaming as they have synthetic package
11578 // names to allow install of multiple versions, so use name from manifest.
11579 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11580 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11581 pkg.manifestPackageName, pkg.mVersionCode)) {
11582 hasStaticSharedLibs = true;
11584 Slog.w(TAG, "Package " + pkg.packageName + " library "
11585 + pkg.staticSharedLibName + " already exists; skipping");
11587 // Static shared libs cannot be updated once installed since they
11588 // use synthetic package name which includes the version code, so
11589 // not need to update other packages's shared lib dependencies.
11592 if (!hasStaticSharedLibs
11593 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11594 // Only system apps can add new dynamic shared libraries.
11595 if (pkg.libraryNames != null) {
11596 for (int i = 0; i < pkg.libraryNames.size(); i++) {
11597 String name = pkg.libraryNames.get(i);
11598 boolean allowed = false;
11599 if (pkg.isUpdatedSystemApp()) {
11600 // New library entries can only be added through the
11601 // system image. This is important to get rid of a lot
11602 // of nasty edge cases: for example if we allowed a non-
11603 // system update of the app to add a library, then uninstalling
11604 // the update would make the library go away, and assumptions
11605 // we made such as through app install filtering would now
11606 // have allowed apps on the device which aren't compatible
11607 // with it. Better to just have the restriction here, be
11608 // conservative, and create many fewer cases that can negatively
11609 // impact the user experience.
11610 final PackageSetting sysPs = mSettings
11611 .getDisabledSystemPkgLPr(pkg.packageName);
11612 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11613 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11614 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11624 if (!addSharedLibraryLPw(null, pkg.packageName, name,
11625 SharedLibraryInfo.VERSION_UNDEFINED,
11626 SharedLibraryInfo.TYPE_DYNAMIC,
11627 pkg.packageName, pkg.mVersionCode)) {
11628 Slog.w(TAG, "Package " + pkg.packageName + " library "
11629 + name + " already exists; skipping");
11632 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11633 + name + " that is not declared on system image; skipping");
11637 if ((scanFlags & SCAN_BOOTING) == 0) {
11638 // If we are not booting, we need to update any applications
11639 // that are clients of our shared library. If we are booting,
11640 // this will all be done once the scan is complete.
11641 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11647 if ((scanFlags & SCAN_BOOTING) != 0) {
11648 // No apps can run during boot scan, so they don't need to be frozen
11649 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11650 // Caller asked to not kill app, so it's probably not frozen
11651 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11652 // Caller asked us to ignore frozen check for some reason; they
11653 // probably didn't know the package name
11655 // We're doing major surgery on this package, so it better be frozen
11656 // right now to keep it from launching
11657 checkPackageFrozen(pkgName);
11660 // Also need to kill any apps that are dependent on the library.
11661 if (clientLibPkgs != null) {
11662 for (int i=0; i<clientLibPkgs.size(); i++) {
11663 PackageParser.Package clientPkg = clientLibPkgs.get(i);
11664 killApplication(clientPkg.applicationInfo.packageName,
11665 clientPkg.applicationInfo.uid, "update lib");
11670 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11672 synchronized (mPackages) {
11673 // We don't expect installation to fail beyond this point
11675 // Add the new setting to mSettings
11676 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11677 // Add the new setting to mPackages
11678 mPackages.put(pkg.applicationInfo.packageName, pkg);
11679 // Make sure we don't accidentally delete its data.
11680 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11681 while (iter.hasNext()) {
11682 PackageCleanItem item = iter.next();
11683 if (pkgName.equals(item.packageName)) {
11688 // Add the package's KeySets to the global KeySetManagerService
11689 KeySetManagerService ksms = mSettings.mKeySetManagerService;
11690 ksms.addScannedPackageLPw(pkg);
11692 int N = pkg.providers.size();
11693 StringBuilder r = null;
11695 for (i=0; i<N; i++) {
11696 PackageParser.Provider p = pkg.providers.get(i);
11697 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11698 p.info.processName);
11699 mProviders.addProvider(p);
11700 p.syncable = p.info.isSyncable;
11701 if (p.info.authority != null) {
11702 String names[] = p.info.authority.split(";");
11703 p.info.authority = null;
11704 for (int j = 0; j < names.length; j++) {
11705 if (j == 1 && p.syncable) {
11706 // We only want the first authority for a provider to possibly be
11707 // syncable, so if we already added this provider using a different
11708 // authority clear the syncable flag. We copy the provider before
11709 // changing it because the mProviders object contains a reference
11710 // to a provider that we don't want to change.
11711 // Only do this for the second authority since the resulting provider
11712 // object can be the same for all future authorities for this provider.
11713 p = new PackageParser.Provider(p);
11714 p.syncable = false;
11716 if (!mProvidersByAuthority.containsKey(names[j])) {
11717 mProvidersByAuthority.put(names[j], p);
11718 if (p.info.authority == null) {
11719 p.info.authority = names[j];
11721 p.info.authority = p.info.authority + ";" + names[j];
11723 if (DEBUG_PACKAGE_SCANNING) {
11725 Log.d(TAG, "Registered content provider: " + names[j]
11726 + ", className = " + p.info.name + ", isSyncable = "
11727 + p.info.isSyncable);
11730 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11731 Slog.w(TAG, "Skipping provider name " + names[j] +
11732 " (in package " + pkg.applicationInfo.packageName +
11733 "): name already used by "
11734 + ((other != null && other.getComponentName() != null)
11735 ? other.getComponentName().getPackageName() : "?"));
11741 r = new StringBuilder(256);
11745 r.append(p.info.name);
11749 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
11752 N = pkg.services.size();
11754 for (i=0; i<N; i++) {
11755 PackageParser.Service s = pkg.services.get(i);
11756 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11757 s.info.processName);
11758 mServices.addService(s);
11761 r = new StringBuilder(256);
11765 r.append(s.info.name);
11769 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
11772 N = pkg.receivers.size();
11774 for (i=0; i<N; i++) {
11775 PackageParser.Activity a = pkg.receivers.get(i);
11776 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11777 a.info.processName);
11778 mReceivers.addActivity(a, "receiver");
11781 r = new StringBuilder(256);
11785 r.append(a.info.name);
11789 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
11792 N = pkg.activities.size();
11794 for (i=0; i<N; i++) {
11795 PackageParser.Activity a = pkg.activities.get(i);
11796 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11797 a.info.processName);
11798 mActivities.addActivity(a, "activity");
11801 r = new StringBuilder(256);
11805 r.append(a.info.name);
11809 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
11812 N = pkg.permissionGroups.size();
11814 for (i=0; i<N; i++) {
11815 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11816 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11817 final String curPackageName = cur == null ? null : cur.info.packageName;
11818 // Dont allow ephemeral apps to define new permission groups.
11819 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11820 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11821 + pg.info.packageName
11822 + " ignored: instant apps cannot define new permission groups.");
11825 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11826 if (cur == null || isPackageUpdate) {
11827 mPermissionGroups.put(pg.info.name, pg);
11830 r = new StringBuilder(256);
11834 if (isPackageUpdate) {
11837 r.append(pg.info.name);
11840 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11841 + pg.info.packageName + " ignored: original from "
11842 + cur.info.packageName);
11845 r = new StringBuilder(256);
11850 r.append(pg.info.name);
11855 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
11858 N = pkg.permissions.size();
11860 for (i=0; i<N; i++) {
11861 PackageParser.Permission p = pkg.permissions.get(i);
11863 // Dont allow ephemeral apps to define new permissions.
11864 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11865 Slog.w(TAG, "Permission " + p.info.name + " from package "
11866 + p.info.packageName
11867 + " ignored: instant apps cannot define new permissions.");
11871 // Assume by default that we did not install this permission into the system.
11872 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11874 // Now that permission groups have a special meaning, we ignore permission
11875 // groups for legacy apps to prevent unexpected behavior. In particular,
11876 // permissions for one app being granted to someone just because they happen
11877 // to be in a group defined by another app (before this had no implications).
11878 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11879 p.group = mPermissionGroups.get(p.info.group);
11880 // Warn for a permission in an unknown group.
11881 if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11882 Slog.i(TAG, "Permission " + p.info.name + " from package "
11883 + p.info.packageName + " in an unknown group " + p.info.group);
11887 ArrayMap<String, BasePermission> permissionMap =
11888 p.tree ? mSettings.mPermissionTrees
11889 : mSettings.mPermissions;
11890 BasePermission bp = permissionMap.get(p.info.name);
11892 // Allow system apps to redefine non-system permissions
11893 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11894 final boolean currentOwnerIsSystem = (bp.perm != null
11895 && isSystemApp(bp.perm.owner));
11896 if (isSystemApp(p.owner)) {
11897 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11898 // It's a built-in permission and no owner, take ownership now
11899 bp.packageSetting = pkgSetting;
11901 bp.uid = pkg.applicationInfo.uid;
11902 bp.sourcePackage = p.info.packageName;
11903 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11904 } else if (!currentOwnerIsSystem) {
11905 String msg = "New decl " + p.owner + " of permission "
11906 + p.info.name + " is system; overriding " + bp.sourcePackage;
11907 reportSettingsProblem(Log.WARN, msg);
11914 bp = new BasePermission(p.info.name, p.info.packageName,
11915 BasePermission.TYPE_NORMAL);
11916 permissionMap.put(p.info.name, bp);
11919 if (bp.perm == null) {
11920 if (bp.sourcePackage == null
11921 || bp.sourcePackage.equals(p.info.packageName)) {
11922 BasePermission tree = findPermissionTreeLP(p.info.name);
11924 || tree.sourcePackage.equals(p.info.packageName)) {
11925 bp.packageSetting = pkgSetting;
11927 bp.uid = pkg.applicationInfo.uid;
11928 bp.sourcePackage = p.info.packageName;
11929 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11932 r = new StringBuilder(256);
11936 r.append(p.info.name);
11939 Slog.w(TAG, "Permission " + p.info.name + " from package "
11940 + p.info.packageName + " ignored: base tree "
11941 + tree.name + " is from package "
11942 + tree.sourcePackage);
11945 Slog.w(TAG, "Permission " + p.info.name + " from package "
11946 + p.info.packageName + " ignored: original from "
11947 + bp.sourcePackage);
11949 } else if (chatty) {
11951 r = new StringBuilder(256);
11956 r.append(p.info.name);
11958 if (bp.perm == p) {
11959 bp.protectionLevel = p.info.protectionLevel;
11964 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
11967 N = pkg.instrumentation.size();
11969 for (i=0; i<N; i++) {
11970 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11971 a.info.packageName = pkg.applicationInfo.packageName;
11972 a.info.sourceDir = pkg.applicationInfo.sourceDir;
11973 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11974 a.info.splitNames = pkg.splitNames;
11975 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11976 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11977 a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11978 a.info.dataDir = pkg.applicationInfo.dataDir;
11979 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11980 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11981 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11982 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11983 mInstrumentation.put(a.getComponentName(), a);
11986 r = new StringBuilder(256);
11990 r.append(a.info.name);
11994 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
11997 if (pkg.protectedBroadcasts != null) {
11998 N = pkg.protectedBroadcasts.size();
11999 synchronized (mProtectedBroadcasts) {
12000 for (i = 0; i < N; i++) {
12001 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12007 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12011 * Derive the ABI of a non-system package located at {@code scanFile}. This information
12012 * is derived purely on the basis of the contents of {@code scanFile} and
12013 * {@code cpuAbiOverride}.
12015 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12017 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12018 String cpuAbiOverride, boolean extractLibs,
12019 File appLib32InstallDir)
12020 throws PackageManagerException {
12021 // Give ourselves some initial paths; we'll come back for another
12022 // pass once we've determined ABI below.
12023 setNativeLibraryPaths(pkg, appLib32InstallDir);
12025 // We would never need to extract libs for forward-locked and external packages,
12026 // since the container service will do it for us. We shouldn't attempt to
12027 // extract libs from system app when it was not updated.
12028 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12029 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12030 extractLibs = false;
12033 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12034 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12036 NativeLibraryHelper.Handle handle = null;
12038 handle = NativeLibraryHelper.Handle.create(pkg);
12039 // TODO(multiArch): This can be null for apps that didn't go through the
12040 // usual installation process. We can calculate it again, like we
12041 // do during install time.
12043 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12045 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12047 // Null out the abis so that they can be recalculated.
12048 pkg.applicationInfo.primaryCpuAbi = null;
12049 pkg.applicationInfo.secondaryCpuAbi = null;
12050 if (isMultiArch(pkg.applicationInfo)) {
12051 // Warn if we've set an abiOverride for multi-lib packages..
12052 // By definition, we need to copy both 32 and 64 bit libraries for
12054 if (pkg.cpuAbiOverride != null
12055 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12056 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12059 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12060 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12061 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12064 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12065 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12066 useIsaSpecificSubdirs);
12068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12069 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12071 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12074 // Shared library native code should be in the APK zip aligned
12075 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12076 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12077 "Shared library native lib extraction not supported");
12080 maybeThrowExceptionForMultiArchCopy(
12081 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12083 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12085 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12086 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12087 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12088 useIsaSpecificSubdirs);
12090 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12091 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12093 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12096 maybeThrowExceptionForMultiArchCopy(
12097 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12100 // Shared library native libs should be in the APK zip aligned
12101 if (extractLibs && pkg.isLibrary()) {
12102 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12103 "Shared library native lib extraction not supported");
12105 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12109 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12111 if (pkg.use32bitAbi) {
12112 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12113 pkg.applicationInfo.primaryCpuAbi = abi;
12115 pkg.applicationInfo.secondaryCpuAbi = abi;
12118 pkg.applicationInfo.primaryCpuAbi = abi;
12122 String[] abiList = (cpuAbiOverride != null) ?
12123 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12125 // Enable gross and lame hacks for apps that are built with old
12126 // SDK tools. We must scan their APKs for renderscript bitcode and
12127 // not launch them if it's present. Don't bother checking on devices
12128 // that don't have 64 bit support.
12129 boolean needsRenderScriptOverride = false;
12130 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12131 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12132 abiList = Build.SUPPORTED_32_BIT_ABIS;
12133 needsRenderScriptOverride = true;
12138 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12139 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12140 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12142 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12143 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12147 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12148 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12149 "Error unpackaging native libs for app, errorCode=" + copyRet);
12152 if (copyRet >= 0) {
12153 // Shared libraries that have native libs must be multi-architecture
12154 if (pkg.isLibrary()) {
12155 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12156 "Shared library with native libs must be multiarch");
12158 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12159 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12160 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12161 } else if (needsRenderScriptOverride) {
12162 pkg.applicationInfo.primaryCpuAbi = abiList[0];
12165 } catch (IOException ioe) {
12166 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12168 IoUtils.closeQuietly(handle);
12171 // Now that we've calculated the ABIs and determined if it's an internal app,
12172 // we will go ahead and populate the nativeLibraryPath.
12173 setNativeLibraryPaths(pkg, appLib32InstallDir);
12177 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12178 * i.e, so that all packages can be run inside a single process if required.
12180 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12181 * this function will either try and make the ABI for all packages in {@code packagesForUser}
12182 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12183 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12184 * updating a package that belongs to a shared user.
12186 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12187 * adds unnecessary complexity.
12189 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12190 PackageParser.Package scannedPackage) {
12191 String requiredInstructionSet = null;
12192 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12193 requiredInstructionSet = VMRuntime.getInstructionSet(
12194 scannedPackage.applicationInfo.primaryCpuAbi);
12197 PackageSetting requirer = null;
12198 for (PackageSetting ps : packagesForUser) {
12199 // If packagesForUser contains scannedPackage, we skip it. This will happen
12200 // when scannedPackage is an update of an existing package. Without this check,
12201 // we will never be able to change the ABI of any package belonging to a shared
12202 // user, even if it's compatible with other packages.
12203 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12204 if (ps.primaryCpuAbiString == null) {
12208 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12209 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12210 // We have a mismatch between instruction sets (say arm vs arm64) warn about
12211 // this but there's not much we can do.
12212 String errorMessage = "Instruction set mismatch, "
12213 + ((requirer == null) ? "[caller]" : requirer)
12214 + " requires " + requiredInstructionSet + " whereas " + ps
12215 + " requires " + instructionSet;
12216 Slog.w(TAG, errorMessage);
12219 if (requiredInstructionSet == null) {
12220 requiredInstructionSet = instructionSet;
12226 if (requiredInstructionSet != null) {
12227 String adjustedAbi;
12228 if (requirer != null) {
12229 // requirer != null implies that either scannedPackage was null or that scannedPackage
12230 // did not require an ABI, in which case we have to adjust scannedPackage to match
12231 // the ABI of the set (which is the same as requirer's ABI)
12232 adjustedAbi = requirer.primaryCpuAbiString;
12233 if (scannedPackage != null) {
12234 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12237 // requirer == null implies that we're updating all ABIs in the set to
12238 // match scannedPackage.
12239 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
12242 for (PackageSetting ps : packagesForUser) {
12243 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12244 if (ps.primaryCpuAbiString != null) {
12248 ps.primaryCpuAbiString = adjustedAbi;
12249 if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12250 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12251 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12252 if (DEBUG_ABI_SELECTION) {
12253 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12255 + (requirer != null ? requirer.pkg : "null")
12256 + ", scannedPackage="
12257 + (scannedPackage != null ? scannedPackage : "null")
12261 mInstaller.rmdex(ps.codePathString,
12262 getDexCodeInstructionSet(getPreferredInstructionSet()));
12263 } catch (InstallerException ignored) {
12271 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12272 synchronized (mPackages) {
12273 mResolverReplaced = true;
12274 // Set up information for custom user intent resolution activity.
12275 mResolveActivity.applicationInfo = pkg.applicationInfo;
12276 mResolveActivity.name = mCustomResolverComponentName.getClassName();
12277 mResolveActivity.packageName = pkg.applicationInfo.packageName;
12278 mResolveActivity.processName = pkg.applicationInfo.packageName;
12279 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12280 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12281 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12282 mResolveActivity.theme = 0;
12283 mResolveActivity.exported = true;
12284 mResolveActivity.enabled = true;
12285 mResolveInfo.activityInfo = mResolveActivity;
12286 mResolveInfo.priority = 0;
12287 mResolveInfo.preferredOrder = 0;
12288 mResolveInfo.match = 0;
12289 mResolveComponentName = mCustomResolverComponentName;
12290 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12291 mResolveComponentName);
12295 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12296 if (installerActivity == null) {
12297 if (DEBUG_EPHEMERAL) {
12298 Slog.d(TAG, "Clear ephemeral installer activity");
12300 mInstantAppInstallerActivity = null;
12304 if (DEBUG_EPHEMERAL) {
12305 Slog.d(TAG, "Set ephemeral installer activity: "
12306 + installerActivity.getComponentName());
12308 // Set up information for ephemeral installer activity
12309 mInstantAppInstallerActivity = installerActivity;
12310 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12311 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12312 mInstantAppInstallerActivity.exported = true;
12313 mInstantAppInstallerActivity.enabled = true;
12314 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12315 mInstantAppInstallerInfo.priority = 0;
12316 mInstantAppInstallerInfo.preferredOrder = 1;
12317 mInstantAppInstallerInfo.isDefault = true;
12318 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12319 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12322 private static String calculateBundledApkRoot(final String codePathString) {
12323 final File codePath = new File(codePathString);
12324 final File codeRoot;
12325 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12326 codeRoot = Environment.getRootDirectory();
12327 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12328 codeRoot = Environment.getOemDirectory();
12329 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12330 codeRoot = Environment.getVendorDirectory();
12332 // Unrecognized code path; take its top real segment as the apk root:
12333 // e.g. /something/app/blah.apk => /something
12335 File f = codePath.getCanonicalFile();
12336 File parent = f.getParentFile(); // non-null because codePath is a file
12338 while ((tmp = parent.getParentFile()) != null) {
12343 Slog.w(TAG, "Unrecognized code path "
12344 + codePath + " - using " + codeRoot);
12345 } catch (IOException e) {
12346 // Can't canonicalize the code path -- shenanigans?
12347 Slog.w(TAG, "Can't canonicalize code path " + codePath);
12348 return Environment.getRootDirectory().getPath();
12351 return codeRoot.getPath();
12355 * Derive and set the location of native libraries for the given package,
12356 * which varies depending on where and how the package was installed.
12358 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12359 final ApplicationInfo info = pkg.applicationInfo;
12360 final String codePath = pkg.codePath;
12361 final File codeFile = new File(codePath);
12362 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12363 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12365 info.nativeLibraryRootDir = null;
12366 info.nativeLibraryRootRequiresIsa = false;
12367 info.nativeLibraryDir = null;
12368 info.secondaryNativeLibraryDir = null;
12370 if (isApkFile(codeFile)) {
12371 // Monolithic install
12373 // If "/system/lib64/apkname" exists, assume that is the per-package
12374 // native library directory to use; otherwise use "/system/lib/apkname".
12375 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12376 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12377 getPrimaryInstructionSet(info));
12379 // This is a bundled system app so choose the path based on the ABI.
12380 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12381 // is just the default path.
12382 final String apkName = deriveCodePathName(codePath);
12383 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12384 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12385 apkName).getAbsolutePath();
12387 if (info.secondaryCpuAbi != null) {
12388 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12389 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12390 secondaryLibDir, apkName).getAbsolutePath();
12392 } else if (asecApp) {
12393 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12394 .getAbsolutePath();
12396 final String apkName = deriveCodePathName(codePath);
12397 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12398 .getAbsolutePath();
12401 info.nativeLibraryRootRequiresIsa = false;
12402 info.nativeLibraryDir = info.nativeLibraryRootDir;
12405 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12406 info.nativeLibraryRootRequiresIsa = true;
12408 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12409 getPrimaryInstructionSet(info)).getAbsolutePath();
12411 if (info.secondaryCpuAbi != null) {
12412 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12413 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12419 * Calculate the abis and roots for a bundled app. These can uniquely
12420 * be determined from the contents of the system partition, i.e whether
12421 * it contains 64 or 32 bit shared libraries etc. We do not validate any
12422 * of this information, and instead assume that the system was built
12425 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12426 PackageSetting pkgSetting) {
12427 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12429 // If "/system/lib64/apkname" exists, assume that is the per-package
12430 // native library directory to use; otherwise use "/system/lib/apkname".
12431 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12432 setBundledAppAbi(pkg, apkRoot, apkName);
12433 // pkgSetting might be null during rescan following uninstall of updates
12434 // to a bundled app, so accommodate that possibility. The settings in
12435 // that case will be established later from the parsed package.
12437 // If the settings aren't null, sync them up with what we've just derived.
12438 // note that apkRoot isn't stored in the package settings.
12439 if (pkgSetting != null) {
12440 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12441 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12446 * Deduces the ABI of a bundled app and sets the relevant fields on the
12447 * parsed pkg object.
12449 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12450 * under which system libraries are installed.
12451 * @param apkName the name of the installed package.
12453 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12454 final File codeFile = new File(pkg.codePath);
12456 final boolean has64BitLibs;
12457 final boolean has32BitLibs;
12458 if (isApkFile(codeFile)) {
12459 // Monolithic install
12460 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12461 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12464 final File rootDir = new File(codeFile, LIB_DIR_NAME);
12465 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12466 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12467 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12468 has64BitLibs = (new File(rootDir, isa)).exists();
12470 has64BitLibs = false;
12472 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12473 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12474 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12475 has32BitLibs = (new File(rootDir, isa)).exists();
12477 has32BitLibs = false;
12481 if (has64BitLibs && !has32BitLibs) {
12482 // The package has 64 bit libs, but not 32 bit libs. Its primary
12483 // ABI should be 64 bit. We can safely assume here that the bundled
12484 // native libraries correspond to the most preferred ABI in the list.
12486 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12487 pkg.applicationInfo.secondaryCpuAbi = null;
12488 } else if (has32BitLibs && !has64BitLibs) {
12489 // The package has 32 bit libs but not 64 bit libs. Its primary
12490 // ABI should be 32 bit.
12492 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12493 pkg.applicationInfo.secondaryCpuAbi = null;
12494 } else if (has32BitLibs && has64BitLibs) {
12495 // The application has both 64 and 32 bit bundled libraries. We check
12496 // here that the app declares multiArch support, and warn if it doesn't.
12498 // We will be lenient here and record both ABIs. The primary will be the
12499 // ABI that's higher on the list, i.e, a device that's configured to prefer
12500 // 64 bit apps will see a 64 bit primary ABI,
12502 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12503 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12506 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12507 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12508 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12510 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12511 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12514 pkg.applicationInfo.primaryCpuAbi = null;
12515 pkg.applicationInfo.secondaryCpuAbi = null;
12519 private void killApplication(String pkgName, int appId, String reason) {
12520 killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12523 private void killApplication(String pkgName, int appId, int userId, String reason) {
12524 // Request the ActivityManager to kill the process(only for existing packages)
12525 // so that we do not end up in a confused state while the user is still using the older
12526 // version of the application while the new one gets installed.
12527 final long token = Binder.clearCallingIdentity();
12529 IActivityManager am = ActivityManager.getService();
12532 am.killApplication(pkgName, appId, userId, reason);
12533 } catch (RemoteException e) {
12537 Binder.restoreCallingIdentity(token);
12541 private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12542 // Remove the parent package setting
12543 PackageSetting ps = (PackageSetting) pkg.mExtras;
12545 removePackageLI(ps, chatty);
12547 // Remove the child package setting
12548 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12549 for (int i = 0; i < childCount; i++) {
12550 PackageParser.Package childPkg = pkg.childPackages.get(i);
12551 ps = (PackageSetting) childPkg.mExtras;
12553 removePackageLI(ps, chatty);
12558 void removePackageLI(PackageSetting ps, boolean chatty) {
12559 if (DEBUG_INSTALL) {
12561 Log.d(TAG, "Removing package " + ps.name);
12565 synchronized (mPackages) {
12566 mPackages.remove(ps.name);
12567 final PackageParser.Package pkg = ps.pkg;
12569 cleanPackageDataStructuresLILPw(pkg, chatty);
12574 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12575 if (DEBUG_INSTALL) {
12577 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12581 synchronized (mPackages) {
12582 // Remove the parent package
12583 mPackages.remove(pkg.applicationInfo.packageName);
12584 cleanPackageDataStructuresLILPw(pkg, chatty);
12586 // Remove the child packages
12587 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12588 for (int i = 0; i < childCount; i++) {
12589 PackageParser.Package childPkg = pkg.childPackages.get(i);
12590 mPackages.remove(childPkg.applicationInfo.packageName);
12591 cleanPackageDataStructuresLILPw(childPkg, chatty);
12596 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12597 int N = pkg.providers.size();
12598 StringBuilder r = null;
12600 for (i=0; i<N; i++) {
12601 PackageParser.Provider p = pkg.providers.get(i);
12602 mProviders.removeProvider(p);
12603 if (p.info.authority == null) {
12605 /* There was another ContentProvider with this authority when
12606 * this app was installed so this authority is null,
12607 * Ignore it as we don't have to unregister the provider.
12611 String names[] = p.info.authority.split(";");
12612 for (int j = 0; j < names.length; j++) {
12613 if (mProvidersByAuthority.get(names[j]) == p) {
12614 mProvidersByAuthority.remove(names[j]);
12615 if (DEBUG_REMOVE) {
12617 Log.d(TAG, "Unregistered content provider: " + names[j]
12618 + ", className = " + p.info.name + ", isSyncable = "
12619 + p.info.isSyncable);
12623 if (DEBUG_REMOVE && chatty) {
12625 r = new StringBuilder(256);
12629 r.append(p.info.name);
12633 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
12636 N = pkg.services.size();
12638 for (i=0; i<N; i++) {
12639 PackageParser.Service s = pkg.services.get(i);
12640 mServices.removeService(s);
12643 r = new StringBuilder(256);
12647 r.append(s.info.name);
12651 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
12654 N = pkg.receivers.size();
12656 for (i=0; i<N; i++) {
12657 PackageParser.Activity a = pkg.receivers.get(i);
12658 mReceivers.removeActivity(a, "receiver");
12659 if (DEBUG_REMOVE && chatty) {
12661 r = new StringBuilder(256);
12665 r.append(a.info.name);
12669 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
12672 N = pkg.activities.size();
12674 for (i=0; i<N; i++) {
12675 PackageParser.Activity a = pkg.activities.get(i);
12676 mActivities.removeActivity(a, "activity");
12677 if (DEBUG_REMOVE && chatty) {
12679 r = new StringBuilder(256);
12683 r.append(a.info.name);
12687 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
12690 N = pkg.permissions.size();
12692 for (i=0; i<N; i++) {
12693 PackageParser.Permission p = pkg.permissions.get(i);
12694 BasePermission bp = mSettings.mPermissions.get(p.info.name);
12696 bp = mSettings.mPermissionTrees.get(p.info.name);
12698 if (bp != null && bp.perm == p) {
12700 if (DEBUG_REMOVE && chatty) {
12702 r = new StringBuilder(256);
12706 r.append(p.info.name);
12709 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12710 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12711 if (appOpPkgs != null) {
12712 appOpPkgs.remove(pkg.packageName);
12717 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
12720 N = pkg.requestedPermissions.size();
12722 for (i=0; i<N; i++) {
12723 String perm = pkg.requestedPermissions.get(i);
12724 BasePermission bp = mSettings.mPermissions.get(perm);
12725 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12726 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12727 if (appOpPkgs != null) {
12728 appOpPkgs.remove(pkg.packageName);
12729 if (appOpPkgs.isEmpty()) {
12730 mAppOpPermissionPackages.remove(perm);
12736 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
12739 N = pkg.instrumentation.size();
12741 for (i=0; i<N; i++) {
12742 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12743 mInstrumentation.remove(a.getComponentName());
12744 if (DEBUG_REMOVE && chatty) {
12746 r = new StringBuilder(256);
12750 r.append(a.info.name);
12754 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
12758 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12759 // Only system apps can hold shared libraries.
12760 if (pkg.libraryNames != null) {
12761 for (i = 0; i < pkg.libraryNames.size(); i++) {
12762 String name = pkg.libraryNames.get(i);
12763 if (removeSharedLibraryLPw(name, 0)) {
12764 if (DEBUG_REMOVE && chatty) {
12766 r = new StringBuilder(256);
12779 // Any package can hold static shared libraries.
12780 if (pkg.staticSharedLibName != null) {
12781 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12782 if (DEBUG_REMOVE && chatty) {
12784 r = new StringBuilder(256);
12788 r.append(pkg.staticSharedLibName);
12794 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
12798 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12799 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12800 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12807 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12808 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12809 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12811 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12812 // Update the parent permissions
12813 updatePermissionsLPw(pkg.packageName, pkg, flags);
12814 // Update the child permissions
12815 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12816 for (int i = 0; i < childCount; i++) {
12817 PackageParser.Package childPkg = pkg.childPackages.get(i);
12818 updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12822 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12824 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12825 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12828 private void updatePermissionsLPw(String changingPkg,
12829 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12830 // Make sure there are no dangling permission trees.
12831 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12832 while (it.hasNext()) {
12833 final BasePermission bp = it.next();
12834 if (bp.packageSetting == null) {
12835 // We may not yet have parsed the package, so just see if
12836 // we still know about its settings.
12837 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12839 if (bp.packageSetting == null) {
12840 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12841 + " from package " + bp.sourcePackage);
12843 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12844 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12845 Slog.i(TAG, "Removing old permission tree: " + bp.name
12846 + " from package " + bp.sourcePackage);
12847 flags |= UPDATE_PERMISSIONS_ALL;
12853 // Make sure all dynamic permissions have been assigned to a package,
12854 // and make sure there are no dangling permissions.
12855 it = mSettings.mPermissions.values().iterator();
12856 while (it.hasNext()) {
12857 final BasePermission bp = it.next();
12858 if (bp.type == BasePermission.TYPE_DYNAMIC) {
12859 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12860 + bp.name + " pkg=" + bp.sourcePackage
12861 + " info=" + bp.pendingInfo);
12862 if (bp.packageSetting == null && bp.pendingInfo != null) {
12863 final BasePermission tree = findPermissionTreeLP(bp.name);
12864 if (tree != null && tree.perm != null) {
12865 bp.packageSetting = tree.packageSetting;
12866 bp.perm = new PackageParser.Permission(tree.perm.owner,
12867 new PermissionInfo(bp.pendingInfo));
12868 bp.perm.info.packageName = tree.perm.info.packageName;
12869 bp.perm.info.name = bp.name;
12874 if (bp.packageSetting == null) {
12875 // We may not yet have parsed the package, so just see if
12876 // we still know about its settings.
12877 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12879 if (bp.packageSetting == null) {
12880 Slog.w(TAG, "Removing dangling permission: " + bp.name
12881 + " from package " + bp.sourcePackage);
12883 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12884 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12885 Slog.i(TAG, "Removing old permission: " + bp.name
12886 + " from package " + bp.sourcePackage);
12887 flags |= UPDATE_PERMISSIONS_ALL;
12893 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12894 // Now update the permissions for all packages, in particular
12895 // replace the granted permissions of the system packages.
12896 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12897 for (PackageParser.Package pkg : mPackages.values()) {
12898 if (pkg != pkgInfo) {
12899 // Only replace for packages on requested volume
12900 final String volumeUuid = getVolumeUuidForPackage(pkg);
12901 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12902 && Objects.equals(replaceVolumeUuid, volumeUuid);
12903 grantPermissionsLPw(pkg, replace, changingPkg);
12908 if (pkgInfo != null) {
12909 // Only replace for packages on requested volume
12910 final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12911 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12912 && Objects.equals(replaceVolumeUuid, volumeUuid);
12913 grantPermissionsLPw(pkgInfo, replace, changingPkg);
12915 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12918 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12919 String packageOfInterest) {
12920 // IMPORTANT: There are two types of permissions: install and runtime.
12921 // Install time permissions are granted when the app is installed to
12922 // all device users and users added in the future. Runtime permissions
12923 // are granted at runtime explicitly to specific users. Normal and signature
12924 // protected permissions are install time permissions. Dangerous permissions
12925 // are install permissions if the app's target SDK is Lollipop MR1 or older,
12926 // otherwise they are runtime permissions. This function does not manage
12927 // runtime permissions except for the case an app targeting Lollipop MR1
12928 // being upgraded to target a newer SDK, in which case dangerous permissions
12929 // are transformed from install time to runtime ones.
12931 final PackageSetting ps = (PackageSetting) pkg.mExtras;
12936 PermissionsState permissionsState = ps.getPermissionsState();
12937 PermissionsState origPermissions = permissionsState;
12939 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12941 boolean runtimePermissionsRevoked = false;
12942 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12944 boolean changedInstallPermission = false;
12947 ps.installPermissionsFixed = false;
12948 if (!ps.isSharedUser()) {
12949 origPermissions = new PermissionsState(permissionsState);
12950 permissionsState.reset();
12952 // We need to know only about runtime permission changes since the
12953 // calling code always writes the install permissions state but
12954 // the runtime ones are written only if changed. The only cases of
12955 // changed runtime permissions here are promotion of an install to
12956 // runtime and revocation of a runtime from a shared user.
12957 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12958 ps.sharedUser, UserManagerService.getInstance().getUserIds());
12959 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12960 runtimePermissionsRevoked = true;
12965 permissionsState.setGlobalGids(mGlobalGids);
12967 final int N = pkg.requestedPermissions.size();
12968 for (int i=0; i<N; i++) {
12969 final String name = pkg.requestedPermissions.get(i);
12970 final BasePermission bp = mSettings.mPermissions.get(name);
12971 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12972 >= Build.VERSION_CODES.M;
12974 if (DEBUG_INSTALL) {
12975 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12978 if (bp == null || bp.packageSetting == null) {
12979 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12980 if (DEBUG_PERMISSIONS) {
12981 Slog.i(TAG, "Unknown permission " + name
12982 + " in package " + pkg.packageName);
12989 // Limit ephemeral apps to ephemeral allowed permissions.
12990 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12991 if (DEBUG_PERMISSIONS) {
12992 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12993 + pkg.packageName);
12998 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12999 if (DEBUG_PERMISSIONS) {
13000 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
13001 + pkg.packageName);
13006 final String perm = bp.name;
13007 boolean allowedSig = false;
13008 int grant = GRANT_DENIED;
13010 // Keep track of app op permissions.
13011 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
13012 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
13013 if (pkgs == null) {
13014 pkgs = new ArraySet<>();
13015 mAppOpPermissionPackages.put(bp.name, pkgs);
13017 pkgs.add(pkg.packageName);
13020 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13022 case PermissionInfo.PROTECTION_NORMAL: {
13023 // For all apps normal permissions are install time ones.
13024 grant = GRANT_INSTALL;
13027 case PermissionInfo.PROTECTION_DANGEROUS: {
13028 // If a permission review is required for legacy apps we represent
13029 // their permissions as always granted runtime ones since we need
13030 // to keep the review required permission flag per user while an
13031 // install permission's state is shared across all users.
13032 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13033 // For legacy apps dangerous permissions are install time ones.
13034 grant = GRANT_INSTALL;
13035 } else if (origPermissions.hasInstallPermission(bp.name)) {
13036 // For legacy apps that became modern, install becomes runtime.
13037 grant = GRANT_UPGRADE;
13038 } else if (mPromoteSystemApps
13040 && mExistingSystemPackages.contains(ps.name)) {
13041 // For legacy system apps, install becomes runtime.
13042 // We cannot check hasInstallPermission() for system apps since those
13043 // permissions were granted implicitly and not persisted pre-M.
13044 grant = GRANT_UPGRADE;
13046 // For modern apps keep runtime permissions unchanged.
13047 grant = GRANT_RUNTIME;
13051 case PermissionInfo.PROTECTION_SIGNATURE: {
13052 // For all apps signature permissions are install time ones.
13053 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13055 grant = GRANT_INSTALL;
13060 if (DEBUG_PERMISSIONS) {
13061 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13064 if (grant != GRANT_DENIED) {
13065 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13066 // If this is an existing, non-system package, then
13067 // we can't add any new permissions to it.
13068 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13069 // Except... if this is a permission that was added
13070 // to the platform (note: need to only do this when
13071 // updating the platform).
13072 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13073 grant = GRANT_DENIED;
13079 case GRANT_INSTALL: {
13080 // Revoke this as runtime permission to handle the case of
13081 // a runtime permission being downgraded to an install one.
13082 // Also in permission review mode we keep dangerous permissions
13084 for (int userId : UserManagerService.getInstance().getUserIds()) {
13085 if (origPermissions.getRuntimePermissionState(
13086 bp.name, userId) != null) {
13087 // Revoke the runtime permission and clear the flags.
13088 origPermissions.revokeRuntimePermission(bp, userId);
13089 origPermissions.updatePermissionFlags(bp, userId,
13090 PackageManager.MASK_PERMISSION_FLAGS, 0);
13091 // If we revoked a permission permission, we have to write.
13092 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13093 changedRuntimePermissionUserIds, userId);
13096 // Grant an install permission.
13097 if (permissionsState.grantInstallPermission(bp) !=
13098 PermissionsState.PERMISSION_OPERATION_FAILURE) {
13099 changedInstallPermission = true;
13103 case GRANT_RUNTIME: {
13104 // Grant previously granted runtime permissions.
13105 for (int userId : UserManagerService.getInstance().getUserIds()) {
13106 PermissionState permissionState = origPermissions
13107 .getRuntimePermissionState(bp.name, userId);
13108 int flags = permissionState != null
13109 ? permissionState.getFlags() : 0;
13110 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13111 // Don't propagate the permission in a permission review mode if
13112 // the former was revoked, i.e. marked to not propagate on upgrade.
13113 // Note that in a permission review mode install permissions are
13114 // represented as constantly granted runtime ones since we need to
13115 // keep a per user state associated with the permission. Also the
13116 // revoke on upgrade flag is no longer applicable and is reset.
13117 final boolean revokeOnUpgrade = (flags & PackageManager
13118 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13119 if (revokeOnUpgrade) {
13120 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13121 // Since we changed the flags, we have to write.
13122 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13123 changedRuntimePermissionUserIds, userId);
13125 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13126 if (permissionsState.grantRuntimePermission(bp, userId) ==
13127 PermissionsState.PERMISSION_OPERATION_FAILURE) {
13128 // If we cannot put the permission as it was,
13129 // we have to write.
13130 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13131 changedRuntimePermissionUserIds, userId);
13135 // If the app supports runtime permissions no need for a review.
13136 if (mPermissionReviewRequired
13137 && appSupportsRuntimePermissions
13138 && (flags & PackageManager
13139 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13140 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13141 // Since we changed the flags, we have to write.
13142 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13143 changedRuntimePermissionUserIds, userId);
13145 } else if (mPermissionReviewRequired
13146 && !appSupportsRuntimePermissions) {
13147 // For legacy apps that need a permission review, every new
13148 // runtime permission is granted but it is pending a review.
13149 // We also need to review only platform defined runtime
13150 // permissions as these are the only ones the platform knows
13151 // how to disable the API to simulate revocation as legacy
13152 // apps don't expect to run with revoked permissions.
13153 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13154 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13155 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13156 // We changed the flags, hence have to write.
13157 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13158 changedRuntimePermissionUserIds, userId);
13161 if (permissionsState.grantRuntimePermission(bp, userId)
13162 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13163 // We changed the permission, hence have to write.
13164 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13165 changedRuntimePermissionUserIds, userId);
13168 // Propagate the permission flags.
13169 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13173 case GRANT_UPGRADE: {
13174 // Grant runtime permissions for a previously held install permission.
13175 PermissionState permissionState = origPermissions
13176 .getInstallPermissionState(bp.name);
13177 final int flags = permissionState != null ? permissionState.getFlags() : 0;
13179 if (origPermissions.revokeInstallPermission(bp)
13180 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13181 // We will be transferring the permission flags, so clear them.
13182 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13183 PackageManager.MASK_PERMISSION_FLAGS, 0);
13184 changedInstallPermission = true;
13187 // If the permission is not to be promoted to runtime we ignore it and
13188 // also its other flags as they are not applicable to install permissions.
13189 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13190 for (int userId : currentUserIds) {
13191 if (permissionsState.grantRuntimePermission(bp, userId) !=
13192 PermissionsState.PERMISSION_OPERATION_FAILURE) {
13193 // Transfer the permission flags.
13194 permissionsState.updatePermissionFlags(bp, userId,
13196 // If we granted the permission, we have to write.
13197 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13198 changedRuntimePermissionUserIds, userId);
13205 if (packageOfInterest == null
13206 || packageOfInterest.equals(pkg.packageName)) {
13207 if (DEBUG_PERMISSIONS) {
13208 Slog.i(TAG, "Not granting permission " + perm
13209 + " to package " + pkg.packageName
13210 + " because it was previously installed without");
13216 if (permissionsState.revokeInstallPermission(bp) !=
13217 PermissionsState.PERMISSION_OPERATION_FAILURE) {
13218 // Also drop the permission flags.
13219 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13220 PackageManager.MASK_PERMISSION_FLAGS, 0);
13221 changedInstallPermission = true;
13222 Slog.i(TAG, "Un-granting permission " + perm
13223 + " from package " + pkg.packageName
13224 + " (protectionLevel=" + bp.protectionLevel
13225 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13227 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13228 // Don't print warning for app op permissions, since it is fine for them
13229 // not to be granted, there is a UI for the user to decide.
13230 if (DEBUG_PERMISSIONS
13231 && (packageOfInterest == null
13232 || packageOfInterest.equals(pkg.packageName))) {
13233 Slog.i(TAG, "Not granting permission " + perm
13234 + " to package " + pkg.packageName
13235 + " (protectionLevel=" + bp.protectionLevel
13236 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13243 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13244 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13245 // This is the first that we have heard about this package, so the
13246 // permissions we have now selected are fixed until explicitly
13248 ps.installPermissionsFixed = true;
13251 // Persist the runtime permissions state for users with changes. If permissions
13252 // were revoked because no app in the shared user declares them we have to
13253 // write synchronously to avoid losing runtime permissions state.
13254 for (int userId : changedRuntimePermissionUserIds) {
13255 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13259 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13260 boolean allowed = false;
13261 final int NP = PackageParser.NEW_PERMISSIONS.length;
13262 for (int ip=0; ip<NP; ip++) {
13263 final PackageParser.NewPermissionInfo npi
13264 = PackageParser.NEW_PERMISSIONS[ip];
13265 if (npi.name.equals(perm)
13266 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13268 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13269 + pkg.packageName);
13276 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13277 BasePermission bp, PermissionsState origPermissions) {
13278 boolean privilegedPermission = (bp.protectionLevel
13279 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13280 boolean privappPermissionsDisable =
13281 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13282 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13283 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13284 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13285 && !platformPackage && platformPermission) {
13286 final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13287 .getPrivAppPermissions(pkg.packageName);
13288 final boolean whitelisted =
13289 allowedPermissions != null && allowedPermissions.contains(perm);
13290 if (!whitelisted) {
13291 Slog.w(TAG, "Privileged permission " + perm + " for package "
13292 + pkg.packageName + " - not in privapp-permissions whitelist");
13293 // Only report violations for apps on system image
13294 if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13295 // it's only a reportable violation if the permission isn't explicitly denied
13296 final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13297 .getPrivAppDenyPermissions(pkg.packageName);
13298 final boolean permissionViolation =
13299 deniedPermissions == null || !deniedPermissions.contains(perm);
13300 if (permissionViolation) {
13301 if (mPrivappPermissionsViolations == null) {
13302 mPrivappPermissionsViolations = new ArraySet<>();
13304 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13309 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13314 boolean allowed = (compareSignatures(
13315 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13316 == PackageManager.SIGNATURE_MATCH)
13317 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13318 == PackageManager.SIGNATURE_MATCH);
13319 if (!allowed && privilegedPermission) {
13320 if (isSystemApp(pkg)) {
13321 // For updated system applications, a system permission
13322 // is granted only if it had been defined by the original application.
13323 if (pkg.isUpdatedSystemApp()) {
13324 final PackageSetting sysPs = mSettings
13325 .getDisabledSystemPkgLPr(pkg.packageName);
13326 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13327 // If the original was granted this permission, we take
13328 // that grant decision as read and propagate it to the
13330 if (sysPs.isPrivileged()) {
13334 // The system apk may have been updated with an older
13335 // version of the one on the data partition, but which
13336 // granted a new system permission that it didn't have
13337 // before. In this case we do want to allow the app to
13338 // now get the new permission if the ancestral apk is
13339 // privileged to get it.
13340 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13341 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13342 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13348 // Also if a privileged parent package on the system image or any of
13349 // its children requested a privileged permission, the updated child
13350 // packages can also get the permission.
13351 if (pkg.parentPackage != null) {
13352 final PackageSetting disabledSysParentPs = mSettings
13353 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13354 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13355 && disabledSysParentPs.isPrivileged()) {
13356 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13358 } else if (disabledSysParentPs.pkg.childPackages != null) {
13359 final int count = disabledSysParentPs.pkg.childPackages.size();
13360 for (int i = 0; i < count; i++) {
13361 PackageParser.Package disabledSysChildPkg =
13362 disabledSysParentPs.pkg.childPackages.get(i);
13363 if (isPackageRequestingPermission(disabledSysChildPkg,
13374 allowed = isPrivilegedApp(pkg);
13379 if (!allowed && (bp.protectionLevel
13380 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13381 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13382 // If this was a previously normal/dangerous permission that got moved
13383 // to a system permission as part of the runtime permission redesign, then
13384 // we still want to blindly grant it to old apps.
13387 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13388 && pkg.packageName.equals(mRequiredInstallerPackage)) {
13389 // If this permission is to be granted to the system installer and
13390 // this app is an installer, then it gets the permission.
13393 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13394 && pkg.packageName.equals(mRequiredVerifierPackage)) {
13395 // If this permission is to be granted to the system verifier and
13396 // this app is a verifier, then it gets the permission.
13399 if (!allowed && (bp.protectionLevel
13400 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13401 && isSystemApp(pkg)) {
13402 // Any pre-installed system app is allowed to get this permission.
13405 if (!allowed && (bp.protectionLevel
13406 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13407 // For development permissions, a development permission
13408 // is granted only if it was already granted.
13409 allowed = origPermissions.hasInstallPermission(perm);
13411 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13412 && pkg.packageName.equals(mSetupWizardPackage)) {
13413 // If this permission is to be granted to the system setup wizard and
13414 // this app is a setup wizard, then it gets the permission.
13421 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13422 final int permCount = pkg.requestedPermissions.size();
13423 for (int j = 0; j < permCount; j++) {
13424 String requestedPermission = pkg.requestedPermissions.get(j);
13425 if (permission.equals(requestedPermission)) {
13432 final class ActivityIntentResolver
13433 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13434 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13435 boolean defaultOnly, int userId) {
13436 if (!sUserManager.exists(userId)) return null;
13437 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13438 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13441 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13443 if (!sUserManager.exists(userId)) return null;
13445 return super.queryIntent(intent, resolvedType,
13446 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13450 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13451 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13452 if (!sUserManager.exists(userId)) return null;
13453 if (packageActivities == null) {
13457 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13458 final int N = packageActivities.size();
13459 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13460 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13462 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13463 for (int i = 0; i < N; ++i) {
13464 intentFilters = packageActivities.get(i).intents;
13465 if (intentFilters != null && intentFilters.size() > 0) {
13466 PackageParser.ActivityIntentInfo[] array =
13467 new PackageParser.ActivityIntentInfo[intentFilters.size()];
13468 intentFilters.toArray(array);
13469 listCut.add(array);
13472 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13476 * Finds a privileged activity that matches the specified activity names.
13478 private PackageParser.Activity findMatchingActivity(
13479 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13480 for (PackageParser.Activity sysActivity : activityList) {
13481 if (sysActivity.info.name.equals(activityInfo.name)) {
13482 return sysActivity;
13484 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13485 return sysActivity;
13487 if (sysActivity.info.targetActivity != null) {
13488 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13489 return sysActivity;
13491 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13492 return sysActivity;
13499 public class IterGenerator<E> {
13500 public Iterator<E> generate(ActivityIntentInfo info) {
13505 public class ActionIterGenerator extends IterGenerator<String> {
13507 public Iterator<String> generate(ActivityIntentInfo info) {
13508 return info.actionsIterator();
13512 public class CategoriesIterGenerator extends IterGenerator<String> {
13514 public Iterator<String> generate(ActivityIntentInfo info) {
13515 return info.categoriesIterator();
13519 public class SchemesIterGenerator extends IterGenerator<String> {
13521 public Iterator<String> generate(ActivityIntentInfo info) {
13522 return info.schemesIterator();
13526 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13528 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13529 return info.authoritiesIterator();
13534 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13535 * MODIFIED. Do not pass in a list that should not be changed.
13537 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13538 IterGenerator<T> generator, Iterator<T> searchIterator) {
13539 // loop through the set of actions; every one must be found in the intent filter
13540 while (searchIterator.hasNext()) {
13541 // we must have at least one filter in the list to consider a match
13542 if (intentList.size() == 0) {
13546 final T searchAction = searchIterator.next();
13548 // loop through the set of intent filters
13549 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13550 while (intentIter.hasNext()) {
13551 final ActivityIntentInfo intentInfo = intentIter.next();
13552 boolean selectionFound = false;
13554 // loop through the intent filter's selection criteria; at least one
13555 // of them must match the searched criteria
13556 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13557 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13558 final T intentSelection = intentSelectionIter.next();
13559 if (intentSelection != null && intentSelection.equals(searchAction)) {
13560 selectionFound = true;
13565 // the selection criteria wasn't found in this filter's set; this filter
13566 // is not a potential match
13567 if (!selectionFound) {
13568 intentIter.remove();
13574 private boolean isProtectedAction(ActivityIntentInfo filter) {
13575 final Iterator<String> actionsIter = filter.actionsIterator();
13576 while (actionsIter != null && actionsIter.hasNext()) {
13577 final String filterAction = actionsIter.next();
13578 if (PROTECTED_ACTIONS.contains(filterAction)) {
13586 * Adjusts the priority of the given intent filter according to policy.
13589 * <li>The priority for non privileged applications is capped to '0'</li>
13590 * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13591 * <li>The priority for unbundled updates to privileged applications is capped to the
13592 * priority defined on the system partition</li>
13595 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13596 * allowed to obtain any priority on any action.
13598 private void adjustPriority(
13599 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13600 // nothing to do; priority is fine as-is
13601 if (intent.getPriority() <= 0) {
13605 final ActivityInfo activityInfo = intent.activity.info;
13606 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13608 final boolean privilegedApp =
13609 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13610 if (!privilegedApp) {
13611 // non-privileged applications can never define a priority >0
13612 if (DEBUG_FILTERS) {
13613 Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13614 + " package: " + applicationInfo.packageName
13615 + " activity: " + intent.activity.className
13616 + " origPrio: " + intent.getPriority());
13618 intent.setPriority(0);
13622 if (systemActivities == null) {
13623 // the system package is not disabled; we're parsing the system partition
13624 if (isProtectedAction(intent)) {
13625 if (mDeferProtectedFilters) {
13626 // We can't deal with these just yet. No component should ever obtain a
13627 // >0 priority for a protected actions, with ONE exception -- the setup
13628 // wizard. The setup wizard, however, cannot be known until we're able to
13629 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13630 // until all intent filters have been processed. Chicken, meet egg.
13631 // Let the filter temporarily have a high priority and rectify the
13632 // priorities after all system packages have been scanned.
13633 mProtectedFilters.add(intent);
13634 if (DEBUG_FILTERS) {
13635 Slog.i(TAG, "Protected action; save for later;"
13636 + " package: " + applicationInfo.packageName
13637 + " activity: " + intent.activity.className
13638 + " origPrio: " + intent.getPriority());
13642 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13643 Slog.i(TAG, "No setup wizard;"
13644 + " All protected intents capped to priority 0");
13646 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13647 if (DEBUG_FILTERS) {
13648 Slog.i(TAG, "Found setup wizard;"
13649 + " allow priority " + intent.getPriority() + ";"
13650 + " package: " + intent.activity.info.packageName
13651 + " activity: " + intent.activity.className
13652 + " priority: " + intent.getPriority());
13654 // setup wizard gets whatever it wants
13657 if (DEBUG_FILTERS) {
13658 Slog.i(TAG, "Protected action; cap priority to 0;"
13659 + " package: " + intent.activity.info.packageName
13660 + " activity: " + intent.activity.className
13661 + " origPrio: " + intent.getPriority());
13663 intent.setPriority(0);
13667 // privileged apps on the system image get whatever priority they request
13671 // privileged app unbundled update ... try to find the same activity
13672 final PackageParser.Activity foundActivity =
13673 findMatchingActivity(systemActivities, activityInfo);
13674 if (foundActivity == null) {
13675 // this is a new activity; it cannot obtain >0 priority
13676 if (DEBUG_FILTERS) {
13677 Slog.i(TAG, "New activity; cap priority to 0;"
13678 + " package: " + applicationInfo.packageName
13679 + " activity: " + intent.activity.className
13680 + " origPrio: " + intent.getPriority());
13682 intent.setPriority(0);
13686 // found activity, now check for filter equivalence
13688 // a shallow copy is enough; we modify the list, not its contents
13689 final List<ActivityIntentInfo> intentListCopy =
13690 new ArrayList<>(foundActivity.intents);
13691 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13693 // find matching action subsets
13694 final Iterator<String> actionsIterator = intent.actionsIterator();
13695 if (actionsIterator != null) {
13696 getIntentListSubset(
13697 intentListCopy, new ActionIterGenerator(), actionsIterator);
13698 if (intentListCopy.size() == 0) {
13699 // no more intents to match; we're not equivalent
13700 if (DEBUG_FILTERS) {
13701 Slog.i(TAG, "Mismatched action; cap priority to 0;"
13702 + " package: " + applicationInfo.packageName
13703 + " activity: " + intent.activity.className
13704 + " origPrio: " + intent.getPriority());
13706 intent.setPriority(0);
13711 // find matching category subsets
13712 final Iterator<String> categoriesIterator = intent.categoriesIterator();
13713 if (categoriesIterator != null) {
13714 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13715 categoriesIterator);
13716 if (intentListCopy.size() == 0) {
13717 // no more intents to match; we're not equivalent
13718 if (DEBUG_FILTERS) {
13719 Slog.i(TAG, "Mismatched category; cap priority to 0;"
13720 + " package: " + applicationInfo.packageName
13721 + " activity: " + intent.activity.className
13722 + " origPrio: " + intent.getPriority());
13724 intent.setPriority(0);
13729 // find matching schemes subsets
13730 final Iterator<String> schemesIterator = intent.schemesIterator();
13731 if (schemesIterator != null) {
13732 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13734 if (intentListCopy.size() == 0) {
13735 // no more intents to match; we're not equivalent
13736 if (DEBUG_FILTERS) {
13737 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13738 + " package: " + applicationInfo.packageName
13739 + " activity: " + intent.activity.className
13740 + " origPrio: " + intent.getPriority());
13742 intent.setPriority(0);
13747 // find matching authorities subsets
13748 final Iterator<IntentFilter.AuthorityEntry>
13749 authoritiesIterator = intent.authoritiesIterator();
13750 if (authoritiesIterator != null) {
13751 getIntentListSubset(intentListCopy,
13752 new AuthoritiesIterGenerator(),
13753 authoritiesIterator);
13754 if (intentListCopy.size() == 0) {
13755 // no more intents to match; we're not equivalent
13756 if (DEBUG_FILTERS) {
13757 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13758 + " package: " + applicationInfo.packageName
13759 + " activity: " + intent.activity.className
13760 + " origPrio: " + intent.getPriority());
13762 intent.setPriority(0);
13767 // we found matching filter(s); app gets the max priority of all intents
13768 int cappedPriority = 0;
13769 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13770 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13772 if (intent.getPriority() > cappedPriority) {
13773 if (DEBUG_FILTERS) {
13774 Slog.i(TAG, "Found matching filter(s);"
13775 + " cap priority to " + cappedPriority + ";"
13776 + " package: " + applicationInfo.packageName
13777 + " activity: " + intent.activity.className
13778 + " origPrio: " + intent.getPriority());
13780 intent.setPriority(cappedPriority);
13783 // all this for nothing; the requested priority was <= what was on the system
13786 public final void addActivity(PackageParser.Activity a, String type) {
13787 mActivities.put(a.getComponentName(), a);
13788 if (DEBUG_SHOW_INFO)
13790 TAG, " " + type + " " +
13791 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13792 if (DEBUG_SHOW_INFO)
13793 Log.v(TAG, " Class=" + a.info.name);
13794 final int NI = a.intents.size();
13795 for (int j=0; j<NI; j++) {
13796 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13797 if ("activity".equals(type)) {
13798 final PackageSetting ps =
13799 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13800 final List<PackageParser.Activity> systemActivities =
13801 ps != null && ps.pkg != null ? ps.pkg.activities : null;
13802 adjustPriority(systemActivities, intent);
13804 if (DEBUG_SHOW_INFO) {
13805 Log.v(TAG, " IntentFilter:");
13806 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13808 if (!intent.debugCheck()) {
13809 Log.w(TAG, "==> For Activity " + a.info.name);
13815 public final void removeActivity(PackageParser.Activity a, String type) {
13816 mActivities.remove(a.getComponentName());
13817 if (DEBUG_SHOW_INFO) {
13818 Log.v(TAG, " " + type + " "
13819 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13820 : a.info.name) + ":");
13821 Log.v(TAG, " Class=" + a.info.name);
13823 final int NI = a.intents.size();
13824 for (int j=0; j<NI; j++) {
13825 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13826 if (DEBUG_SHOW_INFO) {
13827 Log.v(TAG, " IntentFilter:");
13828 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13830 removeFilter(intent);
13835 protected boolean allowFilterResult(
13836 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13837 ActivityInfo filterAi = filter.activity.info;
13838 for (int i=dest.size()-1; i>=0; i--) {
13839 ActivityInfo destAi = dest.get(i).activityInfo;
13840 if (destAi.name == filterAi.name
13841 && destAi.packageName == filterAi.packageName) {
13849 protected ActivityIntentInfo[] newArray(int size) {
13850 return new ActivityIntentInfo[size];
13854 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13855 if (!sUserManager.exists(userId)) return true;
13856 PackageParser.Package p = filter.activity.owner;
13858 PackageSetting ps = (PackageSetting)p.mExtras;
13860 // System apps are never considered stopped for purposes of
13861 // filtering, because there may be no way for the user to
13862 // actually re-launch them.
13863 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13864 && ps.getStopped(userId);
13871 protected boolean isPackageForFilter(String packageName,
13872 PackageParser.ActivityIntentInfo info) {
13873 return packageName.equals(info.activity.owner.packageName);
13877 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13878 int match, int userId) {
13879 if (!sUserManager.exists(userId)) return null;
13880 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13883 final PackageParser.Activity activity = info.activity;
13884 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13888 final PackageUserState userState = ps.readUserState(userId);
13890 PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13894 final boolean matchExplicitlyVisibleOnly =
13895 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13896 final boolean matchVisibleToInstantApp =
13897 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13898 final boolean componentVisible =
13899 matchVisibleToInstantApp
13900 && info.isVisibleToInstantApp()
13901 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13902 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13903 // throw out filters that aren't visible to ephemeral apps
13904 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13907 // throw out instant app filters if we're not explicitly requesting them
13908 if (!matchInstantApp && userState.instantApp) {
13911 // throw out instant app filters if updates are available; will trigger
13912 // instant app resolution
13913 if (userState.instantApp && ps.isUpdateAvailable()) {
13916 final ResolveInfo res = new ResolveInfo();
13917 res.activityInfo = ai;
13918 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13921 if (info != null) {
13922 res.handleAllWebDataURI = info.handleAllWebDataURI();
13924 res.priority = info.getPriority();
13925 res.preferredOrder = activity.owner.mPreferredOrder;
13926 //System.out.println("Result: " + res.activityInfo.className +
13927 // " = " + res.priority);
13929 res.isDefault = info.hasDefault;
13930 res.labelRes = info.labelRes;
13931 res.nonLocalizedLabel = info.nonLocalizedLabel;
13932 if (userNeedsBadging(userId)) {
13933 res.noResourceId = true;
13935 res.icon = info.icon;
13937 res.iconResourceId = info.icon;
13938 res.system = res.activityInfo.applicationInfo.isSystemApp();
13939 res.isInstantAppAvailable = userState.instantApp;
13944 protected void sortResults(List<ResolveInfo> results) {
13945 Collections.sort(results, mResolvePrioritySorter);
13949 protected void dumpFilter(PrintWriter out, String prefix,
13950 PackageParser.ActivityIntentInfo filter) {
13951 out.print(prefix); out.print(
13952 Integer.toHexString(System.identityHashCode(filter.activity)));
13954 filter.activity.printComponentShortName(out);
13955 out.print(" filter ");
13956 out.println(Integer.toHexString(System.identityHashCode(filter)));
13960 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13961 return filter.activity;
13964 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13965 PackageParser.Activity activity = (PackageParser.Activity)label;
13966 out.print(prefix); out.print(
13967 Integer.toHexString(System.identityHashCode(activity)));
13969 activity.printComponentShortName(out);
13971 out.print(" ("); out.print(count); out.print(" filters)");
13976 // Keys are String (activity class name), values are Activity.
13977 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13978 = new ArrayMap<ComponentName, PackageParser.Activity>();
13979 private int mFlags;
13982 private final class ServiceIntentResolver
13983 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13984 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13985 boolean defaultOnly, int userId) {
13986 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13987 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13990 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13992 if (!sUserManager.exists(userId)) return null;
13994 return super.queryIntent(intent, resolvedType,
13995 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13999 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14000 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14001 if (!sUserManager.exists(userId)) return null;
14002 if (packageServices == null) {
14006 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14007 final int N = packageServices.size();
14008 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14009 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14011 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14012 for (int i = 0; i < N; ++i) {
14013 intentFilters = packageServices.get(i).intents;
14014 if (intentFilters != null && intentFilters.size() > 0) {
14015 PackageParser.ServiceIntentInfo[] array =
14016 new PackageParser.ServiceIntentInfo[intentFilters.size()];
14017 intentFilters.toArray(array);
14018 listCut.add(array);
14021 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14024 public final void addService(PackageParser.Service s) {
14025 mServices.put(s.getComponentName(), s);
14026 if (DEBUG_SHOW_INFO) {
14028 + (s.info.nonLocalizedLabel != null
14029 ? s.info.nonLocalizedLabel : s.info.name) + ":");
14030 Log.v(TAG, " Class=" + s.info.name);
14032 final int NI = s.intents.size();
14034 for (j=0; j<NI; j++) {
14035 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14036 if (DEBUG_SHOW_INFO) {
14037 Log.v(TAG, " IntentFilter:");
14038 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
14040 if (!intent.debugCheck()) {
14041 Log.w(TAG, "==> For Service " + s.info.name);
14047 public final void removeService(PackageParser.Service s) {
14048 mServices.remove(s.getComponentName());
14049 if (DEBUG_SHOW_INFO) {
14050 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
14051 ? s.info.nonLocalizedLabel : s.info.name) + ":");
14052 Log.v(TAG, " Class=" + s.info.name);
14054 final int NI = s.intents.size();
14056 for (j=0; j<NI; j++) {
14057 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14058 if (DEBUG_SHOW_INFO) {
14059 Log.v(TAG, " IntentFilter:");
14060 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
14062 removeFilter(intent);
14067 protected boolean allowFilterResult(
14068 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14069 ServiceInfo filterSi = filter.service.info;
14070 for (int i=dest.size()-1; i>=0; i--) {
14071 ServiceInfo destAi = dest.get(i).serviceInfo;
14072 if (destAi.name == filterSi.name
14073 && destAi.packageName == filterSi.packageName) {
14081 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14082 return new PackageParser.ServiceIntentInfo[size];
14086 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14087 if (!sUserManager.exists(userId)) return true;
14088 PackageParser.Package p = filter.service.owner;
14090 PackageSetting ps = (PackageSetting)p.mExtras;
14092 // System apps are never considered stopped for purposes of
14093 // filtering, because there may be no way for the user to
14094 // actually re-launch them.
14095 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14096 && ps.getStopped(userId);
14103 protected boolean isPackageForFilter(String packageName,
14104 PackageParser.ServiceIntentInfo info) {
14105 return packageName.equals(info.service.owner.packageName);
14109 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14110 int match, int userId) {
14111 if (!sUserManager.exists(userId)) return null;
14112 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14113 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14116 final PackageParser.Service service = info.service;
14117 PackageSetting ps = (PackageSetting) service.owner.mExtras;
14121 final PackageUserState userState = ps.readUserState(userId);
14122 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14123 userState, userId);
14127 final boolean matchVisibleToInstantApp =
14128 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14129 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14130 // throw out filters that aren't visible to ephemeral apps
14131 if (matchVisibleToInstantApp
14132 && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14135 // throw out ephemeral filters if we're not explicitly requesting them
14136 if (!isInstantApp && userState.instantApp) {
14139 // throw out instant app filters if updates are available; will trigger
14140 // instant app resolution
14141 if (userState.instantApp && ps.isUpdateAvailable()) {
14144 final ResolveInfo res = new ResolveInfo();
14145 res.serviceInfo = si;
14146 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14147 res.filter = filter;
14149 res.priority = info.getPriority();
14150 res.preferredOrder = service.owner.mPreferredOrder;
14152 res.isDefault = info.hasDefault;
14153 res.labelRes = info.labelRes;
14154 res.nonLocalizedLabel = info.nonLocalizedLabel;
14155 res.icon = info.icon;
14156 res.system = res.serviceInfo.applicationInfo.isSystemApp();
14161 protected void sortResults(List<ResolveInfo> results) {
14162 Collections.sort(results, mResolvePrioritySorter);
14166 protected void dumpFilter(PrintWriter out, String prefix,
14167 PackageParser.ServiceIntentInfo filter) {
14168 out.print(prefix); out.print(
14169 Integer.toHexString(System.identityHashCode(filter.service)));
14171 filter.service.printComponentShortName(out);
14172 out.print(" filter ");
14173 out.println(Integer.toHexString(System.identityHashCode(filter)));
14177 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14178 return filter.service;
14181 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14182 PackageParser.Service service = (PackageParser.Service)label;
14183 out.print(prefix); out.print(
14184 Integer.toHexString(System.identityHashCode(service)));
14186 service.printComponentShortName(out);
14188 out.print(" ("); out.print(count); out.print(" filters)");
14193 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14194 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14195 // final List<ResolveInfo> retList = Lists.newArrayList();
14196 // while (i.hasNext()) {
14197 // final ResolveInfo resolveInfo = (ResolveInfo) i;
14198 // if (isEnabledLP(resolveInfo.serviceInfo)) {
14199 // retList.add(resolveInfo);
14205 // Keys are String (activity class name), values are Activity.
14206 private final ArrayMap<ComponentName, PackageParser.Service> mServices
14207 = new ArrayMap<ComponentName, PackageParser.Service>();
14208 private int mFlags;
14211 private final class ProviderIntentResolver
14212 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14213 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14214 boolean defaultOnly, int userId) {
14215 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14216 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14221 if (!sUserManager.exists(userId))
14224 return super.queryIntent(intent, resolvedType,
14225 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14229 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14230 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14231 if (!sUserManager.exists(userId))
14233 if (packageProviders == null) {
14237 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14238 final int N = packageProviders.size();
14239 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14240 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14242 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14243 for (int i = 0; i < N; ++i) {
14244 intentFilters = packageProviders.get(i).intents;
14245 if (intentFilters != null && intentFilters.size() > 0) {
14246 PackageParser.ProviderIntentInfo[] array =
14247 new PackageParser.ProviderIntentInfo[intentFilters.size()];
14248 intentFilters.toArray(array);
14249 listCut.add(array);
14252 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14255 public final void addProvider(PackageParser.Provider p) {
14256 if (mProviders.containsKey(p.getComponentName())) {
14257 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14261 mProviders.put(p.getComponentName(), p);
14262 if (DEBUG_SHOW_INFO) {
14264 + (p.info.nonLocalizedLabel != null
14265 ? p.info.nonLocalizedLabel : p.info.name) + ":");
14266 Log.v(TAG, " Class=" + p.info.name);
14268 final int NI = p.intents.size();
14270 for (j = 0; j < NI; j++) {
14271 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14272 if (DEBUG_SHOW_INFO) {
14273 Log.v(TAG, " IntentFilter:");
14274 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
14276 if (!intent.debugCheck()) {
14277 Log.w(TAG, "==> For Provider " + p.info.name);
14283 public final void removeProvider(PackageParser.Provider p) {
14284 mProviders.remove(p.getComponentName());
14285 if (DEBUG_SHOW_INFO) {
14286 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
14287 ? p.info.nonLocalizedLabel : p.info.name) + ":");
14288 Log.v(TAG, " Class=" + p.info.name);
14290 final int NI = p.intents.size();
14292 for (j = 0; j < NI; j++) {
14293 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14294 if (DEBUG_SHOW_INFO) {
14295 Log.v(TAG, " IntentFilter:");
14296 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
14298 removeFilter(intent);
14303 protected boolean allowFilterResult(
14304 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14305 ProviderInfo filterPi = filter.provider.info;
14306 for (int i = dest.size() - 1; i >= 0; i--) {
14307 ProviderInfo destPi = dest.get(i).providerInfo;
14308 if (destPi.name == filterPi.name
14309 && destPi.packageName == filterPi.packageName) {
14317 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14318 return new PackageParser.ProviderIntentInfo[size];
14322 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14323 if (!sUserManager.exists(userId))
14325 PackageParser.Package p = filter.provider.owner;
14327 PackageSetting ps = (PackageSetting) p.mExtras;
14329 // System apps are never considered stopped for purposes of
14330 // filtering, because there may be no way for the user to
14331 // actually re-launch them.
14332 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14333 && ps.getStopped(userId);
14340 protected boolean isPackageForFilter(String packageName,
14341 PackageParser.ProviderIntentInfo info) {
14342 return packageName.equals(info.provider.owner.packageName);
14346 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14347 int match, int userId) {
14348 if (!sUserManager.exists(userId))
14350 final PackageParser.ProviderIntentInfo info = filter;
14351 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14354 final PackageParser.Provider provider = info.provider;
14355 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14359 final PackageUserState userState = ps.readUserState(userId);
14360 final boolean matchVisibleToInstantApp =
14361 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14362 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14363 // throw out filters that aren't visible to instant applications
14364 if (matchVisibleToInstantApp
14365 && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14368 // throw out instant application filters if we're not explicitly requesting them
14369 if (!isInstantApp && userState.instantApp) {
14372 // throw out instant application filters if updates are available; will trigger
14373 // instant application resolution
14374 if (userState.instantApp && ps.isUpdateAvailable()) {
14377 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14378 userState, userId);
14382 final ResolveInfo res = new ResolveInfo();
14383 res.providerInfo = pi;
14384 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14385 res.filter = filter;
14387 res.priority = info.getPriority();
14388 res.preferredOrder = provider.owner.mPreferredOrder;
14390 res.isDefault = info.hasDefault;
14391 res.labelRes = info.labelRes;
14392 res.nonLocalizedLabel = info.nonLocalizedLabel;
14393 res.icon = info.icon;
14394 res.system = res.providerInfo.applicationInfo.isSystemApp();
14399 protected void sortResults(List<ResolveInfo> results) {
14400 Collections.sort(results, mResolvePrioritySorter);
14404 protected void dumpFilter(PrintWriter out, String prefix,
14405 PackageParser.ProviderIntentInfo filter) {
14408 Integer.toHexString(System.identityHashCode(filter.provider)));
14410 filter.provider.printComponentShortName(out);
14411 out.print(" filter ");
14412 out.println(Integer.toHexString(System.identityHashCode(filter)));
14416 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14417 return filter.provider;
14420 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14421 PackageParser.Provider provider = (PackageParser.Provider)label;
14422 out.print(prefix); out.print(
14423 Integer.toHexString(System.identityHashCode(provider)));
14425 provider.printComponentShortName(out);
14427 out.print(" ("); out.print(count); out.print(" filters)");
14432 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14433 = new ArrayMap<ComponentName, PackageParser.Provider>();
14434 private int mFlags;
14437 static final class EphemeralIntentResolver
14438 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14440 * The result that has the highest defined order. Ordering applies on a
14441 * per-package basis. Mapping is from package name to Pair of order and
14442 * EphemeralResolveInfo.
14444 * NOTE: This is implemented as a field variable for convenience and efficiency.
14445 * By having a field variable, we're able to track filter ordering as soon as
14446 * a non-zero order is defined. Otherwise, multiple loops across the result set
14447 * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14448 * this needs to be contained entirely within {@link #filterResults}.
14450 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14453 protected AuxiliaryResolveInfo[] newArray(int size) {
14454 return new AuxiliaryResolveInfo[size];
14458 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14463 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14465 if (!sUserManager.exists(userId)) {
14468 final String packageName = responseObj.resolveInfo.getPackageName();
14469 final Integer order = responseObj.getOrder();
14470 final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14471 mOrderResult.get(packageName);
14472 // ordering is enabled and this item's order isn't high enough
14473 if (lastOrderResult != null && lastOrderResult.first >= order) {
14476 final InstantAppResolveInfo res = responseObj.resolveInfo;
14478 // non-zero order, enable ordering
14479 mOrderResult.put(packageName, new Pair<>(order, res));
14481 return responseObj;
14485 protected void filterResults(List<AuxiliaryResolveInfo> results) {
14486 // only do work if ordering is enabled [most of the time it won't be]
14487 if (mOrderResult.size() == 0) {
14490 int resultSize = results.size();
14491 for (int i = 0; i < resultSize; i++) {
14492 final InstantAppResolveInfo info = results.get(i).resolveInfo;
14493 final String packageName = info.getPackageName();
14494 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14495 if (savedInfo == null) {
14496 // package doesn't having ordering
14499 if (savedInfo.second == info) {
14500 // circled back to the highest ordered item; remove from order list
14501 mOrderResult.remove(packageName);
14502 if (mOrderResult.size() == 0) {
14503 // no more ordered items
14508 // item has a worse order, remove it from the result list
14516 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14517 new Comparator<ResolveInfo>() {
14518 public int compare(ResolveInfo r1, ResolveInfo r2) {
14519 int v1 = r1.priority;
14520 int v2 = r2.priority;
14521 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14523 return (v1 > v2) ? -1 : 1;
14525 v1 = r1.preferredOrder;
14526 v2 = r2.preferredOrder;
14528 return (v1 > v2) ? -1 : 1;
14530 if (r1.isDefault != r2.isDefault) {
14531 return r1.isDefault ? -1 : 1;
14535 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14537 return (v1 > v2) ? -1 : 1;
14539 if (r1.system != r2.system) {
14540 return r1.system ? -1 : 1;
14542 if (r1.activityInfo != null) {
14543 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14545 if (r1.serviceInfo != null) {
14546 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14548 if (r1.providerInfo != null) {
14549 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14555 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14556 new Comparator<ProviderInfo>() {
14557 public int compare(ProviderInfo p1, ProviderInfo p2) {
14558 final int v1 = p1.initOrder;
14559 final int v2 = p2.initOrder;
14560 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14564 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14565 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14566 final int[] userIds) {
14567 mHandler.post(new Runnable() {
14569 public void run() {
14571 final IActivityManager am = ActivityManager.getService();
14572 if (am == null) return;
14573 final int[] resolvedUserIds;
14574 if (userIds == null) {
14575 resolvedUserIds = am.getRunningUserIds();
14577 resolvedUserIds = userIds;
14579 for (int id : resolvedUserIds) {
14580 final Intent intent = new Intent(action,
14581 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14582 if (extras != null) {
14583 intent.putExtras(extras);
14585 if (targetPkg != null) {
14586 intent.setPackage(targetPkg);
14588 // Modify the UID when posting to other users
14589 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14590 if (uid > 0 && UserHandle.getUserId(uid) != id) {
14591 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14592 intent.putExtra(Intent.EXTRA_UID, uid);
14594 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14595 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14596 if (DEBUG_BROADCASTS) {
14597 RuntimeException here = new RuntimeException("here");
14598 here.fillInStackTrace();
14599 Slog.d(TAG, "Sending to user " + id + ": "
14600 + intent.toShortString(false, true, false, false)
14601 + " " + intent.getExtras(), here);
14603 am.broadcastIntent(null, intent, null, finishedReceiver,
14604 0, null, null, null, android.app.AppOpsManager.OP_NONE,
14605 null, finishedReceiver != null, false, id);
14607 } catch (RemoteException ex) {
14614 * Check if the external storage media is available. This is true if there
14615 * is a mounted external storage medium or if the external storage is
14618 private boolean isExternalMediaAvailable() {
14619 return mMediaMounted || Environment.isExternalStorageEmulated();
14623 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14624 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14628 synchronized (mPackages) {
14629 if (!isExternalMediaAvailable()) {
14630 // If the external storage is no longer mounted at this point,
14631 // the caller may not have been able to delete all of this
14632 // packages files and can not delete any more. Bail.
14635 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14636 if (lastPackage != null) {
14637 pkgs.remove(lastPackage);
14639 if (pkgs.size() > 0) {
14640 return pkgs.get(0);
14646 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14647 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14648 userId, andCode ? 1 : 0, packageName);
14649 if (mSystemReady) {
14650 msg.sendToTarget();
14652 if (mPostSystemReadyMessages == null) {
14653 mPostSystemReadyMessages = new ArrayList<>();
14655 mPostSystemReadyMessages.add(msg);
14659 void startCleaningPackages() {
14661 if (!isExternalMediaAvailable()) {
14664 synchronized (mPackages) {
14665 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14669 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14670 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14671 IActivityManager am = ActivityManager.getService();
14674 synchronized (mPackages) {
14675 if (!mDefaultContainerWhitelisted) {
14676 mDefaultContainerWhitelisted = true;
14677 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14678 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14683 am.backgroundWhitelistUid(dcsUid);
14685 am.startService(null, intent, null, false, mContext.getOpPackageName(),
14686 UserHandle.USER_SYSTEM);
14687 } catch (RemoteException e) {
14693 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14694 int installFlags, String installerPackageName, int userId) {
14695 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14697 final int callingUid = Binder.getCallingUid();
14698 enforceCrossUserPermission(callingUid, userId,
14699 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14701 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14703 if (observer != null) {
14704 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14706 } catch (RemoteException re) {
14711 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14712 installFlags |= PackageManager.INSTALL_FROM_ADB;
14715 // Caller holds INSTALL_PACKAGES permission, so we're less strict
14716 // about installerPackageName.
14718 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14719 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14723 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14724 user = UserHandle.ALL;
14726 user = new UserHandle(userId);
14729 // Only system components can circumvent runtime permissions when installing.
14730 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14731 && mContext.checkCallingOrSelfPermission(Manifest.permission
14732 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14733 throw new SecurityException("You need the "
14734 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14735 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14738 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14739 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14740 throw new IllegalArgumentException(
14741 "New installs into ASEC containers no longer supported");
14744 final File originFile = new File(originPath);
14745 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14747 final Message msg = mHandler.obtainMessage(INIT_COPY);
14748 final VerificationInfo verificationInfo = new VerificationInfo(
14749 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14750 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14751 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14752 null /*packageAbiOverride*/, null /*grantedPermissions*/,
14753 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14754 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14757 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14758 System.identityHashCode(msg.obj));
14759 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14760 System.identityHashCode(msg.obj));
14762 mHandler.sendMessage(msg);
14767 * Ensure that the install reason matches what we know about the package installer (e.g. whether
14768 * it is acting on behalf on an enterprise or the user).
14770 * Note that the ordering of the conditionals in this method is important. The checks we perform
14771 * are as follows, in this order:
14773 * 1) If the install is being performed by a system app, we can trust the app to have set the
14774 * install reason correctly. Thus, we pass through the install reason unchanged, no matter
14776 * 2) If the install is being performed by a device or profile owner app, the install reason
14777 * should be enterprise policy. However, we cannot be sure that the device or profile owner
14778 * set the install reason correctly. If the app targets an older SDK version where install
14779 * reasons did not exist yet, or if the app author simply forgot, the install reason may be
14780 * unset or wrong. Thus, we force the install reason to be enterprise policy.
14781 * 3) In all other cases, the install is being performed by a regular app that is neither part
14782 * of the system nor a device or profile owner. We have no reason to believe that this app is
14783 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14784 * set to enterprise policy and if so, change it to unknown instead.
14786 private int fixUpInstallReason(String installerPackageName, int installerUid,
14787 int installReason) {
14788 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14789 == PERMISSION_GRANTED) {
14790 // If the install is being performed by a system app, we trust that app to have set the
14791 // install reason correctly.
14792 return installReason;
14795 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14796 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14798 ComponentName owner = null;
14800 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14801 if (owner == null) {
14802 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14804 } catch (RemoteException e) {
14806 if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14807 // If the install is being performed by a device or profile owner, the install
14808 // reason should be enterprise policy.
14809 return PackageManager.INSTALL_REASON_POLICY;
14813 if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14814 // If the install is being performed by a regular app (i.e. neither system app nor
14815 // device or profile owner), we have no reason to believe that the app is acting on
14816 // behalf of an enterprise. If the app set the install reason to enterprise policy,
14817 // change it to unknown instead.
14818 return PackageManager.INSTALL_REASON_UNKNOWN;
14821 // If the install is being performed by a regular app and the install reason was set to any
14822 // value but enterprise policy, leave the install reason unchanged.
14823 return installReason;
14826 void installStage(String packageName, File stagedDir, String stagedCid,
14827 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14828 String installerPackageName, int installerUid, UserHandle user,
14829 Certificate[][] certificates) {
14830 if (DEBUG_EPHEMERAL) {
14831 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14832 Slog.d(TAG, "Ephemeral install of " + packageName);
14835 final VerificationInfo verificationInfo = new VerificationInfo(
14836 sessionParams.originatingUri, sessionParams.referrerUri,
14837 sessionParams.originatingUid, installerUid);
14839 final OriginInfo origin;
14840 if (stagedDir != null) {
14841 origin = OriginInfo.fromStagedFile(stagedDir);
14843 origin = OriginInfo.fromStagedContainer(stagedCid);
14846 final Message msg = mHandler.obtainMessage(INIT_COPY);
14847 final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14848 sessionParams.installReason);
14849 final InstallParams params = new InstallParams(origin, null, observer,
14850 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14851 verificationInfo, user, sessionParams.abiOverride,
14852 sessionParams.grantedRuntimePermissions, certificates, installReason);
14853 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14856 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14857 System.identityHashCode(msg.obj));
14858 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14859 System.identityHashCode(msg.obj));
14861 mHandler.sendMessage(msg);
14864 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14866 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14867 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14868 false /*startReceiver*/, pkgSetting.appId, userId);
14870 // Send a session commit broadcast
14871 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14872 info.installReason = pkgSetting.getInstallReason(userId);
14873 info.appPackageName = packageName;
14874 sendSessionCommitBroadcast(info, userId);
14877 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14878 boolean includeStopped, int appId, int... userIds) {
14879 if (ArrayUtils.isEmpty(userIds)) {
14882 Bundle extras = new Bundle(1);
14883 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14884 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14886 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14887 packageName, extras, 0, null, null, userIds);
14888 if (sendBootCompleted) {
14889 mHandler.post(() -> {
14890 for (int userId : userIds) {
14891 sendBootCompletedBroadcastToSystemApp(
14892 packageName, includeStopped, userId);
14900 * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14901 * automatically without needing an explicit launch.
14902 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14904 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14906 // If user is not running, the app didn't miss any broadcast
14907 if (!mUserManagerInternal.isUserRunning(userId)) {
14910 final IActivityManager am = ActivityManager.getService();
14912 // Deliver LOCKED_BOOT_COMPLETED first
14913 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14914 .setPackage(packageName);
14915 if (includeStopped) {
14916 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14918 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14919 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14920 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14922 // Deliver BOOT_COMPLETED only if user is unlocked
14923 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14924 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14925 if (includeStopped) {
14926 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14928 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14929 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14931 } catch (RemoteException e) {
14932 throw e.rethrowFromSystemServer();
14937 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14939 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14940 PackageSetting pkgSetting;
14941 final int callingUid = Binder.getCallingUid();
14942 enforceCrossUserPermission(callingUid, userId,
14943 true /* requireFullPermission */, true /* checkShell */,
14944 "setApplicationHiddenSetting for user " + userId);
14946 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14947 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14951 long callingId = Binder.clearCallingIdentity();
14953 boolean sendAdded = false;
14954 boolean sendRemoved = false;
14956 synchronized (mPackages) {
14957 pkgSetting = mSettings.mPackages.get(packageName);
14958 if (pkgSetting == null) {
14961 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14964 // Do not allow "android" is being disabled
14965 if ("android".equals(packageName)) {
14966 Slog.w(TAG, "Cannot hide package: android");
14969 // Cannot hide static shared libs as they are considered
14970 // a part of the using app (emulating static linking). Also
14971 // static libs are installed always on internal storage.
14972 PackageParser.Package pkg = mPackages.get(packageName);
14973 if (pkg != null && pkg.staticSharedLibName != null) {
14974 Slog.w(TAG, "Cannot hide package: " + packageName
14975 + " providing static shared library: "
14976 + pkg.staticSharedLibName);
14979 // Only allow protected packages to hide themselves.
14980 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14981 && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14982 Slog.w(TAG, "Not hiding protected package: " + packageName);
14986 if (pkgSetting.getHidden(userId) != hidden) {
14987 pkgSetting.setHidden(hidden, userId);
14988 mSettings.writePackageRestrictionsLPr(userId);
14990 sendRemoved = true;
14997 sendPackageAddedForUser(packageName, pkgSetting, userId);
15001 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15003 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15007 Binder.restoreCallingIdentity(callingId);
15012 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15014 final PackageRemovedInfo info = new PackageRemovedInfo(this);
15015 info.removedPackage = packageName;
15016 info.installerPackageName = pkgSetting.installerPackageName;
15017 info.removedUsers = new int[] {userId};
15018 info.broadcastUsers = new int[] {userId};
15019 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15020 info.sendPackageRemovedBroadcasts(true /*killApp*/);
15023 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15024 if (pkgList.length > 0) {
15025 Bundle extras = new Bundle(1);
15026 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15028 sendPackageBroadcast(
15029 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15030 : Intent.ACTION_PACKAGES_UNSUSPENDED,
15031 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15032 new int[] {userId});
15037 * Returns true if application is not found or there was an error. Otherwise it returns
15038 * the hidden state of the package for the given user.
15041 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15042 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15043 final int callingUid = Binder.getCallingUid();
15044 enforceCrossUserPermission(callingUid, userId,
15045 true /* requireFullPermission */, false /* checkShell */,
15046 "getApplicationHidden for user " + userId);
15048 long callingId = Binder.clearCallingIdentity();
15051 synchronized (mPackages) {
15052 ps = mSettings.mPackages.get(packageName);
15056 if (filterAppAccessLPr(ps, callingUid, userId)) {
15059 return ps.getHidden(userId);
15062 Binder.restoreCallingIdentity(callingId);
15070 public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15071 int installReason) {
15072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15074 PackageSetting pkgSetting;
15075 final int callingUid = Binder.getCallingUid();
15076 enforceCrossUserPermission(callingUid, userId,
15077 true /* requireFullPermission */, true /* checkShell */,
15078 "installExistingPackage for user " + userId);
15079 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15080 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15083 long callingId = Binder.clearCallingIdentity();
15085 boolean installed = false;
15086 final boolean instantApp =
15087 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15088 final boolean fullApp =
15089 (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15092 synchronized (mPackages) {
15093 pkgSetting = mSettings.mPackages.get(packageName);
15094 if (pkgSetting == null) {
15095 return PackageManager.INSTALL_FAILED_INVALID_URI;
15097 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15098 // only allow the existing package to be used if it's installed as a full
15099 // application for at least one user
15100 boolean installAllowed = false;
15101 for (int checkUserId : sUserManager.getUserIds()) {
15102 installAllowed = !pkgSetting.getInstantApp(checkUserId);
15103 if (installAllowed) {
15107 if (!installAllowed) {
15108 return PackageManager.INSTALL_FAILED_INVALID_URI;
15111 if (!pkgSetting.getInstalled(userId)) {
15112 pkgSetting.setInstalled(true, userId);
15113 pkgSetting.setHidden(false, userId);
15114 pkgSetting.setInstallReason(installReason, userId);
15115 mSettings.writePackageRestrictionsLPr(userId);
15116 mSettings.writeKernelMappingLPr(pkgSetting);
15118 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15119 // upgrade app from instant to full; we don't allow app downgrade
15122 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15126 if (pkgSetting.pkg != null) {
15127 synchronized (mInstallLock) {
15128 // We don't need to freeze for a brand new install
15129 prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15132 sendPackageAddedForUser(packageName, pkgSetting, userId);
15133 synchronized (mPackages) {
15134 updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15138 Binder.restoreCallingIdentity(callingId);
15141 return PackageManager.INSTALL_SUCCEEDED;
15144 void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15145 boolean instantApp, boolean fullApp) {
15146 // no state specified; do nothing
15147 if (!instantApp && !fullApp) {
15150 if (userId != UserHandle.USER_ALL) {
15151 if (instantApp && !pkgSetting.getInstantApp(userId)) {
15152 pkgSetting.setInstantApp(true /*instantApp*/, userId);
15153 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15154 pkgSetting.setInstantApp(false /*instantApp*/, userId);
15157 for (int currentUserId : sUserManager.getUserIds()) {
15158 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15159 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15160 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15161 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15167 boolean isUserRestricted(int userId, String restrictionKey) {
15168 Bundle restrictions = sUserManager.getUserRestrictions(userId);
15169 if (restrictions.getBoolean(restrictionKey, false)) {
15170 Log.w(TAG, "User is restricted: " + restrictionKey);
15177 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15179 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15180 final int callingUid = Binder.getCallingUid();
15181 enforceCrossUserPermission(callingUid, userId,
15182 true /* requireFullPermission */, true /* checkShell */,
15183 "setPackagesSuspended for user " + userId);
15185 if (ArrayUtils.isEmpty(packageNames)) {
15186 return packageNames;
15189 // List of package names for whom the suspended state has changed.
15190 List<String> changedPackages = new ArrayList<>(packageNames.length);
15191 // List of package names for whom the suspended state is not set as requested in this
15193 List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15194 long callingId = Binder.clearCallingIdentity();
15196 for (int i = 0; i < packageNames.length; i++) {
15197 String packageName = packageNames[i];
15198 boolean changed = false;
15200 synchronized (mPackages) {
15201 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15202 if (pkgSetting == null
15203 || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15204 Slog.w(TAG, "Could not find package setting for package \"" + packageName
15205 + "\". Skipping suspending/un-suspending.");
15206 unactionedPackages.add(packageName);
15209 appId = pkgSetting.appId;
15210 if (pkgSetting.getSuspended(userId) != suspended) {
15211 if (!canSuspendPackageForUserLocked(packageName, userId)) {
15212 unactionedPackages.add(packageName);
15215 pkgSetting.setSuspended(suspended, userId);
15216 mSettings.writePackageRestrictionsLPr(userId);
15218 changedPackages.add(packageName);
15222 if (changed && suspended) {
15223 killApplication(packageName, UserHandle.getUid(userId, appId),
15224 "suspending package");
15228 Binder.restoreCallingIdentity(callingId);
15231 if (!changedPackages.isEmpty()) {
15232 sendPackagesSuspendedForUser(changedPackages.toArray(
15233 new String[changedPackages.size()]), userId, suspended);
15236 return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15240 public boolean isPackageSuspendedForUser(String packageName, int userId) {
15241 final int callingUid = Binder.getCallingUid();
15242 enforceCrossUserPermission(callingUid, userId,
15243 true /* requireFullPermission */, false /* checkShell */,
15244 "isPackageSuspendedForUser for user " + userId);
15245 synchronized (mPackages) {
15246 final PackageSetting ps = mSettings.mPackages.get(packageName);
15247 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15248 throw new IllegalArgumentException("Unknown target package: " + packageName);
15250 return ps.getSuspended(userId);
15254 private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15255 if (isPackageDeviceAdmin(packageName, userId)) {
15256 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15257 + "\": has an active device admin");
15261 String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15262 if (packageName.equals(activeLauncherPackageName)) {
15263 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15264 + "\": contains the active launcher");
15268 if (packageName.equals(mRequiredInstallerPackage)) {
15269 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15270 + "\": required for package installation");
15274 if (packageName.equals(mRequiredUninstallerPackage)) {
15275 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15276 + "\": required for package uninstallation");
15280 if (packageName.equals(mRequiredVerifierPackage)) {
15281 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15282 + "\": required for package verification");
15286 if (packageName.equals(getDefaultDialerPackageName(userId))) {
15287 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15288 + "\": is the default dialer");
15292 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15293 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15294 + "\": protected package");
15298 // Cannot suspend static shared libs as they are considered
15299 // a part of the using app (emulating static linking). Also
15300 // static libs are installed always on internal storage.
15301 PackageParser.Package pkg = mPackages.get(packageName);
15302 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15303 Slog.w(TAG, "Cannot suspend package: " + packageName
15304 + " providing static shared library: "
15305 + pkg.staticSharedLibName);
15312 private String getActiveLauncherPackageName(int userId) {
15313 Intent intent = new Intent(Intent.ACTION_MAIN);
15314 intent.addCategory(Intent.CATEGORY_HOME);
15315 ResolveInfo resolveInfo = resolveIntent(
15317 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15318 PackageManager.MATCH_DEFAULT_ONLY,
15321 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15324 private String getDefaultDialerPackageName(int userId) {
15325 synchronized (mPackages) {
15326 return mSettings.getDefaultDialerPackageNameLPw(userId);
15331 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15332 mContext.enforceCallingOrSelfPermission(
15333 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15334 "Only package verification agents can verify applications");
15336 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15337 final PackageVerificationResponse response = new PackageVerificationResponse(
15338 verificationCode, Binder.getCallingUid());
15340 msg.obj = response;
15341 mHandler.sendMessage(msg);
15345 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15346 long millisecondsToDelay) {
15347 mContext.enforceCallingOrSelfPermission(
15348 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15349 "Only package verification agents can extend verification timeouts");
15351 final PackageVerificationState state = mPendingVerification.get(id);
15352 final PackageVerificationResponse response = new PackageVerificationResponse(
15353 verificationCodeAtTimeout, Binder.getCallingUid());
15355 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15356 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15358 if (millisecondsToDelay < 0) {
15359 millisecondsToDelay = 0;
15361 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15362 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15363 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15366 if ((state != null) && !state.timeoutExtended()) {
15367 state.extendTimeout();
15369 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15371 msg.obj = response;
15372 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15376 private void broadcastPackageVerified(int verificationId, Uri packageUri,
15377 int verificationCode, UserHandle user) {
15378 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15379 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15380 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15381 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15382 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15384 mContext.sendBroadcastAsUser(intent, user,
15385 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15388 private ComponentName matchComponentForVerifier(String packageName,
15389 List<ResolveInfo> receivers) {
15390 ActivityInfo targetReceiver = null;
15392 final int NR = receivers.size();
15393 for (int i = 0; i < NR; i++) {
15394 final ResolveInfo info = receivers.get(i);
15395 if (info.activityInfo == null) {
15399 if (packageName.equals(info.activityInfo.packageName)) {
15400 targetReceiver = info.activityInfo;
15405 if (targetReceiver == null) {
15409 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15412 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15413 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15414 if (pkgInfo.verifiers.length == 0) {
15418 final int N = pkgInfo.verifiers.length;
15419 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15420 for (int i = 0; i < N; i++) {
15421 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15423 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15425 if (comp == null) {
15429 final int verifierUid = getUidForVerifier(verifierInfo);
15430 if (verifierUid == -1) {
15434 if (DEBUG_VERIFY) {
15435 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15436 + " with the correct signature");
15438 sufficientVerifiers.add(comp);
15439 verificationState.addSufficientVerifier(verifierUid);
15442 return sufficientVerifiers;
15445 private int getUidForVerifier(VerifierInfo verifierInfo) {
15446 synchronized (mPackages) {
15447 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15450 } else if (pkg.mSignatures.length != 1) {
15451 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15452 + " has more than one signature; ignoring");
15457 * If the public key of the package's signature does not match
15458 * our expected public key, then this is a different package and
15462 final byte[] expectedPublicKey;
15464 final Signature verifierSig = pkg.mSignatures[0];
15465 final PublicKey publicKey = verifierSig.getPublicKey();
15466 expectedPublicKey = publicKey.getEncoded();
15467 } catch (CertificateException e) {
15471 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15473 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15474 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15475 + " does not have the expected public key; ignoring");
15479 return pkg.applicationInfo.uid;
15484 public void finishPackageInstall(int token, boolean didLaunch) {
15485 enforceSystemOrRoot("Only the system is allowed to finish installs");
15487 if (DEBUG_INSTALL) {
15488 Slog.v(TAG, "BM finishing package install for " + token);
15490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15492 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15493 mHandler.sendMessage(msg);
15497 * Get the verification agent timeout. Used for both the APK verifier and the
15498 * intent filter verifier.
15500 * @return verification timeout in milliseconds
15502 private long getVerificationTimeout() {
15503 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15504 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15505 DEFAULT_VERIFICATION_TIMEOUT);
15509 * Get the default verification agent response code.
15511 * @return default verification response code
15513 private int getDefaultVerificationResponse(UserHandle user) {
15514 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15515 return PackageManager.VERIFICATION_REJECT;
15517 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15518 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15519 DEFAULT_VERIFICATION_RESPONSE);
15523 * Check whether or not package verification has been enabled.
15525 * @return true if verification should be performed
15527 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15528 if (!DEFAULT_VERIFY_ENABLE) {
15532 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15534 // Check if installing from ADB
15535 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15536 // Do not run verification in a test harness environment
15537 if (ActivityManager.isRunningInTestHarness()) {
15540 if (ensureVerifyAppsEnabled) {
15543 // Check if the developer does not want package verification for ADB installs
15544 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15545 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15549 // only when not installed from ADB, skip verification for instant apps when
15550 // the installer and verifier are the same.
15551 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15552 if (mInstantAppInstallerActivity != null
15553 && mInstantAppInstallerActivity.packageName.equals(
15554 mRequiredVerifierPackage)) {
15556 mContext.getSystemService(AppOpsManager.class)
15557 .checkPackage(installerUid, mRequiredVerifierPackage);
15558 if (DEBUG_VERIFY) {
15559 Slog.i(TAG, "disable verification for instant app");
15562 } catch (SecurityException ignore) { }
15567 if (ensureVerifyAppsEnabled) {
15571 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15572 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15576 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15577 throws RemoteException {
15578 mContext.enforceCallingOrSelfPermission(
15579 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15580 "Only intentfilter verification agents can verify applications");
15582 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15583 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15584 Binder.getCallingUid(), verificationCode, failedDomains);
15586 msg.obj = response;
15587 mHandler.sendMessage(msg);
15591 public int getIntentVerificationStatus(String packageName, int userId) {
15592 final int callingUid = Binder.getCallingUid();
15593 if (UserHandle.getUserId(callingUid) != userId) {
15594 mContext.enforceCallingOrSelfPermission(
15595 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15596 "getIntentVerificationStatus" + userId);
15598 if (getInstantAppPackageName(callingUid) != null) {
15599 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15601 synchronized (mPackages) {
15602 final PackageSetting ps = mSettings.mPackages.get(packageName);
15604 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15605 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15607 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15612 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15613 mContext.enforceCallingOrSelfPermission(
15614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15616 boolean result = false;
15617 synchronized (mPackages) {
15618 final PackageSetting ps = mSettings.mPackages.get(packageName);
15619 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15622 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15625 scheduleWritePackageRestrictionsLocked(userId);
15631 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15632 String packageName) {
15633 final int callingUid = Binder.getCallingUid();
15634 if (getInstantAppPackageName(callingUid) != null) {
15635 return ParceledListSlice.emptyList();
15637 synchronized (mPackages) {
15638 final PackageSetting ps = mSettings.mPackages.get(packageName);
15639 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15640 return ParceledListSlice.emptyList();
15642 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15647 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15648 if (TextUtils.isEmpty(packageName)) {
15649 return ParceledListSlice.emptyList();
15651 final int callingUid = Binder.getCallingUid();
15652 final int callingUserId = UserHandle.getUserId(callingUid);
15653 synchronized (mPackages) {
15654 PackageParser.Package pkg = mPackages.get(packageName);
15655 if (pkg == null || pkg.activities == null) {
15656 return ParceledListSlice.emptyList();
15658 if (pkg.mExtras == null) {
15659 return ParceledListSlice.emptyList();
15661 final PackageSetting ps = (PackageSetting) pkg.mExtras;
15662 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15663 return ParceledListSlice.emptyList();
15665 final int count = pkg.activities.size();
15666 ArrayList<IntentFilter> result = new ArrayList<>();
15667 for (int n=0; n<count; n++) {
15668 PackageParser.Activity activity = pkg.activities.get(n);
15669 if (activity.intents != null && activity.intents.size() > 0) {
15670 result.addAll(activity.intents);
15673 return new ParceledListSlice<>(result);
15678 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15679 mContext.enforceCallingOrSelfPermission(
15680 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15681 if (UserHandle.getCallingUserId() != userId) {
15682 mContext.enforceCallingOrSelfPermission(
15683 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15686 synchronized (mPackages) {
15687 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15688 if (packageName != null) {
15689 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15690 packageName, userId);
15697 public String getDefaultBrowserPackageName(int userId) {
15698 if (UserHandle.getCallingUserId() != userId) {
15699 mContext.enforceCallingOrSelfPermission(
15700 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15702 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15705 synchronized (mPackages) {
15706 return mSettings.getDefaultBrowserPackageNameLPw(userId);
15711 * Get the "allow unknown sources" setting.
15713 * @return the current "allow unknown sources" setting
15715 private int getUnknownSourcesSettings() {
15716 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15717 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15722 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15723 final int callingUid = Binder.getCallingUid();
15724 if (getInstantAppPackageName(callingUid) != null) {
15728 synchronized (mPackages) {
15729 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15730 if (targetPackageSetting == null
15731 || filterAppAccessLPr(
15732 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15733 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15736 PackageSetting installerPackageSetting;
15737 if (installerPackageName != null) {
15738 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15739 if (installerPackageSetting == null) {
15740 throw new IllegalArgumentException("Unknown installer package: "
15741 + installerPackageName);
15744 installerPackageSetting = null;
15747 Signature[] callerSignature;
15748 Object obj = mSettings.getUserIdLPr(callingUid);
15750 if (obj instanceof SharedUserSetting) {
15751 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15752 } else if (obj instanceof PackageSetting) {
15753 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15755 throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15758 throw new SecurityException("Unknown calling UID: " + callingUid);
15761 // Verify: can't set installerPackageName to a package that is
15762 // not signed with the same cert as the caller.
15763 if (installerPackageSetting != null) {
15764 if (compareSignatures(callerSignature,
15765 installerPackageSetting.signatures.mSignatures)
15766 != PackageManager.SIGNATURE_MATCH) {
15767 throw new SecurityException(
15768 "Caller does not have same cert as new installer package "
15769 + installerPackageName);
15773 // Verify: if target already has an installer package, it must
15774 // be signed with the same cert as the caller.
15775 if (targetPackageSetting.installerPackageName != null) {
15776 PackageSetting setting = mSettings.mPackages.get(
15777 targetPackageSetting.installerPackageName);
15778 // If the currently set package isn't valid, then it's always
15779 // okay to change it.
15780 if (setting != null) {
15781 if (compareSignatures(callerSignature,
15782 setting.signatures.mSignatures)
15783 != PackageManager.SIGNATURE_MATCH) {
15784 throw new SecurityException(
15785 "Caller does not have same cert as old installer package "
15786 + targetPackageSetting.installerPackageName);
15792 targetPackageSetting.installerPackageName = installerPackageName;
15793 if (installerPackageName != null) {
15794 mSettings.mInstallerPackages.add(installerPackageName);
15796 scheduleWriteSettingsLocked();
15801 public void setApplicationCategoryHint(String packageName, int categoryHint,
15802 String callerPackageName) {
15803 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15804 throw new SecurityException("Instant applications don't have access to this method");
15806 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15807 callerPackageName);
15808 synchronized (mPackages) {
15809 PackageSetting ps = mSettings.mPackages.get(packageName);
15811 throw new IllegalArgumentException("Unknown target package " + packageName);
15813 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15814 throw new IllegalArgumentException("Unknown target package " + packageName);
15816 if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15817 throw new IllegalArgumentException("Calling package " + callerPackageName
15818 + " is not installer for " + packageName);
15821 if (ps.categoryHint != categoryHint) {
15822 ps.categoryHint = categoryHint;
15823 scheduleWriteSettingsLocked();
15828 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15829 // Queue up an async operation since the package installation may take a little while.
15830 mHandler.post(new Runnable() {
15831 public void run() {
15832 mHandler.removeCallbacks(this);
15833 // Result object to be returned
15834 PackageInstalledInfo res = new PackageInstalledInfo();
15835 res.setReturnCode(currentStatus);
15838 res.removedInfo = null;
15839 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15840 args.doPreInstall(res.returnCode);
15841 synchronized (mInstallLock) {
15842 installPackageTracedLI(args, res);
15844 args.doPostInstall(res.returnCode, res.uid);
15847 // A restore should be performed at this point if (a) the install
15848 // succeeded, (b) the operation is not an update, and (c) the new
15849 // package has not opted out of backup participation.
15850 final boolean update = res.removedInfo != null
15851 && res.removedInfo.removedPackage != null;
15852 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15853 boolean doRestore = !update
15854 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15856 // Set up the post-install work request bookkeeping. This will be used
15857 // and cleaned up by the post-install event handling regardless of whether
15858 // there's a restore pass performed. Token values are >= 1.
15860 if (mNextInstallToken < 0) mNextInstallToken = 1;
15861 token = mNextInstallToken++;
15863 PostInstallData data = new PostInstallData(args, res);
15864 mRunningInstalls.put(token, data);
15865 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15867 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15868 // Pass responsibility to the Backup Manager. It will perform a
15869 // restore if appropriate, then pass responsibility back to the
15870 // Package Manager to run the post-install observer callbacks
15872 IBackupManager bm = IBackupManager.Stub.asInterface(
15873 ServiceManager.getService(Context.BACKUP_SERVICE));
15875 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15876 + " to BM for possible restore");
15877 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15879 // TODO: http://b/22388012
15880 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15881 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15885 } catch (RemoteException e) {
15886 // can't happen; the backup manager is local
15887 } catch (Exception e) {
15888 Slog.e(TAG, "Exception trying to enqueue restore", e);
15892 Slog.e(TAG, "Backup Manager not found!");
15898 // No restore possible, or the Backup Manager was mysteriously not
15899 // available -- just fire the post-install work request directly.
15900 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15902 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15904 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15905 mHandler.sendMessage(msg);
15912 * Callback from PackageSettings whenever an app is first transitioned out of the
15913 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if
15914 * the app was "launched" for a restoreAtInstall operation. Therefore we check
15915 * here whether the app is the target of an ongoing install, and only send the
15916 * broadcast immediately if it is not in that state. If it *is* undergoing a restore,
15917 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15920 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15921 // Serialize this with the rest of the install-process message chain. In the
15922 // restore-at-install case, this Runnable will necessarily run before the
15923 // POST_INSTALL message is processed, so the contents of mRunningInstalls
15924 // are coherent. In the non-restore case, the app has already completed install
15925 // and been launched through some other means, so it is not in a problematic
15926 // state for observers to see the FIRST_LAUNCH signal.
15927 mHandler.post(new Runnable() {
15929 public void run() {
15930 for (int i = 0; i < mRunningInstalls.size(); i++) {
15931 final PostInstallData data = mRunningInstalls.valueAt(i);
15932 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15935 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15936 // right package; but is it for the right user?
15937 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15938 if (userId == data.res.newUsers[uIndex]) {
15939 if (DEBUG_BACKUP) {
15940 Slog.i(TAG, "Package " + pkgName
15941 + " being restored so deferring FIRST_LAUNCH");
15948 // didn't find it, so not being restored
15949 if (DEBUG_BACKUP) {
15950 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15952 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15957 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15958 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15959 installerPkg, null, userIds);
15962 private abstract class HandlerParams {
15963 private static final int MAX_RETRIES = 4;
15966 * Number of times startCopy() has been attempted and had a non-fatal
15969 private int mRetries = 0;
15971 /** User handle for the user requesting the information or installation. */
15972 private final UserHandle mUser;
15973 String traceMethod;
15976 HandlerParams(UserHandle user) {
15980 UserHandle getUser() {
15984 HandlerParams setTraceMethod(String traceMethod) {
15985 this.traceMethod = traceMethod;
15989 HandlerParams setTraceCookie(int traceCookie) {
15990 this.traceCookie = traceCookie;
15994 final boolean startCopy() {
15997 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15999 if (++mRetries > MAX_RETRIES) {
16000 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16001 mHandler.sendEmptyMessage(MCS_GIVE_UP);
16002 handleServiceError();
16008 } catch (RemoteException e) {
16009 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16010 mHandler.sendEmptyMessage(MCS_RECONNECT);
16013 handleReturnCode();
16017 final void serviceError() {
16018 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16019 handleServiceError();
16020 handleReturnCode();
16023 abstract void handleStartCopy() throws RemoteException;
16024 abstract void handleServiceError();
16025 abstract void handleReturnCode();
16028 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16029 for (File path : paths) {
16031 mcs.clearDirectory(path.getAbsolutePath());
16032 } catch (RemoteException e) {
16037 static class OriginInfo {
16039 * Location where install is coming from, before it has been
16040 * copied/renamed into place. This could be a single monolithic APK
16041 * file, or a cluster directory. This location may be untrusted.
16047 * Flag indicating that {@link #file} or {@link #cid} has already been
16048 * staged, meaning downstream users don't need to defensively copy the
16051 final boolean staged;
16054 * Flag indicating that {@link #file} or {@link #cid} is an already
16055 * installed app that is being moved.
16057 final boolean existing;
16059 final String resolvedPath;
16060 final File resolvedFile;
16062 static OriginInfo fromNothing() {
16063 return new OriginInfo(null, null, false, false);
16066 static OriginInfo fromUntrustedFile(File file) {
16067 return new OriginInfo(file, null, false, false);
16070 static OriginInfo fromExistingFile(File file) {
16071 return new OriginInfo(file, null, false, true);
16074 static OriginInfo fromStagedFile(File file) {
16075 return new OriginInfo(file, null, true, false);
16078 static OriginInfo fromStagedContainer(String cid) {
16079 return new OriginInfo(null, cid, true, false);
16082 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16085 this.staged = staged;
16086 this.existing = existing;
16089 resolvedPath = PackageHelper.getSdDir(cid);
16090 resolvedFile = new File(resolvedPath);
16091 } else if (file != null) {
16092 resolvedPath = file.getAbsolutePath();
16093 resolvedFile = file;
16095 resolvedPath = null;
16096 resolvedFile = null;
16101 static class MoveInfo {
16103 final String fromUuid;
16104 final String toUuid;
16105 final String packageName;
16106 final String dataAppName;
16108 final String seinfo;
16109 final int targetSdkVersion;
16111 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16112 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16113 this.moveId = moveId;
16114 this.fromUuid = fromUuid;
16115 this.toUuid = toUuid;
16116 this.packageName = packageName;
16117 this.dataAppName = dataAppName;
16118 this.appId = appId;
16119 this.seinfo = seinfo;
16120 this.targetSdkVersion = targetSdkVersion;
16124 static class VerificationInfo {
16125 /** A constant used to indicate that a uid value is not present. */
16126 public static final int NO_UID = -1;
16128 /** URI referencing where the package was downloaded from. */
16129 final Uri originatingUri;
16131 /** HTTP referrer URI associated with the originatingURI. */
16132 final Uri referrer;
16134 /** UID of the application that the install request originated from. */
16135 final int originatingUid;
16137 /** UID of application requesting the install */
16138 final int installerUid;
16140 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16141 this.originatingUri = originatingUri;
16142 this.referrer = referrer;
16143 this.originatingUid = originatingUid;
16144 this.installerUid = installerUid;
16148 class InstallParams extends HandlerParams {
16149 final OriginInfo origin;
16150 final MoveInfo move;
16151 final IPackageInstallObserver2 observer;
16153 final String installerPackageName;
16154 final String volumeUuid;
16155 private InstallArgs mArgs;
16157 final String packageAbiOverride;
16158 final String[] grantedRuntimePermissions;
16159 final VerificationInfo verificationInfo;
16160 final Certificate[][] certificates;
16161 final int installReason;
16163 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16164 int installFlags, String installerPackageName, String volumeUuid,
16165 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16166 String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16168 this.origin = origin;
16170 this.observer = observer;
16171 this.installFlags = installFlags;
16172 this.installerPackageName = installerPackageName;
16173 this.volumeUuid = volumeUuid;
16174 this.verificationInfo = verificationInfo;
16175 this.packageAbiOverride = packageAbiOverride;
16176 this.grantedRuntimePermissions = grantedPermissions;
16177 this.certificates = certificates;
16178 this.installReason = installReason;
16182 public String toString() {
16183 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16184 + " file=" + origin.file + " cid=" + origin.cid + "}";
16187 private int installLocationPolicy(PackageInfoLite pkgLite) {
16188 String packageName = pkgLite.packageName;
16189 int installLocation = pkgLite.installLocation;
16190 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16192 synchronized (mPackages) {
16193 // Currently installed package which the new package is attempting to replace or
16194 // null if no such package is installed.
16195 PackageParser.Package installedPkg = mPackages.get(packageName);
16196 // Package which currently owns the data which the new package will own if installed.
16197 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16198 // will be null whereas dataOwnerPkg will contain information about the package
16199 // which was uninstalled while keeping its data.
16200 PackageParser.Package dataOwnerPkg = installedPkg;
16201 if (dataOwnerPkg == null) {
16202 PackageSetting ps = mSettings.mPackages.get(packageName);
16204 dataOwnerPkg = ps.pkg;
16208 if (dataOwnerPkg != null) {
16209 // If installed, the package will get access to data left on the device by its
16210 // predecessor. As a security measure, this is permited only if this is not a
16211 // version downgrade or if the predecessor package is marked as debuggable and
16212 // a downgrade is explicitly requested.
16214 // On debuggable platform builds, downgrades are permitted even for
16215 // non-debuggable packages to make testing easier. Debuggable platform builds do
16216 // not offer security guarantees and thus it's OK to disable some security
16217 // mechanisms to make debugging/testing easier on those builds. However, even on
16218 // debuggable builds downgrades of packages are permitted only if requested via
16219 // installFlags. This is because we aim to keep the behavior of debuggable
16220 // platform builds as close as possible to the behavior of non-debuggable
16221 // platform builds.
16222 final boolean downgradeRequested =
16223 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16224 final boolean packageDebuggable =
16225 (dataOwnerPkg.applicationInfo.flags
16226 & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16227 final boolean downgradePermitted =
16228 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16229 if (!downgradePermitted) {
16231 checkDowngrade(dataOwnerPkg, pkgLite);
16232 } catch (PackageManagerException e) {
16233 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16234 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16239 if (installedPkg != null) {
16240 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16241 // Check for updated system application.
16242 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16244 Slog.w(TAG, "Cannot install update to system app on sdcard");
16245 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16247 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16250 // Install flag overrides everything.
16251 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16253 // If current upgrade specifies particular preference
16254 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16255 // Application explicitly specified internal.
16256 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16257 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16258 // App explictly prefers external. Let policy decide
16260 // Prefer previous location
16261 if (isExternal(installedPkg)) {
16262 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16264 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16268 // Invalid install. Return error code
16269 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16273 // All the special cases have been taken care of.
16274 // Return result based on recommended install location.
16276 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16278 return pkgLite.recommendedInstallLocation;
16282 * Invoke remote method to get package information and install
16283 * location values. Override install location based on default
16284 * policy if needed and then create install arguments based
16285 * on the install location.
16287 public void handleStartCopy() throws RemoteException {
16288 int ret = PackageManager.INSTALL_SUCCEEDED;
16290 // If we're already staged, we've firmly committed to an install location
16291 if (origin.staged) {
16292 if (origin.file != null) {
16293 installFlags |= PackageManager.INSTALL_INTERNAL;
16294 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16295 } else if (origin.cid != null) {
16296 installFlags |= PackageManager.INSTALL_EXTERNAL;
16297 installFlags &= ~PackageManager.INSTALL_INTERNAL;
16299 throw new IllegalStateException("Invalid stage location");
16303 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16304 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16305 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16306 PackageInfoLite pkgLite = null;
16308 if (onInt && onSd) {
16309 // Check if both bits are set.
16310 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16311 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16312 } else if (onSd && ephemeral) {
16313 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external");
16314 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16316 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16317 packageAbiOverride);
16319 if (DEBUG_EPHEMERAL && ephemeral) {
16320 Slog.v(TAG, "pkgLite for install: " + pkgLite);
16324 * If we have too little free space, try to free cache
16325 * before giving up.
16327 if (!origin.staged && pkgLite.recommendedInstallLocation
16328 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16329 // TODO: focus freeing disk space on the target device
16330 final StorageManager storage = StorageManager.from(mContext);
16331 final long lowThreshold = storage.getStorageLowBytes(
16332 Environment.getDataDirectory());
16334 final long sizeBytes = mContainerService.calculateInstalledSize(
16335 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16338 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16339 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16340 installFlags, packageAbiOverride);
16341 } catch (InstallerException e) {
16342 Slog.w(TAG, "Failed to free cache", e);
16346 * The cache free must have deleted the file we
16347 * downloaded to install.
16349 * TODO: fix the "freeCache" call to not delete
16350 * the file we care about.
16352 if (pkgLite.recommendedInstallLocation
16353 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16354 pkgLite.recommendedInstallLocation
16355 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16360 if (ret == PackageManager.INSTALL_SUCCEEDED) {
16361 int loc = pkgLite.recommendedInstallLocation;
16362 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16363 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16364 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16365 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16366 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16367 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16368 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16369 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16370 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16371 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16372 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16373 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16375 // Override with defaults if needed.
16376 loc = installLocationPolicy(pkgLite);
16377 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16378 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16379 } else if (!onSd && !onInt) {
16380 // Override install location with flags
16381 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16382 // Set the flag to install on external media.
16383 installFlags |= PackageManager.INSTALL_EXTERNAL;
16384 installFlags &= ~PackageManager.INSTALL_INTERNAL;
16385 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16386 if (DEBUG_EPHEMERAL) {
16387 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16389 installFlags |= PackageManager.INSTALL_INSTANT_APP;
16390 installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16391 |PackageManager.INSTALL_INTERNAL);
16393 // Make sure the flag for installing on external
16395 installFlags |= PackageManager.INSTALL_INTERNAL;
16396 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16402 final InstallArgs args = createInstallArgs(this);
16405 if (ret == PackageManager.INSTALL_SUCCEEDED) {
16406 // TODO: http://b/22976637
16407 // Apps installed for "all" users use the device owner to verify the app
16408 UserHandle verifierUser = getUser();
16409 if (verifierUser == UserHandle.ALL) {
16410 verifierUser = UserHandle.SYSTEM;
16414 * Determine if we have any installed package verifiers. If we
16415 * do, then we'll defer to them to verify the packages.
16417 final int requiredUid = mRequiredVerifierPackage == null ? -1
16418 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16419 verifierUser.getIdentifier());
16420 final int installerUid =
16421 verificationInfo == null ? -1 : verificationInfo.installerUid;
16422 if (!origin.existing && requiredUid != -1
16423 && isVerificationEnabled(
16424 verifierUser.getIdentifier(), installFlags, installerUid)) {
16425 final Intent verification = new Intent(
16426 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16427 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16428 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16429 PACKAGE_MIME_TYPE);
16430 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16432 // Query all live verifiers based on current user state
16433 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16434 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16435 false /*allowDynamicSplits*/);
16437 if (DEBUG_VERIFY) {
16438 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16439 + verification.toString() + " with " + pkgLite.verifiers.length
16440 + " optional verifiers");
16443 final int verificationId = mPendingVerificationToken++;
16445 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16447 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16448 installerPackageName);
16450 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16453 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16454 pkgLite.packageName);
16456 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16457 pkgLite.versionCode);
16459 if (verificationInfo != null) {
16460 if (verificationInfo.originatingUri != null) {
16461 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16462 verificationInfo.originatingUri);
16464 if (verificationInfo.referrer != null) {
16465 verification.putExtra(Intent.EXTRA_REFERRER,
16466 verificationInfo.referrer);
16468 if (verificationInfo.originatingUid >= 0) {
16469 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16470 verificationInfo.originatingUid);
16472 if (verificationInfo.installerUid >= 0) {
16473 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16474 verificationInfo.installerUid);
16478 final PackageVerificationState verificationState = new PackageVerificationState(
16479 requiredUid, args);
16481 mPendingVerification.append(verificationId, verificationState);
16483 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16484 receivers, verificationState);
16486 DeviceIdleController.LocalService idleController = getDeviceIdleController();
16487 final long idleDuration = getVerificationTimeout();
16490 * If any sufficient verifiers were listed in the package
16491 * manifest, attempt to ask them.
16493 if (sufficientVerifiers != null) {
16494 final int N = sufficientVerifiers.size();
16496 Slog.i(TAG, "Additional verifiers required, but none installed.");
16497 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16499 for (int i = 0; i < N; i++) {
16500 final ComponentName verifierComponent = sufficientVerifiers.get(i);
16501 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16502 verifierComponent.getPackageName(), idleDuration,
16503 verifierUser.getIdentifier(), false, "package verifier");
16505 final Intent sufficientIntent = new Intent(verification);
16506 sufficientIntent.setComponent(verifierComponent);
16507 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16512 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16513 mRequiredVerifierPackage, receivers);
16514 if (ret == PackageManager.INSTALL_SUCCEEDED
16515 && mRequiredVerifierPackage != null) {
16516 Trace.asyncTraceBegin(
16517 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16519 * Send the intent to the required verification agent,
16520 * but only start the verification timeout after the
16521 * target BroadcastReceivers have run.
16523 verification.setComponent(requiredVerifierComponent);
16524 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16525 mRequiredVerifierPackage, idleDuration,
16526 verifierUser.getIdentifier(), false, "package verifier");
16527 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16528 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16529 new BroadcastReceiver() {
16531 public void onReceive(Context context, Intent intent) {
16532 final Message msg = mHandler
16533 .obtainMessage(CHECK_PENDING_VERIFICATION);
16534 msg.arg1 = verificationId;
16535 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16537 }, null, 0, null, null);
16540 * We don't want the copy to proceed until verification
16541 * succeeds, so null out this field.
16547 * No package verification is enabled, so immediately start
16548 * the remote call to initiate copy using temporary file.
16550 ret = args.copyApk(mContainerService, true);
16558 void handleReturnCode() {
16559 // If mArgs is null, then MCS couldn't be reached. When it
16560 // reconnects, it will try again to install. At that point, this
16562 if (mArgs != null) {
16563 processPendingInstall(mArgs, mRet);
16568 void handleServiceError() {
16569 mArgs = createInstallArgs(this);
16570 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16573 public boolean isForwardLocked() {
16574 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16579 * Used during creation of InstallArgs
16581 * @param installFlags package installation flags
16582 * @return true if should be installed on external storage
16584 private static boolean installOnExternalAsec(int installFlags) {
16585 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16588 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16595 * Used during creation of InstallArgs
16597 * @param installFlags package installation flags
16598 * @return true if should be installed as forward locked
16600 private static boolean installForwardLocked(int installFlags) {
16601 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16604 private InstallArgs createInstallArgs(InstallParams params) {
16605 if (params.move != null) {
16606 return new MoveInstallArgs(params);
16607 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16608 return new AsecInstallArgs(params);
16610 return new FileInstallArgs(params);
16615 * Create args that describe an existing installed package. Typically used
16616 * when cleaning up old installs, or used as a move source.
16618 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16619 String resourcePath, String[] instructionSets) {
16620 final boolean isInAsec;
16621 if (installOnExternalAsec(installFlags)) {
16622 /* Apps on SD card are always in ASEC containers. */
16624 } else if (installForwardLocked(installFlags)
16625 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16627 * Forward-locked apps are only in ASEC containers if they're the
16636 return new AsecInstallArgs(codePath, instructionSets,
16637 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16639 return new FileInstallArgs(codePath, resourcePath, instructionSets);
16643 static abstract class InstallArgs {
16644 /** @see InstallParams#origin */
16645 final OriginInfo origin;
16646 /** @see InstallParams#move */
16647 final MoveInfo move;
16649 final IPackageInstallObserver2 observer;
16650 // Always refers to PackageManager flags only
16651 final int installFlags;
16652 final String installerPackageName;
16653 final String volumeUuid;
16654 final UserHandle user;
16655 final String abiOverride;
16656 final String[] installGrantPermissions;
16657 /** If non-null, drop an async trace when the install completes */
16658 final String traceMethod;
16659 final int traceCookie;
16660 final Certificate[][] certificates;
16661 final int installReason;
16663 // The list of instruction sets supported by this app. This is currently
16664 // only used during the rmdex() phase to clean up resources. We can get rid of this
16665 // if we move dex files under the common app path.
16666 /* nullable */ String[] instructionSets;
16668 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16669 int installFlags, String installerPackageName, String volumeUuid,
16670 UserHandle user, String[] instructionSets,
16671 String abiOverride, String[] installGrantPermissions,
16672 String traceMethod, int traceCookie, Certificate[][] certificates,
16673 int installReason) {
16674 this.origin = origin;
16676 this.installFlags = installFlags;
16677 this.observer = observer;
16678 this.installerPackageName = installerPackageName;
16679 this.volumeUuid = volumeUuid;
16681 this.instructionSets = instructionSets;
16682 this.abiOverride = abiOverride;
16683 this.installGrantPermissions = installGrantPermissions;
16684 this.traceMethod = traceMethod;
16685 this.traceCookie = traceCookie;
16686 this.certificates = certificates;
16687 this.installReason = installReason;
16690 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16691 abstract int doPreInstall(int status);
16694 * Rename package into final resting place. All paths on the given
16695 * scanned package should be updated to reflect the rename.
16697 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16698 abstract int doPostInstall(int status, int uid);
16700 /** @see PackageSettingBase#codePathString */
16701 abstract String getCodePath();
16702 /** @see PackageSettingBase#resourcePathString */
16703 abstract String getResourcePath();
16705 // Need installer lock especially for dex file removal.
16706 abstract void cleanUpResourcesLI();
16707 abstract boolean doPostDeleteLI(boolean delete);
16710 * Called before the source arguments are copied. This is used mostly
16711 * for MoveParams when it needs to read the source file to put it in the
16715 return PackageManager.INSTALL_SUCCEEDED;
16719 * Called after the source arguments are copied. This is used mostly for
16720 * MoveParams when it needs to read the source file to put it in the
16723 int doPostCopy(int uid) {
16724 return PackageManager.INSTALL_SUCCEEDED;
16727 protected boolean isFwdLocked() {
16728 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16731 protected boolean isExternalAsec() {
16732 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16735 protected boolean isEphemeral() {
16736 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16739 UserHandle getUser() {
16744 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16745 if (!allCodePaths.isEmpty()) {
16746 if (instructionSets == null) {
16747 throw new IllegalStateException("instructionSet == null");
16749 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16750 for (String codePath : allCodePaths) {
16751 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16753 mInstaller.rmdex(codePath, dexCodeInstructionSet);
16754 } catch (InstallerException ignored) {
16762 * Logic to handle installation of non-ASEC applications, including copying
16763 * and renaming logic.
16765 class FileInstallArgs extends InstallArgs {
16766 private File codeFile;
16767 private File resourceFile;
16769 // Example topology:
16770 // /data/app/com.example/base.apk
16771 // /data/app/com.example/split_foo.apk
16772 // /data/app/com.example/lib/arm/libfoo.so
16773 // /data/app/com.example/lib/arm64/libfoo.so
16774 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16777 FileInstallArgs(InstallParams params) {
16778 super(params.origin, params.move, params.observer, params.installFlags,
16779 params.installerPackageName, params.volumeUuid,
16780 params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16781 params.grantedRuntimePermissions,
16782 params.traceMethod, params.traceCookie, params.certificates,
16783 params.installReason);
16784 if (isFwdLocked()) {
16785 throw new IllegalArgumentException("Forward locking only supported in ASEC");
16789 /** Existing install */
16790 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16791 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16792 null, null, null, 0, null /*certificates*/,
16793 PackageManager.INSTALL_REASON_UNKNOWN);
16794 this.codeFile = (codePath != null) ? new File(codePath) : null;
16795 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16798 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16801 return doCopyApk(imcs, temp);
16803 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16807 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16808 if (origin.staged) {
16809 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16810 codeFile = origin.file;
16811 resourceFile = origin.file;
16812 return PackageManager.INSTALL_SUCCEEDED;
16816 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16817 final File tempDir =
16818 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16819 codeFile = tempDir;
16820 resourceFile = tempDir;
16821 } catch (IOException e) {
16822 Slog.w(TAG, "Failed to create copy file: " + e);
16823 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16826 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16828 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16829 if (!FileUtils.isValidExtFilename(name)) {
16830 throw new IllegalArgumentException("Invalid filename: " + name);
16833 final File file = new File(codeFile, name);
16834 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16835 O_RDWR | O_CREAT, 0644);
16836 Os.chmod(file.getAbsolutePath(), 0644);
16837 return new ParcelFileDescriptor(fd);
16838 } catch (ErrnoException e) {
16839 throw new RemoteException("Failed to open: " + e.getMessage());
16844 int ret = PackageManager.INSTALL_SUCCEEDED;
16845 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16846 if (ret != PackageManager.INSTALL_SUCCEEDED) {
16847 Slog.e(TAG, "Failed to copy package");
16851 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16852 NativeLibraryHelper.Handle handle = null;
16854 handle = NativeLibraryHelper.Handle.create(codeFile);
16855 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16857 } catch (IOException e) {
16858 Slog.e(TAG, "Copying native libraries failed", e);
16859 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16861 IoUtils.closeQuietly(handle);
16867 int doPreInstall(int status) {
16868 if (status != PackageManager.INSTALL_SUCCEEDED) {
16874 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16875 if (status != PackageManager.INSTALL_SUCCEEDED) {
16880 final File targetDir = codeFile.getParentFile();
16881 final File beforeCodeFile = codeFile;
16882 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16884 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16886 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16887 } catch (ErrnoException e) {
16888 Slog.w(TAG, "Failed to rename", e);
16892 if (!SELinux.restoreconRecursive(afterCodeFile)) {
16893 Slog.w(TAG, "Failed to restorecon");
16897 // Reflect the rename internally
16898 codeFile = afterCodeFile;
16899 resourceFile = afterCodeFile;
16901 // Reflect the rename in scanned details
16902 pkg.setCodePath(afterCodeFile.getAbsolutePath());
16903 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16904 afterCodeFile, pkg.baseCodePath));
16905 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16906 afterCodeFile, pkg.splitCodePaths));
16908 // Reflect the rename in app info
16909 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16910 pkg.setApplicationInfoCodePath(pkg.codePath);
16911 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16912 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16913 pkg.setApplicationInfoResourcePath(pkg.codePath);
16914 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16915 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16920 int doPostInstall(int status, int uid) {
16921 if (status != PackageManager.INSTALL_SUCCEEDED) {
16928 String getCodePath() {
16929 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16933 String getResourcePath() {
16934 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16937 private boolean cleanUp() {
16938 if (codeFile == null || !codeFile.exists()) {
16942 removeCodePathLI(codeFile);
16944 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16945 resourceFile.delete();
16951 void cleanUpResourcesLI() {
16952 // Try enumerating all code paths before deleting
16953 List<String> allCodePaths = Collections.EMPTY_LIST;
16954 if (codeFile != null && codeFile.exists()) {
16956 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16957 allCodePaths = pkg.getAllCodePaths();
16958 } catch (PackageParserException e) {
16959 // Ignored; we tried our best
16964 removeDexFiles(allCodePaths, instructionSets);
16967 boolean doPostDeleteLI(boolean delete) {
16968 // XXX err, shouldn't we respect the delete flag?
16969 cleanUpResourcesLI();
16974 private boolean isAsecExternal(String cid) {
16975 final String asecPath = PackageHelper.getSdFilesystem(cid);
16976 return !asecPath.startsWith(mAsecInternalPath);
16979 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16980 PackageManagerException {
16982 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16983 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16984 throw new PackageManagerException(copyRet, message);
16990 * Extract the StorageManagerService "container ID" from the full code path of an
16993 static String cidFromCodePath(String fullCodePath) {
16994 int eidx = fullCodePath.lastIndexOf("/");
16995 String subStr1 = fullCodePath.substring(0, eidx);
16996 int sidx = subStr1.lastIndexOf("/");
16997 return subStr1.substring(sidx+1, eidx);
17001 * Logic to handle installation of ASEC applications, including copying and
17004 class AsecInstallArgs extends InstallArgs {
17005 static final String RES_FILE_NAME = "pkg.apk";
17006 static final String PUBLIC_RES_FILE_NAME = "res.zip";
17009 String packagePath;
17010 String resourcePath;
17013 AsecInstallArgs(InstallParams params) {
17014 super(params.origin, params.move, params.observer, params.installFlags,
17015 params.installerPackageName, params.volumeUuid,
17016 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17017 params.grantedRuntimePermissions,
17018 params.traceMethod, params.traceCookie, params.certificates,
17019 params.installReason);
17022 /** Existing install */
17023 AsecInstallArgs(String fullCodePath, String[] instructionSets,
17024 boolean isExternal, boolean isForwardLocked) {
17025 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17026 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17027 instructionSets, null, null, null, 0, null /*certificates*/,
17028 PackageManager.INSTALL_REASON_UNKNOWN);
17029 // Hackily pretend we're still looking at a full code path
17030 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17031 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17034 // Extract cid from fullCodePath
17035 int eidx = fullCodePath.lastIndexOf("/");
17036 String subStr1 = fullCodePath.substring(0, eidx);
17037 int sidx = subStr1.lastIndexOf("/");
17038 cid = subStr1.substring(sidx+1, eidx);
17039 setMountPath(subStr1);
17042 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17043 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17044 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17045 instructionSets, null, null, null, 0, null /*certificates*/,
17046 PackageManager.INSTALL_REASON_UNKNOWN);
17048 setMountPath(PackageHelper.getSdDir(cid));
17051 void createCopyFile() {
17052 cid = mInstallerService.allocateExternalStageCidLegacy();
17055 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17056 if (origin.staged && origin.cid != null) {
17057 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17059 setMountPath(PackageHelper.getSdDir(cid));
17060 return PackageManager.INSTALL_SUCCEEDED;
17067 * Pre-emptively destroy the container since it's destroyed if
17068 * copying fails due to it existing anyway.
17070 PackageHelper.destroySdDir(cid);
17073 final String newMountPath = imcs.copyPackageToContainer(
17074 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17075 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17077 if (newMountPath != null) {
17078 setMountPath(newMountPath);
17079 return PackageManager.INSTALL_SUCCEEDED;
17081 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17086 String getCodePath() {
17087 return packagePath;
17091 String getResourcePath() {
17092 return resourcePath;
17095 int doPreInstall(int status) {
17096 if (status != PackageManager.INSTALL_SUCCEEDED) {
17097 // Destroy container
17098 PackageHelper.destroySdDir(cid);
17100 boolean mounted = PackageHelper.isContainerMounted(cid);
17102 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17103 Process.SYSTEM_UID);
17104 if (newMountPath != null) {
17105 setMountPath(newMountPath);
17107 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17114 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17115 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17116 String newMountPath = null;
17117 if (PackageHelper.isContainerMounted(cid)) {
17118 // Unmount the container
17119 if (!PackageHelper.unMountSdDir(cid)) {
17120 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17124 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17125 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17126 " which might be stale. Will try to clean up.");
17127 // Clean up the stale container and proceed to recreate.
17128 if (!PackageHelper.destroySdDir(newCacheId)) {
17129 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17132 // Successfully cleaned up stale container. Try to rename again.
17133 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17134 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17135 + " inspite of cleaning it up.");
17139 if (!PackageHelper.isContainerMounted(newCacheId)) {
17140 Slog.w(TAG, "Mounting container " + newCacheId);
17141 newMountPath = PackageHelper.mountSdDir(newCacheId,
17142 getEncryptKey(), Process.SYSTEM_UID);
17144 newMountPath = PackageHelper.getSdDir(newCacheId);
17146 if (newMountPath == null) {
17147 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
17150 Log.i(TAG, "Succesfully renamed " + cid +
17151 " to " + newCacheId +
17152 " at new path: " + newMountPath);
17155 final File beforeCodeFile = new File(packagePath);
17156 setMountPath(newMountPath);
17157 final File afterCodeFile = new File(packagePath);
17159 // Reflect the rename in scanned details
17160 pkg.setCodePath(afterCodeFile.getAbsolutePath());
17161 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17162 afterCodeFile, pkg.baseCodePath));
17163 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17164 afterCodeFile, pkg.splitCodePaths));
17166 // Reflect the rename in app info
17167 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17168 pkg.setApplicationInfoCodePath(pkg.codePath);
17169 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17170 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17171 pkg.setApplicationInfoResourcePath(pkg.codePath);
17172 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17173 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17178 private void setMountPath(String mountPath) {
17179 final File mountFile = new File(mountPath);
17181 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17182 if (monolithicFile.exists()) {
17183 packagePath = monolithicFile.getAbsolutePath();
17184 if (isFwdLocked()) {
17185 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17187 resourcePath = packagePath;
17190 packagePath = mountFile.getAbsolutePath();
17191 resourcePath = packagePath;
17195 int doPostInstall(int status, int uid) {
17196 if (status != PackageManager.INSTALL_SUCCEEDED) {
17199 final int groupOwner;
17200 final String protectedFile;
17201 if (isFwdLocked()) {
17202 groupOwner = UserHandle.getSharedAppGid(uid);
17203 protectedFile = RES_FILE_NAME;
17206 protectedFile = null;
17209 if (uid < Process.FIRST_APPLICATION_UID
17210 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17211 Slog.e(TAG, "Failed to finalize " + cid);
17212 PackageHelper.destroySdDir(cid);
17213 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17216 boolean mounted = PackageHelper.isContainerMounted(cid);
17218 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17224 private void cleanUp() {
17225 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17227 // Destroy secure container
17228 PackageHelper.destroySdDir(cid);
17231 private List<String> getAllCodePaths() {
17232 final File codeFile = new File(getCodePath());
17233 if (codeFile != null && codeFile.exists()) {
17235 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17236 return pkg.getAllCodePaths();
17237 } catch (PackageParserException e) {
17238 // Ignored; we tried our best
17241 return Collections.EMPTY_LIST;
17244 void cleanUpResourcesLI() {
17245 // Enumerate all code paths before deleting
17246 cleanUpResourcesLI(getAllCodePaths());
17249 private void cleanUpResourcesLI(List<String> allCodePaths) {
17251 removeDexFiles(allCodePaths, instructionSets);
17254 String getPackageName() {
17255 return getAsecPackageName(cid);
17258 boolean doPostDeleteLI(boolean delete) {
17259 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17260 final List<String> allCodePaths = getAllCodePaths();
17261 boolean mounted = PackageHelper.isContainerMounted(cid);
17264 if (PackageHelper.unMountSdDir(cid)) {
17268 if (!mounted && delete) {
17269 cleanUpResourcesLI(allCodePaths);
17276 if (isFwdLocked()) {
17277 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17278 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17279 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17283 return PackageManager.INSTALL_SUCCEEDED;
17287 int doPostCopy(int uid) {
17288 if (isFwdLocked()) {
17289 if (uid < Process.FIRST_APPLICATION_UID
17290 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17292 Slog.e(TAG, "Failed to finalize " + cid);
17293 PackageHelper.destroySdDir(cid);
17294 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17298 return PackageManager.INSTALL_SUCCEEDED;
17303 * Logic to handle movement of existing installed applications.
17305 class MoveInstallArgs extends InstallArgs {
17306 private File codeFile;
17307 private File resourceFile;
17310 MoveInstallArgs(InstallParams params) {
17311 super(params.origin, params.move, params.observer, params.installFlags,
17312 params.installerPackageName, params.volumeUuid,
17313 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17314 params.grantedRuntimePermissions,
17315 params.traceMethod, params.traceCookie, params.certificates,
17316 params.installReason);
17319 int copyApk(IMediaContainerService imcs, boolean temp) {
17320 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17321 + move.fromUuid + " to " + move.toUuid);
17322 synchronized (mInstaller) {
17324 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17325 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17326 } catch (InstallerException e) {
17327 Slog.w(TAG, "Failed to move app", e);
17328 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17332 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17333 resourceFile = codeFile;
17334 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17336 return PackageManager.INSTALL_SUCCEEDED;
17339 int doPreInstall(int status) {
17340 if (status != PackageManager.INSTALL_SUCCEEDED) {
17341 cleanUp(move.toUuid);
17346 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17347 if (status != PackageManager.INSTALL_SUCCEEDED) {
17348 cleanUp(move.toUuid);
17352 // Reflect the move in app info
17353 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17354 pkg.setApplicationInfoCodePath(pkg.codePath);
17355 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17356 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17357 pkg.setApplicationInfoResourcePath(pkg.codePath);
17358 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17359 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17364 int doPostInstall(int status, int uid) {
17365 if (status == PackageManager.INSTALL_SUCCEEDED) {
17366 cleanUp(move.fromUuid);
17368 cleanUp(move.toUuid);
17374 String getCodePath() {
17375 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17379 String getResourcePath() {
17380 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17383 private boolean cleanUp(String volumeUuid) {
17384 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17386 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17387 final int[] userIds = sUserManager.getUserIds();
17388 synchronized (mInstallLock) {
17389 // Clean up both app data and code
17390 // All package moves are frozen until finished
17391 for (int userId : userIds) {
17393 mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17394 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17395 } catch (InstallerException e) {
17396 Slog.w(TAG, String.valueOf(e));
17399 removeCodePathLI(codeFile);
17404 void cleanUpResourcesLI() {
17405 throw new UnsupportedOperationException();
17408 boolean doPostDeleteLI(boolean delete) {
17409 throw new UnsupportedOperationException();
17413 static String getAsecPackageName(String packageCid) {
17414 int idx = packageCid.lastIndexOf("-");
17418 return packageCid.substring(0, idx);
17421 // Utility method used to create code paths based on package name and available index.
17422 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17423 String idxStr = "";
17425 // Fall back to default value of idx=1 if prefix is not
17426 // part of oldCodePath
17427 if (oldCodePath != null) {
17428 String subStr = oldCodePath;
17429 // Drop the suffix right away
17430 if (suffix != null && subStr.endsWith(suffix)) {
17431 subStr = subStr.substring(0, subStr.length() - suffix.length());
17433 // If oldCodePath already contains prefix find out the
17434 // ending index to either increment or decrement.
17435 int sidx = subStr.lastIndexOf(prefix);
17437 subStr = subStr.substring(sidx + prefix.length());
17438 if (subStr != null) {
17439 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17440 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17443 idx = Integer.parseInt(subStr);
17449 } catch(NumberFormatException e) {
17454 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17455 return prefix + idxStr;
17458 private File getNextCodePath(File targetDir, String packageName) {
17460 SecureRandom random = new SecureRandom();
17461 byte[] bytes = new byte[16];
17463 random.nextBytes(bytes);
17464 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17465 result = new File(targetDir, packageName + "-" + suffix);
17466 } while (result.exists());
17470 // Utility method that returns the relative package path with respect
17471 // to the installation directory. Like say for /data/data/com.test-1.apk
17472 // string com.test-1 is returned.
17473 static String deriveCodePathName(String codePath) {
17474 if (codePath == null) {
17477 final File codeFile = new File(codePath);
17478 final String name = codeFile.getName();
17479 if (codeFile.isDirectory()) {
17481 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17482 final int lastDot = name.lastIndexOf('.');
17483 return name.substring(0, lastDot);
17485 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17490 static class PackageInstalledInfo {
17493 // The set of users that originally had this package installed.
17495 // The set of users that now have this package installed.
17497 PackageParser.Package pkg;
17500 String installerPackageName;
17501 PackageRemovedInfo removedInfo;
17502 ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17504 public void setError(int code, String msg) {
17505 setReturnCode(code);
17506 setReturnMessage(msg);
17510 public void setError(String msg, PackageParserException e) {
17511 setReturnCode(e.error);
17512 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17513 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17514 for (int i = 0; i < childCount; i++) {
17515 addedChildPackages.valueAt(i).setError(msg, e);
17517 Slog.w(TAG, msg, e);
17520 public void setError(String msg, PackageManagerException e) {
17521 returnCode = e.error;
17522 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17523 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17524 for (int i = 0; i < childCount; i++) {
17525 addedChildPackages.valueAt(i).setError(msg, e);
17527 Slog.w(TAG, msg, e);
17530 public void setReturnCode(int returnCode) {
17531 this.returnCode = returnCode;
17532 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17533 for (int i = 0; i < childCount; i++) {
17534 addedChildPackages.valueAt(i).returnCode = returnCode;
17538 private void setReturnMessage(String returnMsg) {
17539 this.returnMsg = returnMsg;
17540 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17541 for (int i = 0; i < childCount; i++) {
17542 addedChildPackages.valueAt(i).returnMsg = returnMsg;
17546 // In some error cases we want to convey more info back to the observer
17547 String origPackage;
17548 String origPermission;
17552 * Install a non-existing package.
17554 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17555 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17556 PackageInstalledInfo res, int installReason) {
17557 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17559 // Remember this for later, in case we need to rollback this install
17560 String pkgName = pkg.packageName;
17562 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17564 synchronized(mPackages) {
17565 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17566 if (renamedPackage != null) {
17567 // A package with the same name is already installed, though
17568 // it has been renamed to an older name. The package we
17569 // are trying to install should be installed as an update to
17570 // the existing one, but that has not been requested, so bail.
17571 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17572 + " without first uninstalling package running as "
17576 if (mPackages.containsKey(pkgName)) {
17577 // Don't allow installation over an existing package with the same name.
17578 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17579 + " without first uninstalling.");
17585 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17586 System.currentTimeMillis(), user);
17588 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17590 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17591 prepareAppDataAfterInstallLIF(newPackage);
17594 // Remove package from internal structures, but keep around any
17595 // data that might have already existed
17596 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17597 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17599 } catch (PackageManagerException e) {
17600 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17606 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17607 // Can't rotate keys during boot or if sharedUser.
17608 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17609 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17612 // app is using upgradeKeySets; make sure all are valid
17613 KeySetManagerService ksms = mSettings.mKeySetManagerService;
17614 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17615 for (int i = 0; i < upgradeKeySets.length; i++) {
17616 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17617 Slog.wtf(TAG, "Package "
17618 + (oldPs.name != null ? oldPs.name : "<null>")
17619 + " contains upgrade-key-set reference to unknown key-set: "
17620 + upgradeKeySets[i]
17621 + " reverting to signatures check.");
17628 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17629 // Upgrade keysets are being used. Determine if new package has a superset of the
17631 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17632 KeySetManagerService ksms = mSettings.mKeySetManagerService;
17633 for (int i = 0; i < upgradeKeySets.length; i++) {
17634 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17635 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17642 private static void updateDigest(MessageDigest digest, File file) throws IOException {
17643 try (DigestInputStream digestStream =
17644 new DigestInputStream(new FileInputStream(file), digest)) {
17645 while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17649 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17650 UserHandle user, String installerPackageName, PackageInstalledInfo res,
17651 int installReason) {
17652 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17654 final PackageParser.Package oldPackage;
17655 final PackageSetting ps;
17656 final String pkgName = pkg.packageName;
17657 final int[] allUsers;
17658 final int[] installedUsers;
17660 synchronized(mPackages) {
17661 oldPackage = mPackages.get(pkgName);
17662 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17664 // don't allow upgrade to target a release SDK from a pre-release SDK
17665 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17666 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17667 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17668 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17669 if (oldTargetsPreRelease
17670 && !newTargetsPreRelease
17671 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17672 Slog.w(TAG, "Can't install package targeting released sdk");
17673 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17677 ps = mSettings.mPackages.get(pkgName);
17679 // verify signatures are valid
17680 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17681 if (!checkUpgradeKeySetLP(ps, pkg)) {
17682 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17683 "New package not signed by keys specified by upgrade-keysets: "
17688 // default to original signature matching
17689 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17690 != PackageManager.SIGNATURE_MATCH) {
17691 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17692 "New package has a different signature: " + pkgName);
17697 // don't allow a system upgrade unless the upgrade hash matches
17698 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17699 byte[] digestBytes = null;
17701 final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17702 updateDigest(digest, new File(pkg.baseCodePath));
17703 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17704 for (String path : pkg.splitCodePaths) {
17705 updateDigest(digest, new File(path));
17708 digestBytes = digest.digest();
17709 } catch (NoSuchAlgorithmException | IOException e) {
17710 res.setError(INSTALL_FAILED_INVALID_APK,
17711 "Could not compute hash: " + pkgName);
17714 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17715 res.setError(INSTALL_FAILED_INVALID_APK,
17716 "New package fails restrict-update check: " + pkgName);
17719 // retain upgrade restriction
17720 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17723 // Check for shared user id changes
17724 String invalidPackageName =
17725 getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17726 if (invalidPackageName != null) {
17727 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17728 "Package " + invalidPackageName + " tried to change user "
17729 + oldPackage.mSharedUserId);
17733 // In case of rollback, remember per-user/profile install state
17734 allUsers = sUserManager.getUserIds();
17735 installedUsers = ps.queryInstalledUsers(allUsers, true);
17737 // don't allow an upgrade from full to ephemeral
17738 if (isInstantApp) {
17739 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17740 for (int currentUser : allUsers) {
17741 if (!ps.getInstantApp(currentUser)) {
17742 // can't downgrade from full to instant
17743 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17744 + " for user: " + currentUser);
17745 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17749 } else if (!ps.getInstantApp(user.getIdentifier())) {
17750 // can't downgrade from full to instant
17751 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17752 + " for user: " + user.getIdentifier());
17753 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17759 // Update what is removed
17760 res.removedInfo = new PackageRemovedInfo(this);
17761 res.removedInfo.uid = oldPackage.applicationInfo.uid;
17762 res.removedInfo.removedPackage = oldPackage.packageName;
17763 res.removedInfo.installerPackageName = ps.installerPackageName;
17764 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17765 res.removedInfo.isUpdate = true;
17766 res.removedInfo.origUsers = installedUsers;
17767 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17768 for (int i = 0; i < installedUsers.length; i++) {
17769 final int userId = installedUsers[i];
17770 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17773 final int childCount = (oldPackage.childPackages != null)
17774 ? oldPackage.childPackages.size() : 0;
17775 for (int i = 0; i < childCount; i++) {
17776 boolean childPackageUpdated = false;
17777 PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17778 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17779 if (res.addedChildPackages != null) {
17780 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17781 if (childRes != null) {
17782 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17783 childRes.removedInfo.removedPackage = childPkg.packageName;
17784 if (childPs != null) {
17785 childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17787 childRes.removedInfo.isUpdate = true;
17788 childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17789 childPackageUpdated = true;
17792 if (!childPackageUpdated) {
17793 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17794 childRemovedRes.removedPackage = childPkg.packageName;
17795 if (childPs != null) {
17796 childRemovedRes.installerPackageName = childPs.installerPackageName;
17798 childRemovedRes.isUpdate = false;
17799 childRemovedRes.dataRemoved = true;
17800 synchronized (mPackages) {
17801 if (childPs != null) {
17802 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17805 if (res.removedInfo.removedChildPackages == null) {
17806 res.removedInfo.removedChildPackages = new ArrayMap<>();
17808 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17812 boolean sysPkg = (isSystemApp(oldPackage));
17814 // Set the system/privileged flags as needed
17815 final boolean privileged =
17816 (oldPackage.applicationInfo.privateFlags
17817 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17818 final int systemPolicyFlags = policyFlags
17819 | PackageParser.PARSE_IS_SYSTEM
17820 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17822 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17823 user, allUsers, installerPackageName, res, installReason);
17825 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17826 user, allUsers, installerPackageName, res, installReason);
17831 public List<String> getPreviousCodePaths(String packageName) {
17832 final int callingUid = Binder.getCallingUid();
17833 final List<String> result = new ArrayList<>();
17834 if (getInstantAppPackageName(callingUid) != null) {
17837 final PackageSetting ps = mSettings.mPackages.get(packageName);
17839 && ps.oldCodePaths != null
17840 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17841 result.addAll(ps.oldCodePaths);
17846 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17847 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17848 int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17849 int installReason) {
17850 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17853 String pkgName = deletedPackage.packageName;
17854 boolean deletedPkg = true;
17855 boolean addedPkg = false;
17856 boolean updatedSettings = false;
17857 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17858 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17859 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17861 final long origUpdateTime = (pkg.mExtras != null)
17862 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17864 // First delete the existing package while retaining the data directory
17865 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17866 res.removedInfo, true, pkg)) {
17867 // If the existing package wasn't successfully deleted
17868 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17869 deletedPkg = false;
17871 // Successfully deleted the old package; proceed with replace.
17873 // If deleted package lived in a container, give users a chance to
17874 // relinquish resources before killing.
17875 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17876 if (DEBUG_INSTALL) {
17877 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17879 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17880 final ArrayList<String> pkgList = new ArrayList<String>(1);
17881 pkgList.add(deletedPackage.applicationInfo.packageName);
17882 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17885 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17886 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17887 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17890 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17891 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17892 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17895 // Update the in-memory copy of the previous code paths.
17896 PackageSetting ps = mSettings.mPackages.get(pkgName);
17898 if (ps.oldCodePaths == null) {
17899 ps.oldCodePaths = new ArraySet<>();
17901 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17902 if (deletedPackage.splitCodePaths != null) {
17903 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17906 ps.oldCodePaths = null;
17908 if (ps.childPackageNames != null) {
17909 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17910 final String childPkgName = ps.childPackageNames.get(i);
17911 final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17912 childPs.oldCodePaths = ps.oldCodePaths;
17915 // set instant app status, but, only if it's explicitly specified
17916 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17917 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17918 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17919 prepareAppDataAfterInstallLIF(newPackage);
17921 mDexManager.notifyPackageUpdated(newPackage.packageName,
17922 newPackage.baseCodePath, newPackage.splitCodePaths);
17923 } catch (PackageManagerException e) {
17924 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17928 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17929 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17931 // Revert all internal state mutations and added folders for the failed install
17933 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17934 res.removedInfo, true, null);
17937 // Restore the old package
17939 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17940 File restoreFile = new File(deletedPackage.codePath);
17941 // Parse old package
17942 boolean oldExternal = isExternal(deletedPackage);
17943 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
17944 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17945 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17946 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17948 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17950 } catch (PackageManagerException e) {
17951 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17956 synchronized (mPackages) {
17957 // Ensure the installer package name up to date
17958 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17960 // Update permissions for restored package
17961 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17963 mSettings.writeLPr();
17966 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17969 synchronized (mPackages) {
17970 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17972 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17973 if (res.removedInfo.removedChildPackages != null) {
17974 final int childCount = res.removedInfo.removedChildPackages.size();
17975 // Iterate in reverse as we may modify the collection
17976 for (int i = childCount - 1; i >= 0; i--) {
17977 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17978 if (res.addedChildPackages.containsKey(childPackageName)) {
17979 res.removedInfo.removedChildPackages.removeAt(i);
17981 PackageRemovedInfo childInfo = res.removedInfo
17982 .removedChildPackages.valueAt(i);
17983 childInfo.removedForAllUsers = mPackages.get(
17984 childInfo.removedPackage) == null;
17993 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17994 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17995 int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17996 int installReason) {
17997 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17998 + ", old=" + deletedPackage);
18000 final boolean disabledSystem;
18002 // Remove existing system package
18003 removePackageLI(deletedPackage, true);
18005 synchronized (mPackages) {
18006 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18008 if (!disabledSystem) {
18009 // We didn't need to disable the .apk as a current system package,
18010 // which means we are replacing another update that is already
18011 // installed. We need to make sure to delete the older one's .apk.
18012 res.removedInfo.args = createInstallArgsForExisting(0,
18013 deletedPackage.applicationInfo.getCodePath(),
18014 deletedPackage.applicationInfo.getResourcePath(),
18015 getAppDexInstructionSets(deletedPackage.applicationInfo));
18017 res.removedInfo.args = null;
18020 // Successfully disabled the old package. Now proceed with re-installation
18021 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18022 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18023 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18025 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18026 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18027 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18029 PackageParser.Package newPackage = null;
18031 // Add the package to the internal data structures
18032 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18034 // Set the update and install times
18035 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18036 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18037 System.currentTimeMillis());
18039 // Update the package dynamic state if succeeded
18040 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18041 // Now that the install succeeded make sure we remove data
18042 // directories for any child package the update removed.
18043 final int deletedChildCount = (deletedPackage.childPackages != null)
18044 ? deletedPackage.childPackages.size() : 0;
18045 final int newChildCount = (newPackage.childPackages != null)
18046 ? newPackage.childPackages.size() : 0;
18047 for (int i = 0; i < deletedChildCount; i++) {
18048 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18049 boolean childPackageDeleted = true;
18050 for (int j = 0; j < newChildCount; j++) {
18051 PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18052 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18053 childPackageDeleted = false;
18057 if (childPackageDeleted) {
18058 PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18059 deletedChildPkg.packageName);
18060 if (ps != null && res.removedInfo.removedChildPackages != null) {
18061 PackageRemovedInfo removedChildRes = res.removedInfo
18062 .removedChildPackages.get(deletedChildPkg.packageName);
18063 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18064 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18069 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18071 prepareAppDataAfterInstallLIF(newPackage);
18073 mDexManager.notifyPackageUpdated(newPackage.packageName,
18074 newPackage.baseCodePath, newPackage.splitCodePaths);
18076 } catch (PackageManagerException e) {
18077 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18078 res.setError("Package couldn't be installed in " + pkg.codePath, e);
18081 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18082 // Re installation failed. Restore old information
18083 // Remove new pkg information
18084 if (newPackage != null) {
18085 removeInstalledPackageLI(newPackage, true);
18087 // Add back the old system package
18089 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18090 } catch (PackageManagerException e) {
18091 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18094 synchronized (mPackages) {
18095 if (disabledSystem) {
18096 enableSystemPackageLPw(deletedPackage);
18099 // Ensure the installer package name up to date
18100 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18102 // Update permissions for restored package
18103 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18105 mSettings.writeLPr();
18108 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18109 + " after failed upgrade");
18114 * Checks whether the parent or any of the child packages have a change shared
18115 * user. For a package to be a valid update the shred users of the parent and
18116 * the children should match. We may later support changing child shared users.
18117 * @param oldPkg The updated package.
18118 * @param newPkg The update package.
18119 * @return The shared user that change between the versions.
18121 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18122 PackageParser.Package newPkg) {
18123 // Check parent shared user
18124 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18125 return newPkg.packageName;
18127 // Check child shared users
18128 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18129 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18130 for (int i = 0; i < newChildCount; i++) {
18131 PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18132 // If this child was present, did it have the same shared user?
18133 for (int j = 0; j < oldChildCount; j++) {
18134 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18135 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18136 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18137 return newChildPkg.packageName;
18144 private void removeNativeBinariesLI(PackageSetting ps) {
18145 // Remove the lib path for the parent package
18147 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18148 // Remove the lib path for the child packages
18149 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18150 for (int i = 0; i < childCount; i++) {
18151 PackageSetting childPs = null;
18152 synchronized (mPackages) {
18153 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18155 if (childPs != null) {
18156 NativeLibraryHelper.removeNativeBinariesLI(childPs
18157 .legacyNativeLibraryPathString);
18163 private void enableSystemPackageLPw(PackageParser.Package pkg) {
18164 // Enable the parent package
18165 mSettings.enableSystemPackageLPw(pkg.packageName);
18166 // Enable the child packages
18167 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18168 for (int i = 0; i < childCount; i++) {
18169 PackageParser.Package childPkg = pkg.childPackages.get(i);
18170 mSettings.enableSystemPackageLPw(childPkg.packageName);
18174 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18175 PackageParser.Package newPkg) {
18176 // Disable the parent package (parent always replaced)
18177 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18178 // Disable the child packages
18179 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18180 for (int i = 0; i < childCount; i++) {
18181 PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18182 final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18183 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18188 private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18189 String installerPackageName) {
18190 // Enable the parent package
18191 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18192 // Enable the child packages
18193 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18194 for (int i = 0; i < childCount; i++) {
18195 PackageParser.Package childPkg = pkg.childPackages.get(i);
18196 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18200 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18201 // Collect all used permissions in the UID
18202 ArraySet<String> usedPermissions = new ArraySet<>();
18203 final int packageCount = su.packages.size();
18204 for (int i = 0; i < packageCount; i++) {
18205 PackageSetting ps = su.packages.valueAt(i);
18206 if (ps.pkg == null) {
18209 final int requestedPermCount = ps.pkg.requestedPermissions.size();
18210 for (int j = 0; j < requestedPermCount; j++) {
18211 String permission = ps.pkg.requestedPermissions.get(j);
18212 BasePermission bp = mSettings.mPermissions.get(permission);
18214 usedPermissions.add(permission);
18219 PermissionsState permissionsState = su.getPermissionsState();
18220 // Prune install permissions
18221 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18222 final int installPermCount = installPermStates.size();
18223 for (int i = installPermCount - 1; i >= 0; i--) {
18224 PermissionState permissionState = installPermStates.get(i);
18225 if (!usedPermissions.contains(permissionState.getName())) {
18226 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18228 permissionsState.revokeInstallPermission(bp);
18229 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18230 PackageManager.MASK_PERMISSION_FLAGS, 0);
18235 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18237 // Prune runtime permissions
18238 for (int userId : allUserIds) {
18239 List<PermissionState> runtimePermStates = permissionsState
18240 .getRuntimePermissionStates(userId);
18241 final int runtimePermCount = runtimePermStates.size();
18242 for (int i = runtimePermCount - 1; i >= 0; i--) {
18243 PermissionState permissionState = runtimePermStates.get(i);
18244 if (!usedPermissions.contains(permissionState.getName())) {
18245 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18247 permissionsState.revokeRuntimePermission(bp, userId);
18248 permissionsState.updatePermissionFlags(bp, userId,
18249 PackageManager.MASK_PERMISSION_FLAGS, 0);
18250 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18251 runtimePermissionChangedUserIds, userId);
18257 return runtimePermissionChangedUserIds;
18260 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18261 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18262 // Update the parent package setting
18263 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18264 res, user, installReason);
18265 // Update the child packages setting
18266 final int childCount = (newPackage.childPackages != null)
18267 ? newPackage.childPackages.size() : 0;
18268 for (int i = 0; i < childCount; i++) {
18269 PackageParser.Package childPackage = newPackage.childPackages.get(i);
18270 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18271 updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18272 childRes.origUsers, childRes, user, installReason);
18276 private void updateSettingsInternalLI(PackageParser.Package newPackage,
18277 String installerPackageName, int[] allUsers, int[] installedForUsers,
18278 PackageInstalledInfo res, UserHandle user, int installReason) {
18279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18281 String pkgName = newPackage.packageName;
18282 synchronized (mPackages) {
18283 //write settings. the installStatus will be incomplete at this stage.
18284 //note that the new package setting would have already been
18285 //added to mPackages. It hasn't been persisted yet.
18286 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18287 // TODO: Remove this write? It's also written at the end of this method
18288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18289 mSettings.writeLPr();
18290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18293 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18294 synchronized (mPackages) {
18295 updatePermissionsLPw(newPackage.packageName, newPackage,
18296 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18297 ? UPDATE_PERMISSIONS_ALL : 0));
18298 // For system-bundled packages, we assume that installing an upgraded version
18299 // of the package implies that the user actually wants to run that new code,
18300 // so we enable the package.
18301 PackageSetting ps = mSettings.mPackages.get(pkgName);
18302 final int userId = user.getIdentifier();
18304 if (isSystemApp(newPackage)) {
18305 if (DEBUG_INSTALL) {
18306 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18308 // Enable system package for requested users
18309 if (res.origUsers != null) {
18310 for (int origUserId : res.origUsers) {
18311 if (userId == UserHandle.USER_ALL || userId == origUserId) {
18312 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18313 origUserId, installerPackageName);
18317 // Also convey the prior install/uninstall state
18318 if (allUsers != null && installedForUsers != null) {
18319 for (int currentUserId : allUsers) {
18320 final boolean installed = ArrayUtils.contains(
18321 installedForUsers, currentUserId);
18322 if (DEBUG_INSTALL) {
18323 Slog.d(TAG, " user " + currentUserId + " => " + installed);
18325 ps.setInstalled(installed, currentUserId);
18327 // these install state changes will be persisted in the
18328 // upcoming call to mSettings.writeLPr().
18331 // It's implied that when a user requests installation, they want the app to be
18332 // installed and enabled.
18333 if (userId != UserHandle.USER_ALL) {
18334 ps.setInstalled(true, userId);
18335 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18338 // When replacing an existing package, preserve the original install reason for all
18339 // users that had the package installed before.
18340 final Set<Integer> previousUserIds = new ArraySet<>();
18341 if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18342 final int installReasonCount = res.removedInfo.installReasons.size();
18343 for (int i = 0; i < installReasonCount; i++) {
18344 final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18345 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18346 ps.setInstallReason(previousInstallReason, previousUserId);
18347 previousUserIds.add(previousUserId);
18351 // Set install reason for users that are having the package newly installed.
18352 if (userId == UserHandle.USER_ALL) {
18353 for (int currentUserId : sUserManager.getUserIds()) {
18354 if (!previousUserIds.contains(currentUserId)) {
18355 ps.setInstallReason(installReason, currentUserId);
18358 } else if (!previousUserIds.contains(userId)) {
18359 ps.setInstallReason(installReason, userId);
18361 mSettings.writeKernelMappingLPr(ps);
18363 res.name = pkgName;
18364 res.uid = newPackage.applicationInfo.uid;
18365 res.pkg = newPackage;
18366 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18367 mSettings.setInstallerPackageName(pkgName, installerPackageName);
18368 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18369 //to update install status
18370 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18371 mSettings.writeLPr();
18372 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18378 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18381 installPackageLI(args, res);
18383 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18387 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18388 final int installFlags = args.installFlags;
18389 final String installerPackageName = args.installerPackageName;
18390 final String volumeUuid = args.volumeUuid;
18391 final File tmpPackageFile = new File(args.getCodePath());
18392 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18393 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18394 || (args.volumeUuid != null));
18395 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18396 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18397 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18398 final boolean virtualPreload =
18399 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18400 boolean replace = false;
18401 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18402 if (args.move != null) {
18403 // moving a complete application; perform an initial scan on the new install location
18404 scanFlags |= SCAN_INITIAL;
18406 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18407 scanFlags |= SCAN_DONT_KILL_APP;
18410 scanFlags |= SCAN_AS_INSTANT_APP;
18413 scanFlags |= SCAN_AS_FULL_APP;
18415 if (virtualPreload) {
18416 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18419 // Result object to be returned
18420 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18421 res.installerPackageName = installerPackageName;
18423 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18426 if (instantApp && (forwardLocked || onExternal)) {
18427 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18428 + " external=" + onExternal);
18429 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18433 // Retrieve PackageSettings and parse package
18434 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18435 | PackageParser.PARSE_ENFORCE_CODE
18436 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18437 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18438 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18439 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18440 PackageParser pp = new PackageParser();
18441 pp.setSeparateProcesses(mSeparateProcesses);
18442 pp.setDisplayMetrics(mMetrics);
18443 pp.setCallback(mPackageParserCallback);
18445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18446 final PackageParser.Package pkg;
18448 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18449 } catch (PackageParserException e) {
18450 res.setError("Failed parse during installPackageLI", e);
18453 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18456 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18457 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18458 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18459 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18460 "Instant app package must target O");
18463 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18464 Slog.w(TAG, "Instant app package " + pkg.packageName
18465 + " does not target targetSandboxVersion 2");
18466 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18467 "Instant app package must use targetSanboxVersion 2");
18471 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18472 // Static shared libraries have synthetic package names
18473 renameStaticSharedLibraryPackage(pkg);
18475 // No static shared libs on external storage
18477 Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18478 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18479 "Packages declaring static-shared libs cannot be updated");
18484 // If we are installing a clustered package add results for the children
18485 if (pkg.childPackages != null) {
18486 synchronized (mPackages) {
18487 final int childCount = pkg.childPackages.size();
18488 for (int i = 0; i < childCount; i++) {
18489 PackageParser.Package childPkg = pkg.childPackages.get(i);
18490 PackageInstalledInfo childRes = new PackageInstalledInfo();
18491 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18492 childRes.pkg = childPkg;
18493 childRes.name = childPkg.packageName;
18494 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18495 if (childPs != null) {
18496 childRes.origUsers = childPs.queryInstalledUsers(
18497 sUserManager.getUserIds(), true);
18499 if ((mPackages.containsKey(childPkg.packageName))) {
18500 childRes.removedInfo = new PackageRemovedInfo(this);
18501 childRes.removedInfo.removedPackage = childPkg.packageName;
18502 childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18504 if (res.addedChildPackages == null) {
18505 res.addedChildPackages = new ArrayMap<>();
18507 res.addedChildPackages.put(childPkg.packageName, childRes);
18512 // If package doesn't declare API override, mark that we have an install
18513 // time CPU ABI override.
18514 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18515 pkg.cpuAbiOverride = args.abiOverride;
18518 String pkgName = res.name = pkg.packageName;
18519 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18520 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18521 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18527 // either use what we've been given or parse directly from the APK
18528 if (args.certificates != null) {
18530 PackageParser.populateCertificates(pkg, args.certificates);
18531 } catch (PackageParserException e) {
18532 // there was something wrong with the certificates we were given;
18533 // try to pull them from the APK
18534 PackageParser.collectCertificates(pkg, parseFlags);
18537 PackageParser.collectCertificates(pkg, parseFlags);
18539 } catch (PackageParserException e) {
18540 res.setError("Failed collect during installPackageLI", e);
18544 // Get rid of all references to package scan path via parser.
18546 String oldCodePath = null;
18547 boolean systemApp = false;
18548 synchronized (mPackages) {
18549 // Check if installing already existing package
18550 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18551 String oldName = mSettings.getRenamedPackageLPr(pkgName);
18552 if (pkg.mOriginalPackages != null
18553 && pkg.mOriginalPackages.contains(oldName)
18554 && mPackages.containsKey(oldName)) {
18555 // This package is derived from an original package,
18556 // and this device has been updating from that original
18557 // name. We must continue using the original name, so
18558 // rename the new package here.
18559 pkg.setPackageName(oldName);
18560 pkgName = pkg.packageName;
18562 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18563 + oldName + " pkgName=" + pkgName);
18564 } else if (mPackages.containsKey(pkgName)) {
18565 // This package, under its official name, already exists
18566 // on the device; we should replace it.
18568 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18571 // Child packages are installed through the parent package
18572 if (pkg.parentPackage != null) {
18573 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18574 "Package " + pkg.packageName + " is child of package "
18575 + pkg.parentPackage.parentPackage + ". Child packages "
18576 + "can be updated only through the parent package.");
18581 // Prevent apps opting out from runtime permissions
18582 PackageParser.Package oldPackage = mPackages.get(pkgName);
18583 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18584 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18585 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18586 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18587 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18588 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18589 + " doesn't support runtime permissions but the old"
18590 + " target SDK " + oldTargetSdk + " does.");
18593 // Prevent apps from downgrading their targetSandbox.
18594 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18595 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18596 if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18597 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18598 "Package " + pkg.packageName + " new target sandbox "
18599 + newTargetSandbox + " is incompatible with the previous value of"
18600 + oldTargetSandbox + ".");
18604 // Prevent installing of child packages
18605 if (oldPackage.parentPackage != null) {
18606 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18607 "Package " + pkg.packageName + " is child of package "
18608 + oldPackage.parentPackage + ". Child packages "
18609 + "can be updated only through the parent package.");
18615 PackageSetting ps = mSettings.mPackages.get(pkgName);
18617 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18619 // Static shared libs have same package with different versions where
18620 // we internally use a synthetic package name to allow multiple versions
18621 // of the same package, therefore we need to compare signatures against
18622 // the package setting for the latest library version.
18623 PackageSetting signatureCheckPs = ps;
18624 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18625 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18626 if (libraryEntry != null) {
18627 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18631 // Quick sanity check that we're signed correctly if updating;
18632 // we'll check this again later when scanning, but we want to
18633 // bail early here before tripping over redefined permissions.
18634 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18635 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18636 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18637 + pkg.packageName + " upgrade keys do not match the "
18638 + "previously installed version");
18643 verifySignaturesLP(signatureCheckPs, pkg);
18644 } catch (PackageManagerException e) {
18645 res.setError(e.error, e.getMessage());
18650 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18651 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18652 systemApp = (ps.pkg.applicationInfo.flags &
18653 ApplicationInfo.FLAG_SYSTEM) != 0;
18655 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18658 int N = pkg.permissions.size();
18659 for (int i = N-1; i >= 0; i--) {
18660 PackageParser.Permission perm = pkg.permissions.get(i);
18661 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18663 // Don't allow anyone but the system to define ephemeral permissions.
18664 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18666 Slog.w(TAG, "Non-System package " + pkg.packageName
18667 + " attempting to delcare ephemeral permission "
18668 + perm.info.name + "; Removing ephemeral.");
18669 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18671 // Check whether the newly-scanned package wants to define an already-defined perm
18673 // If the defining package is signed with our cert, it's okay. This
18674 // also includes the "updating the same package" case, of course.
18675 // "updating same package" could also involve key-rotation.
18676 final boolean sigsOk;
18677 if (bp.sourcePackage.equals(pkg.packageName)
18678 && (bp.packageSetting instanceof PackageSetting)
18679 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18681 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18683 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18684 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18687 // If the owning package is the system itself, we log but allow
18688 // install to proceed; we fail the install on all other permission
18690 if (!bp.sourcePackage.equals("android")) {
18691 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18692 + pkg.packageName + " attempting to redeclare permission "
18693 + perm.info.name + " already owned by " + bp.sourcePackage);
18694 res.origPermission = perm.info.name;
18695 res.origPackage = bp.sourcePackage;
18698 Slog.w(TAG, "Package " + pkg.packageName
18699 + " attempting to redeclare system permission "
18700 + perm.info.name + "; ignoring new declaration");
18701 pkg.permissions.remove(i);
18703 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18704 // Prevent apps to change protection level to dangerous from any other
18705 // type as this would allow a privilege escalation where an app adds a
18706 // normal/signature permission in other app's group and later redefines
18707 // it as dangerous leading to the group auto-grant.
18708 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18709 == PermissionInfo.PROTECTION_DANGEROUS) {
18710 if (bp != null && !bp.isRuntime()) {
18711 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18712 + "non-runtime permission " + perm.info.name
18713 + " to runtime; keeping old protection level");
18714 perm.info.protectionLevel = bp.protectionLevel;
18724 // Abort update; system app can't be replaced with app on sdcard
18725 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18726 "Cannot install updates to system apps on sdcard");
18728 } else if (instantApp) {
18729 // Abort update; system app can't be replaced with an instant app
18730 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18731 "Cannot update a system app with an instant app");
18736 if (args.move != null) {
18737 // We did an in-place move, so dex is ready to roll
18738 scanFlags |= SCAN_NO_DEX;
18739 scanFlags |= SCAN_MOVE;
18741 synchronized (mPackages) {
18742 final PackageSetting ps = mSettings.mPackages.get(pkgName);
18744 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18745 "Missing settings for moved package " + pkgName);
18748 // We moved the entire application as-is, so bring over the
18749 // previously derived ABI information.
18750 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18751 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18754 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18755 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18756 scanFlags |= SCAN_NO_DEX;
18759 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18760 args.abiOverride : pkg.cpuAbiOverride);
18761 final boolean extractNativeLibs = !pkg.isLibrary();
18762 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18763 extractNativeLibs, mAppLib32InstallDir);
18764 } catch (PackageManagerException pme) {
18765 Slog.e(TAG, "Error deriving application ABI", pme);
18766 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18770 // Shared libraries for the package need to be updated.
18771 synchronized (mPackages) {
18773 updateSharedLibrariesLPr(pkg, null);
18774 } catch (PackageManagerException e) {
18775 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18780 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18781 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18785 // Verify if we need to dexopt the app.
18787 // NOTE: it is *important* to call dexopt after doRename which will sync the
18788 // package data from PackageParser.Package and its corresponding ApplicationInfo.
18790 // We only need to dexopt if the package meets ALL of the following conditions:
18791 // 1) it is not forward locked.
18792 // 2) it is not on on an external ASEC container.
18793 // 3) it is not an instant app or if it is then dexopt is enabled via gservices.
18795 // Note that we do not dexopt instant apps by default. dexopt can take some time to
18796 // complete, so we skip this step during installation. Instead, we'll take extra time
18797 // the first time the instant app starts. It's preferred to do it this way to provide
18798 // continuous progress to the useur instead of mysteriously blocking somewhere in the
18799 // middle of running an instant app. The default behaviour can be overridden
18801 final boolean performDexopt = !forwardLocked
18802 && !pkg.applicationInfo.isExternalAsec()
18803 && (!instantApp || Global.getInt(mContext.getContentResolver(),
18804 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18806 if (performDexopt) {
18807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18808 // Do not run PackageDexOptimizer through the local performDexOpt
18809 // method because `pkg` may not be in `mPackages` yet.
18811 // Also, don't fail application installs if the dexopt step fails.
18812 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18814 DexoptOptions.DEXOPT_BOOT_COMPLETE);
18815 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18816 null /* instructionSets */,
18817 getOrCreateCompilerPackageStats(pkg),
18818 mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18820 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18823 // Notify BackgroundDexOptService that the package has been changed.
18824 // If this is an update of a package which used to fail to compile,
18825 // BackgroundDexOptService will remove it from its blacklist.
18826 // TODO: Layering violation
18827 BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18829 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18831 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18832 "installPackageLI")) {
18834 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18835 // Static libs have a synthetic package name containing the version
18836 // and cannot be updated as an update would get a new package name,
18837 // unless this is the exact same version code which is useful for
18839 PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18840 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18841 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18842 + "static-shared libs cannot be updated");
18846 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18847 installerPackageName, res, args.installReason);
18849 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18850 args.user, installerPackageName, volumeUuid, res, args.installReason);
18854 synchronized (mPackages) {
18855 final PackageSetting ps = mSettings.mPackages.get(pkgName);
18857 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18858 ps.setUpdateAvailable(false /*updateAvailable*/);
18861 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18862 for (int i = 0; i < childCount; i++) {
18863 PackageParser.Package childPkg = pkg.childPackages.get(i);
18864 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18865 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18866 if (childPs != null) {
18867 childRes.newUsers = childPs.queryInstalledUsers(
18868 sUserManager.getUserIds(), true);
18872 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18873 updateSequenceNumberLP(ps, res.newUsers);
18874 updateInstantAppInstallerLocked(pkgName);
18879 private void startIntentFilterVerifications(int userId, boolean replacing,
18880 PackageParser.Package pkg) {
18881 if (mIntentFilterVerifierComponent == null) {
18882 Slog.w(TAG, "No IntentFilter verification will not be done as "
18883 + "there is no IntentFilterVerifier available!");
18887 final int verifierUid = getPackageUid(
18888 mIntentFilterVerifierComponent.getPackageName(),
18889 MATCH_DEBUG_TRIAGED_MISSING,
18890 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18892 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18893 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18894 mHandler.sendMessage(msg);
18896 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18897 for (int i = 0; i < childCount; i++) {
18898 PackageParser.Package childPkg = pkg.childPackages.get(i);
18899 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18900 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18901 mHandler.sendMessage(msg);
18905 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18906 PackageParser.Package pkg) {
18907 int size = pkg.activities.size();
18909 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18910 "No activity, so no need to verify any IntentFilter!");
18914 final boolean hasDomainURLs = hasDomainURLs(pkg);
18915 if (!hasDomainURLs) {
18916 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18917 "No domain URLs, so no need to verify any IntentFilter!");
18921 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18922 + " if any IntentFilter from the " + size
18923 + " Activities needs verification ...");
18926 final String packageName = pkg.packageName;
18928 synchronized (mPackages) {
18929 // If this is a new install and we see that we've already run verification for this
18930 // package, we have nothing to do: it means the state was restored from backup.
18932 IntentFilterVerificationInfo ivi =
18933 mSettings.getIntentFilterVerificationLPr(packageName);
18935 if (DEBUG_DOMAIN_VERIFICATION) {
18936 Slog.i(TAG, "Package " + packageName+ " already verified: status="
18937 + ivi.getStatusString());
18943 // If any filters need to be verified, then all need to be.
18944 boolean needToVerify = false;
18945 for (PackageParser.Activity a : pkg.activities) {
18946 for (ActivityIntentInfo filter : a.intents) {
18947 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18948 if (DEBUG_DOMAIN_VERIFICATION) {
18949 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18951 needToVerify = true;
18957 if (needToVerify) {
18958 final int verificationId = mIntentFilterVerificationToken++;
18959 for (PackageParser.Activity a : pkg.activities) {
18960 for (ActivityIntentInfo filter : a.intents) {
18961 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18962 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18963 "Verification needed for IntentFilter:" + filter.toString());
18964 mIntentFilterVerifier.addOneIntentFilterVerification(
18965 verifierUid, userId, verificationId, filter, packageName);
18974 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18975 + " IntentFilter verification" + (count > 1 ? "s" : "")
18976 + " for userId:" + userId);
18977 mIntentFilterVerifier.startVerifications(userId);
18979 if (DEBUG_DOMAIN_VERIFICATION) {
18980 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18985 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18986 final ComponentName cn = filter.activity.getComponentName();
18987 final String packageName = cn.getPackageName();
18989 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18994 int status = ivi.getStatus();
18996 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18997 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19006 private static boolean isMultiArch(ApplicationInfo info) {
19007 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19010 private static boolean isExternal(PackageParser.Package pkg) {
19011 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19014 private static boolean isExternal(PackageSetting ps) {
19015 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19018 private static boolean isSystemApp(PackageParser.Package pkg) {
19019 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19022 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19023 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19026 private static boolean hasDomainURLs(PackageParser.Package pkg) {
19027 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19030 private static boolean isSystemApp(PackageSetting ps) {
19031 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19034 private static boolean isUpdatedSystemApp(PackageSetting ps) {
19035 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19038 private int packageFlagsToInstallFlags(PackageSetting ps) {
19039 int installFlags = 0;
19040 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19041 // This existing package was an external ASEC install when we have
19042 // the external flag without a UUID
19043 installFlags |= PackageManager.INSTALL_EXTERNAL;
19045 if (ps.isForwardLocked()) {
19046 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19048 return installFlags;
19051 private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19052 if (isExternal(pkg)) {
19053 if (TextUtils.isEmpty(pkg.volumeUuid)) {
19054 return StorageManager.UUID_PRIMARY_PHYSICAL;
19056 return pkg.volumeUuid;
19059 return StorageManager.UUID_PRIVATE_INTERNAL;
19063 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19064 if (isExternal(pkg)) {
19065 if (TextUtils.isEmpty(pkg.volumeUuid)) {
19066 return mSettings.getExternalVersion();
19068 return mSettings.findOrCreateVersion(pkg.volumeUuid);
19071 return mSettings.getInternalVersion();
19075 private void deleteTempPackageFiles() {
19076 final FilenameFilter filter = new FilenameFilter() {
19077 public boolean accept(File dir, String name) {
19078 return name.startsWith("vmdl") && name.endsWith(".tmp");
19081 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19087 public void deletePackageAsUser(String packageName, int versionCode,
19088 IPackageDeleteObserver observer, int userId, int flags) {
19089 deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19090 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19094 public void deletePackageVersioned(VersionedPackage versionedPackage,
19095 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19096 final int callingUid = Binder.getCallingUid();
19097 mContext.enforceCallingOrSelfPermission(
19098 android.Manifest.permission.DELETE_PACKAGES, null);
19099 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19100 Preconditions.checkNotNull(versionedPackage);
19101 Preconditions.checkNotNull(observer);
19102 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19103 PackageManager.VERSION_CODE_HIGHEST,
19104 Integer.MAX_VALUE, "versionCode must be >= -1");
19106 final String packageName = versionedPackage.getPackageName();
19107 final int versionCode = versionedPackage.getVersionCode();
19108 final String internalPackageName;
19109 synchronized (mPackages) {
19110 // Normalize package name to handle renamed packages and static libs
19111 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19112 versionedPackage.getVersionCode());
19115 final int uid = Binder.getCallingUid();
19116 if (!isOrphaned(internalPackageName)
19117 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19119 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19120 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19121 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19122 observer.onUserActionRequired(intent);
19123 } catch (RemoteException re) {
19127 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19128 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19129 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19130 mContext.enforceCallingOrSelfPermission(
19131 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19132 "deletePackage for user " + userId);
19135 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19137 observer.onPackageDeleted(packageName,
19138 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19139 } catch (RemoteException re) {
19144 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19146 observer.onPackageDeleted(packageName,
19147 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19148 } catch (RemoteException re) {
19153 if (DEBUG_REMOVE) {
19154 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19155 + " deleteAllUsers: " + deleteAllUsers + " version="
19156 + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19157 ? "VERSION_CODE_HIGHEST" : versionCode));
19159 // Queue up an async operation since the package deletion may take a little while.
19160 mHandler.post(new Runnable() {
19161 public void run() {
19162 mHandler.removeCallbacks(this);
19164 final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19165 boolean doDeletePackage = true;
19167 final boolean targetIsInstantApp =
19168 ps.getInstantApp(UserHandle.getUserId(callingUid));
19169 doDeletePackage = !targetIsInstantApp
19170 || canViewInstantApps;
19172 if (doDeletePackage) {
19173 if (!deleteAllUsers) {
19174 returnCode = deletePackageX(internalPackageName, versionCode,
19175 userId, deleteFlags);
19177 int[] blockUninstallUserIds = getBlockUninstallForUsers(
19178 internalPackageName, users);
19179 // If nobody is blocking uninstall, proceed with delete for all users
19180 if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19181 returnCode = deletePackageX(internalPackageName, versionCode,
19182 userId, deleteFlags);
19184 // Otherwise uninstall individually for users with blockUninstalls=false
19185 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19186 for (int userId : users) {
19187 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19188 returnCode = deletePackageX(internalPackageName, versionCode,
19189 userId, userFlags);
19190 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19191 Slog.w(TAG, "Package delete failed for user " + userId
19192 + ", returnCode " + returnCode);
19196 // The app has only been marked uninstalled for certain users.
19197 // We still need to report that delete was blocked
19198 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19202 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19205 observer.onPackageDeleted(packageName, returnCode, null);
19206 } catch (RemoteException e) {
19207 Log.i(TAG, "Observer no longer exists.");
19213 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19214 if (pkg.staticSharedLibName != null) {
19215 return pkg.manifestPackageName;
19217 return pkg.packageName;
19220 private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19221 // Handle renamed packages
19222 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19223 packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19225 // Is this a static library?
19226 SparseArray<SharedLibraryEntry> versionedLib =
19227 mStaticLibsByDeclaringPackage.get(packageName);
19228 if (versionedLib == null || versionedLib.size() <= 0) {
19229 return packageName;
19232 // Figure out which lib versions the caller can see
19233 SparseIntArray versionsCallerCanSee = null;
19234 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19235 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19236 && callingAppId != Process.ROOT_UID) {
19237 versionsCallerCanSee = new SparseIntArray();
19238 String libName = versionedLib.valueAt(0).info.getName();
19239 String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19240 if (uidPackages != null) {
19241 for (String uidPackage : uidPackages) {
19242 PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19243 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19245 final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19246 versionsCallerCanSee.append(libVersion, libVersion);
19252 // Caller can see nothing - done
19253 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19254 return packageName;
19257 // Find the version the caller can see and the app version code
19258 SharedLibraryEntry highestVersion = null;
19259 final int versionCount = versionedLib.size();
19260 for (int i = 0; i < versionCount; i++) {
19261 SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19262 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19263 libEntry.info.getVersion()) < 0) {
19266 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19267 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19268 if (libVersionCode == versionCode) {
19269 return libEntry.apk;
19271 } else if (highestVersion == null) {
19272 highestVersion = libEntry;
19273 } else if (libVersionCode > highestVersion.info
19274 .getDeclaringPackage().getVersionCode()) {
19275 highestVersion = libEntry;
19279 if (highestVersion != null) {
19280 return highestVersion.apk;
19283 return packageName;
19286 boolean isCallerVerifier(int callingUid) {
19287 final int callingUserId = UserHandle.getUserId(callingUid);
19288 return mRequiredVerifierPackage != null &&
19289 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19292 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19293 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19294 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19297 final int callingUserId = UserHandle.getUserId(callingUid);
19298 // If the caller installed the pkgName, then allow it to silently uninstall.
19299 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19303 // Allow package verifier to silently uninstall.
19304 if (mRequiredVerifierPackage != null &&
19305 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19309 // Allow package uninstaller to silently uninstall.
19310 if (mRequiredUninstallerPackage != null &&
19311 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19315 // Allow storage manager to silently uninstall.
19316 if (mStorageManagerPackage != null &&
19317 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19321 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19322 // uninstall for device owner provisioning.
19323 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19324 == PERMISSION_GRANTED) {
19331 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19332 int[] result = EMPTY_INT_ARRAY;
19333 for (int userId : userIds) {
19334 if (getBlockUninstallForUser(packageName, userId)) {
19335 result = ArrayUtils.appendInt(result, userId);
19342 public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19343 final int callingUid = Binder.getCallingUid();
19344 if (getInstantAppPackageName(callingUid) != null
19345 && !isCallerSameApp(packageName, callingUid)) {
19348 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19351 private boolean isPackageDeviceAdmin(String packageName, int userId) {
19352 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19353 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19356 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19357 /* callingUserOnly =*/ false);
19358 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19359 : deviceOwnerComponentName.getPackageName();
19360 // Does the package contains the device owner?
19361 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise,
19362 // this check is probably not needed, since DO should be registered as a device
19363 // admin on some user too. (Original bug for this: b/17657954)
19364 if (packageName.equals(deviceOwnerPackageName)) {
19367 // Does it contain a device admin for any user?
19369 if (userId == UserHandle.USER_ALL) {
19370 users = sUserManager.getUserIds();
19372 users = new int[]{userId};
19374 for (int i = 0; i < users.length; ++i) {
19375 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19380 } catch (RemoteException e) {
19385 private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19386 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19390 * This method is an internal method that could be get invoked either
19391 * to delete an installed package or to clean up a failed installation.
19392 * After deleting an installed package, a broadcast is sent to notify any
19393 * listeners that the package has been removed. For cleaning up a failed
19394 * installation, the broadcast is not necessary since the package's
19395 * installation wouldn't have sent the initial broadcast either
19396 * The key steps in deleting a package are
19397 * deleting the package information in internal structures like mPackages,
19398 * deleting the packages base directories through installd
19399 * updating mSettings to reflect current status
19400 * persisting settings for later use
19401 * sending a broadcast if necessary
19403 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19404 final PackageRemovedInfo info = new PackageRemovedInfo(this);
19407 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19408 ? UserHandle.USER_ALL : userId;
19410 if (isPackageDeviceAdmin(packageName, removeUser)) {
19411 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19412 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19415 PackageSetting uninstalledPs = null;
19416 PackageParser.Package pkg = null;
19418 // for the uninstall-updates case and restricted profiles, remember the per-
19419 // user handle installed state
19421 synchronized (mPackages) {
19422 uninstalledPs = mSettings.mPackages.get(packageName);
19423 if (uninstalledPs == null) {
19424 Slog.w(TAG, "Not removing non-existent package " + packageName);
19425 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19428 if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19429 && uninstalledPs.versionCode != versionCode) {
19430 Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19431 + uninstalledPs.versionCode + " != " + versionCode);
19432 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19435 // Static shared libs can be declared by any package, so let us not
19436 // allow removing a package if it provides a lib others depend on.
19437 pkg = mPackages.get(packageName);
19439 allUsers = sUserManager.getUserIds();
19441 if (pkg != null && pkg.staticSharedLibName != null) {
19442 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19443 pkg.staticSharedLibVersion);
19444 if (libEntry != null) {
19445 for (int currUserId : allUsers) {
19446 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19449 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19450 libEntry.info, 0, currUserId);
19451 if (!ArrayUtils.isEmpty(libClientPackages)) {
19452 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19453 + " hosting lib " + libEntry.info.getName() + " version "
19454 + libEntry.info.getVersion() + " used by " + libClientPackages
19455 + " for user " + currUserId);
19456 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19462 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19465 final int freezeUser;
19466 if (isUpdatedSystemApp(uninstalledPs)
19467 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19468 // We're downgrading a system app, which will apply to all users, so
19469 // freeze them all during the downgrade
19470 freezeUser = UserHandle.USER_ALL;
19472 freezeUser = removeUser;
19475 synchronized (mInstallLock) {
19476 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19477 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19478 deleteFlags, "deletePackageX")) {
19479 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19480 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19482 synchronized (mPackages) {
19485 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19487 updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19488 updateInstantAppInstallerLocked(packageName);
19494 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19495 info.sendPackageRemovedBroadcasts(killApp);
19496 info.sendSystemPackageUpdatedBroadcasts();
19497 info.sendSystemPackageAppearedBroadcasts();
19499 // Force a gc here.
19500 Runtime.getRuntime().gc();
19501 // Delete the resources here after sending the broadcast to let
19502 // other processes clean up before deleting resources.
19503 if (info.args != null) {
19504 synchronized (mInstallLock) {
19505 info.args.doPostDeleteLI(true);
19509 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19512 static class PackageRemovedInfo {
19513 final PackageSender packageSender;
19514 String removedPackage;
19515 String installerPackageName;
19517 int removedAppId = -1;
19519 int[] removedUsers = null;
19520 int[] broadcastUsers = null;
19521 SparseArray<Integer> installReasons;
19522 boolean isRemovedPackageSystemUpdate = false;
19524 boolean dataRemoved;
19525 boolean removedForAllUsers;
19526 boolean isStaticSharedLib;
19527 // Clean up resources deleted packages.
19528 InstallArgs args = null;
19529 ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19530 ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19532 PackageRemovedInfo(PackageSender packageSender) {
19533 this.packageSender = packageSender;
19536 void sendPackageRemovedBroadcasts(boolean killApp) {
19537 sendPackageRemovedBroadcastInternal(killApp);
19538 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19539 for (int i = 0; i < childCount; i++) {
19540 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19541 childInfo.sendPackageRemovedBroadcastInternal(killApp);
19545 void sendSystemPackageUpdatedBroadcasts() {
19546 if (isRemovedPackageSystemUpdate) {
19547 sendSystemPackageUpdatedBroadcastsInternal();
19548 final int childCount = (removedChildPackages != null)
19549 ? removedChildPackages.size() : 0;
19550 for (int i = 0; i < childCount; i++) {
19551 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19552 if (childInfo.isRemovedPackageSystemUpdate) {
19553 childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19559 void sendSystemPackageAppearedBroadcasts() {
19560 final int packageCount = (appearedChildPackages != null)
19561 ? appearedChildPackages.size() : 0;
19562 for (int i = 0; i < packageCount; i++) {
19563 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19564 packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19565 true /*sendBootCompleted*/, false /*startReceiver*/,
19566 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19570 private void sendSystemPackageUpdatedBroadcastsInternal() {
19571 Bundle extras = new Bundle(2);
19572 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19573 extras.putBoolean(Intent.EXTRA_REPLACING, true);
19574 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19575 removedPackage, extras, 0, null /*targetPackage*/, null, null);
19576 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19577 removedPackage, extras, 0, null /*targetPackage*/, null, null);
19578 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19579 null, null, 0, removedPackage, null, null);
19580 if (installerPackageName != null) {
19581 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19582 removedPackage, extras, 0 /*flags*/,
19583 installerPackageName, null, null);
19584 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19585 removedPackage, extras, 0 /*flags*/,
19586 installerPackageName, null, null);
19590 private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19591 // Don't send static shared library removal broadcasts as these
19592 // libs are visible only the the apps that depend on them an one
19593 // cannot remove the library if it has a dependency.
19594 if (isStaticSharedLib) {
19597 Bundle extras = new Bundle(2);
19598 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19599 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19600 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19601 if (isUpdate || isRemovedPackageSystemUpdate) {
19602 extras.putBoolean(Intent.EXTRA_REPLACING, true);
19604 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19605 if (removedPackage != null) {
19606 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19607 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19608 if (installerPackageName != null) {
19609 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19610 removedPackage, extras, 0 /*flags*/,
19611 installerPackageName, null, broadcastUsers);
19613 if (dataRemoved && !isRemovedPackageSystemUpdate) {
19614 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19615 removedPackage, extras,
19616 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19617 null, null, broadcastUsers);
19620 if (removedAppId >= 0) {
19621 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19622 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19623 null, null, broadcastUsers);
19627 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19628 removedUsers = userIds;
19629 if (removedUsers == null) {
19630 broadcastUsers = null;
19634 broadcastUsers = EMPTY_INT_ARRAY;
19635 for (int i = userIds.length - 1; i >= 0; --i) {
19636 final int userId = userIds[i];
19637 if (deletedPackageSetting.getInstantApp(userId)) {
19640 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19646 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19647 * flag is not set, the data directory is removed as well.
19648 * make sure this flag is set for partially installed apps. If not its meaningless to
19649 * delete a partially installed application.
19651 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19652 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19653 String packageName = ps.name;
19654 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19655 // Retrieve object to delete permissions for shared user later on
19656 final PackageParser.Package deletedPkg;
19657 final PackageSetting deletedPs;
19659 synchronized (mPackages) {
19660 deletedPkg = mPackages.get(packageName);
19661 deletedPs = mSettings.mPackages.get(packageName);
19662 if (outInfo != null) {
19663 outInfo.removedPackage = packageName;
19664 outInfo.installerPackageName = ps.installerPackageName;
19665 outInfo.isStaticSharedLib = deletedPkg != null
19666 && deletedPkg.staticSharedLibName != null;
19667 outInfo.populateUsers(deletedPs == null ? null
19668 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19672 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19674 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19675 final PackageParser.Package resolvedPkg;
19676 if (deletedPkg != null) {
19677 resolvedPkg = deletedPkg;
19679 // We don't have a parsed package when it lives on an ejected
19680 // adopted storage device, so fake something together
19681 resolvedPkg = new PackageParser.Package(ps.name);
19682 resolvedPkg.setVolumeUuid(ps.volumeUuid);
19684 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19685 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19686 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19687 if (outInfo != null) {
19688 outInfo.dataRemoved = true;
19690 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19693 int removedAppId = -1;
19696 synchronized (mPackages) {
19697 boolean installedStateChanged = false;
19698 if (deletedPs != null) {
19699 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19700 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19701 clearDefaultBrowserIfNeeded(packageName);
19702 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19703 removedAppId = mSettings.removePackageLPw(packageName);
19704 if (outInfo != null) {
19705 outInfo.removedAppId = removedAppId;
19707 updatePermissionsLPw(deletedPs.name, null, 0);
19708 if (deletedPs.sharedUser != null) {
19709 // Remove permissions associated with package. Since runtime
19710 // permissions are per user we have to kill the removed package
19711 // or packages running under the shared user of the removed
19712 // package if revoking the permissions requested only by the removed
19713 // package is successful and this causes a change in gids.
19714 for (int userId : UserManagerService.getInstance().getUserIds()) {
19715 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19717 if (userIdToKill == UserHandle.USER_ALL
19718 || userIdToKill >= UserHandle.USER_SYSTEM) {
19719 // If gids changed for this user, kill all affected packages.
19720 mHandler.post(new Runnable() {
19722 public void run() {
19723 // This has to happen with no lock held.
19724 killApplication(deletedPs.name, deletedPs.appId,
19725 KILL_APP_REASON_GIDS_CHANGED);
19732 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19734 // make sure to preserve per-user disabled state if this removal was just
19735 // a downgrade of a system app to the factory package
19736 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19737 if (DEBUG_REMOVE) {
19738 Slog.d(TAG, "Propagating install state across downgrade");
19740 for (int userId : allUserHandles) {
19741 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19742 if (DEBUG_REMOVE) {
19743 Slog.d(TAG, " user " + userId + " => " + installed);
19745 if (installed != ps.getInstalled(userId)) {
19746 installedStateChanged = true;
19748 ps.setInstalled(installed, userId);
19752 // can downgrade to reader
19753 if (writeSettings) {
19754 // Save settings now
19755 mSettings.writeLPr();
19757 if (installedStateChanged) {
19758 mSettings.writeKernelMappingLPr(ps);
19761 if (removedAppId != -1) {
19762 // A user ID was deleted here. Go through all users and remove it
19764 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19768 static boolean locationIsPrivileged(File path) {
19770 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19771 .getCanonicalPath();
19772 return path.getCanonicalPath().startsWith(privilegedAppDir);
19773 } catch (IOException e) {
19774 Slog.e(TAG, "Unable to access code path " + path);
19780 * Tries to delete system package.
19782 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19783 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19784 boolean writeSettings) {
19785 if (deletedPs.parentPackageName != null) {
19786 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19790 final boolean applyUserRestrictions
19791 = (allUserHandles != null) && (outInfo.origUsers != null);
19792 final PackageSetting disabledPs;
19793 // Confirm if the system package has been updated
19794 // An updated system app can be deleted. This will also have to restore
19795 // the system pkg from system partition
19797 synchronized (mPackages) {
19798 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19801 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19802 + " disabledPs=" + disabledPs);
19804 if (disabledPs == null) {
19805 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19807 } else if (DEBUG_REMOVE) {
19808 Slog.d(TAG, "Deleting system pkg from data partition");
19811 if (DEBUG_REMOVE) {
19812 if (applyUserRestrictions) {
19813 Slog.d(TAG, "Remembering install states:");
19814 for (int userId : allUserHandles) {
19815 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19816 Slog.d(TAG, " u=" + userId + " inst=" + finstalled);
19821 // Delete the updated package
19822 outInfo.isRemovedPackageSystemUpdate = true;
19823 if (outInfo.removedChildPackages != null) {
19824 final int childCount = (deletedPs.childPackageNames != null)
19825 ? deletedPs.childPackageNames.size() : 0;
19826 for (int i = 0; i < childCount; i++) {
19827 String childPackageName = deletedPs.childPackageNames.get(i);
19828 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19829 .contains(childPackageName)) {
19830 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19832 if (childInfo != null) {
19833 childInfo.isRemovedPackageSystemUpdate = true;
19839 if (disabledPs.versionCode < deletedPs.versionCode) {
19840 // Delete data for downgrades
19841 flags &= ~PackageManager.DELETE_KEEP_DATA;
19843 // Preserve data by setting flag
19844 flags |= PackageManager.DELETE_KEEP_DATA;
19847 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19848 outInfo, writeSettings, disabledPs.pkg);
19854 synchronized (mPackages) {
19855 // NOTE: The system package always needs to be enabled; even if it's for
19856 // a compressed stub. If we don't, installing the system package fails
19857 // during scan [scanning checks the disabled packages]. We will reverse
19858 // this later, after we've "installed" the stub.
19859 // Reinstate the old system package
19860 enableSystemPackageLPw(disabledPs.pkg);
19861 // Remove any native libraries from the upgraded package.
19862 removeNativeBinariesLI(deletedPs);
19865 // Install the system package
19866 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19868 installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19869 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19870 } catch (PackageManagerException e) {
19871 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19875 if (disabledPs.pkg.isStub) {
19876 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19883 * Installs a package that's already on the system partition.
19885 private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19886 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19887 @Nullable PermissionsState origPermissionState, boolean writeSettings)
19888 throws PackageManagerException {
19889 int parseFlags = mDefParseFlags
19890 | PackageParser.PARSE_MUST_BE_APK
19891 | PackageParser.PARSE_IS_SYSTEM
19892 | PackageParser.PARSE_IS_SYSTEM_DIR;
19893 if (isPrivileged || locationIsPrivileged(codePath)) {
19894 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19897 final PackageParser.Package newPkg =
19898 scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19901 // update shared libraries for the newly re-installed system package
19902 updateSharedLibrariesLPr(newPkg, null);
19903 } catch (PackageManagerException e) {
19904 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19907 prepareAppDataAfterInstallLIF(newPkg);
19910 synchronized (mPackages) {
19911 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19913 // Propagate the permissions state as we do not want to drop on the floor
19914 // runtime permissions. The update permissions method below will take
19915 // care of removing obsolete permissions and grant install permissions.
19916 if (origPermissionState != null) {
19917 ps.getPermissionsState().copyFrom(origPermissionState);
19919 updatePermissionsLPw(newPkg.packageName, newPkg,
19920 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19922 final boolean applyUserRestrictions
19923 = (allUserHandles != null) && (origUserHandles != null);
19924 if (applyUserRestrictions) {
19925 boolean installedStateChanged = false;
19926 if (DEBUG_REMOVE) {
19927 Slog.d(TAG, "Propagating install state across reinstall");
19929 for (int userId : allUserHandles) {
19930 final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19931 if (DEBUG_REMOVE) {
19932 Slog.d(TAG, " user " + userId + " => " + installed);
19934 if (installed != ps.getInstalled(userId)) {
19935 installedStateChanged = true;
19937 ps.setInstalled(installed, userId);
19939 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19941 // Regardless of writeSettings we need to ensure that this restriction
19942 // state propagation is persisted
19943 mSettings.writeAllUsersPackageRestrictionsLPr();
19944 if (installedStateChanged) {
19945 mSettings.writeKernelMappingLPr(ps);
19948 // can downgrade to reader here
19949 if (writeSettings) {
19950 mSettings.writeLPr();
19956 private boolean deleteInstalledPackageLIF(PackageSetting ps,
19957 boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19958 PackageRemovedInfo outInfo, boolean writeSettings,
19959 PackageParser.Package replacingPackage) {
19960 synchronized (mPackages) {
19961 if (outInfo != null) {
19962 outInfo.uid = ps.appId;
19965 if (outInfo != null && outInfo.removedChildPackages != null) {
19966 final int childCount = (ps.childPackageNames != null)
19967 ? ps.childPackageNames.size() : 0;
19968 for (int i = 0; i < childCount; i++) {
19969 String childPackageName = ps.childPackageNames.get(i);
19970 PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19971 if (childPs == null) {
19974 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19976 if (childInfo != null) {
19977 childInfo.uid = childPs.appId;
19983 // Delete package data from internal structures and also remove data if flag is set
19984 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19986 // Delete the child packages data
19987 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19988 for (int i = 0; i < childCount; i++) {
19989 PackageSetting childPs;
19990 synchronized (mPackages) {
19991 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19993 if (childPs != null) {
19994 PackageRemovedInfo childOutInfo = (outInfo != null
19995 && outInfo.removedChildPackages != null)
19996 ? outInfo.removedChildPackages.get(childPs.name) : null;
19997 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19998 && (replacingPackage != null
19999 && !replacingPackage.hasChildPackage(childPs.name))
20000 ? flags & ~DELETE_KEEP_DATA : flags;
20001 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20002 deleteFlags, writeSettings);
20006 // Delete application code and resources only for parent packages
20007 if (ps.parentPackageName == null) {
20008 if (deleteCodeAndResources && (outInfo != null)) {
20009 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20010 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20011 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20019 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20021 mContext.enforceCallingOrSelfPermission(
20022 android.Manifest.permission.DELETE_PACKAGES, null);
20023 synchronized (mPackages) {
20024 // Cannot block uninstall of static shared libs as they are
20025 // considered a part of the using app (emulating static linking).
20026 // Also static libs are installed always on internal storage.
20027 PackageParser.Package pkg = mPackages.get(packageName);
20028 if (pkg != null && pkg.staticSharedLibName != null) {
20029 Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20030 + " providing static shared library: " + pkg.staticSharedLibName);
20033 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20034 mSettings.writePackageRestrictionsLPr(userId);
20040 public boolean getBlockUninstallForUser(String packageName, int userId) {
20041 synchronized (mPackages) {
20042 final PackageSetting ps = mSettings.mPackages.get(packageName);
20043 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20046 return mSettings.getBlockUninstallLPr(userId, packageName);
20051 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20052 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20053 synchronized (mPackages) {
20054 PackageSetting ps = mSettings.mPackages.get(packageName);
20056 Log.w(TAG, "Package doesn't exist: " + packageName);
20059 if (systemUserApp) {
20060 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20062 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20064 mSettings.writeLPr();
20070 * This method handles package deletion in general
20072 private boolean deletePackageLIF(String packageName, UserHandle user,
20073 boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20074 PackageRemovedInfo outInfo, boolean writeSettings,
20075 PackageParser.Package replacingPackage) {
20076 if (packageName == null) {
20077 Slog.w(TAG, "Attempt to delete null packageName.");
20081 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20084 synchronized (mPackages) {
20085 ps = mSettings.mPackages.get(packageName);
20087 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20091 if (ps.parentPackageName != null && (!isSystemApp(ps)
20092 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20093 if (DEBUG_REMOVE) {
20094 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20095 + ((user == null) ? UserHandle.USER_ALL : user));
20097 final int removedUserId = (user != null) ? user.getIdentifier()
20098 : UserHandle.USER_ALL;
20099 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20102 markPackageUninstalledForUserLPw(ps, user);
20103 scheduleWritePackageRestrictionsLocked(user);
20108 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20109 && user.getIdentifier() != UserHandle.USER_ALL)) {
20110 // The caller is asking that the package only be deleted for a single
20111 // user. To do this, we just mark its uninstalled state and delete
20112 // its data. If this is a system app, we only allow this to happen if
20113 // they have set the special DELETE_SYSTEM_APP which requests different
20114 // semantics than normal for uninstalling system apps.
20115 markPackageUninstalledForUserLPw(ps, user);
20117 if (!isSystemApp(ps)) {
20118 // Do not uninstall the APK if an app should be cached
20119 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20120 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20121 // Other user still have this package installed, so all
20122 // we need to do is clear this user's data and save that
20123 // it is uninstalled.
20124 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20125 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20128 scheduleWritePackageRestrictionsLocked(user);
20131 // We need to set it back to 'installed' so the uninstall
20132 // broadcasts will be sent correctly.
20133 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20134 ps.setInstalled(true, user.getIdentifier());
20135 mSettings.writeKernelMappingLPr(ps);
20138 // This is a system app, so we assume that the
20139 // other users still have this package installed, so all
20140 // we need to do is clear this user's data and save that
20141 // it is uninstalled.
20142 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20143 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20146 scheduleWritePackageRestrictionsLocked(user);
20151 // If we are deleting a composite package for all users, keep track
20152 // of result for each child.
20153 if (ps.childPackageNames != null && outInfo != null) {
20154 synchronized (mPackages) {
20155 final int childCount = ps.childPackageNames.size();
20156 outInfo.removedChildPackages = new ArrayMap<>(childCount);
20157 for (int i = 0; i < childCount; i++) {
20158 String childPackageName = ps.childPackageNames.get(i);
20159 PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20160 childInfo.removedPackage = childPackageName;
20161 childInfo.installerPackageName = ps.installerPackageName;
20162 outInfo.removedChildPackages.put(childPackageName, childInfo);
20163 PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20164 if (childPs != null) {
20165 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20171 boolean ret = false;
20172 if (isSystemApp(ps)) {
20173 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20174 // When an updated system application is deleted we delete the existing resources
20175 // as well and fall back to existing code in system partition
20176 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20178 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20179 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20180 outInfo, writeSettings, replacingPackage);
20183 // Take a note whether we deleted the package for all users
20184 if (outInfo != null) {
20185 outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20186 if (outInfo.removedChildPackages != null) {
20187 synchronized (mPackages) {
20188 final int childCount = outInfo.removedChildPackages.size();
20189 for (int i = 0; i < childCount; i++) {
20190 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20191 if (childInfo != null) {
20192 childInfo.removedForAllUsers = mPackages.get(
20193 childInfo.removedPackage) == null;
20198 // If we uninstalled an update to a system app there may be some
20199 // child packages that appeared as they are declared in the system
20200 // app but were not declared in the update.
20201 if (isSystemApp(ps)) {
20202 synchronized (mPackages) {
20203 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20204 final int childCount = (updatedPs.childPackageNames != null)
20205 ? updatedPs.childPackageNames.size() : 0;
20206 for (int i = 0; i < childCount; i++) {
20207 String childPackageName = updatedPs.childPackageNames.get(i);
20208 if (outInfo.removedChildPackages == null
20209 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20210 PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20211 if (childPs == null) {
20214 PackageInstalledInfo installRes = new PackageInstalledInfo();
20215 installRes.name = childPackageName;
20216 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20217 installRes.pkg = mPackages.get(childPackageName);
20218 installRes.uid = childPs.pkg.applicationInfo.uid;
20219 if (outInfo.appearedChildPackages == null) {
20220 outInfo.appearedChildPackages = new ArrayMap<>();
20222 outInfo.appearedChildPackages.put(childPackageName, installRes);
20232 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20233 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20234 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20235 for (int nextUserId : userIds) {
20236 if (DEBUG_REMOVE) {
20237 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20239 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20240 false /*installed*/,
20242 true /*notLaunched*/,
20244 false /*suspended*/,
20245 false /*instantApp*/,
20246 false /*virtualPreload*/,
20247 null /*lastDisableAppCaller*/,
20248 null /*enabledComponents*/,
20249 null /*disabledComponents*/,
20250 ps.readUserState(nextUserId).domainVerificationStatus,
20251 0, PackageManager.INSTALL_REASON_UNKNOWN);
20253 mSettings.writeKernelMappingLPr(ps);
20256 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20257 PackageRemovedInfo outInfo) {
20258 final PackageParser.Package pkg;
20259 synchronized (mPackages) {
20260 pkg = mPackages.get(ps.name);
20263 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20264 : new int[] {userId};
20265 for (int nextUserId : userIds) {
20266 if (DEBUG_REMOVE) {
20267 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20271 destroyAppDataLIF(pkg, userId,
20272 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20273 destroyAppProfilesLIF(pkg, userId);
20274 clearDefaultBrowserIfNeededForUser(ps.name, userId);
20275 removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20276 schedulePackageCleaning(ps.name, nextUserId, false);
20277 synchronized (mPackages) {
20278 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20279 scheduleWritePackageRestrictionsLocked(nextUserId);
20281 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20285 if (outInfo != null) {
20286 outInfo.removedPackage = ps.name;
20287 outInfo.installerPackageName = ps.installerPackageName;
20288 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20289 outInfo.removedAppId = ps.appId;
20290 outInfo.removedUsers = userIds;
20291 outInfo.broadcastUsers = userIds;
20297 private final class ClearStorageConnection implements ServiceConnection {
20298 IMediaContainerService mContainerService;
20301 public void onServiceConnected(ComponentName name, IBinder service) {
20302 synchronized (this) {
20303 mContainerService = IMediaContainerService.Stub
20304 .asInterface(Binder.allowBlocking(service));
20310 public void onServiceDisconnected(ComponentName name) {
20314 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20315 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20317 final boolean mounted;
20318 if (Environment.isExternalStorageEmulated()) {
20321 final String status = Environment.getExternalStorageState();
20323 mounted = status.equals(Environment.MEDIA_MOUNTED)
20324 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20331 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20333 if (userId == UserHandle.USER_ALL) {
20334 users = sUserManager.getUserIds();
20336 users = new int[] { userId };
20338 final ClearStorageConnection conn = new ClearStorageConnection();
20339 if (mContext.bindServiceAsUser(
20340 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20342 for (int curUser : users) {
20343 long timeout = SystemClock.uptimeMillis() + 5000;
20344 synchronized (conn) {
20346 while (conn.mContainerService == null &&
20347 (now = SystemClock.uptimeMillis()) < timeout) {
20349 conn.wait(timeout - now);
20350 } catch (InterruptedException e) {
20354 if (conn.mContainerService == null) {
20358 final UserEnvironment userEnv = new UserEnvironment(curUser);
20359 clearDirectory(conn.mContainerService,
20360 userEnv.buildExternalStorageAppCacheDirs(packageName));
20362 clearDirectory(conn.mContainerService,
20363 userEnv.buildExternalStorageAppDataDirs(packageName));
20364 clearDirectory(conn.mContainerService,
20365 userEnv.buildExternalStorageAppMediaDirs(packageName));
20369 mContext.unbindService(conn);
20375 public void clearApplicationProfileData(String packageName) {
20376 enforceSystemOrRoot("Only the system can clear all profile data");
20378 final PackageParser.Package pkg;
20379 synchronized (mPackages) {
20380 pkg = mPackages.get(packageName);
20383 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20384 synchronized (mInstallLock) {
20385 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20391 public void clearApplicationUserData(final String packageName,
20392 final IPackageDataObserver observer, final int userId) {
20393 mContext.enforceCallingOrSelfPermission(
20394 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20396 final int callingUid = Binder.getCallingUid();
20397 enforceCrossUserPermission(callingUid, userId,
20398 true /* requireFullPermission */, false /* checkShell */, "clear application data");
20400 final PackageSetting ps = mSettings.getPackageLPr(packageName);
20401 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20402 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20403 throw new SecurityException("Cannot clear data for a protected package: "
20406 // Queue up an async operation since the package deletion may take a little while.
20407 mHandler.post(new Runnable() {
20408 public void run() {
20409 mHandler.removeCallbacks(this);
20410 final boolean succeeded;
20412 try (PackageFreezer freezer = freezePackage(packageName,
20413 "clearApplicationUserData")) {
20414 synchronized (mInstallLock) {
20415 succeeded = clearApplicationUserDataLIF(packageName, userId);
20417 clearExternalStorageDataSync(packageName, userId, true);
20418 synchronized (mPackages) {
20419 mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20420 packageName, userId);
20424 // invoke DeviceStorageMonitor's update method to clear any notifications
20425 DeviceStorageMonitorInternal dsm = LocalServices
20426 .getService(DeviceStorageMonitorInternal.class);
20434 if (observer != null) {
20436 observer.onRemoveCompleted(packageName, succeeded);
20437 } catch (RemoteException e) {
20438 Log.i(TAG, "Observer no longer exists.");
20440 } //end if observer
20445 private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20446 if (packageName == null) {
20447 Slog.w(TAG, "Attempt to delete null packageName.");
20451 // Try finding details about the requested package
20452 PackageParser.Package pkg;
20453 synchronized (mPackages) {
20454 pkg = mPackages.get(packageName);
20456 final PackageSetting ps = mSettings.mPackages.get(packageName);
20463 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20467 PackageSetting ps = (PackageSetting) pkg.mExtras;
20468 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20471 clearAppDataLIF(pkg, userId,
20472 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20474 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20475 removeKeystoreDataIfNeeded(userId, appId);
20477 UserManagerInternal umInternal = getUserManagerInternal();
20479 if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20480 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20481 } else if (umInternal.isUserRunning(userId)) {
20482 flags = StorageManager.FLAG_STORAGE_DE;
20486 prepareAppDataContentsLIF(pkg, userId, flags);
20492 * Reverts user permission state changes (permissions and flags) in
20493 * all packages for a given user.
20495 * @param userId The device user for which to do a reset.
20497 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20498 final int packageCount = mPackages.size();
20499 for (int i = 0; i < packageCount; i++) {
20500 PackageParser.Package pkg = mPackages.valueAt(i);
20501 PackageSetting ps = (PackageSetting) pkg.mExtras;
20502 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20506 private void resetNetworkPolicies(int userId) {
20507 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20511 * Reverts user permission state changes (permissions and flags).
20513 * @param ps The package for which to reset.
20514 * @param userId The device user for which to do a reset.
20516 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20517 final PackageSetting ps, final int userId) {
20518 if (ps.pkg == null) {
20522 // These are flags that can change base on user actions.
20523 final int userSettableMask = FLAG_PERMISSION_USER_SET
20524 | FLAG_PERMISSION_USER_FIXED
20525 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20526 | FLAG_PERMISSION_REVIEW_REQUIRED;
20528 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20529 | FLAG_PERMISSION_POLICY_FIXED;
20531 boolean writeInstallPermissions = false;
20532 boolean writeRuntimePermissions = false;
20534 final int permissionCount = ps.pkg.requestedPermissions.size();
20535 for (int i = 0; i < permissionCount; i++) {
20536 String permission = ps.pkg.requestedPermissions.get(i);
20538 BasePermission bp = mSettings.mPermissions.get(permission);
20543 // If shared user we just reset the state to which only this app contributed.
20544 if (ps.sharedUser != null) {
20545 boolean used = false;
20546 final int packageCount = ps.sharedUser.packages.size();
20547 for (int j = 0; j < packageCount; j++) {
20548 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20549 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20550 && pkg.pkg.requestedPermissions.contains(permission)) {
20560 PermissionsState permissionsState = ps.getPermissionsState();
20562 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20564 // Always clear the user settable flags.
20565 final boolean hasInstallState = permissionsState.getInstallPermissionState(
20567 // If permission review is enabled and this is a legacy app, mark the
20568 // permission as requiring a review as this is the initial state.
20570 if (mPermissionReviewRequired
20571 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20572 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20574 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20575 if (hasInstallState) {
20576 writeInstallPermissions = true;
20578 writeRuntimePermissions = true;
20582 // Below is only runtime permission handling.
20583 if (!bp.isRuntime()) {
20587 // Never clobber system or policy.
20588 if ((oldFlags & policyOrSystemFlags) != 0) {
20592 // If this permission was granted by default, make sure it is.
20593 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20594 if (permissionsState.grantRuntimePermission(bp, userId)
20595 != PERMISSION_OPERATION_FAILURE) {
20596 writeRuntimePermissions = true;
20598 // If permission review is enabled the permissions for a legacy apps
20599 // are represented as constantly granted runtime ones, so don't revoke.
20600 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20601 // Otherwise, reset the permission.
20602 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20603 switch (revokeResult) {
20604 case PERMISSION_OPERATION_SUCCESS:
20605 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20606 writeRuntimePermissions = true;
20607 final int appId = ps.appId;
20608 mHandler.post(new Runnable() {
20610 public void run() {
20611 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20619 // Synchronously write as we are taking permissions away.
20620 if (writeRuntimePermissions) {
20621 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20624 // Synchronously write as we are taking permissions away.
20625 if (writeInstallPermissions) {
20626 mSettings.writeLPr();
20631 * Remove entries from the keystore daemon. Will only remove it if the
20632 * {@code appId} is valid.
20634 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20639 final KeyStore keyStore = KeyStore.getInstance();
20640 if (keyStore != null) {
20641 if (userId == UserHandle.USER_ALL) {
20642 for (final int individual : sUserManager.getUserIds()) {
20643 keyStore.clearUid(UserHandle.getUid(individual, appId));
20646 keyStore.clearUid(UserHandle.getUid(userId, appId));
20649 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20654 public void deleteApplicationCacheFiles(final String packageName,
20655 final IPackageDataObserver observer) {
20656 final int userId = UserHandle.getCallingUserId();
20657 deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20661 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20662 final IPackageDataObserver observer) {
20663 final int callingUid = Binder.getCallingUid();
20664 mContext.enforceCallingOrSelfPermission(
20665 android.Manifest.permission.DELETE_CACHE_FILES, null);
20666 enforceCrossUserPermission(callingUid, userId,
20667 /* requireFullPermission= */ true, /* checkShell= */ false,
20668 "delete application cache files");
20669 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20670 android.Manifest.permission.ACCESS_INSTANT_APPS);
20672 final PackageParser.Package pkg;
20673 synchronized (mPackages) {
20674 pkg = mPackages.get(packageName);
20677 // Queue up an async operation since the package deletion may take a little while.
20678 mHandler.post(new Runnable() {
20679 public void run() {
20680 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20681 boolean doClearData = true;
20683 final boolean targetIsInstantApp =
20684 ps.getInstantApp(UserHandle.getUserId(callingUid));
20685 doClearData = !targetIsInstantApp
20686 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20689 synchronized (mInstallLock) {
20690 final int flags = StorageManager.FLAG_STORAGE_DE
20691 | StorageManager.FLAG_STORAGE_CE;
20692 // We're only clearing cache files, so we don't care if the
20693 // app is unfrozen and still able to run
20694 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20695 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20697 clearExternalStorageDataSync(packageName, userId, false);
20699 if (observer != null) {
20701 observer.onRemoveCompleted(packageName, true);
20702 } catch (RemoteException e) {
20703 Log.i(TAG, "Observer no longer exists.");
20711 public void getPackageSizeInfo(final String packageName, int userHandle,
20712 final IPackageStatsObserver observer) {
20713 throw new UnsupportedOperationException(
20714 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20717 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20718 final PackageSetting ps;
20719 synchronized (mPackages) {
20720 ps = mSettings.mPackages.get(packageName);
20722 Slog.w(TAG, "Failed to find settings for " + packageName);
20727 final String[] packageNames = { packageName };
20728 final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20729 final String[] codePaths = { ps.codePathString };
20732 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20733 ps.appId, ceDataInodes, codePaths, stats);
20735 // For now, ignore code size of packages on system partition
20736 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20737 stats.codeSize = 0;
20740 // External clients expect these to be tracked separately
20741 stats.dataSize -= stats.cacheSize;
20743 } catch (InstallerException e) {
20744 Slog.w(TAG, String.valueOf(e));
20751 private int getUidTargetSdkVersionLockedLPr(int uid) {
20752 Object obj = mSettings.getUserIdLPr(uid);
20753 if (obj instanceof SharedUserSetting) {
20754 final SharedUserSetting sus = (SharedUserSetting) obj;
20755 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20756 final Iterator<PackageSetting> it = sus.packages.iterator();
20757 while (it.hasNext()) {
20758 final PackageSetting ps = it.next();
20759 if (ps.pkg != null) {
20760 int v = ps.pkg.applicationInfo.targetSdkVersion;
20761 if (v < vers) vers = v;
20765 } else if (obj instanceof PackageSetting) {
20766 final PackageSetting ps = (PackageSetting) obj;
20767 if (ps.pkg != null) {
20768 return ps.pkg.applicationInfo.targetSdkVersion;
20771 return Build.VERSION_CODES.CUR_DEVELOPMENT;
20775 public void addPreferredActivity(IntentFilter filter, int match,
20776 ComponentName[] set, ComponentName activity, int userId) {
20777 addPreferredActivityInternal(filter, match, set, activity, true, userId,
20778 "Adding preferred");
20781 private void addPreferredActivityInternal(IntentFilter filter, int match,
20782 ComponentName[] set, ComponentName activity, boolean always, int userId,
20785 int callingUid = Binder.getCallingUid();
20786 enforceCrossUserPermission(callingUid, userId,
20787 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20788 if (filter.countActions() == 0) {
20789 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20792 synchronized (mPackages) {
20793 if (mContext.checkCallingOrSelfPermission(
20794 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20795 != PackageManager.PERMISSION_GRANTED) {
20796 if (getUidTargetSdkVersionLockedLPr(callingUid)
20797 < Build.VERSION_CODES.FROYO) {
20798 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20802 mContext.enforceCallingOrSelfPermission(
20803 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20806 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20807 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20809 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20810 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20811 scheduleWritePackageRestrictionsLocked(userId);
20812 postPreferredActivityChangedBroadcast(userId);
20816 private void postPreferredActivityChangedBroadcast(int userId) {
20817 mHandler.post(() -> {
20818 final IActivityManager am = ActivityManager.getService();
20823 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20824 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20826 am.broadcastIntent(null, intent, null, null,
20827 0, null, null, null, android.app.AppOpsManager.OP_NONE,
20828 null, false, false, userId);
20829 } catch (RemoteException e) {
20835 public void replacePreferredActivity(IntentFilter filter, int match,
20836 ComponentName[] set, ComponentName activity, int userId) {
20837 if (filter.countActions() != 1) {
20838 throw new IllegalArgumentException(
20839 "replacePreferredActivity expects filter to have only 1 action.");
20841 if (filter.countDataAuthorities() != 0
20842 || filter.countDataPaths() != 0
20843 || filter.countDataSchemes() > 1
20844 || filter.countDataTypes() != 0) {
20845 throw new IllegalArgumentException(
20846 "replacePreferredActivity expects filter to have no data authorities, " +
20847 "paths, or types; and at most one scheme.");
20850 final int callingUid = Binder.getCallingUid();
20851 enforceCrossUserPermission(callingUid, userId,
20852 true /* requireFullPermission */, false /* checkShell */,
20853 "replace preferred activity");
20854 synchronized (mPackages) {
20855 if (mContext.checkCallingOrSelfPermission(
20856 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20857 != PackageManager.PERMISSION_GRANTED) {
20858 if (getUidTargetSdkVersionLockedLPr(callingUid)
20859 < Build.VERSION_CODES.FROYO) {
20860 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20861 + Binder.getCallingUid());
20864 mContext.enforceCallingOrSelfPermission(
20865 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20868 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20870 // Get all of the existing entries that exactly match this filter.
20871 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20872 if (existing != null && existing.size() == 1) {
20873 PreferredActivity cur = existing.get(0);
20874 if (DEBUG_PREFERRED) {
20875 Slog.i(TAG, "Checking replace of preferred:");
20876 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20877 if (!cur.mPref.mAlways) {
20878 Slog.i(TAG, " -- CUR; not mAlways!");
20880 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
20881 Slog.i(TAG, " -- CUR: mSet="
20882 + Arrays.toString(cur.mPref.mSetComponents));
20883 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
20884 Slog.i(TAG, " -- NEW: mMatch="
20885 + (match&IntentFilter.MATCH_CATEGORY_MASK));
20886 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
20887 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
20890 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20891 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20892 && cur.mPref.sameSet(set)) {
20893 // Setting the preferred activity to what it happens to be already
20894 if (DEBUG_PREFERRED) {
20895 Slog.i(TAG, "Replacing with same preferred activity "
20896 + cur.mPref.mShortComponent + " for user "
20898 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20904 if (existing != null) {
20905 if (DEBUG_PREFERRED) {
20906 Slog.i(TAG, existing.size() + " existing preferred matches for:");
20907 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20909 for (int i = 0; i < existing.size(); i++) {
20910 PreferredActivity pa = existing.get(i);
20911 if (DEBUG_PREFERRED) {
20912 Slog.i(TAG, "Removing existing preferred activity "
20913 + pa.mPref.mComponent + ":");
20914 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
20916 pir.removeFilter(pa);
20920 addPreferredActivityInternal(filter, match, set, activity, true, userId,
20921 "Replacing preferred");
20926 public void clearPackagePreferredActivities(String packageName) {
20927 final int callingUid = Binder.getCallingUid();
20928 if (getInstantAppPackageName(callingUid) != null) {
20932 synchronized (mPackages) {
20933 PackageParser.Package pkg = mPackages.get(packageName);
20934 if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20935 if (mContext.checkCallingOrSelfPermission(
20936 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20937 != PackageManager.PERMISSION_GRANTED) {
20938 if (getUidTargetSdkVersionLockedLPr(callingUid)
20939 < Build.VERSION_CODES.FROYO) {
20940 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20944 mContext.enforceCallingOrSelfPermission(
20945 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20948 final PackageSetting ps = mSettings.getPackageLPr(packageName);
20950 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20953 int user = UserHandle.getCallingUserId();
20954 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20955 scheduleWritePackageRestrictionsLocked(user);
20960 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20961 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20962 ArrayList<PreferredActivity> removed = null;
20963 boolean changed = false;
20964 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20965 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20966 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20967 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20970 Iterator<PreferredActivity> it = pir.filterIterator();
20971 while (it.hasNext()) {
20972 PreferredActivity pa = it.next();
20973 // Mark entry for removal only if it matches the package name
20974 // and the entry is of type "always".
20975 if (packageName == null ||
20976 (pa.mPref.mComponent.getPackageName().equals(packageName)
20977 && pa.mPref.mAlways)) {
20978 if (removed == null) {
20979 removed = new ArrayList<PreferredActivity>();
20984 if (removed != null) {
20985 for (int j=0; j<removed.size(); j++) {
20986 PreferredActivity pa = removed.get(j);
20987 pir.removeFilter(pa);
20993 postPreferredActivityChangedBroadcast(userId);
20998 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20999 private void clearIntentFilterVerificationsLPw(int userId) {
21000 final int packageCount = mPackages.size();
21001 for (int i = 0; i < packageCount; i++) {
21002 PackageParser.Package pkg = mPackages.valueAt(i);
21003 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21007 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21008 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21009 if (userId == UserHandle.USER_ALL) {
21010 if (mSettings.removeIntentFilterVerificationLPw(packageName,
21011 sUserManager.getUserIds())) {
21012 for (int oneUserId : sUserManager.getUserIds()) {
21013 scheduleWritePackageRestrictionsLocked(oneUserId);
21017 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21018 scheduleWritePackageRestrictionsLocked(userId);
21023 /** Clears state for all users, and touches intent filter verification policy */
21024 void clearDefaultBrowserIfNeeded(String packageName) {
21025 for (int oneUserId : sUserManager.getUserIds()) {
21026 clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21030 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21031 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21032 if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21033 if (packageName.equals(defaultBrowserPackageName)) {
21034 setDefaultBrowserPackageName(null, userId);
21040 public void resetApplicationPreferences(int userId) {
21041 mContext.enforceCallingOrSelfPermission(
21042 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21043 final long identity = Binder.clearCallingIdentity();
21046 synchronized (mPackages) {
21047 clearPackagePreferredActivitiesLPw(null, userId);
21048 mSettings.applyDefaultPreferredAppsLPw(this, userId);
21049 // TODO: We have to reset the default SMS and Phone. This requires
21050 // significant refactoring to keep all default apps in the package
21051 // manager (cleaner but more work) or have the services provide
21052 // callbacks to the package manager to request a default app reset.
21053 applyFactoryDefaultBrowserLPw(userId);
21054 clearIntentFilterVerificationsLPw(userId);
21055 primeDomainVerificationsLPw(userId);
21056 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21057 scheduleWritePackageRestrictionsLocked(userId);
21059 resetNetworkPolicies(userId);
21061 Binder.restoreCallingIdentity(identity);
21066 public int getPreferredActivities(List<IntentFilter> outFilters,
21067 List<ComponentName> outActivities, String packageName) {
21068 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21072 final int userId = UserHandle.getCallingUserId();
21074 synchronized (mPackages) {
21075 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21077 final Iterator<PreferredActivity> it = pir.filterIterator();
21078 while (it.hasNext()) {
21079 final PreferredActivity pa = it.next();
21080 if (packageName == null
21081 || (pa.mPref.mComponent.getPackageName().equals(packageName)
21082 && pa.mPref.mAlways)) {
21083 if (outFilters != null) {
21084 outFilters.add(new IntentFilter(pa));
21086 if (outActivities != null) {
21087 outActivities.add(pa.mPref.mComponent);
21098 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21100 int callingUid = Binder.getCallingUid();
21101 if (callingUid != Process.SYSTEM_UID) {
21102 throw new SecurityException(
21103 "addPersistentPreferredActivity can only be run by the system");
21105 if (filter.countActions() == 0) {
21106 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21109 synchronized (mPackages) {
21110 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21112 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
21113 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21114 new PersistentPreferredActivity(filter, activity));
21115 scheduleWritePackageRestrictionsLocked(userId);
21116 postPreferredActivityChangedBroadcast(userId);
21121 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21122 int callingUid = Binder.getCallingUid();
21123 if (callingUid != Process.SYSTEM_UID) {
21124 throw new SecurityException(
21125 "clearPackagePersistentPreferredActivities can only be run by the system");
21127 ArrayList<PersistentPreferredActivity> removed = null;
21128 boolean changed = false;
21129 synchronized (mPackages) {
21130 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21131 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21132 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21134 if (userId != thisUserId) {
21137 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21138 while (it.hasNext()) {
21139 PersistentPreferredActivity ppa = it.next();
21140 // Mark entry for removal only if it matches the package name.
21141 if (ppa.mComponent.getPackageName().equals(packageName)) {
21142 if (removed == null) {
21143 removed = new ArrayList<PersistentPreferredActivity>();
21148 if (removed != null) {
21149 for (int j=0; j<removed.size(); j++) {
21150 PersistentPreferredActivity ppa = removed.get(j);
21151 ppir.removeFilter(ppa);
21158 scheduleWritePackageRestrictionsLocked(userId);
21159 postPreferredActivityChangedBroadcast(userId);
21165 * Common machinery for picking apart a restored XML blob and passing
21166 * it to a caller-supplied functor to be applied to the running system.
21168 private void restoreFromXml(XmlPullParser parser, int userId,
21169 String expectedStartTag, BlobXmlRestorer functor)
21170 throws IOException, XmlPullParserException {
21172 while ((type = parser.next()) != XmlPullParser.START_TAG
21173 && type != XmlPullParser.END_DOCUMENT) {
21175 if (type != XmlPullParser.START_TAG) {
21176 // oops didn't find a start tag?!
21177 if (DEBUG_BACKUP) {
21178 Slog.e(TAG, "Didn't find start tag during restore");
21182 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21183 // this is supposed to be TAG_PREFERRED_BACKUP
21184 if (!expectedStartTag.equals(parser.getName())) {
21185 if (DEBUG_BACKUP) {
21186 Slog.e(TAG, "Found unexpected tag " + parser.getName());
21191 // skip interfering stuff, then we're aligned with the backing implementation
21192 while ((type = parser.next()) == XmlPullParser.TEXT) { }
21193 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21194 functor.apply(parser, userId);
21197 private interface BlobXmlRestorer {
21198 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21202 * Non-Binder method, support for the backup/restore mechanism: write the
21203 * full set of preferred activities in its canonical XML format. Returns the
21204 * XML output as a byte array, or null if there is none.
21207 public byte[] getPreferredActivityBackup(int userId) {
21208 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21209 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21212 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21214 final XmlSerializer serializer = new FastXmlSerializer();
21215 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21216 serializer.startDocument(null, true);
21217 serializer.startTag(null, TAG_PREFERRED_BACKUP);
21219 synchronized (mPackages) {
21220 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21223 serializer.endTag(null, TAG_PREFERRED_BACKUP);
21224 serializer.endDocument();
21225 serializer.flush();
21226 } catch (Exception e) {
21227 if (DEBUG_BACKUP) {
21228 Slog.e(TAG, "Unable to write preferred activities for backup", e);
21233 return dataStream.toByteArray();
21237 public void restorePreferredActivities(byte[] backup, int userId) {
21238 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21239 throw new SecurityException("Only the system may call restorePreferredActivities()");
21243 final XmlPullParser parser = Xml.newPullParser();
21244 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21245 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21246 new BlobXmlRestorer() {
21248 public void apply(XmlPullParser parser, int userId)
21249 throws XmlPullParserException, IOException {
21250 synchronized (mPackages) {
21251 mSettings.readPreferredActivitiesLPw(parser, userId);
21255 } catch (Exception e) {
21256 if (DEBUG_BACKUP) {
21257 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21263 * Non-Binder method, support for the backup/restore mechanism: write the
21264 * default browser (etc) settings in its canonical XML format. Returns the default
21265 * browser XML representation as a byte array, or null if there is none.
21268 public byte[] getDefaultAppsBackup(int userId) {
21269 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21270 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21273 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21275 final XmlSerializer serializer = new FastXmlSerializer();
21276 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21277 serializer.startDocument(null, true);
21278 serializer.startTag(null, TAG_DEFAULT_APPS);
21280 synchronized (mPackages) {
21281 mSettings.writeDefaultAppsLPr(serializer, userId);
21284 serializer.endTag(null, TAG_DEFAULT_APPS);
21285 serializer.endDocument();
21286 serializer.flush();
21287 } catch (Exception e) {
21288 if (DEBUG_BACKUP) {
21289 Slog.e(TAG, "Unable to write default apps for backup", e);
21294 return dataStream.toByteArray();
21298 public void restoreDefaultApps(byte[] backup, int userId) {
21299 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21300 throw new SecurityException("Only the system may call restoreDefaultApps()");
21304 final XmlPullParser parser = Xml.newPullParser();
21305 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21306 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21307 new BlobXmlRestorer() {
21309 public void apply(XmlPullParser parser, int userId)
21310 throws XmlPullParserException, IOException {
21311 synchronized (mPackages) {
21312 mSettings.readDefaultAppsLPw(parser, userId);
21316 } catch (Exception e) {
21317 if (DEBUG_BACKUP) {
21318 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21324 public byte[] getIntentFilterVerificationBackup(int userId) {
21325 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21326 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21329 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21331 final XmlSerializer serializer = new FastXmlSerializer();
21332 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21333 serializer.startDocument(null, true);
21334 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21336 synchronized (mPackages) {
21337 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21340 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21341 serializer.endDocument();
21342 serializer.flush();
21343 } catch (Exception e) {
21344 if (DEBUG_BACKUP) {
21345 Slog.e(TAG, "Unable to write default apps for backup", e);
21350 return dataStream.toByteArray();
21354 public void restoreIntentFilterVerification(byte[] backup, int userId) {
21355 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21356 throw new SecurityException("Only the system may call restorePreferredActivities()");
21360 final XmlPullParser parser = Xml.newPullParser();
21361 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21362 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21363 new BlobXmlRestorer() {
21365 public void apply(XmlPullParser parser, int userId)
21366 throws XmlPullParserException, IOException {
21367 synchronized (mPackages) {
21368 mSettings.readAllDomainVerificationsLPr(parser, userId);
21369 mSettings.writeLPr();
21373 } catch (Exception e) {
21374 if (DEBUG_BACKUP) {
21375 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21381 public byte[] getPermissionGrantBackup(int userId) {
21382 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21383 throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21386 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21388 final XmlSerializer serializer = new FastXmlSerializer();
21389 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21390 serializer.startDocument(null, true);
21391 serializer.startTag(null, TAG_PERMISSION_BACKUP);
21393 synchronized (mPackages) {
21394 serializeRuntimePermissionGrantsLPr(serializer, userId);
21397 serializer.endTag(null, TAG_PERMISSION_BACKUP);
21398 serializer.endDocument();
21399 serializer.flush();
21400 } catch (Exception e) {
21401 if (DEBUG_BACKUP) {
21402 Slog.e(TAG, "Unable to write default apps for backup", e);
21407 return dataStream.toByteArray();
21411 public void restorePermissionGrants(byte[] backup, int userId) {
21412 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21413 throw new SecurityException("Only the system may call restorePermissionGrants()");
21417 final XmlPullParser parser = Xml.newPullParser();
21418 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21419 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21420 new BlobXmlRestorer() {
21422 public void apply(XmlPullParser parser, int userId)
21423 throws XmlPullParserException, IOException {
21424 synchronized (mPackages) {
21425 processRestoredPermissionGrantsLPr(parser, userId);
21429 } catch (Exception e) {
21430 if (DEBUG_BACKUP) {
21431 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21436 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21437 throws IOException {
21438 serializer.startTag(null, TAG_ALL_GRANTS);
21440 final int N = mSettings.mPackages.size();
21441 for (int i = 0; i < N; i++) {
21442 final PackageSetting ps = mSettings.mPackages.valueAt(i);
21443 boolean pkgGrantsKnown = false;
21445 PermissionsState packagePerms = ps.getPermissionsState();
21447 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21448 final int grantFlags = state.getFlags();
21449 // only look at grants that are not system/policy fixed
21450 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21451 final boolean isGranted = state.isGranted();
21452 // And only back up the user-twiddled state bits
21453 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21454 final String packageName = mSettings.mPackages.keyAt(i);
21455 if (!pkgGrantsKnown) {
21456 serializer.startTag(null, TAG_GRANT);
21457 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21458 pkgGrantsKnown = true;
21461 final boolean userSet =
21462 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21463 final boolean userFixed =
21464 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21465 final boolean revoke =
21466 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21468 serializer.startTag(null, TAG_PERMISSION);
21469 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21471 serializer.attribute(null, ATTR_IS_GRANTED, "true");
21474 serializer.attribute(null, ATTR_USER_SET, "true");
21477 serializer.attribute(null, ATTR_USER_FIXED, "true");
21480 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21482 serializer.endTag(null, TAG_PERMISSION);
21487 if (pkgGrantsKnown) {
21488 serializer.endTag(null, TAG_GRANT);
21492 serializer.endTag(null, TAG_ALL_GRANTS);
21495 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21496 throws XmlPullParserException, IOException {
21497 String pkgName = null;
21498 int outerDepth = parser.getDepth();
21500 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21501 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21502 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21506 final String tagName = parser.getName();
21507 if (tagName.equals(TAG_GRANT)) {
21508 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21509 if (DEBUG_BACKUP) {
21510 Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21512 } else if (tagName.equals(TAG_PERMISSION)) {
21514 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21515 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21517 int newFlagSet = 0;
21518 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21519 newFlagSet |= FLAG_PERMISSION_USER_SET;
21521 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21522 newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21524 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21525 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21527 if (DEBUG_BACKUP) {
21528 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName
21529 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21531 final PackageSetting ps = mSettings.mPackages.get(pkgName);
21533 // Already installed so we apply the grant immediately
21534 if (DEBUG_BACKUP) {
21535 Slog.v(TAG, " + already installed; applying");
21537 PermissionsState perms = ps.getPermissionsState();
21538 BasePermission bp = mSettings.mPermissions.get(permName);
21541 perms.grantRuntimePermission(bp, userId);
21543 if (newFlagSet != 0) {
21544 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21548 // Need to wait for post-restore install to apply the grant
21549 if (DEBUG_BACKUP) {
21550 Slog.v(TAG, " - not yet installed; saving for later");
21552 mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21553 isGranted, newFlagSet, userId);
21556 PackageManagerService.reportSettingsProblem(Log.WARN,
21557 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21558 XmlUtils.skipCurrentTag(parser);
21562 scheduleWriteSettingsLocked();
21563 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21567 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21568 int sourceUserId, int targetUserId, int flags) {
21569 mContext.enforceCallingOrSelfPermission(
21570 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21571 int callingUid = Binder.getCallingUid();
21572 enforceOwnerRights(ownerPackage, callingUid);
21573 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21574 if (intentFilter.countActions() == 0) {
21575 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21578 synchronized (mPackages) {
21579 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21580 ownerPackage, targetUserId, flags);
21581 CrossProfileIntentResolver resolver =
21582 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21583 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21584 // We have all those whose filter is equal. Now checking if the rest is equal as well.
21585 if (existing != null) {
21586 int size = existing.size();
21587 for (int i = 0; i < size; i++) {
21588 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21593 resolver.addFilter(newFilter);
21594 scheduleWritePackageRestrictionsLocked(sourceUserId);
21599 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21600 mContext.enforceCallingOrSelfPermission(
21601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21602 final int callingUid = Binder.getCallingUid();
21603 enforceOwnerRights(ownerPackage, callingUid);
21604 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21605 synchronized (mPackages) {
21606 CrossProfileIntentResolver resolver =
21607 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21608 ArraySet<CrossProfileIntentFilter> set =
21609 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21610 for (CrossProfileIntentFilter filter : set) {
21611 if (filter.getOwnerPackage().equals(ownerPackage)) {
21612 resolver.removeFilter(filter);
21615 scheduleWritePackageRestrictionsLocked(sourceUserId);
21619 // Enforcing that callingUid is owning pkg on userId
21620 private void enforceOwnerRights(String pkg, int callingUid) {
21621 // The system owns everything.
21622 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21625 final int callingUserId = UserHandle.getUserId(callingUid);
21626 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21628 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21631 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21632 throw new SecurityException("Calling uid " + callingUid
21633 + " does not own package " + pkg);
21638 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21639 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21642 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21645 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21646 UserManagerService ums = UserManagerService.getInstance();
21648 final UserInfo parent = ums.getProfileParent(userId);
21649 final int launcherUid = (parent != null) ? parent.id : userId;
21650 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21651 if (launcherComponent != null) {
21652 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21653 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21654 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21655 .setPackage(launcherComponent.getPackageName());
21656 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21662 * Report the 'Home' activity which is currently set as "always use this one". If non is set
21663 * then reports the most likely home activity or null if there are more than one.
21665 private ComponentName getDefaultHomeActivity(int userId) {
21666 List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21667 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21672 // Find the launcher with the highest priority and return that component if there are no
21673 // other home activity with the same priority.
21674 int lastPriority = Integer.MIN_VALUE;
21675 ComponentName lastComponent = null;
21676 final int size = allHomeCandidates.size();
21677 for (int i = 0; i < size; i++) {
21678 final ResolveInfo ri = allHomeCandidates.get(i);
21679 if (ri.priority > lastPriority) {
21680 lastComponent = ri.activityInfo.getComponentName();
21681 lastPriority = ri.priority;
21682 } else if (ri.priority == lastPriority) {
21683 // Two components found with same priority.
21684 lastComponent = null;
21687 return lastComponent;
21690 private Intent getHomeIntent() {
21691 Intent intent = new Intent(Intent.ACTION_MAIN);
21692 intent.addCategory(Intent.CATEGORY_HOME);
21693 intent.addCategory(Intent.CATEGORY_DEFAULT);
21697 private IntentFilter getHomeFilter() {
21698 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21699 filter.addCategory(Intent.CATEGORY_HOME);
21700 filter.addCategory(Intent.CATEGORY_DEFAULT);
21704 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21706 Intent intent = getHomeIntent();
21707 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21708 PackageManager.GET_META_DATA, userId);
21709 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21710 true, false, false, userId);
21712 allHomeCandidates.clear();
21713 if (list != null) {
21714 for (ResolveInfo ri : list) {
21715 allHomeCandidates.add(ri);
21718 return (preferred == null || preferred.activityInfo == null)
21720 : new ComponentName(preferred.activityInfo.packageName,
21721 preferred.activityInfo.name);
21725 public void setHomeActivity(ComponentName comp, int userId) {
21726 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21729 ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21730 getHomeActivitiesAsUser(homeActivities, userId);
21732 boolean found = false;
21734 final int size = homeActivities.size();
21735 final ComponentName[] set = new ComponentName[size];
21736 for (int i = 0; i < size; i++) {
21737 final ResolveInfo candidate = homeActivities.get(i);
21738 final ActivityInfo info = candidate.activityInfo;
21739 final ComponentName activityName = new ComponentName(info.packageName, info.name);
21740 set[i] = activityName;
21741 if (!found && activityName.equals(comp)) {
21746 throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21749 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21750 set, comp, userId);
21753 private @Nullable String getSetupWizardPackageName() {
21754 final Intent intent = new Intent(Intent.ACTION_MAIN);
21755 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21757 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21758 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21759 | MATCH_DISABLED_COMPONENTS,
21760 UserHandle.myUserId());
21761 if (matches.size() == 1) {
21762 return matches.get(0).getComponentInfo().packageName;
21764 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21765 + ": matches=" + matches);
21770 private @Nullable String getStorageManagerPackageName() {
21771 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21773 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21774 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21775 | MATCH_DISABLED_COMPONENTS,
21776 UserHandle.myUserId());
21777 if (matches.size() == 1) {
21778 return matches.get(0).getComponentInfo().packageName;
21780 Slog.e(TAG, "There should probably be exactly one storage manager; found "
21781 + matches.size() + ": matches=" + matches);
21787 public void setApplicationEnabledSetting(String appPackageName,
21788 int newState, int flags, int userId, String callingPackage) {
21789 if (!sUserManager.exists(userId)) return;
21790 if (callingPackage == null) {
21791 callingPackage = Integer.toString(Binder.getCallingUid());
21793 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21797 public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21799 synchronized (mPackages) {
21800 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21801 if (pkgSetting != null) {
21802 pkgSetting.setUpdateAvailable(updateAvailable);
21808 public void setComponentEnabledSetting(ComponentName componentName,
21809 int newState, int flags, int userId) {
21810 if (!sUserManager.exists(userId)) return;
21811 setEnabledSetting(componentName.getPackageName(),
21812 componentName.getClassName(), newState, flags, userId, null);
21815 private void setEnabledSetting(final String packageName, String className, int newState,
21816 final int flags, int userId, String callingPackage) {
21817 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21818 || newState == COMPONENT_ENABLED_STATE_ENABLED
21819 || newState == COMPONENT_ENABLED_STATE_DISABLED
21820 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21821 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21822 throw new IllegalArgumentException("Invalid new component state: "
21825 PackageSetting pkgSetting;
21826 final int callingUid = Binder.getCallingUid();
21827 final int permission;
21828 if (callingUid == Process.SYSTEM_UID) {
21829 permission = PackageManager.PERMISSION_GRANTED;
21831 permission = mContext.checkCallingOrSelfPermission(
21832 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21834 enforceCrossUserPermission(callingUid, userId,
21835 false /* requireFullPermission */, true /* checkShell */, "set enabled");
21836 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21837 boolean sendNow = false;
21838 boolean isApp = (className == null);
21839 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21840 String componentName = isApp ? packageName : className;
21841 int packageUid = -1;
21842 ArrayList<String> components;
21845 synchronized (mPackages) {
21846 pkgSetting = mSettings.mPackages.get(packageName);
21847 if (pkgSetting == null) {
21848 if (!isCallerInstantApp) {
21849 if (className == null) {
21850 throw new IllegalArgumentException("Unknown package: " + packageName);
21852 throw new IllegalArgumentException(
21853 "Unknown component: " + packageName + "/" + className);
21855 // throw SecurityException to prevent leaking package information
21856 throw new SecurityException(
21857 "Attempt to change component state; "
21858 + "pid=" + Binder.getCallingPid()
21859 + ", uid=" + callingUid
21860 + (className == null
21861 ? ", package=" + packageName
21862 : ", component=" + packageName + "/" + className));
21867 // Limit who can change which apps
21868 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21869 // Don't allow apps that don't have permission to modify other apps
21870 if (!allowedByPermission
21871 || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21872 throw new SecurityException(
21873 "Attempt to change component state; "
21874 + "pid=" + Binder.getCallingPid()
21875 + ", uid=" + callingUid
21876 + (className == null
21877 ? ", package=" + packageName
21878 : ", component=" + packageName + "/" + className));
21880 // Don't allow changing protected packages.
21881 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21882 throw new SecurityException("Cannot disable a protected package: " + packageName);
21886 synchronized (mPackages) {
21887 if (callingUid == Process.SHELL_UID
21888 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21889 // Shell can only change whole packages between ENABLED and DISABLED_USER states
21890 // unless it is a test package.
21891 int oldState = pkgSetting.getEnabled(userId);
21892 if (className == null
21894 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21895 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21896 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21898 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21899 || newState == COMPONENT_ENABLED_STATE_DEFAULT
21900 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21903 throw new SecurityException(
21904 "Shell cannot change component state for " + packageName + "/"
21905 + className + " to " + newState);
21909 if (className == null) {
21910 // We're dealing with an application/package level state change
21911 synchronized (mPackages) {
21912 if (pkgSetting.getEnabled(userId) == newState) {
21917 // If we're enabling a system stub, there's a little more work to do.
21918 // Prior to enabling the package, we need to decompress the APK(s) to the
21919 // data partition and then replace the version on the system partition.
21920 final PackageParser.Package deletedPkg = pkgSetting.pkg;
21921 final boolean isSystemStub = deletedPkg.isStub
21922 && deletedPkg.isSystemApp();
21924 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21925 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21926 final File codePath = decompressPackage(deletedPkg);
21927 if (codePath == null) {
21928 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21931 // TODO remove direct parsing of the package object during internal cleanup
21933 // We need to call parse directly here for no other reason than we need
21934 // the new package in order to disable the old one [we use the information
21935 // for some internal optimization to optionally create a new package setting
21936 // object on replace]. However, we can't get the package from the scan
21937 // because the scan modifies live structures and we need to remove the
21938 // old [system] package from the system before a scan can be attempted.
21939 // Once scan is indempotent we can remove this parse and use the package
21940 // object we scanned, prior to adding it to package settings.
21941 final PackageParser pp = new PackageParser();
21942 pp.setSeparateProcesses(mSeparateProcesses);
21943 pp.setDisplayMetrics(mMetrics);
21944 pp.setCallback(mPackageParserCallback);
21945 final PackageParser.Package tmpPkg;
21947 final int parseFlags = mDefParseFlags
21948 | PackageParser.PARSE_MUST_BE_APK
21949 | PackageParser.PARSE_IS_SYSTEM
21950 | PackageParser.PARSE_IS_SYSTEM_DIR;
21951 tmpPkg = pp.parsePackage(codePath, parseFlags);
21952 } catch (PackageParserException e) {
21953 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21956 synchronized (mInstallLock) {
21957 // Disable the stub and remove any package entries
21958 removePackageLI(deletedPkg, true);
21959 synchronized (mPackages) {
21960 disableSystemPackageLPw(deletedPkg, tmpPkg);
21962 final PackageParser.Package newPkg;
21963 try (PackageFreezer freezer =
21964 freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21965 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21966 | PackageParser.PARSE_ENFORCE_CODE;
21967 newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21968 0 /*currentTime*/, null /*user*/);
21969 prepareAppDataAfterInstallLIF(newPkg);
21970 synchronized (mPackages) {
21972 updateSharedLibrariesLPr(newPkg, null);
21973 } catch (PackageManagerException e) {
21974 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21976 updatePermissionsLPw(newPkg.packageName, newPkg,
21977 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21978 mSettings.writeLPr();
21980 } catch (PackageManagerException e) {
21981 // Whoops! Something went wrong; try to roll back to the stub
21982 Slog.w(TAG, "Failed to install compressed system package:"
21983 + pkgSetting.name, e);
21984 // Remove the failed install
21985 removeCodePathLI(codePath);
21987 // Install the system package
21988 try (PackageFreezer freezer =
21989 freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21990 synchronized (mPackages) {
21991 // NOTE: The system package always needs to be enabled; even
21992 // if it's for a compressed stub. If we don't, installing the
21993 // system package fails during scan [scanning checks the disabled
21994 // packages]. We will reverse this later, after we've "installed"
21996 // This leaves us in a fragile state; the stub should never be
21997 // enabled, so, cross your fingers and hope nothing goes wrong
21998 // until we can disable the package later.
21999 enableSystemPackageLPw(deletedPkg);
22001 installPackageFromSystemLIF(new File(deletedPkg.codePath),
22002 false /*isPrivileged*/, null /*allUserHandles*/,
22003 null /*origUserHandles*/, null /*origPermissionsState*/,
22004 true /*writeSettings*/);
22005 } catch (PackageManagerException pme) {
22006 Slog.w(TAG, "Failed to restore system package:"
22007 + deletedPkg.packageName, pme);
22009 synchronized (mPackages) {
22010 mSettings.disableSystemPackageLPw(
22011 deletedPkg.packageName, true /*replaced*/);
22012 mSettings.writeLPr();
22017 clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22018 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22019 clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22020 mDexManager.notifyPackageUpdated(newPkg.packageName,
22021 newPkg.baseCodePath, newPkg.splitCodePaths);
22024 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22025 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22026 // Don't care about who enables an app.
22027 callingPackage = null;
22029 synchronized (mPackages) {
22030 pkgSetting.setEnabled(newState, userId, callingPackage);
22033 synchronized (mPackages) {
22034 // We're dealing with a component level state change
22035 // First, verify that this is a valid class name.
22036 PackageParser.Package pkg = pkgSetting.pkg;
22037 if (pkg == null || !pkg.hasComponentClassName(className)) {
22039 pkg.applicationInfo.targetSdkVersion >=
22040 Build.VERSION_CODES.JELLY_BEAN) {
22041 throw new IllegalArgumentException("Component class " + className
22042 + " does not exist in " + packageName);
22044 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22045 + className + " does not exist in " + packageName);
22048 switch (newState) {
22049 case COMPONENT_ENABLED_STATE_ENABLED:
22050 if (!pkgSetting.enableComponentLPw(className, userId)) {
22054 case COMPONENT_ENABLED_STATE_DISABLED:
22055 if (!pkgSetting.disableComponentLPw(className, userId)) {
22059 case COMPONENT_ENABLED_STATE_DEFAULT:
22060 if (!pkgSetting.restoreComponentLPw(className, userId)) {
22065 Slog.e(TAG, "Invalid new component state: " + newState);
22070 synchronized (mPackages) {
22071 scheduleWritePackageRestrictionsLocked(userId);
22072 updateSequenceNumberLP(pkgSetting, new int[] { userId });
22073 final long callingId = Binder.clearCallingIdentity();
22075 updateInstantAppInstallerLocked(packageName);
22077 Binder.restoreCallingIdentity(callingId);
22079 components = mPendingBroadcasts.get(userId, packageName);
22080 final boolean newPackage = components == null;
22082 components = new ArrayList<String>();
22084 if (!components.contains(componentName)) {
22085 components.add(componentName);
22087 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22089 // Purge entry from pending broadcast list if another one exists already
22090 // since we are sending one right away.
22091 mPendingBroadcasts.remove(userId, packageName);
22094 mPendingBroadcasts.put(userId, packageName, components);
22096 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22097 // Schedule a message
22098 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22103 long callingId = Binder.clearCallingIdentity();
22106 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22107 sendPackageChangedBroadcast(packageName,
22108 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22111 Binder.restoreCallingIdentity(callingId);
22116 public void flushPackageRestrictionsAsUser(int userId) {
22117 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22120 if (!sUserManager.exists(userId)) {
22123 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22124 false /* checkShell */, "flushPackageRestrictions");
22125 synchronized (mPackages) {
22126 mSettings.writePackageRestrictionsLPr(userId);
22127 mDirtyUsers.remove(userId);
22128 if (mDirtyUsers.isEmpty()) {
22129 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22134 private void sendPackageChangedBroadcast(String packageName,
22135 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22137 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22139 Bundle extras = new Bundle(4);
22140 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22141 String nameList[] = new String[componentNames.size()];
22142 componentNames.toArray(nameList);
22143 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22144 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22145 extras.putInt(Intent.EXTRA_UID, packageUid);
22146 // If this is not reporting a change of the overall package, then only send it
22147 // to registered receivers. We don't want to launch a swath of apps for every
22148 // little component state change.
22149 final int flags = !componentNames.contains(packageName)
22150 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22151 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null,
22152 new int[] {UserHandle.getUserId(packageUid)});
22156 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22157 if (!sUserManager.exists(userId)) return;
22158 final int callingUid = Binder.getCallingUid();
22159 if (getInstantAppPackageName(callingUid) != null) {
22162 final int permission = mContext.checkCallingOrSelfPermission(
22163 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22164 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22165 enforceCrossUserPermission(callingUid, userId,
22166 true /* requireFullPermission */, true /* checkShell */, "stop package");
22168 synchronized (mPackages) {
22169 final PackageSetting ps = mSettings.mPackages.get(packageName);
22170 if (!filterAppAccessLPr(ps, callingUid, userId)
22171 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22172 allowedByPermission, callingUid, userId)) {
22173 scheduleWritePackageRestrictionsLocked(userId);
22179 public String getInstallerPackageName(String packageName) {
22180 final int callingUid = Binder.getCallingUid();
22181 if (getInstantAppPackageName(callingUid) != null) {
22185 synchronized (mPackages) {
22186 final PackageSetting ps = mSettings.mPackages.get(packageName);
22187 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22190 return mSettings.getInstallerPackageNameLPr(packageName);
22194 public boolean isOrphaned(String packageName) {
22196 synchronized (mPackages) {
22197 return mSettings.isOrphaned(packageName);
22202 public int getApplicationEnabledSetting(String packageName, int userId) {
22203 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22204 int callingUid = Binder.getCallingUid();
22205 enforceCrossUserPermission(callingUid, userId,
22206 false /* requireFullPermission */, false /* checkShell */, "get enabled");
22208 synchronized (mPackages) {
22209 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22210 return COMPONENT_ENABLED_STATE_DISABLED;
22212 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22217 public int getComponentEnabledSetting(ComponentName component, int userId) {
22218 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22219 int callingUid = Binder.getCallingUid();
22220 enforceCrossUserPermission(callingUid, userId,
22221 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22222 synchronized (mPackages) {
22223 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22224 component, TYPE_UNKNOWN, userId)) {
22225 return COMPONENT_ENABLED_STATE_DISABLED;
22227 return mSettings.getComponentEnabledSettingLPr(component, userId);
22232 public void enterSafeMode() {
22233 enforceSystemOrRoot("Only the system can request entering safe mode");
22235 if (!mSystemReady) {
22241 public void systemReady() {
22242 enforceSystemOrRoot("Only the system can claim the system is ready");
22244 mSystemReady = true;
22245 final ContentResolver resolver = mContext.getContentResolver();
22246 ContentObserver co = new ContentObserver(mHandler) {
22248 public void onChange(boolean selfChange) {
22249 mEphemeralAppsDisabled =
22250 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22251 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22254 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22255 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22256 false, co, UserHandle.USER_SYSTEM);
22257 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22258 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22261 // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22262 // disabled after already being started.
22263 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22264 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22266 // Read the compatibilty setting when the system is ready.
22267 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22268 mContext.getContentResolver(),
22269 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22270 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22271 if (DEBUG_SETTINGS) {
22272 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22275 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22277 synchronized (mPackages) {
22278 // Verify that all of the preferred activity components actually
22279 // exist. It is possible for applications to be updated and at
22280 // that point remove a previously declared activity component that
22281 // had been set as a preferred activity. We try to clean this up
22282 // the next time we encounter that preferred activity, but it is
22283 // possible for the user flow to never be able to return to that
22284 // situation so here we do a sanity check to make sure we haven't
22285 // left any junk around.
22286 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22287 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22288 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22290 for (PreferredActivity pa : pir.filterSet()) {
22291 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22295 if (removed.size() > 0) {
22296 for (int r=0; r<removed.size(); r++) {
22297 PreferredActivity pa = removed.get(r);
22298 Slog.w(TAG, "Removing dangling preferred activity: "
22299 + pa.mPref.mComponent);
22300 pir.removeFilter(pa);
22302 mSettings.writePackageRestrictionsLPr(
22303 mSettings.mPreferredActivities.keyAt(i));
22307 for (int userId : UserManagerService.getInstance().getUserIds()) {
22308 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22309 grantPermissionsUserIds = ArrayUtils.appendInt(
22310 grantPermissionsUserIds, userId);
22314 sUserManager.systemReady();
22316 // If we upgraded grant all default permissions before kicking off.
22317 for (int userId : grantPermissionsUserIds) {
22318 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22321 // If we did not grant default permissions, we preload from this the
22322 // default permission exceptions lazily to ensure we don't hit the
22323 // disk on a new user creation.
22324 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22325 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22328 // Kick off any messages waiting for system ready
22329 if (mPostSystemReadyMessages != null) {
22330 for (Message msg : mPostSystemReadyMessages) {
22331 msg.sendToTarget();
22333 mPostSystemReadyMessages = null;
22336 // Watch for external volumes that come and go over time
22337 final StorageManager storage = mContext.getSystemService(StorageManager.class);
22338 storage.registerListener(mStorageListener);
22340 mInstallerService.systemReady();
22341 mPackageDexOptimizer.systemReady();
22343 StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22344 StorageManagerInternal.class);
22345 StorageManagerInternal.addExternalStoragePolicy(
22346 new StorageManagerInternal.ExternalStorageMountPolicy() {
22348 public int getMountMode(int uid, String packageName) {
22349 if (Process.isIsolated(uid)) {
22350 return Zygote.MOUNT_EXTERNAL_NONE;
22352 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22353 return Zygote.MOUNT_EXTERNAL_DEFAULT;
22355 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22356 return Zygote.MOUNT_EXTERNAL_DEFAULT;
22358 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22359 return Zygote.MOUNT_EXTERNAL_READ;
22361 return Zygote.MOUNT_EXTERNAL_WRITE;
22365 public boolean hasExternalStorage(int uid, String packageName) {
22370 // Now that we're mostly running, clean up stale users and apps
22371 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22372 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22374 if (mPrivappPermissionsViolations != null) {
22375 Slog.wtf(TAG,"Signature|privileged permissions not in "
22376 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22377 mPrivappPermissionsViolations = null;
22381 public void waitForAppDataPrepared() {
22382 if (mPrepareAppDataFuture == null) {
22385 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22386 mPrepareAppDataFuture = null;
22390 public boolean isSafeMode() {
22391 // allow instant applications
22396 public boolean hasSystemUidErrors() {
22397 // allow instant applications
22398 return mHasSystemUidErrors;
22401 static String arrayToString(int[] array) {
22402 StringBuffer buf = new StringBuffer(128);
22404 if (array != null) {
22405 for (int i=0; i<array.length; i++) {
22406 if (i > 0) buf.append(", ");
22407 buf.append(array[i]);
22411 return buf.toString();
22414 static class DumpState {
22415 public static final int DUMP_LIBS = 1 << 0;
22416 public static final int DUMP_FEATURES = 1 << 1;
22417 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22418 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22419 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22420 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22421 public static final int DUMP_PERMISSIONS = 1 << 6;
22422 public static final int DUMP_PACKAGES = 1 << 7;
22423 public static final int DUMP_SHARED_USERS = 1 << 8;
22424 public static final int DUMP_MESSAGES = 1 << 9;
22425 public static final int DUMP_PROVIDERS = 1 << 10;
22426 public static final int DUMP_VERIFIERS = 1 << 11;
22427 public static final int DUMP_PREFERRED = 1 << 12;
22428 public static final int DUMP_PREFERRED_XML = 1 << 13;
22429 public static final int DUMP_KEYSETS = 1 << 14;
22430 public static final int DUMP_VERSION = 1 << 15;
22431 public static final int DUMP_INSTALLS = 1 << 16;
22432 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22433 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22434 public static final int DUMP_FROZEN = 1 << 19;
22435 public static final int DUMP_DEXOPT = 1 << 20;
22436 public static final int DUMP_COMPILER_STATS = 1 << 21;
22437 public static final int DUMP_CHANGES = 1 << 22;
22438 public static final int DUMP_VOLUMES = 1 << 23;
22440 public static final int OPTION_SHOW_FILTERS = 1 << 0;
22442 private int mTypes;
22444 private int mOptions;
22446 private boolean mTitlePrinted;
22448 private SharedUserSetting mSharedUser;
22450 public boolean isDumping(int type) {
22451 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22455 return (mTypes & type) != 0;
22458 public void setDump(int type) {
22462 public boolean isOptionEnabled(int option) {
22463 return (mOptions & option) != 0;
22466 public void setOptionEnabled(int option) {
22467 mOptions |= option;
22470 public boolean onTitlePrinted() {
22471 final boolean printed = mTitlePrinted;
22472 mTitlePrinted = true;
22476 public boolean getTitlePrinted() {
22477 return mTitlePrinted;
22480 public void setTitlePrinted(boolean enabled) {
22481 mTitlePrinted = enabled;
22484 public SharedUserSetting getSharedUser() {
22485 return mSharedUser;
22488 public void setSharedUser(SharedUserSetting user) {
22489 mSharedUser = user;
22494 public void onShellCommand(FileDescriptor in, FileDescriptor out,
22495 FileDescriptor err, String[] args, ShellCallback callback,
22496 ResultReceiver resultReceiver) {
22497 (new PackageManagerShellCommand(this)).exec(
22498 this, in, out, err, args, callback, resultReceiver);
22502 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22503 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22505 DumpState dumpState = new DumpState();
22506 boolean fullPreferred = false;
22507 boolean checkin = false;
22509 String packageName = null;
22510 ArraySet<String> permissionNames = null;
22513 while (opti < args.length) {
22514 String opt = args[opti];
22515 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22520 if ("-a".equals(opt)) {
22521 // Right now we only know how to print all.
22522 } else if ("-h".equals(opt)) {
22523 pw.println("Package manager dump options:");
22524 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
22525 pw.println(" --checkin: dump for a checkin");
22526 pw.println(" -f: print details of intent filters");
22527 pw.println(" -h: print this help");
22528 pw.println(" cmd may be one of:");
22529 pw.println(" l[ibraries]: list known shared libraries");
22530 pw.println(" f[eatures]: list device features");
22531 pw.println(" k[eysets]: print known keysets");
22532 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22533 pw.println(" perm[issions]: dump permissions");
22534 pw.println(" permission [name ...]: dump declaration and use of given permission");
22535 pw.println(" pref[erred]: print preferred package settings");
22536 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
22537 pw.println(" prov[iders]: dump content providers");
22538 pw.println(" p[ackages]: dump installed packages");
22539 pw.println(" s[hared-users]: dump shared user IDs");
22540 pw.println(" m[essages]: print collected runtime messages");
22541 pw.println(" v[erifiers]: print package verifier info");
22542 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
22543 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22544 pw.println(" version: print database version info");
22545 pw.println(" write: write current settings now");
22546 pw.println(" installs: details about install sessions");
22547 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
22548 pw.println(" dexopt: dump dexopt state");
22549 pw.println(" compiler-stats: dump compiler statistics");
22550 pw.println(" enabled-overlays: dump list of enabled overlay packages");
22551 pw.println(" <package.name>: info about given package");
22553 } else if ("--checkin".equals(opt)) {
22555 } else if ("-f".equals(opt)) {
22556 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22557 } else if ("--proto".equals(opt)) {
22561 pw.println("Unknown argument: " + opt + "; use -h for help");
22565 // Is the caller requesting to dump a particular piece of data?
22566 if (opti < args.length) {
22567 String cmd = args[opti];
22569 // Is this a package name?
22570 if ("android".equals(cmd) || cmd.contains(".")) {
22572 // When dumping a single package, we always dump all of its
22573 // filter information since the amount of data will be reasonable.
22574 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22575 } else if ("check-permission".equals(cmd)) {
22576 if (opti >= args.length) {
22577 pw.println("Error: check-permission missing permission argument");
22580 String perm = args[opti];
22582 if (opti >= args.length) {
22583 pw.println("Error: check-permission missing package argument");
22587 String pkg = args[opti];
22589 int user = UserHandle.getUserId(Binder.getCallingUid());
22590 if (opti < args.length) {
22592 user = Integer.parseInt(args[opti]);
22593 } catch (NumberFormatException e) {
22594 pw.println("Error: check-permission user argument is not a number: "
22600 // Normalize package name to handle renamed packages and static libs
22601 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22603 pw.println(checkPermission(perm, pkg, user));
22605 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22606 dumpState.setDump(DumpState.DUMP_LIBS);
22607 } else if ("f".equals(cmd) || "features".equals(cmd)) {
22608 dumpState.setDump(DumpState.DUMP_FEATURES);
22609 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22610 if (opti >= args.length) {
22611 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22612 | DumpState.DUMP_SERVICE_RESOLVERS
22613 | DumpState.DUMP_RECEIVER_RESOLVERS
22614 | DumpState.DUMP_CONTENT_RESOLVERS);
22616 while (opti < args.length) {
22617 String name = args[opti];
22618 if ("a".equals(name) || "activity".equals(name)) {
22619 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22620 } else if ("s".equals(name) || "service".equals(name)) {
22621 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22622 } else if ("r".equals(name) || "receiver".equals(name)) {
22623 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22624 } else if ("c".equals(name) || "content".equals(name)) {
22625 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22627 pw.println("Error: unknown resolver table type: " + name);
22633 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22634 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22635 } else if ("permission".equals(cmd)) {
22636 if (opti >= args.length) {
22637 pw.println("Error: permission requires permission name");
22640 permissionNames = new ArraySet<>();
22641 while (opti < args.length) {
22642 permissionNames.add(args[opti]);
22645 dumpState.setDump(DumpState.DUMP_PERMISSIONS
22646 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22647 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22648 dumpState.setDump(DumpState.DUMP_PREFERRED);
22649 } else if ("preferred-xml".equals(cmd)) {
22650 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22651 if (opti < args.length && "--full".equals(args[opti])) {
22652 fullPreferred = true;
22655 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22656 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22657 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22658 dumpState.setDump(DumpState.DUMP_PACKAGES);
22659 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22660 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22661 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22662 dumpState.setDump(DumpState.DUMP_PROVIDERS);
22663 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22664 dumpState.setDump(DumpState.DUMP_MESSAGES);
22665 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22666 dumpState.setDump(DumpState.DUMP_VERIFIERS);
22667 } else if ("i".equals(cmd) || "ifv".equals(cmd)
22668 || "intent-filter-verifiers".equals(cmd)) {
22669 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22670 } else if ("version".equals(cmd)) {
22671 dumpState.setDump(DumpState.DUMP_VERSION);
22672 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22673 dumpState.setDump(DumpState.DUMP_KEYSETS);
22674 } else if ("installs".equals(cmd)) {
22675 dumpState.setDump(DumpState.DUMP_INSTALLS);
22676 } else if ("frozen".equals(cmd)) {
22677 dumpState.setDump(DumpState.DUMP_FROZEN);
22678 } else if ("volumes".equals(cmd)) {
22679 dumpState.setDump(DumpState.DUMP_VOLUMES);
22680 } else if ("dexopt".equals(cmd)) {
22681 dumpState.setDump(DumpState.DUMP_DEXOPT);
22682 } else if ("compiler-stats".equals(cmd)) {
22683 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22684 } else if ("changes".equals(cmd)) {
22685 dumpState.setDump(DumpState.DUMP_CHANGES);
22686 } else if ("write".equals(cmd)) {
22687 synchronized (mPackages) {
22688 mSettings.writeLPr();
22689 pw.println("Settings written.");
22696 pw.println("vers,1");
22700 synchronized (mPackages) {
22701 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22703 if (dumpState.onTitlePrinted())
22705 pw.println("Database versions:");
22706 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
22710 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22712 if (dumpState.onTitlePrinted())
22714 pw.println("Verifiers:");
22715 pw.print(" Required: ");
22716 pw.print(mRequiredVerifierPackage);
22717 pw.print(" (uid=");
22718 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22719 UserHandle.USER_SYSTEM));
22721 } else if (mRequiredVerifierPackage != null) {
22722 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22724 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22725 UserHandle.USER_SYSTEM));
22729 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22730 packageName == null) {
22731 if (mIntentFilterVerifierComponent != null) {
22732 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22734 if (dumpState.onTitlePrinted())
22736 pw.println("Intent Filter Verifier:");
22737 pw.print(" Using: ");
22738 pw.print(verifierPackageName);
22739 pw.print(" (uid=");
22740 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22741 UserHandle.USER_SYSTEM));
22743 } else if (verifierPackageName != null) {
22744 pw.print("ifv,"); pw.print(verifierPackageName);
22746 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22747 UserHandle.USER_SYSTEM));
22751 pw.println("No Intent Filter Verifier available!");
22755 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22756 boolean printedHeader = false;
22757 final Iterator<String> it = mSharedLibraries.keySet().iterator();
22758 while (it.hasNext()) {
22759 String libName = it.next();
22760 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22761 if (versionedLib == null) {
22764 final int versionCount = versionedLib.size();
22765 for (int i = 0; i < versionCount; i++) {
22766 SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22768 if (!printedHeader) {
22769 if (dumpState.onTitlePrinted())
22771 pw.println("Libraries:");
22772 printedHeader = true;
22778 pw.print(libEntry.info.getName());
22779 if (libEntry.info.isStatic()) {
22780 pw.print(" version=" + libEntry.info.getVersion());
22785 if (libEntry.path != null) {
22786 pw.print(" (jar) ");
22787 pw.print(libEntry.path);
22789 pw.print(" (apk) ");
22790 pw.print(libEntry.apk);
22797 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22798 if (dumpState.onTitlePrinted())
22801 pw.println("Features:");
22804 synchronized (mAvailableFeatures) {
22805 for (FeatureInfo feat : mAvailableFeatures.values()) {
22808 pw.print(feat.name);
22810 pw.println(feat.version);
22813 pw.print(feat.name);
22814 if (feat.version > 0) {
22815 pw.print(" version=");
22816 pw.print(feat.version);
22824 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22825 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22826 : "Activity Resolver Table:", " ", packageName,
22827 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22828 dumpState.setTitlePrinted(true);
22831 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22832 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22833 : "Receiver Resolver Table:", " ", packageName,
22834 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22835 dumpState.setTitlePrinted(true);
22838 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22839 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22840 : "Service Resolver Table:", " ", packageName,
22841 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22842 dumpState.setTitlePrinted(true);
22845 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22846 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22847 : "Provider Resolver Table:", " ", packageName,
22848 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22849 dumpState.setTitlePrinted(true);
22853 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22854 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22855 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22856 int user = mSettings.mPreferredActivities.keyAt(i);
22858 dumpState.getTitlePrinted()
22859 ? "\nPreferred Activities User " + user + ":"
22860 : "Preferred Activities User " + user + ":", " ",
22861 packageName, true, false)) {
22862 dumpState.setTitlePrinted(true);
22867 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22869 FileOutputStream fout = new FileOutputStream(fd);
22870 BufferedOutputStream str = new BufferedOutputStream(fout);
22871 XmlSerializer serializer = new FastXmlSerializer();
22873 serializer.setOutput(str, StandardCharsets.UTF_8.name());
22874 serializer.startDocument(null, true);
22875 serializer.setFeature(
22876 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22877 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22878 serializer.endDocument();
22879 serializer.flush();
22880 } catch (IllegalArgumentException e) {
22881 pw.println("Failed writing: " + e);
22882 } catch (IllegalStateException e) {
22883 pw.println("Failed writing: " + e);
22884 } catch (IOException e) {
22885 pw.println("Failed writing: " + e);
22890 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22891 && packageName == null) {
22893 int count = mSettings.mPackages.size();
22895 pw.println("No applications!");
22898 final String prefix = " ";
22899 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22900 if (allPackageSettings.size() == 0) {
22901 pw.println("No domain preferred apps!");
22904 pw.println("App verification status:");
22907 for (PackageSetting ps : allPackageSettings) {
22908 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22909 if (ivi == null || ivi.getPackageName() == null) continue;
22910 pw.println(prefix + "Package: " + ivi.getPackageName());
22911 pw.println(prefix + "Domains: " + ivi.getDomainsString());
22912 pw.println(prefix + "Status: " + ivi.getStatusString());
22917 pw.println(prefix + "No app verification established.");
22920 for (int userId : sUserManager.getUserIds()) {
22921 pw.println("App linkages for user " + userId + ":");
22924 for (PackageSetting ps : allPackageSettings) {
22925 final long status = ps.getDomainVerificationStatusForUser(userId);
22926 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22927 && !DEBUG_DOMAIN_VERIFICATION) {
22930 pw.println(prefix + "Package: " + ps.name);
22931 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22932 String statusStr = IntentFilterVerificationInfo.
22933 getStatusStringFromValue(status);
22934 pw.println(prefix + "Status: " + statusStr);
22939 pw.println(prefix + "No configured app linkages.");
22947 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22948 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22949 if (packageName == null && permissionNames == null) {
22950 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22952 if (dumpState.onTitlePrinted())
22954 pw.println("AppOp Permissions:");
22956 pw.print(" AppOp Permission ");
22957 pw.print(mAppOpPermissionPackages.keyAt(iperm));
22959 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22960 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22961 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
22967 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22968 boolean printedSomething = false;
22969 for (PackageParser.Provider p : mProviders.mProviders.values()) {
22970 if (packageName != null && !packageName.equals(p.info.packageName)) {
22973 if (!printedSomething) {
22974 if (dumpState.onTitlePrinted())
22976 pw.println("Registered ContentProviders:");
22977 printedSomething = true;
22979 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
22980 pw.print(" "); pw.println(p.toString());
22982 printedSomething = false;
22983 for (Map.Entry<String, PackageParser.Provider> entry :
22984 mProvidersByAuthority.entrySet()) {
22985 PackageParser.Provider p = entry.getValue();
22986 if (packageName != null && !packageName.equals(p.info.packageName)) {
22989 if (!printedSomething) {
22990 if (dumpState.onTitlePrinted())
22992 pw.println("ContentProvider Authorities:");
22993 printedSomething = true;
22995 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
22996 pw.print(" "); pw.println(p.toString());
22997 if (p.info != null && p.info.applicationInfo != null) {
22998 final String appInfo = p.info.applicationInfo.toString();
22999 pw.print(" applicationInfo="); pw.println(appInfo);
23004 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23005 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23008 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23009 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23012 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23013 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23016 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23017 if (dumpState.onTitlePrinted()) pw.println();
23018 pw.println("Package Changes:");
23019 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23020 final int K = mChangedPackages.size();
23021 for (int i = 0; i < K; i++) {
23022 final SparseArray<String> changes = mChangedPackages.valueAt(i);
23023 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23024 final int N = changes.size();
23026 pw.print(" "); pw.println("No packages changed");
23028 for (int j = 0; j < N; j++) {
23029 final String pkgName = changes.valueAt(j);
23030 final int sequenceNumber = changes.keyAt(j);
23033 pw.print(sequenceNumber);
23034 pw.print(", package=");
23035 pw.println(pkgName);
23041 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23042 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23045 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23046 // XXX should handle packageName != null by dumping only install data that
23047 // the given package is involved with.
23048 if (dumpState.onTitlePrinted()) pw.println();
23050 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
23052 ipw.println("Frozen packages:");
23053 ipw.increaseIndent();
23054 if (mFrozenPackages.size() == 0) {
23055 ipw.println("(none)");
23057 for (int i = 0; i < mFrozenPackages.size(); i++) {
23058 ipw.println(mFrozenPackages.valueAt(i));
23061 ipw.decreaseIndent();
23064 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23065 if (dumpState.onTitlePrinted()) pw.println();
23067 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
23069 ipw.println("Loaded volumes:");
23070 ipw.increaseIndent();
23071 if (mLoadedVolumes.size() == 0) {
23072 ipw.println("(none)");
23074 for (int i = 0; i < mLoadedVolumes.size(); i++) {
23075 ipw.println(mLoadedVolumes.valueAt(i));
23078 ipw.decreaseIndent();
23081 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23082 if (dumpState.onTitlePrinted()) pw.println();
23083 dumpDexoptStateLPr(pw, packageName);
23086 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23087 if (dumpState.onTitlePrinted()) pw.println();
23088 dumpCompilerStatsLPr(pw, packageName);
23091 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23092 if (dumpState.onTitlePrinted()) pw.println();
23093 mSettings.dumpReadMessagesLPr(pw, dumpState);
23096 pw.println("Package warning messages:");
23097 BufferedReader in = null;
23098 String line = null;
23100 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23101 while ((line = in.readLine()) != null) {
23102 if (line.contains("ignored: updated version")) continue;
23105 } catch (IOException ignored) {
23107 IoUtils.closeQuietly(in);
23111 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23112 BufferedReader in = null;
23113 String line = null;
23115 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23116 while ((line = in.readLine()) != null) {
23117 if (line.contains("ignored: updated version")) continue;
23121 } catch (IOException ignored) {
23123 IoUtils.closeQuietly(in);
23128 // PackageInstaller should be called outside of mPackages lock
23129 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23130 // XXX should handle packageName != null by dumping only install data that
23131 // the given package is involved with.
23132 if (dumpState.onTitlePrinted()) pw.println();
23133 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
23137 private void dumpProto(FileDescriptor fd) {
23138 final ProtoOutputStream proto = new ProtoOutputStream(fd);
23140 synchronized (mPackages) {
23141 final long requiredVerifierPackageToken =
23142 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23143 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23145 PackageServiceDumpProto.PackageShortProto.UID,
23147 mRequiredVerifierPackage,
23148 MATCH_DEBUG_TRIAGED_MISSING,
23149 UserHandle.USER_SYSTEM));
23150 proto.end(requiredVerifierPackageToken);
23152 if (mIntentFilterVerifierComponent != null) {
23153 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23154 final long verifierPackageToken =
23155 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23156 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23158 PackageServiceDumpProto.PackageShortProto.UID,
23160 verifierPackageName,
23161 MATCH_DEBUG_TRIAGED_MISSING,
23162 UserHandle.USER_SYSTEM));
23163 proto.end(verifierPackageToken);
23166 dumpSharedLibrariesProto(proto);
23167 dumpFeaturesProto(proto);
23168 mSettings.dumpPackagesProto(proto);
23169 mSettings.dumpSharedUsersProto(proto);
23170 dumpMessagesProto(proto);
23175 private void dumpMessagesProto(ProtoOutputStream proto) {
23176 BufferedReader in = null;
23177 String line = null;
23179 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23180 while ((line = in.readLine()) != null) {
23181 if (line.contains("ignored: updated version")) continue;
23182 proto.write(PackageServiceDumpProto.MESSAGES, line);
23184 } catch (IOException ignored) {
23186 IoUtils.closeQuietly(in);
23190 private void dumpFeaturesProto(ProtoOutputStream proto) {
23191 synchronized (mAvailableFeatures) {
23192 final int count = mAvailableFeatures.size();
23193 for (int i = 0; i < count; i++) {
23194 final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23195 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23196 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23197 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23198 proto.end(featureToken);
23203 private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23204 final int count = mSharedLibraries.size();
23205 for (int i = 0; i < count; i++) {
23206 final String libName = mSharedLibraries.keyAt(i);
23207 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23208 if (versionedLib == null) {
23211 final int versionCount = versionedLib.size();
23212 for (int j = 0; j < versionCount; j++) {
23213 final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23214 final long sharedLibraryToken =
23215 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23216 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23217 final boolean isJar = (libEntry.path != null);
23218 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23220 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23222 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23224 proto.end(sharedLibraryToken);
23229 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23230 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
23232 ipw.println("Dexopt state:");
23233 ipw.increaseIndent();
23234 Collection<PackageParser.Package> packages = null;
23235 if (packageName != null) {
23236 PackageParser.Package targetPackage = mPackages.get(packageName);
23237 if (targetPackage != null) {
23238 packages = Collections.singletonList(targetPackage);
23240 ipw.println("Unable to find package: " + packageName);
23244 packages = mPackages.values();
23247 for (PackageParser.Package pkg : packages) {
23248 ipw.println("[" + pkg.packageName + "]");
23249 ipw.increaseIndent();
23250 mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23251 mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23252 ipw.decreaseIndent();
23256 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23257 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
23259 ipw.println("Compiler stats:");
23260 ipw.increaseIndent();
23261 Collection<PackageParser.Package> packages = null;
23262 if (packageName != null) {
23263 PackageParser.Package targetPackage = mPackages.get(packageName);
23264 if (targetPackage != null) {
23265 packages = Collections.singletonList(targetPackage);
23267 ipw.println("Unable to find package: " + packageName);
23271 packages = mPackages.values();
23274 for (PackageParser.Package pkg : packages) {
23275 ipw.println("[" + pkg.packageName + "]");
23276 ipw.increaseIndent();
23278 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23279 if (stats == null) {
23280 ipw.println("(No recorded stats)");
23284 ipw.decreaseIndent();
23288 private String dumpDomainString(String packageName) {
23289 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23291 List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23293 ArraySet<String> result = new ArraySet<>();
23294 if (iviList.size() > 0) {
23295 for (IntentFilterVerificationInfo ivi : iviList) {
23296 for (String host : ivi.getDomains()) {
23301 if (filters != null && filters.size() > 0) {
23302 for (IntentFilter filter : filters) {
23303 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23304 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23305 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23306 result.addAll(filter.getHostsList());
23311 StringBuilder sb = new StringBuilder(result.size() * 16);
23312 for (String domain : result) {
23313 if (sb.length() > 0) sb.append(" ");
23316 return sb.toString();
23319 // ------- apps on sdcard specific code -------
23320 static final boolean DEBUG_SD_INSTALL = false;
23322 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23324 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23326 private boolean mMediaMounted = false;
23328 static String getEncryptKey() {
23330 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23331 SD_ENCRYPTION_KEYSTORE_NAME);
23332 if (sdEncKey == null) {
23333 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23334 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23335 if (sdEncKey == null) {
23336 Slog.e(TAG, "Failed to create encryption keys");
23341 } catch (NoSuchAlgorithmException nsae) {
23342 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23344 } catch (IOException ioe) {
23345 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23351 * Update media status on PackageManager.
23354 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23355 enforceSystemOrRoot("Media status can only be updated by the system");
23356 // reader; this apparently protects mMediaMounted, but should probably
23357 // be a different lock in that case.
23358 synchronized (mPackages) {
23359 Log.i(TAG, "Updating external media status from "
23360 + (mMediaMounted ? "mounted" : "unmounted") + " to "
23361 + (mediaStatus ? "mounted" : "unmounted"));
23362 if (DEBUG_SD_INSTALL)
23363 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23364 + ", mMediaMounted=" + mMediaMounted);
23365 if (mediaStatus == mMediaMounted) {
23366 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23368 mHandler.sendMessage(msg);
23371 mMediaMounted = mediaStatus;
23373 // Queue up an async operation since the package installation may take a
23375 mHandler.post(new Runnable() {
23376 public void run() {
23377 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23383 * Called by StorageManagerService when the initial ASECs to scan are available.
23384 * Should block until all the ASEC containers are finished being scanned.
23386 public void scanAvailableAsecs() {
23387 updateExternalMediaStatusInner(true, false, false);
23391 * Collect information of applications on external media, map them against
23392 * existing containers and update information based on current mount status.
23393 * Please note that we always have to report status if reportStatus has been
23394 * set to true especially when unloading packages.
23396 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23397 boolean externalStorage) {
23398 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23399 int[] uidArr = EmptyArray.INT;
23401 final String[] list = PackageHelper.getSecureContainerList();
23402 if (ArrayUtils.isEmpty(list)) {
23403 Log.i(TAG, "No secure containers found");
23405 // Process list of secure containers and categorize them
23406 // as active or stale based on their package internal state.
23409 synchronized (mPackages) {
23410 for (String cid : list) {
23411 // Leave stages untouched for now; installer service owns them
23412 if (PackageInstallerService.isStageName(cid)) continue;
23414 if (DEBUG_SD_INSTALL)
23415 Log.i(TAG, "Processing container " + cid);
23416 String pkgName = getAsecPackageName(cid);
23417 if (pkgName == null) {
23418 Slog.i(TAG, "Found stale container " + cid + " with no package name");
23421 if (DEBUG_SD_INSTALL)
23422 Log.i(TAG, "Looking for pkg : " + pkgName);
23424 final PackageSetting ps = mSettings.mPackages.get(pkgName);
23426 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23431 * Skip packages that are not external if we're unmounting
23432 * external storage.
23434 if (externalStorage && !isMounted && !isExternal(ps)) {
23438 final AsecInstallArgs args = new AsecInstallArgs(cid,
23439 getAppDexInstructionSets(ps), ps.isForwardLocked());
23440 // The package status is changed only if the code path
23441 // matches between settings and the container id.
23442 if (ps.codePathString != null
23443 && ps.codePathString.startsWith(args.getCodePath())) {
23444 if (DEBUG_SD_INSTALL) {
23445 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23446 + " at code path: " + ps.codePathString);
23449 // We do have a valid package installed on sdcard
23450 processCids.put(args, ps.codePathString);
23451 final int uid = ps.appId;
23453 uidArr = ArrayUtils.appendInt(uidArr, uid);
23456 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23457 + ps.codePathString);
23462 Arrays.sort(uidArr);
23465 // Process packages with valid entries.
23467 if (DEBUG_SD_INSTALL)
23468 Log.i(TAG, "Loading packages");
23469 loadMediaPackages(processCids, uidArr, externalStorage);
23470 startCleaningPackages();
23471 mInstallerService.onSecureContainersAvailable();
23473 if (DEBUG_SD_INSTALL)
23474 Log.i(TAG, "Unloading packages");
23475 unloadMediaPackages(processCids, uidArr, reportStatus);
23479 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23480 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23481 final int size = infos.size();
23482 final String[] packageNames = new String[size];
23483 final int[] packageUids = new int[size];
23484 for (int i = 0; i < size; i++) {
23485 final ApplicationInfo info = infos.get(i);
23486 packageNames[i] = info.packageName;
23487 packageUids[i] = info.uid;
23489 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23493 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23494 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23495 sendResourcesChangedBroadcast(mediaStatus, replacing,
23496 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23499 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23500 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23501 int size = pkgList.length;
23503 // Send broadcasts here
23504 Bundle extras = new Bundle();
23505 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23506 if (uidArr != null) {
23507 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23510 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23512 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23513 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23514 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23519 * Look at potentially valid container ids from processCids If package
23520 * information doesn't match the one on record or package scanning fails,
23521 * the cid is added to list of removeCids. We currently don't delete stale
23524 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23525 boolean externalStorage) {
23526 ArrayList<String> pkgList = new ArrayList<String>();
23527 Set<AsecInstallArgs> keys = processCids.keySet();
23529 for (AsecInstallArgs args : keys) {
23530 String codePath = processCids.get(args);
23531 if (DEBUG_SD_INSTALL)
23532 Log.i(TAG, "Loading container : " + args.cid);
23533 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23535 // Make sure there are no container errors first.
23536 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23537 Slog.e(TAG, "Failed to mount cid : " + args.cid
23538 + " when installing from sdcard");
23541 // Check code path here.
23542 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23543 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23544 + " does not match one in settings " + codePath);
23548 int parseFlags = mDefParseFlags;
23549 if (args.isExternalAsec()) {
23550 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23552 if (args.isFwdLocked()) {
23553 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23556 synchronized (mInstallLock) {
23557 PackageParser.Package pkg = null;
23559 // Sadly we don't know the package name yet to freeze it
23560 pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23561 SCAN_IGNORE_FROZEN, 0, null);
23562 } catch (PackageManagerException e) {
23563 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23565 // Scan the package
23568 * TODO why is the lock being held? doPostInstall is
23569 * called in other places without the lock. This needs
23570 * to be straightened out.
23573 synchronized (mPackages) {
23574 retCode = PackageManager.INSTALL_SUCCEEDED;
23575 pkgList.add(pkg.packageName);
23576 // Post process args
23577 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23578 pkg.applicationInfo.uid);
23581 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
23586 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23587 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23592 synchronized (mPackages) {
23593 // If the platform SDK has changed since the last time we booted,
23594 // we need to re-grant app permission to catch any new ones that
23595 // appear. This is really a hack, and means that apps can in some
23596 // cases get permissions that the user didn't initially explicitly
23597 // allow... it would be nice to have some better way to handle
23599 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23600 : mSettings.getInternalVersion();
23601 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23602 : StorageManager.UUID_PRIVATE_INTERNAL;
23604 int updateFlags = UPDATE_PERMISSIONS_ALL;
23605 if (ver.sdkVersion != mSdkVersion) {
23606 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23607 + mSdkVersion + "; regranting permissions for external");
23608 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23610 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23612 // Yay, everything is now upgraded
23613 ver.forceCurrent();
23615 // can downgrade to reader
23616 // Persist settings
23617 mSettings.writeLPr();
23619 // Send a broadcast to let everyone know we are done processing
23620 if (pkgList.size() > 0) {
23621 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23626 * Utility method to unload a list of specified containers
23628 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23629 // Just unmount all valid containers.
23630 for (AsecInstallArgs arg : cidArgs) {
23631 synchronized (mInstallLock) {
23632 arg.doPostDeleteLI(false);
23638 * Unload packages mounted on external media. This involves deleting package
23639 * data from internal structures, sending broadcasts about disabled packages,
23640 * gc'ing to free up references, unmounting all secure containers
23641 * corresponding to packages on external media, and posting a
23642 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23643 * that we always have to post this message if status has been requested no
23646 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23647 final boolean reportStatus) {
23648 if (DEBUG_SD_INSTALL)
23649 Log.i(TAG, "unloading media packages");
23650 ArrayList<String> pkgList = new ArrayList<String>();
23651 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23652 final Set<AsecInstallArgs> keys = processCids.keySet();
23653 for (AsecInstallArgs args : keys) {
23654 String pkgName = args.getPackageName();
23655 if (DEBUG_SD_INSTALL)
23656 Log.i(TAG, "Trying to unload pkg : " + pkgName);
23657 // Delete package internally
23658 PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23659 synchronized (mInstallLock) {
23660 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23662 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23663 "unloadMediaPackages")) {
23664 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23668 pkgList.add(pkgName);
23670 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23671 failedList.add(args);
23677 synchronized (mPackages) {
23678 // We didn't update the settings after removing each package;
23679 // write them now for all packages.
23680 mSettings.writeLPr();
23683 // We have to absolutely send UPDATED_MEDIA_STATUS only
23684 // after confirming that all the receivers processed the ordered
23685 // broadcast when packages get disabled, force a gc to clean things up.
23686 // and unload all the containers.
23687 if (pkgList.size() > 0) {
23688 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23689 new IIntentReceiver.Stub() {
23690 public void performReceive(Intent intent, int resultCode, String data,
23691 Bundle extras, boolean ordered, boolean sticky,
23692 int sendingUser) throws RemoteException {
23693 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23694 reportStatus ? 1 : 0, 1, keys);
23695 mHandler.sendMessage(msg);
23699 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23701 mHandler.sendMessage(msg);
23705 private void loadPrivatePackages(final VolumeInfo vol) {
23706 mHandler.post(new Runnable() {
23708 public void run() {
23709 loadPrivatePackagesInner(vol);
23714 private void loadPrivatePackagesInner(VolumeInfo vol) {
23715 final String volumeUuid = vol.fsUuid;
23716 if (TextUtils.isEmpty(volumeUuid)) {
23717 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23721 final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23722 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23723 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23725 final VersionInfo ver;
23726 final List<PackageSetting> packages;
23727 synchronized (mPackages) {
23728 ver = mSettings.findOrCreateVersion(volumeUuid);
23729 packages = mSettings.getVolumePackagesLPr(volumeUuid);
23732 for (PackageSetting ps : packages) {
23733 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23734 synchronized (mInstallLock) {
23735 final PackageParser.Package pkg;
23737 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23738 loaded.add(pkg.applicationInfo);
23740 } catch (PackageManagerException e) {
23741 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23744 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23745 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23746 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23747 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23752 // Reconcile app data for all started/unlocked users
23753 final StorageManager sm = mContext.getSystemService(StorageManager.class);
23754 final UserManager um = mContext.getSystemService(UserManager.class);
23755 UserManagerInternal umInternal = getUserManagerInternal();
23756 for (UserInfo user : um.getUsers()) {
23758 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23759 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23760 } else if (umInternal.isUserRunning(user.id)) {
23761 flags = StorageManager.FLAG_STORAGE_DE;
23767 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23768 synchronized (mInstallLock) {
23769 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23771 } catch (IllegalStateException e) {
23772 // Device was probably ejected, and we'll process that event momentarily
23773 Slog.w(TAG, "Failed to prepare storage: " + e);
23777 synchronized (mPackages) {
23778 int updateFlags = UPDATE_PERMISSIONS_ALL;
23779 if (ver.sdkVersion != mSdkVersion) {
23780 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23781 + mSdkVersion + "; regranting permissions for " + volumeUuid);
23782 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23784 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23786 // Yay, everything is now upgraded
23787 ver.forceCurrent();
23789 mSettings.writeLPr();
23792 for (PackageFreezer freezer : freezers) {
23796 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23797 sendResourcesChangedBroadcast(true, false, loaded, null);
23798 mLoadedVolumes.add(vol.getId());
23801 private void unloadPrivatePackages(final VolumeInfo vol) {
23802 mHandler.post(new Runnable() {
23804 public void run() {
23805 unloadPrivatePackagesInner(vol);
23810 private void unloadPrivatePackagesInner(VolumeInfo vol) {
23811 final String volumeUuid = vol.fsUuid;
23812 if (TextUtils.isEmpty(volumeUuid)) {
23813 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23817 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23818 synchronized (mInstallLock) {
23819 synchronized (mPackages) {
23820 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23821 for (PackageSetting ps : packages) {
23822 if (ps.pkg == null) continue;
23824 final ApplicationInfo info = ps.pkg.applicationInfo;
23825 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23826 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23828 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23829 "unloadPrivatePackagesInner")) {
23830 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23832 unloaded.add(info);
23834 Slog.w(TAG, "Failed to unload " + ps.codePath);
23838 // Try very hard to release any references to this package
23839 // so we don't risk the system server being killed due to
23841 AttributeCache.instance().removePackage(ps.name);
23844 mSettings.writeLPr();
23848 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23849 sendResourcesChangedBroadcast(false, false, unloaded, null);
23850 mLoadedVolumes.remove(vol.getId());
23852 // Try very hard to release any references to this path so we don't risk
23853 // the system server being killed due to open FDs
23854 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23856 for (int i = 0; i < 3; i++) {
23858 System.runFinalization();
23862 private void assertPackageKnown(String volumeUuid, String packageName)
23863 throws PackageManagerException {
23864 synchronized (mPackages) {
23865 // Normalize package name to handle renamed packages
23866 packageName = normalizePackageNameLPr(packageName);
23868 final PackageSetting ps = mSettings.mPackages.get(packageName);
23870 throw new PackageManagerException("Package " + packageName + " is unknown");
23871 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23872 throw new PackageManagerException(
23873 "Package " + packageName + " found on unknown volume " + volumeUuid
23874 + "; expected volume " + ps.volumeUuid);
23879 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23880 throws PackageManagerException {
23881 synchronized (mPackages) {
23882 // Normalize package name to handle renamed packages
23883 packageName = normalizePackageNameLPr(packageName);
23885 final PackageSetting ps = mSettings.mPackages.get(packageName);
23887 throw new PackageManagerException("Package " + packageName + " is unknown");
23888 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23889 throw new PackageManagerException(
23890 "Package " + packageName + " found on unknown volume " + volumeUuid
23891 + "; expected volume " + ps.volumeUuid);
23892 } else if (!ps.getInstalled(userId)) {
23893 throw new PackageManagerException(
23894 "Package " + packageName + " not installed for user " + userId);
23899 private List<String> collectAbsoluteCodePaths() {
23900 synchronized (mPackages) {
23901 List<String> codePaths = new ArrayList<>();
23902 final int packageCount = mSettings.mPackages.size();
23903 for (int i = 0; i < packageCount; i++) {
23904 final PackageSetting ps = mSettings.mPackages.valueAt(i);
23905 codePaths.add(ps.codePath.getAbsolutePath());
23912 * Examine all apps present on given mounted volume, and destroy apps that
23913 * aren't expected, either due to uninstallation or reinstallation on
23916 private void reconcileApps(String volumeUuid) {
23917 List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23918 List<File> filesToDelete = null;
23920 final File[] files = FileUtils.listFilesOrEmpty(
23921 Environment.getDataAppDirectory(volumeUuid));
23922 for (File file : files) {
23923 final boolean isPackage = (isApkFile(file) || file.isDirectory())
23924 && !PackageInstallerService.isStageName(file.getName());
23926 // Ignore entries which are not packages
23930 String absolutePath = file.getAbsolutePath();
23932 boolean pathValid = false;
23933 final int absoluteCodePathCount = absoluteCodePaths.size();
23934 for (int i = 0; i < absoluteCodePathCount; i++) {
23935 String absoluteCodePath = absoluteCodePaths.get(i);
23936 if (absolutePath.startsWith(absoluteCodePath)) {
23943 if (filesToDelete == null) {
23944 filesToDelete = new ArrayList<>();
23946 filesToDelete.add(file);
23950 if (filesToDelete != null) {
23951 final int fileToDeleteCount = filesToDelete.size();
23952 for (int i = 0; i < fileToDeleteCount; i++) {
23953 File fileToDelete = filesToDelete.get(i);
23954 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23955 synchronized (mInstallLock) {
23956 removeCodePathLI(fileToDelete);
23963 * Reconcile all app data for the given user.
23965 * Verifies that directories exist and that ownership and labeling is
23966 * correct for all installed apps on all mounted volumes.
23968 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23969 final StorageManager storage = mContext.getSystemService(StorageManager.class);
23970 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23971 final String volumeUuid = vol.getFsUuid();
23972 synchronized (mInstallLock) {
23973 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23978 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23979 boolean migrateAppData) {
23980 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23984 * Reconcile all app data on given mounted volume.
23986 * Destroys app data that isn't expected, either due to uninstallation or
23987 * reinstallation on another volume.
23989 * Verifies that directories exist and that ownership and labeling is
23990 * correct for all installed apps.
23991 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23993 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23994 boolean migrateAppData, boolean onlyCoreApps) {
23995 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23996 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23997 List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23999 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24000 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24002 // First look for stale data that doesn't belong, and check if things
24003 // have changed since we did our last restorecon
24004 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24005 if (StorageManager.isFileEncryptedNativeOrEmulated()
24006 && !StorageManager.isUserKeyUnlocked(userId)) {
24007 throw new RuntimeException(
24008 "Yikes, someone asked us to reconcile CE storage while " + userId
24009 + " was still locked; this would have caused massive data loss!");
24012 final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24013 for (File file : files) {
24014 final String packageName = file.getName();
24016 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24017 } catch (PackageManagerException e) {
24018 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24020 mInstaller.destroyAppData(volumeUuid, packageName, userId,
24021 StorageManager.FLAG_STORAGE_CE, 0);
24022 } catch (InstallerException e2) {
24023 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24028 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24029 final File[] files = FileUtils.listFilesOrEmpty(deDir);
24030 for (File file : files) {
24031 final String packageName = file.getName();
24033 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24034 } catch (PackageManagerException e) {
24035 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24037 mInstaller.destroyAppData(volumeUuid, packageName, userId,
24038 StorageManager.FLAG_STORAGE_DE, 0);
24039 } catch (InstallerException e2) {
24040 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24046 // Ensure that data directories are ready to roll for all packages
24047 // installed for this volume and user
24048 final List<PackageSetting> packages;
24049 synchronized (mPackages) {
24050 packages = mSettings.getVolumePackagesLPr(volumeUuid);
24052 int preparedCount = 0;
24053 for (PackageSetting ps : packages) {
24054 final String packageName = ps.name;
24055 if (ps.pkg == null) {
24056 Slog.w(TAG, "Odd, missing scanned package " + packageName);
24057 // TODO: might be due to legacy ASEC apps; we should circle back
24058 // and reconcile again once they're scanned
24061 // Skip non-core apps if requested
24062 if (onlyCoreApps && !ps.pkg.coreApp) {
24063 result.add(packageName);
24067 if (ps.getInstalled(userId)) {
24068 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24073 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24078 * Prepare app data for the given app just after it was installed or
24079 * upgraded. This method carefully only touches users that it's installed
24080 * for, and it forces a restorecon to handle any seinfo changes.
24082 * Verifies that directories exist and that ownership and labeling is
24083 * correct for all installed apps. If there is an ownership mismatch, it
24084 * will try recovering system apps by wiping data; third-party app data is
24087 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24089 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24090 final PackageSetting ps;
24091 synchronized (mPackages) {
24092 ps = mSettings.mPackages.get(pkg.packageName);
24093 mSettings.writeKernelMappingLPr(ps);
24096 final UserManager um = mContext.getSystemService(UserManager.class);
24097 UserManagerInternal umInternal = getUserManagerInternal();
24098 for (UserInfo user : um.getUsers()) {
24100 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24101 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24102 } else if (umInternal.isUserRunning(user.id)) {
24103 flags = StorageManager.FLAG_STORAGE_DE;
24108 if (ps.getInstalled(user.id)) {
24109 // TODO: when user data is locked, mark that we're still dirty
24110 prepareAppDataLIF(pkg, user.id, flags);
24116 * Prepare app data for the given app.
24118 * Verifies that directories exist and that ownership and labeling is
24119 * correct for all installed apps. If there is an ownership mismatch, this
24120 * will try recovering system apps by wiping data; third-party app data is
24123 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24125 Slog.wtf(TAG, "Package was null!", new Throwable());
24128 prepareAppDataLeafLIF(pkg, userId, flags);
24129 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24130 for (int i = 0; i < childCount; i++) {
24131 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24135 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24136 boolean maybeMigrateAppData) {
24137 prepareAppDataLIF(pkg, userId, flags);
24139 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24140 // We may have just shuffled around app data directories, so
24141 // prepare them one more time
24142 prepareAppDataLIF(pkg, userId, flags);
24146 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24147 if (DEBUG_APP_DATA) {
24148 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24149 + Integer.toHexString(flags));
24152 final String volumeUuid = pkg.volumeUuid;
24153 final String packageName = pkg.packageName;
24154 final ApplicationInfo app = pkg.applicationInfo;
24155 final int appId = UserHandle.getAppId(app.uid);
24157 Preconditions.checkNotNull(app.seInfo);
24159 long ceDataInode = -1;
24161 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24162 appId, app.seInfo, app.targetSdkVersion);
24163 } catch (InstallerException e) {
24164 if (app.isSystemApp()) {
24165 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24166 + ", but trying to recover: " + e);
24167 destroyAppDataLeafLIF(pkg, userId, flags);
24169 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24170 appId, app.seInfo, app.targetSdkVersion);
24171 logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24172 } catch (InstallerException e2) {
24173 logCriticalInfo(Log.DEBUG, "Recovery failed!");
24176 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24180 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24181 // TODO: mark this structure as dirty so we persist it!
24182 synchronized (mPackages) {
24183 final PackageSetting ps = mSettings.mPackages.get(packageName);
24185 ps.setCeDataInode(ceDataInode, userId);
24190 prepareAppDataContentsLeafLIF(pkg, userId, flags);
24193 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24195 Slog.wtf(TAG, "Package was null!", new Throwable());
24198 prepareAppDataContentsLeafLIF(pkg, userId, flags);
24199 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24200 for (int i = 0; i < childCount; i++) {
24201 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24205 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24206 final String volumeUuid = pkg.volumeUuid;
24207 final String packageName = pkg.packageName;
24208 final ApplicationInfo app = pkg.applicationInfo;
24210 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24211 // Create a native library symlink only if we have native libraries
24212 // and if the native libraries are 32 bit libraries. We do not provide
24213 // this symlink for 64 bit libraries.
24214 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24215 final String nativeLibPath = app.nativeLibraryDir;
24217 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24218 nativeLibPath, userId);
24219 } catch (InstallerException e) {
24220 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24227 * For system apps on non-FBE devices, this method migrates any existing
24228 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24229 * requested by the app.
24231 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24232 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24233 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24234 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24235 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24237 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24239 } catch (InstallerException e) {
24240 logCriticalInfo(Log.WARN,
24241 "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24249 public PackageFreezer freezePackage(String packageName, String killReason) {
24250 return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24253 public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24254 return new PackageFreezer(packageName, userId, killReason);
24257 public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24258 String killReason) {
24259 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24262 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24263 String killReason) {
24264 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24265 return new PackageFreezer();
24267 return freezePackage(packageName, userId, killReason);
24271 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24272 String killReason) {
24273 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24276 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24277 String killReason) {
24278 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24279 return new PackageFreezer();
24281 return freezePackage(packageName, userId, killReason);
24286 * Class that freezes and kills the given package upon creation, and
24287 * unfreezes it upon closing. This is typically used when doing surgery on
24288 * app code/data to prevent the app from running while you're working.
24290 private class PackageFreezer implements AutoCloseable {
24291 private final String mPackageName;
24292 private final PackageFreezer[] mChildren;
24294 private final boolean mWeFroze;
24296 private final AtomicBoolean mClosed = new AtomicBoolean();
24297 private final CloseGuard mCloseGuard = CloseGuard.get();
24300 * Create and return a stub freezer that doesn't actually do anything,
24301 * typically used when someone requested
24302 * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24303 * {@link PackageManager#DELETE_DONT_KILL_APP}.
24305 public PackageFreezer() {
24306 mPackageName = null;
24309 mCloseGuard.open("close");
24312 public PackageFreezer(String packageName, int userId, String killReason) {
24313 synchronized (mPackages) {
24314 mPackageName = packageName;
24315 mWeFroze = mFrozenPackages.add(mPackageName);
24317 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24319 killApplication(ps.name, ps.appId, userId, killReason);
24322 final PackageParser.Package p = mPackages.get(packageName);
24323 if (p != null && p.childPackages != null) {
24324 final int N = p.childPackages.size();
24325 mChildren = new PackageFreezer[N];
24326 for (int i = 0; i < N; i++) {
24327 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24328 userId, killReason);
24334 mCloseGuard.open("close");
24338 protected void finalize() throws Throwable {
24340 if (mCloseGuard != null) {
24341 mCloseGuard.warnIfOpen();
24351 public void close() {
24352 mCloseGuard.close();
24353 if (mClosed.compareAndSet(false, true)) {
24354 synchronized (mPackages) {
24356 mFrozenPackages.remove(mPackageName);
24359 if (mChildren != null) {
24360 for (PackageFreezer freezer : mChildren) {
24370 * Verify that given package is currently frozen.
24372 private void checkPackageFrozen(String packageName) {
24373 synchronized (mPackages) {
24374 if (!mFrozenPackages.contains(packageName)) {
24375 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24381 public int movePackage(final String packageName, final String volumeUuid) {
24382 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24384 final int callingUid = Binder.getCallingUid();
24385 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24386 final int moveId = mNextMoveId.getAndIncrement();
24387 mHandler.post(new Runnable() {
24389 public void run() {
24391 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24392 } catch (PackageManagerException e) {
24393 Slog.w(TAG, "Failed to move " + packageName, e);
24394 mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24401 private void movePackageInternal(final String packageName, final String volumeUuid,
24402 final int moveId, final int callingUid, UserHandle user)
24403 throws PackageManagerException {
24404 final StorageManager storage = mContext.getSystemService(StorageManager.class);
24405 final PackageManager pm = mContext.getPackageManager();
24407 final boolean currentAsec;
24408 final String currentVolumeUuid;
24409 final File codeFile;
24410 final String installerPackageName;
24411 final String packageAbiOverride;
24413 final String seinfo;
24414 final String label;
24415 final int targetSdkVersion;
24416 final PackageFreezer freezer;
24417 final int[] installedUserIds;
24420 synchronized (mPackages) {
24421 final PackageParser.Package pkg = mPackages.get(packageName);
24422 final PackageSetting ps = mSettings.mPackages.get(packageName);
24425 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24426 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24428 if (pkg.applicationInfo.isSystemApp()) {
24429 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24430 "Cannot move system application");
24433 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24434 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24435 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24436 if (isInternalStorage && !allow3rdPartyOnInternal) {
24437 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24438 "3rd party apps are not allowed on internal storage");
24441 if (pkg.applicationInfo.isExternalAsec()) {
24442 currentAsec = true;
24443 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24444 } else if (pkg.applicationInfo.isForwardLocked()) {
24445 currentAsec = true;
24446 currentVolumeUuid = "forward_locked";
24448 currentAsec = false;
24449 currentVolumeUuid = ps.volumeUuid;
24451 final File probe = new File(pkg.codePath);
24452 final File probeOat = new File(probe, "oat");
24453 if (!probe.isDirectory() || !probeOat.isDirectory()) {
24454 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24455 "Move only supported for modern cluster style installs");
24459 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24460 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24461 "Package already moved to " + volumeUuid);
24463 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24464 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24465 "Device admin cannot be moved");
24468 if (mFrozenPackages.contains(packageName)) {
24469 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24470 "Failed to move already frozen package");
24473 codeFile = new File(pkg.codePath);
24474 installerPackageName = ps.installerPackageName;
24475 packageAbiOverride = ps.cpuAbiOverrideString;
24476 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24477 seinfo = pkg.applicationInfo.seInfo;
24478 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24479 targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24480 freezer = freezePackage(packageName, "movePackageInternal");
24481 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24484 final Bundle extras = new Bundle();
24485 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24486 extras.putString(Intent.EXTRA_TITLE, label);
24487 mMoveCallbacks.notifyCreated(moveId, extras);
24490 final boolean moveCompleteApp;
24491 final File measurePath;
24493 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24494 installFlags = INSTALL_INTERNAL;
24495 moveCompleteApp = !currentAsec;
24496 measurePath = Environment.getDataAppDirectory(volumeUuid);
24497 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24498 installFlags = INSTALL_EXTERNAL;
24499 moveCompleteApp = false;
24500 measurePath = storage.getPrimaryPhysicalVolume().getPath();
24502 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24503 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24504 || !volume.isMountedWritable()) {
24506 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24507 "Move location not mounted private volume");
24510 Preconditions.checkState(!currentAsec);
24512 installFlags = INSTALL_INTERNAL;
24513 moveCompleteApp = true;
24514 measurePath = Environment.getDataAppDirectory(volumeUuid);
24517 // If we're moving app data around, we need all the users unlocked
24518 if (moveCompleteApp) {
24519 for (int userId : installedUserIds) {
24520 if (StorageManager.isFileEncryptedNativeOrEmulated()
24521 && !StorageManager.isUserKeyUnlocked(userId)) {
24522 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24523 "User " + userId + " must be unlocked");
24528 final PackageStats stats = new PackageStats(null, -1);
24529 synchronized (mInstaller) {
24530 for (int userId : installedUserIds) {
24531 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24533 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24534 "Failed to measure package size");
24539 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24542 final long startFreeBytes = measurePath.getUsableSpace();
24543 final long sizeBytes;
24544 if (moveCompleteApp) {
24545 sizeBytes = stats.codeSize + stats.dataSize;
24547 sizeBytes = stats.codeSize;
24550 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24552 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24553 "Not enough free space to move");
24556 mMoveCallbacks.notifyStatusChanged(moveId, 10);
24558 final CountDownLatch installedLatch = new CountDownLatch(1);
24559 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24561 public void onUserActionRequired(Intent intent) throws RemoteException {
24562 throw new IllegalStateException();
24566 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24567 Bundle extras) throws RemoteException {
24568 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24569 + PackageManager.installStatusToString(returnCode, msg));
24571 installedLatch.countDown();
24574 final int status = PackageManager.installStatusToPublicStatus(returnCode);
24576 case PackageInstaller.STATUS_SUCCESS:
24577 mMoveCallbacks.notifyStatusChanged(moveId,
24578 PackageManager.MOVE_SUCCEEDED);
24580 case PackageInstaller.STATUS_FAILURE_STORAGE:
24581 mMoveCallbacks.notifyStatusChanged(moveId,
24582 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24585 mMoveCallbacks.notifyStatusChanged(moveId,
24586 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24592 final MoveInfo move;
24593 if (moveCompleteApp) {
24594 // Kick off a thread to report progress estimates
24597 public void run() {
24600 if (installedLatch.await(1, TimeUnit.SECONDS)) {
24603 } catch (InterruptedException ignored) {
24606 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24607 final int progress = 10 + (int) MathUtils.constrain(
24608 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24609 mMoveCallbacks.notifyStatusChanged(moveId, progress);
24614 final String dataAppName = codeFile.getName();
24615 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24616 dataAppName, appId, seinfo, targetSdkVersion);
24621 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24623 final Message msg = mHandler.obtainMessage(INIT_COPY);
24624 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24625 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24626 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24627 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24628 PackageManager.INSTALL_REASON_UNKNOWN);
24629 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24632 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24633 System.identityHashCode(msg.obj));
24634 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24635 System.identityHashCode(msg.obj));
24637 mHandler.sendMessage(msg);
24641 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24642 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24644 final int realMoveId = mNextMoveId.getAndIncrement();
24645 final Bundle extras = new Bundle();
24646 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24647 mMoveCallbacks.notifyCreated(realMoveId, extras);
24649 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24651 public void onCreated(int moveId, Bundle extras) {
24656 public void onStatusChanged(int moveId, int status, long estMillis) {
24657 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24661 final StorageManager storage = mContext.getSystemService(StorageManager.class);
24662 storage.setPrimaryStorageUuid(volumeUuid, callback);
24667 public int getMoveStatus(int moveId) {
24668 mContext.enforceCallingOrSelfPermission(
24669 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24670 return mMoveCallbacks.mLastStatus.get(moveId);
24674 public void registerMoveCallback(IPackageMoveObserver callback) {
24675 mContext.enforceCallingOrSelfPermission(
24676 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24677 mMoveCallbacks.register(callback);
24681 public void unregisterMoveCallback(IPackageMoveObserver callback) {
24682 mContext.enforceCallingOrSelfPermission(
24683 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24684 mMoveCallbacks.unregister(callback);
24688 public boolean setInstallLocation(int loc) {
24689 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24691 if (getInstallLocation() == loc) {
24694 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24695 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24696 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24697 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24704 public int getInstallLocation() {
24705 // allow instant app access
24706 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24707 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24708 PackageHelper.APP_INSTALL_AUTO);
24711 /** Called by UserManagerService */
24712 void cleanUpUser(UserManagerService userManager, int userHandle) {
24713 synchronized (mPackages) {
24714 mDirtyUsers.remove(userHandle);
24715 mUserNeedsBadging.delete(userHandle);
24716 mSettings.removeUserLPw(userHandle);
24717 mPendingBroadcasts.remove(userHandle);
24718 mInstantAppRegistry.onUserRemovedLPw(userHandle);
24719 removeUnusedPackagesLPw(userManager, userHandle);
24724 * We're removing userHandle and would like to remove any downloaded packages
24725 * that are no longer in use by any other user.
24726 * @param userHandle the user being removed
24728 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24729 final boolean DEBUG_CLEAN_APKS = false;
24730 int [] users = userManager.getUserIds();
24731 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24732 while (psit.hasNext()) {
24733 PackageSetting ps = psit.next();
24734 if (ps.pkg == null) {
24737 final String packageName = ps.pkg.packageName;
24738 // Skip over if system app
24739 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24742 if (DEBUG_CLEAN_APKS) {
24743 Slog.i(TAG, "Checking package " + packageName);
24745 boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24747 if (DEBUG_CLEAN_APKS) {
24748 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO");
24751 for (int i = 0; i < users.length; i++) {
24752 if (users[i] != userHandle && ps.getInstalled(users[i])) {
24754 if (DEBUG_CLEAN_APKS) {
24755 Slog.i(TAG, " Keeping package " + packageName + " for user "
24763 if (DEBUG_CLEAN_APKS) {
24764 Slog.i(TAG, " Removing package " + packageName);
24766 mHandler.post(new Runnable() {
24767 public void run() {
24768 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24776 /** Called by UserManagerService */
24777 void createNewUser(int userId, String[] disallowedPackages) {
24778 synchronized (mInstallLock) {
24779 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24781 synchronized (mPackages) {
24782 scheduleWritePackageRestrictionsLocked(userId);
24783 scheduleWritePackageListLocked(userId);
24784 applyFactoryDefaultBrowserLPw(userId);
24785 primeDomainVerificationsLPw(userId);
24789 void onNewUserCreated(final int userId) {
24790 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24791 // If permission review for legacy apps is required, we represent
24792 // dagerous permissions for such apps as always granted runtime
24793 // permissions to keep per user flag state whether review is needed.
24794 // Hence, if a new user is added we have to propagate dangerous
24795 // permission grants for these legacy apps.
24796 if (mPermissionReviewRequired) {
24797 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24798 | UPDATE_PERMISSIONS_REPLACE_ALL);
24803 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24804 mContext.enforceCallingOrSelfPermission(
24805 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24806 "Only package verification agents can read the verifier device identity");
24808 synchronized (mPackages) {
24809 return mSettings.getVerifierDeviceIdentityLPw();
24814 public void setPermissionEnforced(String permission, boolean enforced) {
24815 // TODO: Now that we no longer change GID for storage, this should to away.
24816 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24817 "setPermissionEnforced");
24818 if (READ_EXTERNAL_STORAGE.equals(permission)) {
24819 synchronized (mPackages) {
24820 if (mSettings.mReadExternalStorageEnforced == null
24821 || mSettings.mReadExternalStorageEnforced != enforced) {
24822 mSettings.mReadExternalStorageEnforced = enforced;
24823 mSettings.writeLPr();
24826 // kill any non-foreground processes so we restart them and
24827 // grant/revoke the GID.
24828 final IActivityManager am = ActivityManager.getService();
24830 final long token = Binder.clearCallingIdentity();
24832 am.killProcessesBelowForeground("setPermissionEnforcement");
24833 } catch (RemoteException e) {
24835 Binder.restoreCallingIdentity(token);
24839 throw new IllegalArgumentException("No selective enforcement for " + permission);
24845 public boolean isPermissionEnforced(String permission) {
24846 // allow instant applications
24851 public boolean isStorageLow() {
24852 // allow instant applications
24853 final long token = Binder.clearCallingIdentity();
24855 final DeviceStorageMonitorInternal
24856 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24858 return dsm.isMemoryLow();
24863 Binder.restoreCallingIdentity(token);
24868 public IPackageInstaller getPackageInstaller() {
24869 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24872 return mInstallerService;
24875 private boolean userNeedsBadging(int userId) {
24876 int index = mUserNeedsBadging.indexOfKey(userId);
24878 final UserInfo userInfo;
24879 final long token = Binder.clearCallingIdentity();
24881 userInfo = sUserManager.getUserInfo(userId);
24883 Binder.restoreCallingIdentity(token);
24886 if (userInfo != null && userInfo.isManagedProfile()) {
24891 mUserNeedsBadging.put(userId, b);
24894 return mUserNeedsBadging.valueAt(index);
24898 public KeySet getKeySetByAlias(String packageName, String alias) {
24899 if (packageName == null || alias == null) {
24902 synchronized(mPackages) {
24903 final PackageParser.Package pkg = mPackages.get(packageName);
24905 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24906 throw new IllegalArgumentException("Unknown package: " + packageName);
24908 final PackageSetting ps = (PackageSetting) pkg.mExtras;
24909 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24910 Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24911 throw new IllegalArgumentException("Unknown package: " + packageName);
24913 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24914 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24919 public KeySet getSigningKeySet(String packageName) {
24920 if (packageName == null) {
24923 synchronized(mPackages) {
24924 final int callingUid = Binder.getCallingUid();
24925 final int callingUserId = UserHandle.getUserId(callingUid);
24926 final PackageParser.Package pkg = mPackages.get(packageName);
24928 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24929 throw new IllegalArgumentException("Unknown package: " + packageName);
24931 final PackageSetting ps = (PackageSetting) pkg.mExtras;
24932 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24933 // filter and pretend the package doesn't exist
24934 Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24935 + ", uid:" + callingUid);
24936 throw new IllegalArgumentException("Unknown package: " + packageName);
24938 if (pkg.applicationInfo.uid != callingUid
24939 && Process.SYSTEM_UID != callingUid) {
24940 throw new SecurityException("May not access signing KeySet of other apps.");
24942 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24943 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24948 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24949 final int callingUid = Binder.getCallingUid();
24950 if (getInstantAppPackageName(callingUid) != null) {
24953 if (packageName == null || ks == null) {
24956 synchronized(mPackages) {
24957 final PackageParser.Package pkg = mPackages.get(packageName);
24959 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24960 UserHandle.getUserId(callingUid))) {
24961 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24962 throw new IllegalArgumentException("Unknown package: " + packageName);
24964 IBinder ksh = ks.getToken();
24965 if (ksh instanceof KeySetHandle) {
24966 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24967 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24974 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24975 final int callingUid = Binder.getCallingUid();
24976 if (getInstantAppPackageName(callingUid) != null) {
24979 if (packageName == null || ks == null) {
24982 synchronized(mPackages) {
24983 final PackageParser.Package pkg = mPackages.get(packageName);
24985 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24986 UserHandle.getUserId(callingUid))) {
24987 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24988 throw new IllegalArgumentException("Unknown package: " + packageName);
24990 IBinder ksh = ks.getToken();
24991 if (ksh instanceof KeySetHandle) {
24992 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24993 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24999 private void deletePackageIfUnusedLPr(final String packageName) {
25000 PackageSetting ps = mSettings.mPackages.get(packageName);
25004 if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25005 // TODO Implement atomic delete if package is unused
25006 // It is currently possible that the package will be deleted even if it is installed
25007 // after this method returns.
25008 mHandler.post(new Runnable() {
25009 public void run() {
25010 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25011 0, PackageManager.DELETE_ALL_USERS);
25018 * Check and throw if the given before/after packages would be considered a
25021 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25022 throws PackageManagerException {
25023 if (after.versionCode < before.mVersionCode) {
25024 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25025 "Update version code " + after.versionCode + " is older than current "
25026 + before.mVersionCode);
25027 } else if (after.versionCode == before.mVersionCode) {
25028 if (after.baseRevisionCode < before.baseRevisionCode) {
25029 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25030 "Update base revision code " + after.baseRevisionCode
25031 + " is older than current " + before.baseRevisionCode);
25034 if (!ArrayUtils.isEmpty(after.splitNames)) {
25035 for (int i = 0; i < after.splitNames.length; i++) {
25036 final String splitName = after.splitNames[i];
25037 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25039 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25040 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25041 "Update split " + splitName + " revision code "
25042 + after.splitRevisionCodes[i] + " is older than current "
25043 + before.splitRevisionCodes[j]);
25051 private static class MoveCallbacks extends Handler {
25052 private static final int MSG_CREATED = 1;
25053 private static final int MSG_STATUS_CHANGED = 2;
25055 private final RemoteCallbackList<IPackageMoveObserver>
25056 mCallbacks = new RemoteCallbackList<>();
25058 private final SparseIntArray mLastStatus = new SparseIntArray();
25060 public MoveCallbacks(Looper looper) {
25064 public void register(IPackageMoveObserver callback) {
25065 mCallbacks.register(callback);
25068 public void unregister(IPackageMoveObserver callback) {
25069 mCallbacks.unregister(callback);
25073 public void handleMessage(Message msg) {
25074 final SomeArgs args = (SomeArgs) msg.obj;
25075 final int n = mCallbacks.beginBroadcast();
25076 for (int i = 0; i < n; i++) {
25077 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25079 invokeCallback(callback, msg.what, args);
25080 } catch (RemoteException ignored) {
25083 mCallbacks.finishBroadcast();
25087 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25088 throws RemoteException {
25090 case MSG_CREATED: {
25091 callback.onCreated(args.argi1, (Bundle) args.arg2);
25094 case MSG_STATUS_CHANGED: {
25095 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25101 private void notifyCreated(int moveId, Bundle extras) {
25102 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25104 final SomeArgs args = SomeArgs.obtain();
25105 args.argi1 = moveId;
25106 args.arg2 = extras;
25107 obtainMessage(MSG_CREATED, args).sendToTarget();
25110 private void notifyStatusChanged(int moveId, int status) {
25111 notifyStatusChanged(moveId, status, -1);
25114 private void notifyStatusChanged(int moveId, int status, long estMillis) {
25115 Slog.v(TAG, "Move " + moveId + " status " + status);
25117 final SomeArgs args = SomeArgs.obtain();
25118 args.argi1 = moveId;
25119 args.argi2 = status;
25120 args.arg3 = estMillis;
25121 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25123 synchronized (mLastStatus) {
25124 mLastStatus.put(moveId, status);
25129 private final static class OnPermissionChangeListeners extends Handler {
25130 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25132 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25133 new RemoteCallbackList<>();
25135 public OnPermissionChangeListeners(Looper looper) {
25140 public void handleMessage(Message msg) {
25141 switch (msg.what) {
25142 case MSG_ON_PERMISSIONS_CHANGED: {
25143 final int uid = msg.arg1;
25144 handleOnPermissionsChanged(uid);
25149 public void addListenerLocked(IOnPermissionsChangeListener listener) {
25150 mPermissionListeners.register(listener);
25154 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25155 mPermissionListeners.unregister(listener);
25158 public void onPermissionsChanged(int uid) {
25159 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25160 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25164 private void handleOnPermissionsChanged(int uid) {
25165 final int count = mPermissionListeners.beginBroadcast();
25167 for (int i = 0; i < count; i++) {
25168 IOnPermissionsChangeListener callback = mPermissionListeners
25169 .getBroadcastItem(i);
25171 callback.onPermissionsChanged(uid);
25172 } catch (RemoteException e) {
25173 Log.e(TAG, "Permission listener is dead", e);
25177 mPermissionListeners.finishBroadcast();
25182 private class PackageManagerNative extends IPackageManagerNative.Stub {
25184 public String[] getNamesForUids(int[] uids) throws RemoteException {
25185 final String[] results = PackageManagerService.this.getNamesForUids(uids);
25186 // massage results so they can be parsed by the native binder
25187 for (int i = results.length - 1; i >= 0; --i) {
25188 if (results[i] == null) {
25195 // NB: this differentiates between preloads and sideloads
25197 public String getInstallerForPackage(String packageName) throws RemoteException {
25198 final String installerName = getInstallerPackageName(packageName);
25199 if (!TextUtils.isEmpty(installerName)) {
25200 return installerName;
25202 // differentiate between preload and sideload
25203 int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25204 ApplicationInfo appInfo = getApplicationInfo(packageName,
25206 /*userId*/ callingUser);
25207 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25214 public int getVersionCodeForPackage(String packageName) throws RemoteException {
25216 int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25217 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25218 if (pInfo != null) {
25219 return pInfo.versionCode;
25221 } catch (Exception e) {
25227 private class PackageManagerInternalImpl extends PackageManagerInternal {
25229 public void setLocationPackagesProvider(PackagesProvider provider) {
25230 synchronized (mPackages) {
25231 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25236 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25237 synchronized (mPackages) {
25238 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25243 public void setSmsAppPackagesProvider(PackagesProvider provider) {
25244 synchronized (mPackages) {
25245 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25250 public void setDialerAppPackagesProvider(PackagesProvider provider) {
25251 synchronized (mPackages) {
25252 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25257 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25258 synchronized (mPackages) {
25259 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25264 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25265 synchronized (mPackages) {
25266 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25271 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25272 synchronized (mPackages) {
25273 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25274 packageName, userId);
25279 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25280 synchronized (mPackages) {
25281 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25282 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25283 packageName, userId);
25288 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25289 synchronized (mPackages) {
25290 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25291 packageName, userId);
25296 public void setKeepUninstalledPackages(final List<String> packageList) {
25297 Preconditions.checkNotNull(packageList);
25298 List<String> removedFromList = null;
25299 synchronized (mPackages) {
25300 if (mKeepUninstalledPackages != null) {
25301 final int packagesCount = mKeepUninstalledPackages.size();
25302 for (int i = 0; i < packagesCount; i++) {
25303 String oldPackage = mKeepUninstalledPackages.get(i);
25304 if (packageList != null && packageList.contains(oldPackage)) {
25307 if (removedFromList == null) {
25308 removedFromList = new ArrayList<>();
25310 removedFromList.add(oldPackage);
25313 mKeepUninstalledPackages = new ArrayList<>(packageList);
25314 if (removedFromList != null) {
25315 final int removedCount = removedFromList.size();
25316 for (int i = 0; i < removedCount; i++) {
25317 deletePackageIfUnusedLPr(removedFromList.get(i));
25324 public boolean isPermissionsReviewRequired(String packageName, int userId) {
25325 synchronized (mPackages) {
25326 // If we do not support permission review, done.
25327 if (!mPermissionReviewRequired) {
25331 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25332 if (packageSetting == null) {
25336 // Permission review applies only to apps not supporting the new permission model.
25337 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25341 // Legacy apps have the permission and get user consent on launch.
25342 PermissionsState permissionsState = packageSetting.getPermissionsState();
25343 return permissionsState.isPermissionReviewRequired(userId);
25348 public PackageInfo getPackageInfo(
25349 String packageName, int flags, int filterCallingUid, int userId) {
25350 return PackageManagerService.this
25351 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25352 flags, filterCallingUid, userId);
25356 public ApplicationInfo getApplicationInfo(
25357 String packageName, int flags, int filterCallingUid, int userId) {
25358 return PackageManagerService.this
25359 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25363 public ActivityInfo getActivityInfo(
25364 ComponentName component, int flags, int filterCallingUid, int userId) {
25365 return PackageManagerService.this
25366 .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25370 public List<ResolveInfo> queryIntentActivities(
25371 Intent intent, int flags, int filterCallingUid, int userId) {
25372 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25373 return PackageManagerService.this
25374 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25375 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25379 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25381 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25385 public void setDeviceAndProfileOwnerPackages(
25386 int deviceOwnerUserId, String deviceOwnerPackage,
25387 SparseArray<String> profileOwnerPackages) {
25388 mProtectedPackages.setDeviceAndProfileOwnerPackages(
25389 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25393 public boolean isPackageDataProtected(int userId, String packageName) {
25394 return mProtectedPackages.isPackageDataProtected(userId, packageName);
25398 public boolean isPackageEphemeral(int userId, String packageName) {
25399 synchronized (mPackages) {
25400 final PackageSetting ps = mSettings.mPackages.get(packageName);
25401 return ps != null ? ps.getInstantApp(userId) : false;
25406 public boolean wasPackageEverLaunched(String packageName, int userId) {
25407 synchronized (mPackages) {
25408 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25413 public void grantRuntimePermission(String packageName, String name, int userId,
25414 boolean overridePolicy) {
25415 PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25420 public void revokeRuntimePermission(String packageName, String name, int userId,
25421 boolean overridePolicy) {
25422 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25427 public String getNameForUid(int uid) {
25428 return PackageManagerService.this.getNameForUid(uid);
25432 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25433 Intent origIntent, String resolvedType, String callingPackage,
25434 Bundle verificationBundle, int userId) {
25435 PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25436 responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25441 public void grantEphemeralAccess(int userId, Intent intent,
25442 int targetAppId, int ephemeralAppId) {
25443 synchronized (mPackages) {
25444 mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25445 targetAppId, ephemeralAppId);
25450 public boolean isInstantAppInstallerComponent(ComponentName component) {
25451 synchronized (mPackages) {
25452 return mInstantAppInstallerActivity != null
25453 && mInstantAppInstallerActivity.getComponentName().equals(component);
25458 public void pruneInstantApps() {
25459 mInstantAppRegistry.pruneInstantApps();
25463 public String getSetupWizardPackageName() {
25464 return mSetupWizardPackage;
25467 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25468 if (policy != null) {
25469 mExternalSourcesPolicy = policy;
25474 public boolean isPackagePersistent(String packageName) {
25475 synchronized (mPackages) {
25476 PackageParser.Package pkg = mPackages.get(packageName);
25478 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25479 | ApplicationInfo.FLAG_PERSISTENT)) ==
25480 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25486 public List<PackageInfo> getOverlayPackages(int userId) {
25487 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25488 synchronized (mPackages) {
25489 for (PackageParser.Package p : mPackages.values()) {
25490 if (p.mOverlayTarget != null) {
25491 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25493 overlayPackages.add(pkg);
25498 return overlayPackages;
25502 public List<String> getTargetPackageNames(int userId) {
25503 List<String> targetPackages = new ArrayList<>();
25504 synchronized (mPackages) {
25505 for (PackageParser.Package p : mPackages.values()) {
25506 if (p.mOverlayTarget == null) {
25507 targetPackages.add(p.packageName);
25511 return targetPackages;
25515 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25516 @Nullable List<String> overlayPackageNames) {
25517 synchronized (mPackages) {
25518 if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25519 Slog.e(TAG, "failed to find package " + targetPackageName);
25522 ArrayList<String> overlayPaths = null;
25523 if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25524 final int N = overlayPackageNames.size();
25525 overlayPaths = new ArrayList<>(N);
25526 for (int i = 0; i < N; i++) {
25527 final String packageName = overlayPackageNames.get(i);
25528 final PackageParser.Package pkg = mPackages.get(packageName);
25530 Slog.e(TAG, "failed to find package " + packageName);
25533 overlayPaths.add(pkg.baseCodePath);
25537 final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25538 ps.setOverlayPaths(overlayPaths, userId);
25544 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25545 int flags, int userId) {
25546 return resolveIntentInternal(
25547 intent, resolvedType, flags, userId, true /*resolveForStart*/);
25551 public ResolveInfo resolveService(Intent intent, String resolvedType,
25552 int flags, int userId, int callingUid) {
25553 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25557 public void addIsolatedUid(int isolatedUid, int ownerUid) {
25558 synchronized (mPackages) {
25559 mIsolatedOwners.put(isolatedUid, ownerUid);
25564 public void removeIsolatedUid(int isolatedUid) {
25565 synchronized (mPackages) {
25566 mIsolatedOwners.delete(isolatedUid);
25571 public int getUidTargetSdkVersion(int uid) {
25572 synchronized (mPackages) {
25573 return getUidTargetSdkVersionLockedLPr(uid);
25578 public boolean canAccessInstantApps(int callingUid, int userId) {
25579 return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25583 public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25584 synchronized (mPackages) {
25585 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25590 public void notifyPackageUse(String packageName, int reason) {
25591 synchronized (mPackages) {
25592 PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25598 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25599 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25600 synchronized (mPackages) {
25601 final long identity = Binder.clearCallingIdentity();
25603 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25604 packageNames, userId);
25606 Binder.restoreCallingIdentity(identity);
25612 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25613 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25614 synchronized (mPackages) {
25615 final long identity = Binder.clearCallingIdentity();
25617 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25618 packageNames, userId);
25620 Binder.restoreCallingIdentity(identity);
25625 private static void enforceSystemOrPhoneCaller(String tag) {
25626 int callingUid = Binder.getCallingUid();
25627 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25628 throw new SecurityException(
25629 "Cannot call " + tag + " from UID " + callingUid);
25633 boolean isHistoricalPackageUsageAvailable() {
25634 return mPackageUsage.isHistoricalPackageUsageAvailable();
25638 * Return a <b>copy</b> of the collection of packages known to the package manager.
25639 * @return A copy of the values of mPackages.
25641 Collection<PackageParser.Package> getPackages() {
25642 synchronized (mPackages) {
25643 return new ArrayList<>(mPackages.values());
25648 * Logs process start information (including base APK hash) to the security log.
25652 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25653 String apkFile, int pid) {
25654 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25657 if (!SecurityLog.isLoggingEnabled()) {
25660 Bundle data = new Bundle();
25661 data.putLong("startTimestamp", System.currentTimeMillis());
25662 data.putString("processName", processName);
25663 data.putInt("uid", uid);
25664 data.putString("seinfo", seinfo);
25665 data.putString("apkFile", apkFile);
25666 data.putInt("pid", pid);
25667 Message msg = mProcessLoggingHandler.obtainMessage(
25668 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25670 mProcessLoggingHandler.sendMessage(msg);
25673 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25674 return mCompilerStats.getPackageStats(pkgName);
25677 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25678 return getOrCreateCompilerPackageStats(pkg.packageName);
25681 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25682 return mCompilerStats.getOrCreatePackageStats(pkgName);
25685 public void deleteCompilerPackageStats(String pkgName) {
25686 mCompilerStats.deletePackageStats(pkgName);
25690 public int getInstallReason(String packageName, int userId) {
25691 final int callingUid = Binder.getCallingUid();
25692 enforceCrossUserPermission(callingUid, userId,
25693 true /* requireFullPermission */, false /* checkShell */,
25694 "get install reason");
25695 synchronized (mPackages) {
25696 final PackageSetting ps = mSettings.mPackages.get(packageName);
25697 if (filterAppAccessLPr(ps, callingUid, userId)) {
25698 return PackageManager.INSTALL_REASON_UNKNOWN;
25701 return ps.getInstallReason(userId);
25704 return PackageManager.INSTALL_REASON_UNKNOWN;
25708 public boolean canRequestPackageInstalls(String packageName, int userId) {
25709 return canRequestPackageInstallsInternal(packageName, 0, userId,
25710 true /* throwIfPermNotDeclared*/);
25713 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25714 boolean throwIfPermNotDeclared) {
25715 int callingUid = Binder.getCallingUid();
25716 int uid = getPackageUid(packageName, 0, userId);
25717 if (callingUid != uid && callingUid != Process.ROOT_UID
25718 && callingUid != Process.SYSTEM_UID) {
25719 throw new SecurityException(
25720 "Caller uid " + callingUid + " does not own package " + packageName);
25722 ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25723 if (info == null) {
25726 if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25729 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25730 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25731 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25732 if (throwIfPermNotDeclared) {
25733 throw new SecurityException("Need to declare " + appOpPermission
25734 + " to call this api");
25736 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25740 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25743 if (mExternalSourcesPolicy != null) {
25744 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25745 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25746 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25749 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25753 public ComponentName getInstantAppResolverSettingsComponent() {
25754 return mInstantAppResolverSettingsComponent;
25758 public ComponentName getInstantAppInstallerComponent() {
25759 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25762 return mInstantAppInstallerActivity == null
25763 ? null : mInstantAppInstallerActivity.getComponentName();
25767 public String getInstantAppAndroidId(String packageName, int userId) {
25768 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25769 "getInstantAppAndroidId");
25770 enforceCrossUserPermission(Binder.getCallingUid(), userId,
25771 true /* requireFullPermission */, false /* checkShell */,
25772 "getInstantAppAndroidId");
25773 // Make sure the target is an Instant App.
25774 if (!isInstantApp(packageName, userId)) {
25777 synchronized (mPackages) {
25778 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25782 boolean canHaveOatDir(String packageName) {
25783 synchronized (mPackages) {
25784 PackageParser.Package p = mPackages.get(packageName);
25788 return p.canHaveOatDir();
25792 private String getOatDir(PackageParser.Package pkg) {
25793 if (!pkg.canHaveOatDir()) {
25796 File codePath = new File(pkg.codePath);
25797 if (codePath.isDirectory()) {
25798 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25803 void deleteOatArtifactsOfPackage(String packageName) {
25804 final String[] instructionSets;
25805 final List<String> codePaths;
25806 final String oatDir;
25807 final PackageParser.Package pkg;
25808 synchronized (mPackages) {
25809 pkg = mPackages.get(packageName);
25811 instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25812 codePaths = pkg.getAllCodePaths();
25813 oatDir = getOatDir(pkg);
25815 for (String codePath : codePaths) {
25816 for (String isa : instructionSets) {
25818 mInstaller.deleteOdex(codePath, isa, oatDir);
25819 } catch (InstallerException e) {
25820 Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25826 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25827 Set<String> unusedPackages = new HashSet<>();
25828 long currentTimeInMillis = System.currentTimeMillis();
25829 synchronized (mPackages) {
25830 for (PackageParser.Package pkg : mPackages.values()) {
25831 PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
25835 PackageDexUsage.PackageUseInfo packageUseInfo =
25836 getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25837 if (PackageManagerServiceUtils
25838 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25839 downgradeTimeThresholdMillis, packageUseInfo,
25840 pkg.getLatestPackageUseTimeInMills(),
25841 pkg.getLatestForegroundPackageUseTimeInMills())) {
25842 unusedPackages.add(pkg.packageName);
25846 return unusedPackages;
25850 interface PackageSender {
25851 void sendPackageBroadcast(final String action, final String pkg,
25852 final Bundle extras, final int flags, final String targetPkg,
25853 final IIntentReceiver finishedReceiver, final int[] userIds);
25854 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25855 boolean includeStopped, int appId, int... userIds);