2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.server.pm;
19 import static android.Manifest.permission.DELETE_PACKAGES;
20 import static android.Manifest.permission.INSTALL_PACKAGES;
21 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
61 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66 import static android.content.pm.PackageManager.MATCH_ALL;
67 import static android.content.pm.PackageManager.MATCH_ANY_USER;
68 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76 import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82 import static android.content.pm.PackageManager.PERMISSION_DENIED;
83 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
85 import static android.content.pm.PackageParser.isApkFile;
86 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87 import static android.system.OsConstants.O_CREAT;
88 import static android.system.OsConstants.O_RDWR;
89 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
90 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
91 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
92 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
93 import static com.android.internal.util.ArrayUtils.appendInt;
94 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104 import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106 import android.Manifest;
107 import android.annotation.IntDef;
108 import android.annotation.NonNull;
109 import android.annotation.Nullable;
110 import android.app.ActivityManager;
111 import android.app.AppOpsManager;
112 import android.app.IActivityManager;
113 import android.app.ResourcesManager;
114 import android.app.admin.IDevicePolicyManager;
115 import android.app.admin.SecurityLog;
116 import android.app.backup.IBackupManager;
117 import android.content.BroadcastReceiver;
118 import android.content.ComponentName;
119 import android.content.ContentResolver;
120 import android.content.Context;
121 import android.content.IIntentReceiver;
122 import android.content.Intent;
123 import android.content.IntentFilter;
124 import android.content.IntentSender;
125 import android.content.IntentSender.SendIntentException;
126 import android.content.ServiceConnection;
127 import android.content.pm.ActivityInfo;
128 import android.content.pm.ApplicationInfo;
129 import android.content.pm.AppsQueryHelper;
130 import android.content.pm.AuxiliaryResolveInfo;
131 import android.content.pm.ChangedPackages;
132 import android.content.pm.FallbackCategoryProvider;
133 import android.content.pm.FeatureInfo;
134 import android.content.pm.IOnPermissionsChangeListener;
135 import android.content.pm.IPackageDataObserver;
136 import android.content.pm.IPackageDeleteObserver;
137 import android.content.pm.IPackageDeleteObserver2;
138 import android.content.pm.IPackageInstallObserver2;
139 import android.content.pm.IPackageInstaller;
140 import android.content.pm.IPackageManager;
141 import android.content.pm.IPackageMoveObserver;
142 import android.content.pm.IPackageStatsObserver;
143 import android.content.pm.InstantAppInfo;
144 import android.content.pm.InstantAppRequest;
145 import android.content.pm.InstantAppResolveInfo;
146 import android.content.pm.InstrumentationInfo;
147 import android.content.pm.IntentFilterVerificationInfo;
148 import android.content.pm.KeySet;
149 import android.content.pm.PackageCleanItem;
150 import android.content.pm.PackageInfo;
151 import android.content.pm.PackageInfoLite;
152 import android.content.pm.PackageInstaller;
153 import android.content.pm.PackageManager;
154 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155 import android.content.pm.PackageManagerInternal;
156 import android.content.pm.PackageParser;
157 import android.content.pm.PackageParser.ActivityIntentInfo;
158 import android.content.pm.PackageParser.PackageLite;
159 import android.content.pm.PackageParser.PackageParserException;
160 import android.content.pm.PackageStats;
161 import android.content.pm.PackageUserState;
162 import android.content.pm.ParceledListSlice;
163 import android.content.pm.PermissionGroupInfo;
164 import android.content.pm.PermissionInfo;
165 import android.content.pm.ProviderInfo;
166 import android.content.pm.ResolveInfo;
167 import android.content.pm.ServiceInfo;
168 import android.content.pm.SharedLibraryInfo;
169 import android.content.pm.Signature;
170 import android.content.pm.UserInfo;
171 import android.content.pm.VerifierDeviceIdentity;
172 import android.content.pm.VerifierInfo;
173 import android.content.pm.VersionedPackage;
174 import android.content.res.Resources;
175 import android.database.ContentObserver;
176 import android.graphics.Bitmap;
177 import android.hardware.display.DisplayManager;
178 import android.net.Uri;
179 import android.os.AsyncTask;
180 import android.os.Binder;
181 import android.os.Build;
182 import android.os.Bundle;
183 import android.os.Debug;
184 import android.os.Environment;
185 import android.os.Environment.UserEnvironment;
186 import android.os.FileUtils;
187 import android.os.Handler;
188 import android.os.IBinder;
189 import android.os.Looper;
190 import android.os.Message;
191 import android.os.Parcel;
192 import android.os.ParcelFileDescriptor;
193 import android.os.PatternMatcher;
194 import android.os.Process;
195 import android.os.RemoteCallbackList;
196 import android.os.RemoteException;
197 import android.os.ResultReceiver;
198 import android.os.SELinux;
199 import android.os.ServiceManager;
200 import android.os.ShellCallback;
201 import android.os.SystemClock;
202 import android.os.SystemProperties;
203 import android.os.Trace;
204 import android.os.UserHandle;
205 import android.os.UserManager;
206 import android.os.UserManagerInternal;
207 import android.os.storage.IStorageManager;
208 import android.os.storage.StorageEventListener;
209 import android.os.storage.StorageManager;
210 import android.os.storage.StorageManagerInternal;
211 import android.os.storage.VolumeInfo;
212 import android.os.storage.VolumeRecord;
213 import android.provider.Settings.Global;
214 import android.provider.Settings.Secure;
215 import android.security.KeyStore;
216 import android.security.SystemKeyStore;
217 import android.service.pm.PackageServiceDumpProto;
218 import android.system.ErrnoException;
219 import android.system.Os;
220 import android.text.TextUtils;
221 import android.text.format.DateUtils;
222 import android.util.ArrayMap;
223 import android.util.ArraySet;
224 import android.util.Base64;
225 import android.util.BootTimingsTraceLog;
226 import android.util.DisplayMetrics;
227 import android.util.EventLog;
228 import android.util.ExceptionUtils;
229 import android.util.Log;
230 import android.util.LogPrinter;
231 import android.util.MathUtils;
232 import android.util.PackageUtils;
233 import android.util.Pair;
234 import android.util.PrintStreamPrinter;
235 import android.util.Slog;
236 import android.util.SparseArray;
237 import android.util.SparseBooleanArray;
238 import android.util.SparseIntArray;
239 import android.util.Xml;
240 import android.util.jar.StrictJarFile;
241 import android.util.proto.ProtoOutputStream;
242 import android.view.Display;
244 import com.android.internal.R;
245 import com.android.internal.annotations.GuardedBy;
246 import com.android.internal.app.IMediaContainerService;
247 import com.android.internal.app.ResolverActivity;
248 import com.android.internal.content.NativeLibraryHelper;
249 import com.android.internal.content.PackageHelper;
250 import com.android.internal.logging.MetricsLogger;
251 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
252 import com.android.internal.os.IParcelFileDescriptorFactory;
253 import com.android.internal.os.RoSystemProperties;
254 import com.android.internal.os.SomeArgs;
255 import com.android.internal.os.Zygote;
256 import com.android.internal.telephony.CarrierAppUtils;
257 import com.android.internal.util.ArrayUtils;
258 import com.android.internal.util.ConcurrentUtils;
259 import com.android.internal.util.DumpUtils;
260 import com.android.internal.util.FastPrintWriter;
261 import com.android.internal.util.FastXmlSerializer;
262 import com.android.internal.util.IndentingPrintWriter;
263 import com.android.internal.util.Preconditions;
264 import com.android.internal.util.XmlUtils;
265 import com.android.server.AttributeCache;
266 import com.android.server.DeviceIdleController;
267 import com.android.server.EventLogTags;
268 import com.android.server.FgThread;
269 import com.android.server.IntentResolver;
270 import com.android.server.LocalServices;
271 import com.android.server.LockGuard;
272 import com.android.server.ServiceThread;
273 import com.android.server.SystemConfig;
274 import com.android.server.SystemServerInitThreadPool;
275 import com.android.server.Watchdog;
276 import com.android.server.net.NetworkPolicyManagerInternal;
277 import com.android.server.pm.Installer.InstallerException;
278 import com.android.server.pm.PermissionsState.PermissionState;
279 import com.android.server.pm.Settings.DatabaseVersion;
280 import com.android.server.pm.Settings.VersionInfo;
281 import com.android.server.pm.dex.DexManager;
282 import com.android.server.storage.DeviceStorageMonitorInternal;
284 import dalvik.system.CloseGuard;
285 import dalvik.system.DexFile;
286 import dalvik.system.VMRuntime;
288 import libcore.io.IoUtils;
289 import libcore.util.EmptyArray;
291 import org.xmlpull.v1.XmlPullParser;
292 import org.xmlpull.v1.XmlPullParserException;
293 import org.xmlpull.v1.XmlSerializer;
295 import java.io.BufferedOutputStream;
296 import java.io.BufferedReader;
297 import java.io.ByteArrayInputStream;
298 import java.io.ByteArrayOutputStream;
300 import java.io.FileDescriptor;
301 import java.io.FileInputStream;
302 import java.io.FileOutputStream;
303 import java.io.FileReader;
304 import java.io.FilenameFilter;
305 import java.io.IOException;
306 import java.io.PrintWriter;
307 import java.lang.annotation.Retention;
308 import java.lang.annotation.RetentionPolicy;
309 import java.nio.charset.StandardCharsets;
310 import java.security.DigestInputStream;
311 import java.security.MessageDigest;
312 import java.security.NoSuchAlgorithmException;
313 import java.security.PublicKey;
314 import java.security.SecureRandom;
315 import java.security.cert.Certificate;
316 import java.security.cert.CertificateEncodingException;
317 import java.security.cert.CertificateException;
318 import java.text.SimpleDateFormat;
319 import java.util.ArrayList;
320 import java.util.Arrays;
321 import java.util.Collection;
322 import java.util.Collections;
323 import java.util.Comparator;
324 import java.util.Date;
325 import java.util.HashMap;
326 import java.util.HashSet;
327 import java.util.Iterator;
328 import java.util.List;
329 import java.util.Map;
330 import java.util.Objects;
331 import java.util.Set;
332 import java.util.concurrent.CountDownLatch;
333 import java.util.concurrent.Future;
334 import java.util.concurrent.TimeUnit;
335 import java.util.concurrent.atomic.AtomicBoolean;
336 import java.util.concurrent.atomic.AtomicInteger;
339 * Keep track of all those APKs everywhere.
341 * Internally there are two important locks:
343 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
344 * and other related state. It is a fine-grained lock that should only be held
345 * momentarily, as it's one of the most contended locks in the system.
346 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
347 * operations typically involve heavy lifting of application data on disk. Since
348 * {@code installd} is single-threaded, and it's operations can often be slow,
349 * this lock should never be acquired while already holding {@link #mPackages}.
350 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
351 * holding {@link #mInstallLock}.
353 * Many internal methods rely on the caller to hold the appropriate locks, and
354 * this contract is expressed through method name suffixes:
356 * <li>fooLI(): the caller must hold {@link #mInstallLock}
357 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
358 * being modified must be frozen
359 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
360 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
363 * Because this class is very central to the platform's security; please run all
364 * CTS and unit tests whenever making modifications:
367 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
368 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
371 public class PackageManagerService extends IPackageManager.Stub
372 implements PackageSender {
373 static final String TAG = "PackageManager";
374 static final boolean DEBUG_SETTINGS = false;
375 static final boolean DEBUG_PREFERRED = false;
376 static final boolean DEBUG_UPGRADE = false;
377 static final boolean DEBUG_DOMAIN_VERIFICATION = false;
378 private static final boolean DEBUG_BACKUP = false;
379 private static final boolean DEBUG_INSTALL = false;
380 private static final boolean DEBUG_REMOVE = false;
381 private static final boolean DEBUG_BROADCASTS = false;
382 private static final boolean DEBUG_SHOW_INFO = false;
383 private static final boolean DEBUG_PACKAGE_INFO = false;
384 private static final boolean DEBUG_INTENT_MATCHING = false;
385 private static final boolean DEBUG_PACKAGE_SCANNING = false;
386 private static final boolean DEBUG_VERIFY = false;
387 private static final boolean DEBUG_FILTERS = false;
388 private static final boolean DEBUG_PERMISSIONS = false;
389 private static final boolean DEBUG_SHARED_LIBRARIES = false;
391 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
392 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
393 // user, but by default initialize to this.
394 public static final boolean DEBUG_DEXOPT = false;
396 private static final boolean DEBUG_ABI_SELECTION = false;
397 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
398 private static final boolean DEBUG_TRIAGED_MISSING = false;
399 private static final boolean DEBUG_APP_DATA = false;
401 /** REMOVE. According to Svet, this was only used to reset permissions during development. */
402 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
404 private static final boolean HIDE_EPHEMERAL_APIS = false;
406 private static final boolean ENABLE_FREE_CACHE_V2 =
407 SystemProperties.getBoolean("fw.free_cache_v2", true);
409 private static final int RADIO_UID = Process.PHONE_UID;
410 private static final int LOG_UID = Process.LOG_UID;
411 private static final int NFC_UID = Process.NFC_UID;
412 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
413 private static final int SHELL_UID = Process.SHELL_UID;
415 // Cap the size of permission trees that 3rd party apps can define
416 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text
418 // Suffix used during package installation when copying/moving
419 // package apks to install directory.
420 private static final String INSTALL_PACKAGE_SUFFIX = "-";
422 static final int SCAN_NO_DEX = 1<<1;
423 static final int SCAN_FORCE_DEX = 1<<2;
424 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
425 static final int SCAN_NEW_INSTALL = 1<<4;
426 static final int SCAN_UPDATE_TIME = 1<<5;
427 static final int SCAN_BOOTING = 1<<6;
428 static final int SCAN_TRUSTED_OVERLAY = 1<<7;
429 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
430 static final int SCAN_REPLACING = 1<<9;
431 static final int SCAN_REQUIRE_KNOWN = 1<<10;
432 static final int SCAN_MOVE = 1<<11;
433 static final int SCAN_INITIAL = 1<<12;
434 static final int SCAN_CHECK_ONLY = 1<<13;
435 static final int SCAN_DONT_KILL_APP = 1<<14;
436 static final int SCAN_IGNORE_FROZEN = 1<<15;
437 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
438 static final int SCAN_AS_INSTANT_APP = 1<<17;
439 static final int SCAN_AS_FULL_APP = 1<<18;
440 /** Should not be with the scan flags */
441 static final int FLAGS_REMOVE_CHATTY = 1<<31;
443 private static final String STATIC_SHARED_LIB_DELIMITER = "_";
445 private static final int[] EMPTY_INT_ARRAY = new int[0];
447 private static final int TYPE_UNKNOWN = 0;
448 private static final int TYPE_ACTIVITY = 1;
449 private static final int TYPE_RECEIVER = 2;
450 private static final int TYPE_SERVICE = 3;
451 private static final int TYPE_PROVIDER = 4;
452 @IntDef(prefix = { "TYPE_" }, value = {
459 @Retention(RetentionPolicy.SOURCE)
460 public @interface ComponentType {}
463 * Timeout (in milliseconds) after which the watchdog should declare that
464 * our handler thread is wedged. The usual default for such things is one
465 * minute but we sometimes do very lengthy I/O operations on this thread,
466 * such as installing multi-gigabyte applications, so ours needs to be longer.
468 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes
471 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
472 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
473 * settings entry if available, otherwise we use the hardcoded default. If it's been
474 * more than this long since the last fstrim, we force one during the boot sequence.
476 * This backstops other fstrim scheduling: if the device is alive at midnight+idle,
477 * one gets run at the next available charging+idle time. This final mandatory
478 * no-fstrim check kicks in only of the other scheduling criteria is never met.
480 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
483 * Whether verification is enabled by default.
485 private static final boolean DEFAULT_VERIFY_ENABLE = true;
488 * The default maximum time to wait for the verification agent to return in
491 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
494 * The default response for package verification timeout.
496 * This can be either PackageManager.VERIFICATION_ALLOW or
497 * PackageManager.VERIFICATION_REJECT.
499 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
501 static final String PLATFORM_PACKAGE_NAME = "android";
503 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
505 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
506 DEFAULT_CONTAINER_PACKAGE,
507 "com.android.defcontainer.DefaultContainerService");
509 private static final String KILL_APP_REASON_GIDS_CHANGED =
510 "permission grant or revoke changed gids";
512 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
513 "permissions revoked";
515 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
517 private static final String PACKAGE_SCHEME = "package";
519 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
521 /** Permission grant: not grant the permission. */
522 private static final int GRANT_DENIED = 1;
524 /** Permission grant: grant the permission as an install permission. */
525 private static final int GRANT_INSTALL = 2;
527 /** Permission grant: grant the permission as a runtime one. */
528 private static final int GRANT_RUNTIME = 3;
530 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
531 private static final int GRANT_UPGRADE = 4;
533 /** Canonical intent used to identify what counts as a "web browser" app */
534 private static final Intent sBrowserIntent;
536 sBrowserIntent = new Intent();
537 sBrowserIntent.setAction(Intent.ACTION_VIEW);
538 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
539 sBrowserIntent.setData(Uri.parse("http:"));
543 * The set of all protected actions [i.e. those actions for which a high priority
544 * intent filter is disallowed].
546 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
548 PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
549 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
550 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
551 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
554 // Compilation reasons.
555 public static final int REASON_FIRST_BOOT = 0;
556 public static final int REASON_BOOT = 1;
557 public static final int REASON_INSTALL = 2;
558 public static final int REASON_BACKGROUND_DEXOPT = 3;
559 public static final int REASON_AB_OTA = 4;
561 public static final int REASON_LAST = REASON_AB_OTA;
563 /** All dangerous permission names in the same order as the events in MetricsEvent */
564 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
565 Manifest.permission.READ_CALENDAR,
566 Manifest.permission.WRITE_CALENDAR,
567 Manifest.permission.CAMERA,
568 Manifest.permission.READ_CONTACTS,
569 Manifest.permission.WRITE_CONTACTS,
570 Manifest.permission.GET_ACCOUNTS,
571 Manifest.permission.ACCESS_FINE_LOCATION,
572 Manifest.permission.ACCESS_COARSE_LOCATION,
573 Manifest.permission.RECORD_AUDIO,
574 Manifest.permission.READ_PHONE_STATE,
575 Manifest.permission.CALL_PHONE,
576 Manifest.permission.READ_CALL_LOG,
577 Manifest.permission.WRITE_CALL_LOG,
578 Manifest.permission.ADD_VOICEMAIL,
579 Manifest.permission.USE_SIP,
580 Manifest.permission.PROCESS_OUTGOING_CALLS,
581 Manifest.permission.READ_CELL_BROADCASTS,
582 Manifest.permission.BODY_SENSORS,
583 Manifest.permission.SEND_SMS,
584 Manifest.permission.RECEIVE_SMS,
585 Manifest.permission.READ_SMS,
586 Manifest.permission.RECEIVE_WAP_PUSH,
587 Manifest.permission.RECEIVE_MMS,
588 Manifest.permission.READ_EXTERNAL_STORAGE,
589 Manifest.permission.WRITE_EXTERNAL_STORAGE,
590 Manifest.permission.READ_PHONE_NUMBERS,
591 Manifest.permission.ANSWER_PHONE_CALLS);
595 * Version number for the package parser cache. Increment this whenever the format or
596 * extent of cached data changes. See {@code PackageParser#setCacheDir}.
598 private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
601 * Whether the package parser cache is enabled.
603 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
605 final ServiceThread mHandlerThread;
607 final PackageHandler mHandler;
609 private final ProcessLoggingHandler mProcessLoggingHandler;
612 * Messages for {@link #mHandler} that need to wait for system ready before
615 private ArrayList<Message> mPostSystemReadyMessages;
617 final int mSdkVersion = Build.VERSION.SDK_INT;
619 final Context mContext;
620 final boolean mFactoryTest;
621 final boolean mOnlyCore;
622 final DisplayMetrics mMetrics;
623 final int mDefParseFlags;
624 final String[] mSeparateProcesses;
625 final boolean mIsUpgrade;
626 final boolean mIsPreNUpgrade;
627 final boolean mIsPreNMR1Upgrade;
629 // Have we told the Activity Manager to whitelist the default container service by uid yet?
630 @GuardedBy("mPackages")
631 boolean mDefaultContainerWhitelisted = false;
633 @GuardedBy("mPackages")
634 private boolean mDexOptDialogShown;
636 /** The location for ASEC container files on internal storage. */
637 final String mAsecInternalPath;
639 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
640 // LOCK HELD. Can be called with mInstallLock held.
641 @GuardedBy("mInstallLock")
642 final Installer mInstaller;
644 /** Directory where installed third-party apps stored */
645 final File mAppInstallDir;
648 * Directory to which applications installed internally have their
649 * 32 bit native libraries copied.
651 private File mAppLib32InstallDir;
653 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
655 final File mDrmAppPrivateInstallDir;
657 // ----------------------------------------------------------------
659 // Lock for state used when installing and doing other long running
660 // operations. Methods that must be called with this lock held have
662 final Object mInstallLock = new Object();
664 // ----------------------------------------------------------------
666 // Keys are String (package name), values are Package. This also serves
667 // as the lock for the global state. Methods that must be called with
668 // this lock held have the prefix "LP".
669 @GuardedBy("mPackages")
670 final ArrayMap<String, PackageParser.Package> mPackages =
671 new ArrayMap<String, PackageParser.Package>();
673 final ArrayMap<String, Set<String>> mKnownCodebase =
674 new ArrayMap<String, Set<String>>();
676 // Keys are isolated uids and values are the uid of the application
677 // that created the isolated proccess.
678 @GuardedBy("mPackages")
679 final SparseIntArray mIsolatedOwners = new SparseIntArray();
682 * Tracks new system packages [received in an OTA] that we expect to
683 * find updated user-installed versions. Keys are package name, values
684 * are package location.
686 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
688 * Tracks high priority intent filters for protected actions. During boot, certain
689 * filter actions are protected and should never be allowed to have a high priority
690 * intent filter for them. However, there is one, and only one exception -- the
691 * setup wizard. It must be able to define a high priority intent filter for these
692 * actions to ensure there are no escapes from the wizard. We need to delay processing
693 * of these during boot as we need to look at all of the system packages in order
694 * to know which component is the setup wizard.
696 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
698 * Whether or not processing protected filters should be deferred.
700 private boolean mDeferProtectedFilters = true;
703 * Tracks existing system packages prior to receiving an OTA. Keys are package name.
705 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
707 * Whether or not system app permissions should be promoted from install to runtime.
709 boolean mPromoteSystemApps;
711 @GuardedBy("mPackages")
712 final Settings mSettings;
715 * Set of package names that are currently "frozen", which means active
716 * surgery is being done on the code/data for that package. The platform
717 * will refuse to launch frozen packages to avoid race conditions.
719 * @see PackageFreezer
721 @GuardedBy("mPackages")
722 final ArraySet<String> mFrozenPackages = new ArraySet<>();
724 final ProtectedPackages mProtectedPackages;
728 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
730 // System configuration read by SystemConfig.
731 final int[] mGlobalGids;
732 final SparseArray<ArraySet<String>> mSystemPermissions;
733 @GuardedBy("mAvailableFeatures")
734 final ArrayMap<String, FeatureInfo> mAvailableFeatures;
736 // If mac_permissions.xml was found for seinfo labeling.
737 boolean mFoundPolicyFile;
739 private final InstantAppRegistry mInstantAppRegistry;
741 @GuardedBy("mPackages")
742 int mChangedPackagesSequenceNumber;
744 * List of changed [installed, removed or updated] packages.
745 * mapping from user id -> sequence number -> package name
747 @GuardedBy("mPackages")
748 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
750 * The sequence number of the last change to a package.
751 * mapping from user id -> package name -> sequence number
753 @GuardedBy("mPackages")
754 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
756 class PackageParserCallback implements PackageParser.Callback {
757 @Override public final boolean hasFeature(String feature) {
758 return PackageManagerService.this.hasSystemFeature(feature, 0);
761 final List<PackageParser.Package> getStaticOverlayPackagesLocked(
762 Collection<PackageParser.Package> allPackages, String targetPackageName) {
763 List<PackageParser.Package> overlayPackages = null;
764 for (PackageParser.Package p : allPackages) {
765 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
766 if (overlayPackages == null) {
767 overlayPackages = new ArrayList<PackageParser.Package>();
769 overlayPackages.add(p);
772 if (overlayPackages != null) {
773 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
774 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
775 return p1.mOverlayPriority - p2.mOverlayPriority;
778 Collections.sort(overlayPackages, cmp);
780 return overlayPackages;
783 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
784 String targetPackageName, String targetPath) {
785 if ("android".equals(targetPackageName)) {
786 // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787 // native AssetManager.
790 List<PackageParser.Package> overlayPackages =
791 getStaticOverlayPackagesLocked(allPackages, targetPackageName);
792 if (overlayPackages == null || overlayPackages.isEmpty()) {
795 List<String> overlayPathList = null;
796 for (PackageParser.Package overlayPackage : overlayPackages) {
797 if (targetPath == null) {
798 if (overlayPathList == null) {
799 overlayPathList = new ArrayList<String>();
801 overlayPathList.add(overlayPackage.baseCodePath);
806 // Creates idmaps for system to parse correctly the Android manifest of the
809 // OverlayManagerService will update each of them with a correct gid from its
810 // target package app id.
811 mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
812 UserHandle.getSharedAppGid(
813 UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
814 if (overlayPathList == null) {
815 overlayPathList = new ArrayList<String>();
817 overlayPathList.add(overlayPackage.baseCodePath);
818 } catch (InstallerException e) {
819 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
820 overlayPackage.baseCodePath);
823 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
826 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
827 synchronized (mPackages) {
828 return getStaticOverlayPathsLocked(
829 mPackages.values(), targetPackageName, targetPath);
833 @Override public final String[] getOverlayApks(String targetPackageName) {
834 return getStaticOverlayPaths(targetPackageName, null);
837 @Override public final String[] getOverlayPaths(String targetPackageName,
839 return getStaticOverlayPaths(targetPackageName, targetPath);
843 class ParallelPackageParserCallback extends PackageParserCallback {
844 List<PackageParser.Package> mOverlayPackages = null;
846 void findStaticOverlayPackages() {
847 synchronized (mPackages) {
848 for (PackageParser.Package p : mPackages.values()) {
849 if (p.mIsStaticOverlay) {
850 if (mOverlayPackages == null) {
851 mOverlayPackages = new ArrayList<PackageParser.Package>();
853 mOverlayPackages.add(p);
860 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
861 // We can trust mOverlayPackages without holding mPackages because package uninstall
862 // can't happen while running parallel parsing.
863 // Moreover holding mPackages on each parsing thread causes dead-lock.
864 return mOverlayPackages == null ? null :
865 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
869 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
870 final ParallelPackageParserCallback mParallelPackageParserCallback =
871 new ParallelPackageParserCallback();
873 public static final class SharedLibraryEntry {
874 public final @Nullable String path;
875 public final @Nullable String apk;
876 public final @NonNull SharedLibraryInfo info;
878 SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
879 String declaringPackageName, int declaringPackageVersionCode) {
882 info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
883 declaringPackageName, declaringPackageVersionCode), null);
887 // Currently known shared libraries.
888 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
889 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
892 // All available activities, for your resolving pleasure.
893 final ActivityIntentResolver mActivities =
894 new ActivityIntentResolver();
896 // All available receivers, for your resolving pleasure.
897 final ActivityIntentResolver mReceivers =
898 new ActivityIntentResolver();
900 // All available services, for your resolving pleasure.
901 final ServiceIntentResolver mServices = new ServiceIntentResolver();
903 // All available providers, for your resolving pleasure.
904 final ProviderIntentResolver mProviders = new ProviderIntentResolver();
906 // Mapping from provider base names (first directory in content URI codePath)
907 // to the provider information.
908 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
909 new ArrayMap<String, PackageParser.Provider>();
911 // Mapping from instrumentation class names to info about them.
912 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
913 new ArrayMap<ComponentName, PackageParser.Instrumentation>();
915 // Mapping from permission names to info about them.
916 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
917 new ArrayMap<String, PackageParser.PermissionGroup>();
919 // Packages whose data we have transfered into another package, thus
920 // should no longer exist.
921 final ArraySet<String> mTransferedPackages = new ArraySet<String>();
923 // Broadcast actions that are only available to the system.
924 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
926 /** List of packages waiting for verification. */
927 final SparseArray<PackageVerificationState> mPendingVerification
928 = new SparseArray<PackageVerificationState>();
930 /** Set of packages associated with each app op permission. */
931 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
933 final PackageInstallerService mInstallerService;
935 private final PackageDexOptimizer mPackageDexOptimizer;
936 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
937 // is used by other apps).
938 private final DexManager mDexManager;
940 private AtomicInteger mNextMoveId = new AtomicInteger();
941 private final MoveCallbacks mMoveCallbacks;
943 private final OnPermissionChangeListeners mOnPermissionChangeListeners;
945 // Cache of users who need badging.
946 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
948 /** Token for keys in mPendingVerification. */
949 private int mPendingVerificationToken = 0;
951 volatile boolean mSystemReady;
952 volatile boolean mSafeMode;
953 volatile boolean mHasSystemUidErrors;
954 private volatile boolean mEphemeralAppsDisabled;
956 ApplicationInfo mAndroidApplication;
957 final ActivityInfo mResolveActivity = new ActivityInfo();
958 final ResolveInfo mResolveInfo = new ResolveInfo();
959 ComponentName mResolveComponentName;
960 PackageParser.Package mPlatformPackage;
961 ComponentName mCustomResolverComponentName;
963 boolean mResolverReplaced = false;
965 private final @Nullable ComponentName mIntentFilterVerifierComponent;
966 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
968 private int mIntentFilterVerificationToken = 0;
970 /** The service connection to the ephemeral resolver */
971 final EphemeralResolverConnection mInstantAppResolverConnection;
972 /** Component used to show resolver settings for Instant Apps */
973 final ComponentName mInstantAppResolverSettingsComponent;
975 /** Activity used to install instant applications */
976 ActivityInfo mInstantAppInstallerActivity;
977 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
979 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
980 = new SparseArray<IntentFilterVerificationState>();
982 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
984 // List of packages names to keep cached, even if they are uninstalled for all users
985 private List<String> mKeepUninstalledPackages;
987 private UserManagerInternal mUserManagerInternal;
989 private DeviceIdleController.LocalService mDeviceIdleController;
991 private File mCacheDir;
993 private ArraySet<String> mPrivappPermissionsViolations;
995 private Future<?> mPrepareAppDataFuture;
997 private static class IFVerificationParams {
998 PackageParser.Package pkg;
1003 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1004 int _userId, int _verifierUid) {
1006 replacing = _replacing;
1008 replacing = _replacing;
1009 verifierUid = _verifierUid;
1013 private interface IntentFilterVerifier<T extends IntentFilter> {
1014 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1015 T filter, String packageName);
1016 void startVerifications(int userId);
1017 void receiveVerificationResponse(int verificationId);
1020 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1021 private Context mContext;
1022 private ComponentName mIntentFilterVerifierComponent;
1023 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1025 public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1027 mIntentFilterVerifierComponent = verifierComponent;
1030 private String getDefaultScheme() {
1031 return IntentFilter.SCHEME_HTTPS;
1035 public void startVerifications(int userId) {
1036 // Launch verifications requests
1037 int count = mCurrentIntentFilterVerifications.size();
1038 for (int n=0; n<count; n++) {
1039 int verificationId = mCurrentIntentFilterVerifications.get(n);
1040 final IntentFilterVerificationState ivs =
1041 mIntentFilterVerificationStates.get(verificationId);
1043 String packageName = ivs.getPackageName();
1045 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1046 final int filterCount = filters.size();
1047 ArraySet<String> domainsSet = new ArraySet<>();
1048 for (int m=0; m<filterCount; m++) {
1049 PackageParser.ActivityIntentInfo filter = filters.get(m);
1050 domainsSet.addAll(filter.getHostsList());
1052 synchronized (mPackages) {
1053 if (mSettings.createIntentFilterVerificationIfNeededLPw(
1054 packageName, domainsSet) != null) {
1055 scheduleWriteSettingsLocked();
1058 sendVerificationRequest(userId, verificationId, ivs);
1060 mCurrentIntentFilterVerifications.clear();
1063 private void sendVerificationRequest(int userId, int verificationId,
1064 IntentFilterVerificationState ivs) {
1066 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1067 verificationIntent.putExtra(
1068 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1070 verificationIntent.putExtra(
1071 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1072 getDefaultScheme());
1073 verificationIntent.putExtra(
1074 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1075 ivs.getHostsString());
1076 verificationIntent.putExtra(
1077 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1078 ivs.getPackageName());
1079 verificationIntent.setComponent(mIntentFilterVerifierComponent);
1080 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1082 DeviceIdleController.LocalService idleController = getDeviceIdleController();
1083 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1084 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1085 userId, false, "intent filter verifier");
1087 UserHandle user = new UserHandle(userId);
1088 mContext.sendBroadcastAsUser(verificationIntent, user);
1089 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1090 "Sending IntentFilter verification broadcast");
1093 public void receiveVerificationResponse(int verificationId) {
1094 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1096 final boolean verified = ivs.isVerified();
1098 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1099 final int count = filters.size();
1100 if (DEBUG_DOMAIN_VERIFICATION) {
1101 Slog.i(TAG, "Received verification response " + verificationId
1102 + " for " + count + " filters, verified=" + verified);
1104 for (int n=0; n<count; n++) {
1105 PackageParser.ActivityIntentInfo filter = filters.get(n);
1106 filter.setVerified(verified);
1108 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1109 + " verified with result:" + verified + " and hosts:"
1110 + ivs.getHostsString());
1113 mIntentFilterVerificationStates.remove(verificationId);
1115 final String packageName = ivs.getPackageName();
1116 IntentFilterVerificationInfo ivi = null;
1118 synchronized (mPackages) {
1119 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1122 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1123 + verificationId + " packageName:" + packageName);
1126 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1127 "Updating IntentFilterVerificationInfo for package " + packageName
1128 +" verificationId:" + verificationId);
1130 synchronized (mPackages) {
1132 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1134 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1136 scheduleWriteSettingsLocked();
1138 final int userId = ivs.getUserId();
1139 if (userId != UserHandle.USER_ALL) {
1140 final int userStatus =
1141 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1143 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1144 boolean needUpdate = false;
1146 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1147 // already been set by the User thru the Disambiguation dialog
1148 switch (userStatus) {
1149 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1151 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1153 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1158 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1160 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1170 mSettings.updateIntentFilterVerificationStatusLPw(
1171 packageName, updatedStatus, userId);
1172 scheduleWritePackageRestrictionsLocked(userId);
1179 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1180 ActivityIntentInfo filter, String packageName) {
1181 if (!hasValidDomains(filter)) {
1184 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1186 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1189 if (DEBUG_DOMAIN_VERIFICATION) {
1190 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1192 ivs.addFilter(filter);
1196 private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1197 int userId, int verificationId, String packageName) {
1198 IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1199 verifierUid, userId, packageName);
1200 ivs.setPendingState();
1201 synchronized (mPackages) {
1202 mIntentFilterVerificationStates.append(verificationId, ivs);
1203 mCurrentIntentFilterVerifications.add(verificationId);
1209 private static boolean hasValidDomains(ActivityIntentInfo filter) {
1210 return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1211 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1212 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1215 // Set of pending broadcasts for aggregating enable/disable of components.
1216 static class PendingPackageBroadcasts {
1217 // for each user id, a map of <package name -> components within that package>
1218 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1220 public PendingPackageBroadcasts() {
1221 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1224 public ArrayList<String> get(int userId, String packageName) {
1225 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1226 return packages.get(packageName);
1229 public void put(int userId, String packageName, ArrayList<String> components) {
1230 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231 packages.put(packageName, components);
1234 public void remove(int userId, String packageName) {
1235 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1236 if (packages != null) {
1237 packages.remove(packageName);
1241 public void remove(int userId) {
1242 mUidMap.remove(userId);
1245 public int userIdCount() {
1246 return mUidMap.size();
1249 public int userIdAt(int n) {
1250 return mUidMap.keyAt(n);
1253 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1254 return mUidMap.get(userId);
1258 // total number of pending broadcast entries across all userIds
1260 for (int i = 0; i< mUidMap.size(); i++) {
1261 num += mUidMap.valueAt(i).size();
1266 public void clear() {
1270 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1271 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1273 map = new ArrayMap<String, ArrayList<String>>();
1274 mUidMap.put(userId, map);
1279 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1281 // Service Connection to remote media container service to copy
1282 // package uri's from external media onto secure containers
1283 // or internal storage.
1284 private IMediaContainerService mContainerService = null;
1286 static final int SEND_PENDING_BROADCAST = 1;
1287 static final int MCS_BOUND = 3;
1288 static final int END_COPY = 4;
1289 static final int INIT_COPY = 5;
1290 static final int MCS_UNBIND = 6;
1291 static final int START_CLEANING_PACKAGE = 7;
1292 static final int FIND_INSTALL_LOC = 8;
1293 static final int POST_INSTALL = 9;
1294 static final int MCS_RECONNECT = 10;
1295 static final int MCS_GIVE_UP = 11;
1296 static final int UPDATED_MEDIA_STATUS = 12;
1297 static final int WRITE_SETTINGS = 13;
1298 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1299 static final int PACKAGE_VERIFIED = 15;
1300 static final int CHECK_PENDING_VERIFICATION = 16;
1301 static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1302 static final int INTENT_FILTER_VERIFIED = 18;
1303 static final int WRITE_PACKAGE_LIST = 19;
1304 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1306 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
1308 // Delay time in millisecs
1309 static final int BROADCAST_DELAY = 10 * 1000;
1311 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1312 2 * 60 * 60 * 1000L; /* two hours */
1314 static UserManagerService sUserManager;
1316 // Stores a list of users whose package restrictions file needs to be updated
1317 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1319 final private DefaultContainerConnection mDefContainerConn =
1320 new DefaultContainerConnection();
1321 class DefaultContainerConnection implements ServiceConnection {
1322 public void onServiceConnected(ComponentName name, IBinder service) {
1323 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1324 final IMediaContainerService imcs = IMediaContainerService.Stub
1325 .asInterface(Binder.allowBlocking(service));
1326 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1329 public void onServiceDisconnected(ComponentName name) {
1330 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1334 // Recordkeeping of restore-after-install operations that are currently in flight
1335 // between the Package Manager and the Backup Manager
1336 static class PostInstallData {
1337 public InstallArgs args;
1338 public PackageInstalledInfo res;
1340 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1346 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1347 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
1349 // XML tags for backup/restore of various bits of state
1350 private static final String TAG_PREFERRED_BACKUP = "pa";
1351 private static final String TAG_DEFAULT_APPS = "da";
1352 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1354 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1355 private static final String TAG_ALL_GRANTS = "rt-grants";
1356 private static final String TAG_GRANT = "grant";
1357 private static final String ATTR_PACKAGE_NAME = "pkg";
1359 private static final String TAG_PERMISSION = "perm";
1360 private static final String ATTR_PERMISSION_NAME = "name";
1361 private static final String ATTR_IS_GRANTED = "g";
1362 private static final String ATTR_USER_SET = "set";
1363 private static final String ATTR_USER_FIXED = "fixed";
1364 private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1366 // System/policy permission grants are not backed up
1367 private static final int SYSTEM_RUNTIME_GRANT_MASK =
1368 FLAG_PERMISSION_POLICY_FIXED
1369 | FLAG_PERMISSION_SYSTEM_FIXED
1370 | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1372 // And we back up these user-adjusted states
1373 private static final int USER_RUNTIME_GRANT_MASK =
1374 FLAG_PERMISSION_USER_SET
1375 | FLAG_PERMISSION_USER_FIXED
1376 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1378 final @Nullable String mRequiredVerifierPackage;
1379 final @NonNull String mRequiredInstallerPackage;
1380 final @NonNull String mRequiredUninstallerPackage;
1381 final @Nullable String mSetupWizardPackage;
1382 final @Nullable String mStorageManagerPackage;
1383 final @NonNull String mServicesSystemSharedLibraryPackageName;
1384 final @NonNull String mSharedSystemSharedLibraryPackageName;
1386 final boolean mPermissionReviewRequired;
1388 private final PackageUsage mPackageUsage = new PackageUsage();
1389 private final CompilerStats mCompilerStats = new CompilerStats();
1391 class PackageHandler extends Handler {
1392 private boolean mBound = false;
1393 final ArrayList<HandlerParams> mPendingInstalls =
1394 new ArrayList<HandlerParams>();
1396 private boolean connectToService() {
1397 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1398 " DefaultContainerService");
1399 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1400 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401 if (mContext.bindServiceAsUser(service, mDefContainerConn,
1402 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1407 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1411 private void disconnectService() {
1412 mContainerService = null;
1414 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1415 mContext.unbindService(mDefContainerConn);
1416 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419 PackageHandler(Looper looper) {
1423 public void handleMessage(Message msg) {
1425 doHandleMessage(msg);
1427 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431 void doHandleMessage(Message msg) {
1434 HandlerParams params = (HandlerParams) msg.obj;
1435 int idx = mPendingInstalls.size();
1436 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1437 // If a bind was already initiated we dont really
1438 // need to do anything. The pending install
1439 // will be processed later on.
1441 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1442 System.identityHashCode(mHandler));
1443 // If this is the only one pending we might
1444 // have to bind to the service again.
1445 if (!connectToService()) {
1446 Slog.e(TAG, "Failed to bind to media container service");
1447 params.serviceError();
1448 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449 System.identityHashCode(mHandler));
1450 if (params.traceMethod != null) {
1451 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1452 params.traceCookie);
1456 // Once we bind to the service, the first
1457 // pending request will be processed.
1458 mPendingInstalls.add(idx, params);
1461 mPendingInstalls.add(idx, params);
1462 // Already bound to the service. Just make
1463 // sure we trigger off processing the first request.
1465 mHandler.sendEmptyMessage(MCS_BOUND);
1471 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1472 if (msg.obj != null) {
1473 mContainerService = (IMediaContainerService) msg.obj;
1474 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475 System.identityHashCode(mHandler));
1477 if (mContainerService == null) {
1479 // Something seriously wrong since we are not bound and we are not
1480 // waiting for connection. Bail out.
1481 Slog.e(TAG, "Cannot bind to media container service");
1482 for (HandlerParams params : mPendingInstalls) {
1483 // Indicate service bind error
1484 params.serviceError();
1485 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1486 System.identityHashCode(params));
1487 if (params.traceMethod != null) {
1488 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1489 params.traceMethod, params.traceCookie);
1493 mPendingInstalls.clear();
1495 Slog.w(TAG, "Waiting to connect to media container service");
1497 } else if (mPendingInstalls.size() > 0) {
1498 HandlerParams params = mPendingInstalls.get(0);
1499 if (params != null) {
1500 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501 System.identityHashCode(params));
1502 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1503 if (params.startCopy()) {
1504 // We are done... look for more work or to
1506 if (DEBUG_SD_INSTALL) Log.i(TAG,
1507 "Checking for more work or unbind...");
1508 // Delete pending install
1509 if (mPendingInstalls.size() > 0) {
1510 mPendingInstalls.remove(0);
1512 if (mPendingInstalls.size() == 0) {
1514 if (DEBUG_SD_INSTALL) Log.i(TAG,
1515 "Posting delayed MCS_UNBIND");
1516 removeMessages(MCS_UNBIND);
1517 Message ubmsg = obtainMessage(MCS_UNBIND);
1518 // Unbind after a little delay, to avoid
1519 // continual thrashing.
1520 sendMessageDelayed(ubmsg, 10000);
1523 // There are more pending requests in queue.
1524 // Just post MCS_BOUND message to trigger processing
1525 // of next pending install.
1526 if (DEBUG_SD_INSTALL) Log.i(TAG,
1527 "Posting MCS_BOUND for next work");
1528 mHandler.sendEmptyMessage(MCS_BOUND);
1531 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1534 // Should never happen ideally.
1535 Slog.w(TAG, "Empty queue");
1539 case MCS_RECONNECT: {
1540 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1541 if (mPendingInstalls.size() > 0) {
1543 disconnectService();
1545 if (!connectToService()) {
1546 Slog.e(TAG, "Failed to bind to media container service");
1547 for (HandlerParams params : mPendingInstalls) {
1548 // Indicate service bind error
1549 params.serviceError();
1550 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1551 System.identityHashCode(params));
1553 mPendingInstalls.clear();
1559 // If there is no actual work left, then time to unbind.
1560 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1562 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1564 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1566 disconnectService();
1568 } else if (mPendingInstalls.size() > 0) {
1569 // There are more pending requests in queue.
1570 // Just post MCS_BOUND message to trigger processing
1571 // of next pending install.
1572 mHandler.sendEmptyMessage(MCS_BOUND);
1578 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1579 HandlerParams params = mPendingInstalls.remove(0);
1580 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1581 System.identityHashCode(params));
1584 case SEND_PENDING_BROADCAST: {
1586 ArrayList<String> components[];
1589 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1590 synchronized (mPackages) {
1591 if (mPendingBroadcasts == null) {
1594 size = mPendingBroadcasts.size();
1596 // Nothing to be done. Just return
1599 packages = new String[size];
1600 components = new ArrayList[size];
1601 uids = new int[size];
1602 int i = 0; // filling out the above arrays
1604 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1605 int packageUserId = mPendingBroadcasts.userIdAt(n);
1606 Iterator<Map.Entry<String, ArrayList<String>>> it
1607 = mPendingBroadcasts.packagesForUserId(packageUserId)
1608 .entrySet().iterator();
1609 while (it.hasNext() && i < size) {
1610 Map.Entry<String, ArrayList<String>> ent = it.next();
1611 packages[i] = ent.getKey();
1612 components[i] = ent.getValue();
1613 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1614 uids[i] = (ps != null)
1615 ? UserHandle.getUid(packageUserId, ps.appId)
1621 mPendingBroadcasts.clear();
1624 for (int i = 0; i < size; i++) {
1625 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1627 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1630 case START_CLEANING_PACKAGE: {
1631 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632 final String packageName = (String)msg.obj;
1633 final int userId = msg.arg1;
1634 final boolean andCode = msg.arg2 != 0;
1635 synchronized (mPackages) {
1636 if (userId == UserHandle.USER_ALL) {
1637 int[] users = sUserManager.getUserIds();
1638 for (int user : users) {
1639 mSettings.addPackageToCleanLPw(
1640 new PackageCleanItem(user, packageName, andCode));
1643 mSettings.addPackageToCleanLPw(
1644 new PackageCleanItem(userId, packageName, andCode));
1647 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648 startCleaningPackages();
1650 case POST_INSTALL: {
1651 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1653 PostInstallData data = mRunningInstalls.get(msg.arg1);
1654 final boolean didRestore = (msg.arg2 != 0);
1655 mRunningInstalls.delete(msg.arg1);
1658 InstallArgs args = data.args;
1659 PackageInstalledInfo parentRes = data.res;
1661 final boolean grantPermissions = (args.installFlags
1662 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1663 final boolean killApp = (args.installFlags
1664 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1665 final String[] grantedPermissions = args.installGrantPermissions;
1667 // Handle the parent package
1668 handlePackagePostInstall(parentRes, grantPermissions, killApp,
1669 grantedPermissions, didRestore, args.installerPackageName,
1672 // Handle the child packages
1673 final int childCount = (parentRes.addedChildPackages != null)
1674 ? parentRes.addedChildPackages.size() : 0;
1675 for (int i = 0; i < childCount; i++) {
1676 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1677 handlePackagePostInstall(childRes, grantPermissions, killApp,
1678 grantedPermissions, false, args.installerPackageName,
1682 // Log tracing if needed
1683 if (args.traceMethod != null) {
1684 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1688 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1691 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1693 case UPDATED_MEDIA_STATUS: {
1694 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1695 boolean reportStatus = msg.arg1 == 1;
1696 boolean doGc = msg.arg2 == 1;
1697 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1699 // Force a gc to clear up stale containers.
1700 Runtime.getRuntime().gc();
1702 if (msg.obj != null) {
1703 @SuppressWarnings("unchecked")
1704 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1705 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1706 // Unload containers
1707 unloadAllContainers(args);
1711 if (DEBUG_SD_INSTALL) Log.i(TAG,
1712 "Invoking StorageManagerService call back");
1713 PackageHelper.getStorageManager().finishMediaUpdate();
1714 } catch (RemoteException e) {
1715 Log.e(TAG, "StorageManagerService not running?");
1719 case WRITE_SETTINGS: {
1720 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1721 synchronized (mPackages) {
1722 removeMessages(WRITE_SETTINGS);
1723 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1724 mSettings.writeLPr();
1725 mDirtyUsers.clear();
1727 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1729 case WRITE_PACKAGE_RESTRICTIONS: {
1730 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731 synchronized (mPackages) {
1732 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1733 for (int userId : mDirtyUsers) {
1734 mSettings.writePackageRestrictionsLPr(userId);
1736 mDirtyUsers.clear();
1738 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1740 case WRITE_PACKAGE_LIST: {
1741 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742 synchronized (mPackages) {
1743 removeMessages(WRITE_PACKAGE_LIST);
1744 mSettings.writePackageListLPr(msg.arg1);
1746 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1748 case CHECK_PENDING_VERIFICATION: {
1749 final int verificationId = msg.arg1;
1750 final PackageVerificationState state = mPendingVerification.get(verificationId);
1752 if ((state != null) && !state.timeoutExtended()) {
1753 final InstallArgs args = state.getInstallArgs();
1754 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1756 Slog.i(TAG, "Verification timed out for " + originUri);
1757 mPendingVerification.remove(verificationId);
1759 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1761 final UserHandle user = args.getUser();
1762 if (getDefaultVerificationResponse(user)
1763 == PackageManager.VERIFICATION_ALLOW) {
1764 Slog.i(TAG, "Continuing with installation of " + originUri);
1765 state.setVerifierResponse(Binder.getCallingUid(),
1766 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1767 broadcastPackageVerified(verificationId, originUri,
1768 PackageManager.VERIFICATION_ALLOW, user);
1770 ret = args.copyApk(mContainerService, true);
1771 } catch (RemoteException e) {
1772 Slog.e(TAG, "Could not contact the ContainerService");
1775 broadcastPackageVerified(verificationId, originUri,
1776 PackageManager.VERIFICATION_REJECT, user);
1779 Trace.asyncTraceEnd(
1780 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1782 processPendingInstall(args, ret);
1783 mHandler.sendEmptyMessage(MCS_UNBIND);
1787 case PACKAGE_VERIFIED: {
1788 final int verificationId = msg.arg1;
1790 final PackageVerificationState state = mPendingVerification.get(verificationId);
1791 if (state == null) {
1792 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1796 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1798 state.setVerifierResponse(response.callerUid, response.code);
1800 if (state.isVerificationComplete()) {
1801 mPendingVerification.remove(verificationId);
1803 final InstallArgs args = state.getInstallArgs();
1804 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1807 if (state.isInstallAllowed()) {
1808 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1809 broadcastPackageVerified(verificationId, originUri,
1810 response.code, state.getInstallArgs().getUser());
1812 ret = args.copyApk(mContainerService, true);
1813 } catch (RemoteException e) {
1814 Slog.e(TAG, "Could not contact the ContainerService");
1817 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1820 Trace.asyncTraceEnd(
1821 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1823 processPendingInstall(args, ret);
1824 mHandler.sendEmptyMessage(MCS_UNBIND);
1829 case START_INTENT_FILTER_VERIFICATIONS: {
1830 IFVerificationParams params = (IFVerificationParams) msg.obj;
1831 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1832 params.replacing, params.pkg);
1835 case INTENT_FILTER_VERIFIED: {
1836 final int verificationId = msg.arg1;
1838 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1840 if (state == null) {
1841 Slog.w(TAG, "Invalid IntentFilter verification token "
1842 + verificationId + " received");
1846 final int userId = state.getUserId();
1848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1849 "Processing IntentFilter verification with token:"
1850 + verificationId + " and userId:" + userId);
1852 final IntentFilterVerificationResponse response =
1853 (IntentFilterVerificationResponse) msg.obj;
1855 state.setVerifierResponse(response.callerUid, response.code);
1857 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858 "IntentFilter verification with token:" + verificationId
1859 + " and userId:" + userId
1860 + " is settings verifier response with response code:"
1863 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1864 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1865 + response.getFailedDomainsString());
1868 if (state.isVerificationComplete()) {
1869 mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1871 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872 "IntentFilter verification with token:" + verificationId
1873 + " was not said to be complete");
1878 case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1879 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1880 mInstantAppResolverConnection,
1881 (InstantAppRequest) msg.obj,
1882 mInstantAppInstallerActivity,
1889 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1890 boolean killApp, String[] grantedPermissions,
1891 boolean launchedForRestore, String installerPackage,
1892 IPackageInstallObserver2 installObserver) {
1893 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1894 // Send the removed broadcasts
1895 if (res.removedInfo != null) {
1896 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1899 // Now that we successfully installed the package, grant runtime
1900 // permissions if requested before broadcasting the install. Also
1901 // for legacy apps in permission review mode we clear the permission
1902 // review flag which is used to emulate runtime permissions for
1904 if (grantPermissions) {
1905 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1908 final boolean update = res.removedInfo != null
1909 && res.removedInfo.removedPackage != null;
1910 final String origInstallerPackageName = res.removedInfo != null
1911 ? res.removedInfo.installerPackageName : null;
1913 // If this is the first time we have child packages for a disabled privileged
1914 // app that had no children, we grant requested runtime permissions to the new
1915 // children if the parent on the system image had them already granted.
1916 if (res.pkg.parentPackage != null) {
1917 synchronized (mPackages) {
1918 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1922 synchronized (mPackages) {
1923 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1926 final String packageName = res.pkg.applicationInfo.packageName;
1928 // Determine the set of users who are adding this package for
1929 // the first time vs. those who are seeing an update.
1930 int[] firstUsers = EMPTY_INT_ARRAY;
1931 int[] updateUsers = EMPTY_INT_ARRAY;
1932 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1933 final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1934 for (int newUser : res.newUsers) {
1935 if (ps.getInstantApp(newUser)) {
1939 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1942 boolean isNew = true;
1943 for (int origUser : res.origUsers) {
1944 if (origUser == newUser) {
1950 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1952 updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1956 // Send installed broadcasts if the package is not a static shared lib.
1957 if (res.pkg.staticSharedLibName == null) {
1958 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1960 // Send added for users that see the package for the first time
1961 // sendPackageAddedForNewUsers also deals with system apps
1962 int appId = UserHandle.getAppId(res.uid);
1963 boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1964 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1966 // Send added for users that don't see the package for the first time
1967 Bundle extras = new Bundle(1);
1968 extras.putInt(Intent.EXTRA_UID, res.uid);
1970 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1972 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1973 extras, 0 /*flags*/,
1974 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1975 if (origInstallerPackageName != null) {
1976 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1977 extras, 0 /*flags*/,
1978 origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1981 // Send replaced for users that don't see the package for the first time
1983 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1984 packageName, extras, 0 /*flags*/,
1985 null /*targetPackage*/, null /*finishedReceiver*/,
1987 if (origInstallerPackageName != null) {
1988 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1989 extras, 0 /*flags*/,
1990 origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1992 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1993 null /*package*/, null /*extras*/, 0 /*flags*/,
1994 packageName /*targetPackage*/,
1995 null /*finishedReceiver*/, updateUsers);
1996 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1997 // First-install and we did a restore, so we're responsible for the
1998 // first-launch broadcast.
2000 Slog.i(TAG, "Post-restore of " + packageName
2001 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2003 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2006 // Send broadcast package appeared if forward locked/external for all users
2007 // treat asec-hosted packages like removable media on upgrade
2008 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2009 if (DEBUG_INSTALL) {
2010 Slog.i(TAG, "upgrading pkg " + res.pkg
2011 + " is ASEC-hosted -> AVAILABLE");
2013 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2014 ArrayList<String> pkgList = new ArrayList<>(1);
2015 pkgList.add(packageName);
2016 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2020 // Work that needs to happen on first install within each user
2021 if (firstUsers != null && firstUsers.length > 0) {
2022 synchronized (mPackages) {
2023 for (int userId : firstUsers) {
2024 // If this app is a browser and it's newly-installed for some
2025 // users, clear any default-browser state in those users. The
2026 // app's nature doesn't depend on the user, so we can just check
2027 // its browser nature in any user and generalize.
2028 if (packageIsBrowser(packageName, userId)) {
2029 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2032 // We may also need to apply pending (restored) runtime
2033 // permission grants within these users.
2034 mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2039 // Log current value of "unknown sources" setting
2040 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2041 getUnknownSourcesSettings());
2043 // Remove the replaced package's older resources safely now
2044 // We delete after a gc for applications on sdcard.
2045 if (res.removedInfo != null && res.removedInfo.args != null) {
2046 Runtime.getRuntime().gc();
2047 synchronized (mInstallLock) {
2048 res.removedInfo.args.doPostDeleteLI(true);
2051 // Force a gc to clear up things. Ask for a background one, it's fine to go on
2052 // and not block here.
2053 VMRuntime.getRuntime().requestConcurrentGC();
2056 // Notify DexManager that the package was installed for new users.
2057 // The updated users should already be indexed and the package code paths
2058 // should not change.
2059 // Don't notify the manager for ephemeral apps as they are not expected to
2060 // survive long enough to benefit of background optimizations.
2061 for (int userId : firstUsers) {
2062 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2063 // There's a race currently where some install events may interleave with an uninstall.
2064 // This can lead to package info being null (b/36642664).
2066 mDexManager.notifyPackageInstalled(info, userId);
2071 // If someone is watching installs - notify them
2072 if (installObserver != null) {
2074 Bundle extras = extrasForInstallResult(res);
2075 installObserver.onPackageInstalled(res.name, res.returnCode,
2076 res.returnMsg, extras);
2077 } catch (RemoteException e) {
2078 Slog.i(TAG, "Observer no longer exists.");
2083 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2084 PackageParser.Package pkg) {
2085 if (pkg.parentPackage == null) {
2088 if (pkg.requestedPermissions == null) {
2091 final PackageSetting disabledSysParentPs = mSettings
2092 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2093 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2094 || !disabledSysParentPs.isPrivileged()
2095 || (disabledSysParentPs.childPackageNames != null
2096 && !disabledSysParentPs.childPackageNames.isEmpty())) {
2099 final int[] allUserIds = sUserManager.getUserIds();
2100 final int permCount = pkg.requestedPermissions.size();
2101 for (int i = 0; i < permCount; i++) {
2102 String permission = pkg.requestedPermissions.get(i);
2103 BasePermission bp = mSettings.mPermissions.get(permission);
2104 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2107 for (int userId : allUserIds) {
2108 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2109 permission, userId)) {
2110 grantRuntimePermission(pkg.packageName, permission, userId);
2116 private StorageEventListener mStorageListener = new StorageEventListener() {
2118 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2119 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2120 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2121 final String volumeUuid = vol.getFsUuid();
2123 // Clean up any users or apps that were removed or recreated
2124 // while this volume was missing
2125 sUserManager.reconcileUsers(volumeUuid);
2126 reconcileApps(volumeUuid);
2128 // Clean up any install sessions that expired or were
2129 // cancelled while this volume was missing
2130 mInstallerService.onPrivateVolumeMounted(volumeUuid);
2132 loadPrivatePackages(vol);
2134 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2135 unloadPrivatePackages(vol);
2139 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2140 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2141 updateExternalMediaStatus(true, false);
2142 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2143 updateExternalMediaStatus(false, false);
2149 public void onVolumeForgotten(String fsUuid) {
2150 if (TextUtils.isEmpty(fsUuid)) {
2151 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2155 // Remove any apps installed on the forgotten volume
2156 synchronized (mPackages) {
2157 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2158 for (PackageSetting ps : packages) {
2159 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2160 deletePackageVersioned(new VersionedPackage(ps.name,
2161 PackageManager.VERSION_CODE_HIGHEST),
2162 new LegacyPackageDeleteObserver(null).getBinder(),
2163 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2164 // Try very hard to release any references to this package
2165 // so we don't risk the system server being killed due to
2167 AttributeCache.instance().removePackage(ps.name);
2170 mSettings.onVolumeForgotten(fsUuid);
2171 mSettings.writeLPr();
2176 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2177 String[] grantedPermissions) {
2178 for (int userId : userIds) {
2179 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2183 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2184 String[] grantedPermissions) {
2185 PackageSetting ps = (PackageSetting) pkg.mExtras;
2190 PermissionsState permissionsState = ps.getPermissionsState();
2192 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2193 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2195 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2196 >= Build.VERSION_CODES.M;
2198 final boolean instantApp = isInstantApp(pkg.packageName, userId);
2200 for (String permission : pkg.requestedPermissions) {
2201 final BasePermission bp;
2202 synchronized (mPackages) {
2203 bp = mSettings.mPermissions.get(permission);
2205 if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2206 && (!instantApp || bp.isInstant())
2207 && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2208 && (grantedPermissions == null
2209 || ArrayUtils.contains(grantedPermissions, permission))) {
2210 final int flags = permissionsState.getPermissionFlags(permission, userId);
2211 if (supportsRuntimePermissions) {
2212 // Installer cannot change immutable permissions.
2213 if ((flags & immutableFlags) == 0) {
2214 grantRuntimePermission(pkg.packageName, permission, userId);
2216 } else if (mPermissionReviewRequired) {
2217 // In permission review mode we clear the review flag when we
2218 // are asked to install the app with all permissions granted.
2219 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2220 updatePermissionFlags(permission, pkg.packageName,
2221 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2228 Bundle extrasForInstallResult(PackageInstalledInfo res) {
2229 Bundle extras = null;
2230 switch (res.returnCode) {
2231 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2232 extras = new Bundle();
2233 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2234 res.origPermission);
2235 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2239 case PackageManager.INSTALL_SUCCEEDED: {
2240 extras = new Bundle();
2241 extras.putBoolean(Intent.EXTRA_REPLACING,
2242 res.removedInfo != null && res.removedInfo.removedPackage != null);
2249 void scheduleWriteSettingsLocked() {
2250 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2251 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2255 void scheduleWritePackageListLocked(int userId) {
2256 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2257 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2259 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2263 void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2264 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2265 scheduleWritePackageRestrictionsLocked(userId);
2268 void scheduleWritePackageRestrictionsLocked(int userId) {
2269 final int[] userIds = (userId == UserHandle.USER_ALL)
2270 ? sUserManager.getUserIds() : new int[]{userId};
2271 for (int nextUserId : userIds) {
2272 if (!sUserManager.exists(nextUserId)) return;
2273 mDirtyUsers.add(nextUserId);
2274 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2275 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2280 public static PackageManagerService main(Context context, Installer installer,
2281 boolean factoryTest, boolean onlyCore) {
2282 // Self-check for initial settings.
2283 PackageManagerServiceCompilerMapping.checkProperties();
2285 PackageManagerService m = new PackageManagerService(context, installer,
2286 factoryTest, onlyCore);
2287 m.enableSystemUserPackages();
2288 ServiceManager.addService("package", m);
2292 private void enableSystemUserPackages() {
2293 if (!UserManager.isSplitSystemUser()) {
2296 // For system user, enable apps based on the following conditions:
2297 // - app is whitelisted or belong to one of these groups:
2298 // -- system app which has no launcher icons
2299 // -- system app which has INTERACT_ACROSS_USERS permission
2300 // -- system IME app
2301 // - app is not in the blacklist
2302 AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2303 Set<String> enableApps = new ArraySet<>();
2304 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2305 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2306 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2307 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2308 enableApps.addAll(wlApps);
2309 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2310 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2311 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2312 enableApps.removeAll(blApps);
2313 Log.i(TAG, "Applications installed for system user: " + enableApps);
2314 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2316 final int allAppsSize = allAps.size();
2317 synchronized (mPackages) {
2318 for (int i = 0; i < allAppsSize; i++) {
2319 String pName = allAps.get(i);
2320 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2321 // Should not happen, but we shouldn't be failing if it does
2322 if (pkgSetting == null) {
2325 boolean install = enableApps.contains(pName);
2326 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2327 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2328 + " for system user");
2329 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2332 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2336 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2337 DisplayManager displayManager = (DisplayManager) context.getSystemService(
2338 Context.DISPLAY_SERVICE);
2339 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2343 * Requests that files preopted on a secondary system partition be copied to the data partition
2344 * if possible. Note that the actual copying of the files is accomplished by init for security
2345 * reasons. This simply requests that the copy takes place and awaits confirmation of its
2346 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2348 private static void requestCopyPreoptedFiles() {
2349 final int WAIT_TIME_MS = 100;
2350 final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2351 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2352 SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2353 // We will wait for up to 100 seconds.
2354 final long timeStart = SystemClock.uptimeMillis();
2355 final long timeEnd = timeStart + 100 * 1000;
2356 long timeNow = timeStart;
2357 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2359 Thread.sleep(WAIT_TIME_MS);
2360 } catch (InterruptedException e) {
2363 timeNow = SystemClock.uptimeMillis();
2364 if (timeNow > timeEnd) {
2365 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2366 Slog.wtf(TAG, "cppreopt did not finish!");
2371 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2375 public PackageManagerService(Context context, Installer installer,
2376 boolean factoryTest, boolean onlyCore) {
2377 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2378 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2380 SystemClock.uptimeMillis());
2382 if (mSdkVersion <= 0) {
2383 Slog.w(TAG, "**** ro.build.version.sdk not set!");
2388 mPermissionReviewRequired = context.getResources().getBoolean(
2389 R.bool.config_permissionReviewRequired);
2391 mFactoryTest = factoryTest;
2392 mOnlyCore = onlyCore;
2393 mMetrics = new DisplayMetrics();
2394 mSettings = new Settings(mPackages);
2395 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2396 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2398 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2400 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2402 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2404 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2406 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408 String separateProcesses = SystemProperties.get("debug.separate_processes");
2409 if (separateProcesses != null && separateProcesses.length() > 0) {
2410 if ("*".equals(separateProcesses)) {
2411 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2412 mSeparateProcesses = null;
2413 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2416 mSeparateProcesses = separateProcesses.split(",");
2417 Slog.w(TAG, "Running with debug.separate_processes: "
2418 + separateProcesses);
2422 mSeparateProcesses = null;
2425 mInstaller = installer;
2426 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2428 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2429 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2431 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2432 FgThread.get().getLooper());
2434 getDefaultDisplayMetrics(context, mMetrics);
2436 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2437 SystemConfig systemConfig = SystemConfig.getInstance();
2438 mGlobalGids = systemConfig.getGlobalGids();
2439 mSystemPermissions = systemConfig.getSystemPermissions();
2440 mAvailableFeatures = systemConfig.getAvailableFeatures();
2441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2443 mProtectedPackages = new ProtectedPackages(mContext);
2445 synchronized (mInstallLock) {
2447 synchronized (mPackages) {
2448 mHandlerThread = new ServiceThread(TAG,
2449 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2450 mHandlerThread.start();
2451 mHandler = new PackageHandler(mHandlerThread.getLooper());
2452 mProcessLoggingHandler = new ProcessLoggingHandler();
2453 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2455 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2456 mInstantAppRegistry = new InstantAppRegistry(this);
2458 File dataDir = Environment.getDataDirectory();
2459 mAppInstallDir = new File(dataDir, "app");
2460 mAppLib32InstallDir = new File(dataDir, "app-lib");
2461 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2462 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2463 sUserManager = new UserManagerService(context, this,
2464 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2466 // Propagate permission configuration in to package manager.
2467 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2468 = systemConfig.getPermissions();
2469 for (int i=0; i<permConfig.size(); i++) {
2470 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2471 BasePermission bp = mSettings.mPermissions.get(perm.name);
2473 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2474 mSettings.mPermissions.put(perm.name, bp);
2476 if (perm.gids != null) {
2477 bp.setGids(perm.gids, perm.perUser);
2481 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2482 final int builtInLibCount = libConfig.size();
2483 for (int i = 0; i < builtInLibCount; i++) {
2484 String name = libConfig.keyAt(i);
2485 String path = libConfig.valueAt(i);
2486 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2487 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2490 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2492 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2493 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2494 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2496 // Clean up orphaned packages for which the code path doesn't exist
2497 // and they are an update to a system app - caused by bug/32321269
2498 final int packageSettingCount = mSettings.mPackages.size();
2499 for (int i = packageSettingCount - 1; i >= 0; i--) {
2500 PackageSetting ps = mSettings.mPackages.valueAt(i);
2501 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2502 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2503 mSettings.mPackages.removeAt(i);
2504 mSettings.enableSystemPackageLPw(ps.name);
2509 requestCopyPreoptedFiles();
2512 String customResolverActivity = Resources.getSystem().getString(
2513 R.string.config_customResolverActivity);
2514 if (TextUtils.isEmpty(customResolverActivity)) {
2515 customResolverActivity = null;
2517 mCustomResolverComponentName = ComponentName.unflattenFromString(
2518 customResolverActivity);
2521 long startTime = SystemClock.uptimeMillis();
2523 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2526 final String bootClassPath = System.getenv("BOOTCLASSPATH");
2527 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2529 if (bootClassPath == null) {
2530 Slog.w(TAG, "No BOOTCLASSPATH found!");
2533 if (systemServerClassPath == null) {
2534 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2537 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2539 final VersionInfo ver = mSettings.getInternalVersion();
2540 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2542 logCriticalInfo(Log.INFO,
2543 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2546 // when upgrading from pre-M, promote system app permissions from install to runtime
2547 mPromoteSystemApps =
2548 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2550 // When upgrading from pre-N, we need to handle package extraction like first boot,
2551 // as there is no profiling data available.
2552 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2554 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2556 // save off the names of pre-existing system packages prior to scanning; we don't
2557 // want to automatically grant runtime permissions for new system apps
2558 if (mPromoteSystemApps) {
2559 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2560 while (pkgSettingIter.hasNext()) {
2561 PackageSetting ps = pkgSettingIter.next();
2562 if (isSystemApp(ps)) {
2563 mExistingSystemPackages.add(ps.name);
2568 mCacheDir = preparePackageParserCache(mIsUpgrade);
2570 // Set flag to monitor and not change apk file paths when
2571 // scanning install directories.
2572 int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2574 if (mIsUpgrade || mFirstBoot) {
2575 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2578 // Collect vendor overlay packages. (Do this before scanning any apps.)
2579 // For security and version matching reason, only consider
2580 // overlay packages if they reside in the right directory.
2581 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2582 | PackageParser.PARSE_IS_SYSTEM
2583 | PackageParser.PARSE_IS_SYSTEM_DIR
2584 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2586 mParallelPackageParserCallback.findStaticOverlayPackages();
2588 // Find base frameworks (resource packages without code).
2589 scanDirTracedLI(frameworkDir, mDefParseFlags
2590 | PackageParser.PARSE_IS_SYSTEM
2591 | PackageParser.PARSE_IS_SYSTEM_DIR
2592 | PackageParser.PARSE_IS_PRIVILEGED,
2593 scanFlags | SCAN_NO_DEX, 0);
2595 // Collected privileged system packages.
2596 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2597 scanDirTracedLI(privilegedAppDir, mDefParseFlags
2598 | PackageParser.PARSE_IS_SYSTEM
2599 | PackageParser.PARSE_IS_SYSTEM_DIR
2600 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2602 // Collect ordinary system packages.
2603 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2604 scanDirTracedLI(systemAppDir, mDefParseFlags
2605 | PackageParser.PARSE_IS_SYSTEM
2606 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2608 // Collect all vendor packages.
2609 File vendorAppDir = new File("/vendor/app");
2611 vendorAppDir = vendorAppDir.getCanonicalFile();
2612 } catch (IOException e) {
2613 // failed to look up canonical path, continue with original one
2615 scanDirTracedLI(vendorAppDir, mDefParseFlags
2616 | PackageParser.PARSE_IS_SYSTEM
2617 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2619 // Collect all OEM packages.
2620 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2621 scanDirTracedLI(oemAppDir, mDefParseFlags
2622 | PackageParser.PARSE_IS_SYSTEM
2623 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2625 // Prune any system packages that no longer exist.
2626 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2628 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2629 while (psit.hasNext()) {
2630 PackageSetting ps = psit.next();
2633 * If this is not a system app, it can't be a
2634 * disable system app.
2636 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2641 * If the package is scanned, it's not erased.
2643 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2644 if (scannedPkg != null) {
2646 * If the system app is both scanned and in the
2647 * disabled packages list, then it must have been
2648 * added via OTA. Remove it from the currently
2649 * scanned package so the previously user-installed
2650 * application can be scanned.
2652 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2653 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2654 + ps.name + "; removing system app. Last known codePath="
2655 + ps.codePathString + ", installStatus=" + ps.installStatus
2656 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2657 + scannedPkg.mVersionCode);
2658 removePackageLI(scannedPkg, true);
2659 mExpectingBetter.put(ps.name, ps.codePath);
2665 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2667 logCriticalInfo(Log.WARN, "System package " + ps.name
2668 + " no longer exists; it's data will be wiped");
2669 // Actual deletion of code and data will be handled by later
2670 // reconciliation step
2672 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2673 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2674 possiblyDeletedUpdatedSystemApps.add(ps.name);
2680 //look for any incomplete package installations
2681 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2682 for (int i = 0; i < deletePkgsList.size(); i++) {
2683 // Actual deletion of code and data will be handled by later
2684 // reconciliation step
2685 final String packageName = deletePkgsList.get(i).name;
2686 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2687 synchronized (mPackages) {
2688 mSettings.removePackageLPw(packageName);
2693 deleteTempPackageFiles();
2695 // Remove any shared userIDs that have no associated packages
2696 mSettings.pruneSharedUsersLPw();
2699 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2700 SystemClock.uptimeMillis());
2701 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2703 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2704 | PackageParser.PARSE_FORWARD_LOCK,
2705 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2708 * Remove disable package settings for any updated system
2709 * apps that were removed via an OTA. If they're not a
2710 * previously-updated app, remove them completely.
2711 * Otherwise, just revoke their system-level permissions.
2713 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2714 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2715 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2718 if (deletedPkg == null) {
2719 msg = "Updated system package " + deletedAppName
2720 + " no longer exists; it's data will be wiped";
2721 // Actual deletion of code and data will be handled by later
2722 // reconciliation step
2724 msg = "Updated system app + " + deletedAppName
2725 + " no longer present; removing system privileges for "
2728 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2730 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2731 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2733 logCriticalInfo(Log.WARN, msg);
2737 * Make sure all system apps that we expected to appear on
2738 * the userdata partition actually showed up. If they never
2739 * appeared, crawl back and revive the system version.
2741 for (int i = 0; i < mExpectingBetter.size(); i++) {
2742 final String packageName = mExpectingBetter.keyAt(i);
2743 if (!mPackages.containsKey(packageName)) {
2744 final File scanFile = mExpectingBetter.valueAt(i);
2746 logCriticalInfo(Log.WARN, "Expected better " + packageName
2747 + " but never showed up; reverting to system");
2749 int reparseFlags = mDefParseFlags;
2750 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2751 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2752 | PackageParser.PARSE_IS_SYSTEM_DIR
2753 | PackageParser.PARSE_IS_PRIVILEGED;
2754 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2755 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756 | PackageParser.PARSE_IS_SYSTEM_DIR;
2757 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2758 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2759 | PackageParser.PARSE_IS_SYSTEM_DIR;
2760 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2761 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762 | PackageParser.PARSE_IS_SYSTEM_DIR;
2764 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2768 mSettings.enableSystemPackageLPw(packageName);
2771 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2772 } catch (PackageManagerException e) {
2773 Slog.e(TAG, "Failed to parse original system package: "
2779 mExpectingBetter.clear();
2781 // Resolve the storage manager.
2782 mStorageManagerPackage = getStorageManagerPackageName();
2784 // Resolve protected action filters. Only the setup wizard is allowed to
2785 // have a high priority filter for these actions.
2786 mSetupWizardPackage = getSetupWizardPackageName();
2787 if (mProtectedFilters.size() > 0) {
2788 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2789 Slog.i(TAG, "No setup wizard;"
2790 + " All protected intents capped to priority 0");
2792 for (ActivityIntentInfo filter : mProtectedFilters) {
2793 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2794 if (DEBUG_FILTERS) {
2795 Slog.i(TAG, "Found setup wizard;"
2796 + " allow priority " + filter.getPriority() + ";"
2797 + " package: " + filter.activity.info.packageName
2798 + " activity: " + filter.activity.className
2799 + " priority: " + filter.getPriority());
2801 // skip setup wizard; allow it to keep the high priority filter
2804 if (DEBUG_FILTERS) {
2805 Slog.i(TAG, "Protected action; cap priority to 0;"
2806 + " package: " + filter.activity.info.packageName
2807 + " activity: " + filter.activity.className
2808 + " origPrio: " + filter.getPriority());
2810 filter.setPriority(0);
2813 mDeferProtectedFilters = false;
2814 mProtectedFilters.clear();
2816 // Now that we know all of the shared libraries, update all clients to have
2817 // the correct library paths.
2818 updateAllSharedLibrariesLPw(null);
2820 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2821 // NOTE: We ignore potential failures here during a system scan (like
2822 // the rest of the commands above) because there's precious little we
2823 // can do about it. A settings error is reported, though.
2824 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2827 // Now that we know all the packages we are keeping,
2828 // read and update their last usage times.
2829 mPackageUsage.read(mPackages);
2830 mCompilerStats.read();
2832 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2833 SystemClock.uptimeMillis());
2834 Slog.i(TAG, "Time to scan packages: "
2835 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2838 // If the platform SDK has changed since the last time we booted,
2839 // we need to re-grant app permission to catch any new ones that
2840 // appear. This is really a hack, and means that apps can in some
2841 // cases get permissions that the user didn't initially explicitly
2842 // allow... it would be nice to have some better way to handle
2844 int updateFlags = UPDATE_PERMISSIONS_ALL;
2845 if (ver.sdkVersion != mSdkVersion) {
2846 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2847 + mSdkVersion + "; regranting permissions for internal storage");
2848 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2850 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2851 ver.sdkVersion = mSdkVersion;
2853 // If this is the first boot or an update from pre-M, and it is a normal
2854 // boot, then we need to initialize the default preferred apps across
2855 // all defined users.
2856 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2857 for (UserInfo user : sUserManager.getUsers(true)) {
2858 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2859 applyFactoryDefaultBrowserLPw(user.id);
2860 primeDomainVerificationsLPw(user.id);
2864 // Prepare storage for system user really early during boot,
2865 // since core system apps like SettingsProvider and SystemUI
2866 // can't wait for user to start
2867 final int storageFlags;
2868 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2869 storageFlags = StorageManager.FLAG_STORAGE_DE;
2871 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2873 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2874 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2875 true /* onlyCoreApps */);
2876 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2877 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2878 Trace.TRACE_TAG_PACKAGE_MANAGER);
2879 traceLog.traceBegin("AppDataFixup");
2881 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2882 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2883 } catch (InstallerException e) {
2884 Slog.w(TAG, "Trouble fixing GIDs", e);
2886 traceLog.traceEnd();
2888 traceLog.traceBegin("AppDataPrepare");
2889 if (deferPackages == null || deferPackages.isEmpty()) {
2893 for (String pkgName : deferPackages) {
2894 PackageParser.Package pkg = null;
2895 synchronized (mPackages) {
2896 PackageSetting ps = mSettings.getPackageLPr(pkgName);
2897 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2902 synchronized (mInstallLock) {
2903 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2904 true /* maybeMigrateAppData */);
2909 traceLog.traceEnd();
2910 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2911 }, "prepareAppData");
2913 // If this is first boot after an OTA, and a normal boot, then
2914 // we need to clear code cache directories.
2915 // Note that we do *not* clear the application profiles. These remain valid
2916 // across OTAs and are used to drive profile verification (post OTA) and
2917 // profile compilation (without waiting to collect a fresh set of profiles).
2918 if (mIsUpgrade && !onlyCore) {
2919 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2920 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2921 final PackageSetting ps = mSettings.mPackages.valueAt(i);
2922 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2923 // No apps are running this early, so no need to freeze
2924 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2925 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2926 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2929 ver.fingerprint = Build.FINGERPRINT;
2932 checkDefaultBrowser();
2934 // clear only after permissions and other defaults have been updated
2935 mExistingSystemPackages.clear();
2936 mPromoteSystemApps = false;
2938 // All the changes are done during package scanning.
2939 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2941 // can downgrade to reader
2942 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2943 mSettings.writeLPr();
2944 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2946 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2947 SystemClock.uptimeMillis());
2950 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2951 mRequiredInstallerPackage = getRequiredInstallerLPr();
2952 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2953 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2954 if (mIntentFilterVerifierComponent != null) {
2955 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2956 mIntentFilterVerifierComponent);
2958 mIntentFilterVerifier = null;
2960 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2961 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2962 SharedLibraryInfo.VERSION_UNDEFINED);
2963 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2964 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2965 SharedLibraryInfo.VERSION_UNDEFINED);
2967 mRequiredVerifierPackage = null;
2968 mRequiredInstallerPackage = null;
2969 mRequiredUninstallerPackage = null;
2970 mIntentFilterVerifierComponent = null;
2971 mIntentFilterVerifier = null;
2972 mServicesSystemSharedLibraryPackageName = null;
2973 mSharedSystemSharedLibraryPackageName = null;
2976 mInstallerService = new PackageInstallerService(context, this);
2977 final Pair<ComponentName, String> instantAppResolverComponent =
2978 getInstantAppResolverLPr();
2979 if (instantAppResolverComponent != null) {
2980 if (DEBUG_EPHEMERAL) {
2981 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2983 mInstantAppResolverConnection = new EphemeralResolverConnection(
2984 mContext, instantAppResolverComponent.first,
2985 instantAppResolverComponent.second);
2986 mInstantAppResolverSettingsComponent =
2987 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2989 mInstantAppResolverConnection = null;
2990 mInstantAppResolverSettingsComponent = null;
2992 updateInstantAppInstallerLocked(null);
2994 // Read and update the usage of dex files.
2995 // Do this at the end of PM init so that all the packages have their
2996 // data directory reconciled.
2997 // At this point we know the code paths of the packages, so we can validate
2998 // the disk file and build the internal cache.
2999 // The usage file is expected to be small so loading and verifying it
3000 // should take a fairly small time compare to the other activities (e.g. package
3002 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3003 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3004 for (int userId : currentUserIds) {
3005 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3007 mDexManager.load(userPackages);
3008 } // synchronized (mPackages)
3009 } // synchronized (mInstallLock)
3011 // Now after opening every single application zip, make sure they
3012 // are all flushed. Not really needed, but keeps things nice and
3014 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3015 Runtime.getRuntime().gc();
3016 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3018 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3019 FallbackCategoryProvider.loadFallbacks();
3020 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3022 // The initial scanning above does many calls into installd while
3023 // holding the mPackages lock, but we're mostly interested in yelling
3024 // once we have a booted system.
3025 mInstaller.setWarnIfHeld(mPackages);
3027 // Expose private service for system components to use.
3028 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3029 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3032 private void updateInstantAppInstallerLocked(String modifiedPackage) {
3033 // we're only interested in updating the installer appliction when 1) it's not
3034 // already set or 2) the modified package is the installer
3035 if (mInstantAppInstallerActivity != null
3036 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3037 .equals(modifiedPackage)) {
3040 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3043 private static File preparePackageParserCache(boolean isUpgrade) {
3044 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3048 // Disable package parsing on eng builds to allow for faster incremental development.
3049 if ("eng".equals(Build.TYPE)) {
3053 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3054 Slog.i(TAG, "Disabling package parser cache due to system property.");
3058 // The base directory for the package parser cache lives under /data/system/.
3059 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3061 if (cacheBaseDir == null) {
3065 // If this is a system upgrade scenario, delete the contents of the package cache dir.
3066 // This also serves to "GC" unused entries when the package cache version changes (which
3067 // can only happen during upgrades).
3069 FileUtils.deleteContents(cacheBaseDir);
3073 // Return the versioned package cache directory. This is something like
3074 // "/data/system/package_cache/1"
3075 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3077 // The following is a workaround to aid development on non-numbered userdebug
3078 // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3079 // the system partition is newer.
3081 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3082 // that starts with "eng." to signify that this is an engineering build and not
3083 // destined for release.
3084 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3085 Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3087 // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3088 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3089 // in general and should not be used for production changes. In this specific case,
3090 // we know that they will work.
3091 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3092 if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3093 FileUtils.deleteContents(cacheBaseDir);
3094 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3102 public boolean isFirstBoot() {
3103 // allow instant applications
3108 public boolean isOnlyCoreApps() {
3109 // allow instant applications
3114 public boolean isUpgrade() {
3115 // allow instant applications
3119 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3120 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3122 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3123 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3124 UserHandle.USER_SYSTEM);
3125 if (matches.size() == 1) {
3126 return matches.get(0).getComponentInfo().packageName;
3127 } else if (matches.size() == 0) {
3128 Log.e(TAG, "There should probably be a verifier, but, none were found");
3131 throw new RuntimeException("There must be exactly one verifier; found " + matches);
3134 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3135 synchronized (mPackages) {
3136 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3137 if (libraryEntry == null) {
3138 throw new IllegalStateException("Missing required shared library:" + name);
3140 return libraryEntry.apk;
3144 private @NonNull String getRequiredInstallerLPr() {
3145 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3146 intent.addCategory(Intent.CATEGORY_DEFAULT);
3147 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3149 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3150 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3151 UserHandle.USER_SYSTEM);
3152 if (matches.size() == 1) {
3153 ResolveInfo resolveInfo = matches.get(0);
3154 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3155 throw new RuntimeException("The installer must be a privileged app");
3157 return matches.get(0).getComponentInfo().packageName;
3159 throw new RuntimeException("There must be exactly one installer; found " + matches);
3163 private @NonNull String getRequiredUninstallerLPr() {
3164 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3165 intent.addCategory(Intent.CATEGORY_DEFAULT);
3166 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3168 final ResolveInfo resolveInfo = resolveIntent(intent, null,
3169 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3170 UserHandle.USER_SYSTEM);
3171 if (resolveInfo == null ||
3172 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3173 throw new RuntimeException("There must be exactly one uninstaller; found "
3176 return resolveInfo.getComponentInfo().packageName;
3179 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3180 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3182 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3183 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3184 UserHandle.USER_SYSTEM);
3185 ResolveInfo best = null;
3186 final int N = matches.size();
3187 for (int i = 0; i < N; i++) {
3188 final ResolveInfo cur = matches.get(i);
3189 final String packageName = cur.getComponentInfo().packageName;
3190 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3191 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3195 if (best == null || cur.priority > best.priority) {
3201 return best.getComponentInfo().getComponentName();
3203 Slog.w(TAG, "Intent filter verifier not found");
3208 public @Nullable ComponentName getInstantAppResolverComponent() {
3209 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3212 synchronized (mPackages) {
3213 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3214 if (instantAppResolver == null) {
3217 return instantAppResolver.first;
3221 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3222 final String[] packageArray =
3223 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3224 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3225 if (DEBUG_EPHEMERAL) {
3226 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3231 final int callingUid = Binder.getCallingUid();
3232 final int resolveFlags =
3233 MATCH_DIRECT_BOOT_AWARE
3234 | MATCH_DIRECT_BOOT_UNAWARE
3235 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3236 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3237 final Intent resolverIntent = new Intent(actionName);
3238 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3239 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3240 // temporarily look for the old action
3241 if (resolvers.size() == 0) {
3242 if (DEBUG_EPHEMERAL) {
3243 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3245 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3246 resolverIntent.setAction(actionName);
3247 resolvers = queryIntentServicesInternal(resolverIntent, null,
3248 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3250 final int N = resolvers.size();
3252 if (DEBUG_EPHEMERAL) {
3253 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3258 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3259 for (int i = 0; i < N; i++) {
3260 final ResolveInfo info = resolvers.get(i);
3262 if (info.serviceInfo == null) {
3266 final String packageName = info.serviceInfo.packageName;
3267 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3268 if (DEBUG_EPHEMERAL) {
3269 Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3270 + " pkg: " + packageName + ", info:" + info);
3275 if (DEBUG_EPHEMERAL) {
3276 Slog.v(TAG, "Ephemeral resolver found;"
3277 + " pkg: " + packageName + ", info:" + info);
3279 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3281 if (DEBUG_EPHEMERAL) {
3282 Slog.v(TAG, "Ephemeral resolver NOT found");
3287 private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3288 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3289 intent.addCategory(Intent.CATEGORY_DEFAULT);
3290 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3292 final int resolveFlags =
3293 MATCH_DIRECT_BOOT_AWARE
3294 | MATCH_DIRECT_BOOT_UNAWARE
3295 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3296 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3297 resolveFlags, UserHandle.USER_SYSTEM);
3298 // temporarily look for the old action
3299 if (matches.isEmpty()) {
3300 if (DEBUG_EPHEMERAL) {
3301 Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3303 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3304 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3305 resolveFlags, UserHandle.USER_SYSTEM);
3307 Iterator<ResolveInfo> iter = matches.iterator();
3308 while (iter.hasNext()) {
3309 final ResolveInfo rInfo = iter.next();
3310 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3312 final PermissionsState permissionsState = ps.getPermissionsState();
3313 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3319 if (matches.size() == 0) {
3321 } else if (matches.size() == 1) {
3322 return (ActivityInfo) matches.get(0).getComponentInfo();
3324 throw new RuntimeException(
3325 "There must be at most one ephemeral installer; found " + matches);
3329 private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3330 @NonNull ComponentName resolver) {
3331 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3332 .addCategory(Intent.CATEGORY_DEFAULT)
3333 .setPackage(resolver.getPackageName());
3334 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3335 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3336 UserHandle.USER_SYSTEM);
3337 // temporarily look for the old action
3338 if (matches.isEmpty()) {
3339 if (DEBUG_EPHEMERAL) {
3340 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3342 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3343 matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3344 UserHandle.USER_SYSTEM);
3346 if (matches.isEmpty()) {
3349 return matches.get(0).getComponentInfo().getComponentName();
3352 private void primeDomainVerificationsLPw(int userId) {
3353 if (DEBUG_DOMAIN_VERIFICATION) {
3354 Slog.d(TAG, "Priming domain verifications in user " + userId);
3357 SystemConfig systemConfig = SystemConfig.getInstance();
3358 ArraySet<String> packages = systemConfig.getLinkedApps();
3360 for (String packageName : packages) {
3361 PackageParser.Package pkg = mPackages.get(packageName);
3363 if (!pkg.isSystemApp()) {
3364 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3368 ArraySet<String> domains = null;
3369 for (PackageParser.Activity a : pkg.activities) {
3370 for (ActivityIntentInfo filter : a.intents) {
3371 if (hasValidDomains(filter)) {
3372 if (domains == null) {
3373 domains = new ArraySet<String>();
3375 domains.addAll(filter.getHostsList());
3380 if (domains != null && domains.size() > 0) {
3381 if (DEBUG_DOMAIN_VERIFICATION) {
3382 Slog.v(TAG, " + " + packageName);
3384 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3385 // state w.r.t. the formal app-linkage "no verification attempted" state;
3386 // and then 'always' in the per-user state actually used for intent resolution.
3387 final IntentFilterVerificationInfo ivi;
3388 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3389 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3390 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3391 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3393 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3394 + "' does not handle web links");
3397 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3401 scheduleWritePackageRestrictionsLocked(userId);
3402 scheduleWriteSettingsLocked();
3405 private void applyFactoryDefaultBrowserLPw(int userId) {
3406 // The default browser app's package name is stored in a string resource,
3407 // with a product-specific overlay used for vendor customization.
3408 String browserPkg = mContext.getResources().getString(
3409 com.android.internal.R.string.default_browser);
3410 if (!TextUtils.isEmpty(browserPkg)) {
3411 // non-empty string => required to be a known package
3412 PackageSetting ps = mSettings.mPackages.get(browserPkg);
3414 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3417 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3421 // Nothing valid explicitly set? Make the factory-installed browser the explicit
3422 // default. If there's more than one, just leave everything alone.
3423 if (browserPkg == null) {
3424 calculateDefaultBrowserLPw(userId);
3428 private void calculateDefaultBrowserLPw(int userId) {
3429 List<String> allBrowsers = resolveAllBrowserApps(userId);
3430 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3431 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3434 private List<String> resolveAllBrowserApps(int userId) {
3435 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3436 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3437 PackageManager.MATCH_ALL, userId);
3439 final int count = list.size();
3440 List<String> result = new ArrayList<String>(count);
3441 for (int i=0; i<count; i++) {
3442 ResolveInfo info = list.get(i);
3443 if (info.activityInfo == null
3444 || !info.handleAllWebDataURI
3445 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3446 || result.contains(info.activityInfo.packageName)) {
3449 result.add(info.activityInfo.packageName);
3455 private boolean packageIsBrowser(String packageName, int userId) {
3456 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3457 PackageManager.MATCH_ALL, userId);
3458 final int N = list.size();
3459 for (int i = 0; i < N; i++) {
3460 ResolveInfo info = list.get(i);
3461 if (packageName.equals(info.activityInfo.packageName)) {
3468 private void checkDefaultBrowser() {
3469 final int myUserId = UserHandle.myUserId();
3470 final String packageName = getDefaultBrowserPackageName(myUserId);
3471 if (packageName != null) {
3472 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3474 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3475 synchronized (mPackages) {
3476 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
3483 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3484 throws RemoteException {
3486 return super.onTransact(code, data, reply, flags);
3487 } catch (RuntimeException e) {
3488 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3489 Slog.wtf(TAG, "Package Manager Crash", e);
3495 static int[] appendInts(int[] cur, int[] add) {
3496 if (add == null) return cur;
3497 if (cur == null) return add;
3498 final int N = add.length;
3499 for (int i=0; i<N; i++) {
3500 cur = appendInt(cur, add[i]);
3506 * Returns whether or not a full application can see an instant application.
3508 * Currently, there are three cases in which this can occur:
3510 * <li>The calling application is a "special" process. The special
3511 * processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3512 * and {@code 0}</li>
3513 * <li>The calling application has the permission
3514 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3515 * <li>The calling application is the default launcher on the
3516 * system partition.</li>
3519 private boolean canViewInstantApps(int callingUid, int userId) {
3520 if (callingUid == Process.SYSTEM_UID
3521 || callingUid == Process.SHELL_UID
3522 || callingUid == Process.ROOT_UID) {
3525 if (mContext.checkCallingOrSelfPermission(
3526 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3529 if (mContext.checkCallingOrSelfPermission(
3530 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3531 final ComponentName homeComponent = getDefaultHomeActivity(userId);
3532 if (homeComponent != null
3533 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3540 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3541 if (!sUserManager.exists(userId)) return null;
3545 PackageParser.Package p = ps.pkg;
3549 final int callingUid = Binder.getCallingUid();
3550 // Filter out ephemeral app metadata:
3551 // * The system/shell/root can see metadata for any app
3552 // * An installed app can see metadata for 1) other installed apps
3553 // and 2) ephemeral apps that have explicitly interacted with it
3554 // * Ephemeral apps can only see their own data and exposed installed apps
3555 // * Holding a signature permission allows seeing instant apps
3556 if (filterAppAccessLPr(ps, callingUid, userId)) {
3560 final PermissionsState permissionsState = ps.getPermissionsState();
3562 // Compute GIDs only if requested
3563 final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3564 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3565 // Compute granted permissions only if package has requested permissions
3566 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3567 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3568 final PackageUserState state = ps.readUserState(userId);
3570 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3572 flags |= MATCH_ANY_USER;
3575 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3576 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3578 if (packageInfo == null) {
3582 packageInfo.packageName = packageInfo.applicationInfo.packageName =
3583 resolveExternalPackageNameLPr(p);
3589 public void checkPackageStartable(String packageName, int userId) {
3590 final int callingUid = Binder.getCallingUid();
3591 if (getInstantAppPackageName(callingUid) != null) {
3592 throw new SecurityException("Instant applications don't have access to this method");
3594 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3595 synchronized (mPackages) {
3596 final PackageSetting ps = mSettings.mPackages.get(packageName);
3597 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3598 throw new SecurityException("Package " + packageName + " was not found!");
3601 if (!ps.getInstalled(userId)) {
3602 throw new SecurityException(
3603 "Package " + packageName + " was not installed for user " + userId + "!");
3606 if (mSafeMode && !ps.isSystem()) {
3607 throw new SecurityException("Package " + packageName + " not a system app!");
3610 if (mFrozenPackages.contains(packageName)) {
3611 throw new SecurityException("Package " + packageName + " is currently frozen!");
3614 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3615 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3616 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3622 public boolean isPackageAvailable(String packageName, int userId) {
3623 if (!sUserManager.exists(userId)) return false;
3624 final int callingUid = Binder.getCallingUid();
3625 enforceCrossUserPermission(callingUid, userId,
3626 false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3627 synchronized (mPackages) {
3628 PackageParser.Package p = mPackages.get(packageName);
3630 final PackageSetting ps = (PackageSetting) p.mExtras;
3631 if (filterAppAccessLPr(ps, callingUid, userId)) {
3635 final PackageUserState state = ps.readUserState(userId);
3636 if (state != null) {
3637 return PackageParser.isAvailable(state);
3646 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3647 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3648 flags, Binder.getCallingUid(), userId);
3652 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3653 int flags, int userId) {
3654 return getPackageInfoInternal(versionedPackage.getPackageName(),
3655 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3659 * Important: The provided filterCallingUid is used exclusively to filter out packages
3660 * that can be seen based on user state. It's typically the original caller uid prior
3661 * to clearing. Because it can only be provided by trusted code, it's value can be
3662 * trusted and will be used as-is; unlike userId which will be validated by this method.
3664 private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3665 int flags, int filterCallingUid, int userId) {
3666 if (!sUserManager.exists(userId)) return null;
3667 flags = updateFlagsForPackage(flags, userId, packageName);
3668 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3669 false /* requireFullPermission */, false /* checkShell */, "get package info");
3672 synchronized (mPackages) {
3673 // Normalize package name to handle renamed packages and static libs
3674 packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3676 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3677 if (matchFactoryOnly) {
3678 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3680 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3683 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3686 return generatePackageInfo(ps, flags, userId);
3690 PackageParser.Package p = mPackages.get(packageName);
3691 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3694 if (DEBUG_PACKAGE_INFO)
3695 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3697 final PackageSetting ps = (PackageSetting) p.mExtras;
3698 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3701 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3704 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3706 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3707 final PackageSetting ps = mSettings.mPackages.get(packageName);
3708 if (ps == null) return null;
3709 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3712 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3715 return generatePackageInfo(ps, flags, userId);
3721 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3722 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3725 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3728 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3734 private boolean isComponentVisibleToInstantApp(
3735 @Nullable ComponentName component, @ComponentType int type) {
3736 if (type == TYPE_ACTIVITY) {
3737 final PackageParser.Activity activity = mActivities.mActivities.get(component);
3738 return activity != null
3739 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3741 } else if (type == TYPE_RECEIVER) {
3742 final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3743 return activity != null
3744 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3746 } else if (type == TYPE_SERVICE) {
3747 final PackageParser.Service service = mServices.mServices.get(component);
3748 return service != null
3749 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3751 } else if (type == TYPE_PROVIDER) {
3752 final PackageParser.Provider provider = mProviders.mProviders.get(component);
3753 return provider != null
3754 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3756 } else if (type == TYPE_UNKNOWN) {
3757 return isComponentVisibleToInstantApp(component);
3763 * Returns whether or not access to the application should be filtered.
3765 * Access may be limited based upon whether the calling or target applications
3766 * are instant applications.
3768 * @see #canAccessInstantApps(int)
3770 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3771 @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3772 // if we're in an isolated process, get the real calling UID
3773 if (Process.isIsolated(callingUid)) {
3774 callingUid = mIsolatedOwners.get(callingUid);
3776 final String instantAppPkgName = getInstantAppPackageName(callingUid);
3777 final boolean callerIsInstantApp = instantAppPkgName != null;
3779 if (callerIsInstantApp) {
3780 // pretend the application exists, but, needs to be filtered
3785 // if the target and caller are the same application, don't filter
3786 if (isCallerSameApp(ps.name, callingUid)) {
3789 if (callerIsInstantApp) {
3790 // request for a specific component; if it hasn't been explicitly exposed, filter
3791 if (component != null) {
3792 return !isComponentVisibleToInstantApp(component, componentType);
3794 // request for application; if no components have been explicitly exposed, filter
3795 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3797 if (ps.getInstantApp(userId)) {
3798 // caller can see all components of all instant applications, don't filter
3799 if (canViewInstantApps(callingUid, userId)) {
3802 // request for a specific instant application component, filter
3803 if (component != null) {
3806 // request for an instant application; if the caller hasn't been granted access, filter
3807 return !mInstantAppRegistry.isInstantAccessGranted(
3808 userId, UserHandle.getAppId(callingUid), ps.appId);
3814 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3816 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3817 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3820 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3822 // Callers can access only the libs they depend on, otherwise they need to explicitly
3823 // ask for the shared libraries given the caller is allowed to access all static libs.
3824 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3825 // System/shell/root get to see all static libs
3826 final int appId = UserHandle.getAppId(uid);
3827 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3828 || appId == Process.ROOT_UID) {
3833 // No package means no static lib as it is always on internal storage
3834 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3838 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3839 ps.pkg.staticSharedLibVersion);
3840 if (libEntry == null) {
3844 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3845 final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3846 if (uidPackageNames == null) {
3850 for (String uidPackageName : uidPackageNames) {
3851 if (ps.name.equals(uidPackageName)) {
3854 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3855 if (uidPs != null) {
3856 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3857 libEntry.info.getName());
3861 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3870 public String[] currentToCanonicalPackageNames(String[] names) {
3871 final int callingUid = Binder.getCallingUid();
3872 if (getInstantAppPackageName(callingUid) != null) {
3875 final String[] out = new String[names.length];
3877 synchronized (mPackages) {
3878 final int callingUserId = UserHandle.getUserId(callingUid);
3879 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3880 for (int i=names.length-1; i>=0; i--) {
3881 final PackageSetting ps = mSettings.mPackages.get(names[i]);
3882 boolean translateName = false;
3883 if (ps != null && ps.realName != null) {
3884 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3885 translateName = !targetIsInstantApp
3886 || canViewInstantApps
3887 || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3888 UserHandle.getAppId(callingUid), ps.appId);
3890 out[i] = translateName ? ps.realName : names[i];
3897 public String[] canonicalToCurrentPackageNames(String[] names) {
3898 final int callingUid = Binder.getCallingUid();
3899 if (getInstantAppPackageName(callingUid) != null) {
3902 final String[] out = new String[names.length];
3904 synchronized (mPackages) {
3905 final int callingUserId = UserHandle.getUserId(callingUid);
3906 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3907 for (int i=names.length-1; i>=0; i--) {
3908 final String cur = mSettings.getRenamedPackageLPr(names[i]);
3909 boolean translateName = false;
3911 final PackageSetting ps = mSettings.mPackages.get(names[i]);
3912 final boolean targetIsInstantApp =
3913 ps != null && ps.getInstantApp(callingUserId);
3914 translateName = !targetIsInstantApp
3915 || canViewInstantApps
3916 || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3917 UserHandle.getAppId(callingUid), ps.appId);
3919 out[i] = translateName ? cur : names[i];
3926 public int getPackageUid(String packageName, int flags, int userId) {
3927 if (!sUserManager.exists(userId)) return -1;
3928 final int callingUid = Binder.getCallingUid();
3929 flags = updateFlagsForPackage(flags, userId, packageName);
3930 enforceCrossUserPermission(callingUid, userId,
3931 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3934 synchronized (mPackages) {
3935 final PackageParser.Package p = mPackages.get(packageName);
3936 if (p != null && p.isMatch(flags)) {
3937 PackageSetting ps = (PackageSetting) p.mExtras;
3938 if (filterAppAccessLPr(ps, callingUid, userId)) {
3941 return UserHandle.getUid(userId, p.applicationInfo.uid);
3943 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3944 final PackageSetting ps = mSettings.mPackages.get(packageName);
3945 if (ps != null && ps.isMatch(flags)
3946 && !filterAppAccessLPr(ps, callingUid, userId)) {
3947 return UserHandle.getUid(userId, ps.appId);
3956 public int[] getPackageGids(String packageName, int flags, int userId) {
3957 if (!sUserManager.exists(userId)) return null;
3958 final int callingUid = Binder.getCallingUid();
3959 flags = updateFlagsForPackage(flags, userId, packageName);
3960 enforceCrossUserPermission(callingUid, userId,
3961 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3964 synchronized (mPackages) {
3965 final PackageParser.Package p = mPackages.get(packageName);
3966 if (p != null && p.isMatch(flags)) {
3967 PackageSetting ps = (PackageSetting) p.mExtras;
3968 if (filterAppAccessLPr(ps, callingUid, userId)) {
3971 // TODO: Shouldn't this be checking for package installed state for userId and
3973 return ps.getPermissionsState().computeGids(userId);
3975 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3976 final PackageSetting ps = mSettings.mPackages.get(packageName);
3977 if (ps != null && ps.isMatch(flags)
3978 && !filterAppAccessLPr(ps, callingUid, userId)) {
3979 return ps.getPermissionsState().computeGids(userId);
3987 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3988 if (bp.perm != null) {
3989 return PackageParser.generatePermissionInfo(bp.perm, flags);
3991 PermissionInfo pi = new PermissionInfo();
3993 pi.packageName = bp.sourcePackage;
3994 pi.nonLocalizedLabel = bp.name;
3995 pi.protectionLevel = bp.protectionLevel;
4000 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4001 final int callingUid = Binder.getCallingUid();
4002 if (getInstantAppPackageName(callingUid) != null) {
4006 synchronized (mPackages) {
4007 final BasePermission p = mSettings.mPermissions.get(name);
4011 // If the caller is an app that targets pre 26 SDK drop protection flags.
4012 final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4013 if (permissionInfo != null) {
4014 permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4015 permissionInfo.protectionLevel, packageName, callingUid);
4017 return permissionInfo;
4021 private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4022 String packageName, int uid) {
4023 // Signature permission flags area always reported
4024 final int protectionLevelMasked = protectionLevel
4025 & (PermissionInfo.PROTECTION_NORMAL
4026 | PermissionInfo.PROTECTION_DANGEROUS
4027 | PermissionInfo.PROTECTION_SIGNATURE);
4028 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4029 return protectionLevel;
4032 // System sees all flags.
4033 final int appId = UserHandle.getAppId(uid);
4034 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4035 || appId == Process.SHELL_UID) {
4036 return protectionLevel;
4039 // Normalize package name to handle renamed packages and static libs
4040 packageName = resolveInternalPackageNameLPr(packageName,
4041 PackageManager.VERSION_CODE_HIGHEST);
4043 // Apps that target O see flags for all protection levels.
4044 final PackageSetting ps = mSettings.mPackages.get(packageName);
4046 return protectionLevel;
4048 if (ps.appId != appId) {
4049 return protectionLevel;
4052 final PackageParser.Package pkg = mPackages.get(packageName);
4054 return protectionLevel;
4056 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4057 return protectionLevelMasked;
4060 return protectionLevel;
4064 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4066 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4070 synchronized (mPackages) {
4071 if (group != null && !mPermissionGroups.containsKey(group)) {
4072 // This is thrown as NameNotFoundException
4076 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4077 for (BasePermission p : mSettings.mPermissions.values()) {
4078 if (group == null) {
4079 if (p.perm == null || p.perm.info.group == null) {
4080 out.add(generatePermissionInfo(p, flags));
4083 if (p.perm != null && group.equals(p.perm.info.group)) {
4084 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4088 return new ParceledListSlice<>(out);
4093 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4094 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4098 synchronized (mPackages) {
4099 return PackageParser.generatePermissionGroupInfo(
4100 mPermissionGroups.get(name), flags);
4105 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4106 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4107 return ParceledListSlice.emptyList();
4110 synchronized (mPackages) {
4111 final int N = mPermissionGroups.size();
4112 ArrayList<PermissionGroupInfo> out
4113 = new ArrayList<PermissionGroupInfo>(N);
4114 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4115 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4117 return new ParceledListSlice<>(out);
4121 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4122 int filterCallingUid, int userId) {
4123 if (!sUserManager.exists(userId)) return null;
4124 PackageSetting ps = mSettings.mPackages.get(packageName);
4126 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4129 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4132 if (ps.pkg == null) {
4133 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4134 if (pInfo != null) {
4135 return pInfo.applicationInfo;
4139 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4140 ps.readUserState(userId), userId);
4142 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4150 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4151 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4155 * Important: The provided filterCallingUid is used exclusively to filter out applications
4156 * that can be seen based on user state. It's typically the original caller uid prior
4157 * to clearing. Because it can only be provided by trusted code, it's value can be
4158 * trusted and will be used as-is; unlike userId which will be validated by this method.
4160 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4161 int filterCallingUid, int userId) {
4162 if (!sUserManager.exists(userId)) return null;
4163 flags = updateFlagsForApplication(flags, userId, packageName);
4164 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4165 false /* requireFullPermission */, false /* checkShell */, "get application info");
4168 synchronized (mPackages) {
4169 // Normalize package name to handle renamed packages and static libs
4170 packageName = resolveInternalPackageNameLPr(packageName,
4171 PackageManager.VERSION_CODE_HIGHEST);
4173 PackageParser.Package p = mPackages.get(packageName);
4174 if (DEBUG_PACKAGE_INFO) Log.v(
4175 TAG, "getApplicationInfo " + packageName
4178 PackageSetting ps = mSettings.mPackages.get(packageName);
4179 if (ps == null) return null;
4180 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4183 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4186 // Note: isEnabledLP() does not apply here - always return info
4187 ApplicationInfo ai = PackageParser.generateApplicationInfo(
4188 p, flags, ps.readUserState(userId), userId);
4190 ai.packageName = resolveExternalPackageNameLPr(p);
4194 if ("android".equals(packageName)||"system".equals(packageName)) {
4195 return mAndroidApplication;
4197 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4198 // Already generates the external package name
4199 return generateApplicationInfoFromSettingsLPw(packageName,
4200 flags, filterCallingUid, userId);
4206 private String normalizePackageNameLPr(String packageName) {
4207 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4208 return normalizedPackageName != null ? normalizedPackageName : packageName;
4212 public void deletePreloadsFileCache() {
4213 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4214 throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4216 File dir = Environment.getDataPreloadsFileCacheDirectory();
4217 Slog.i(TAG, "Deleting preloaded file cache " + dir);
4218 FileUtils.deleteContents(dir);
4222 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4223 final int storageFlags, final IPackageDataObserver observer) {
4224 mContext.enforceCallingOrSelfPermission(
4225 android.Manifest.permission.CLEAR_APP_CACHE, null);
4226 mHandler.post(() -> {
4227 boolean success = false;
4229 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4231 } catch (IOException e) {
4234 if (observer != null) {
4236 observer.onRemoveCompleted(null, success);
4237 } catch (RemoteException e) {
4245 public void freeStorage(final String volumeUuid, final long freeStorageSize,
4246 final int storageFlags, final IntentSender pi) {
4247 mContext.enforceCallingOrSelfPermission(
4248 android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4249 mHandler.post(() -> {
4250 boolean success = false;
4252 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4254 } catch (IOException e) {
4259 pi.sendIntent(null, success ? 1 : 0, null, null, null);
4260 } catch (SendIntentException e) {
4268 * Blocking call to clear various types of cached data across the system
4269 * until the requested bytes are available.
4271 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4272 final StorageManager storage = mContext.getSystemService(StorageManager.class);
4273 final File file = storage.findPathForUuid(volumeUuid);
4274 if (file.getUsableSpace() >= bytes) return;
4276 if (ENABLE_FREE_CACHE_V2) {
4277 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4279 final boolean aggressive = (storageFlags
4280 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4281 final boolean defyReserved = (storageFlags
4282 & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4283 final long reservedBytes = (aggressive || defyReserved) ? 0
4284 : storage.getStorageCacheBytes(file);
4286 // 1. Pre-flight to determine if we have any chance to succeed
4287 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4288 if (internalVolume && (aggressive || SystemProperties
4289 .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4290 deletePreloadsFileCache();
4291 if (file.getUsableSpace() >= bytes) return;
4294 // 3. Consider parsed APK data (aggressive only)
4295 if (internalVolume && aggressive) {
4296 FileUtils.deleteContents(mCacheDir);
4297 if (file.getUsableSpace() >= bytes) return;
4300 // 4. Consider cached app data (above quotas)
4302 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4303 Installer.FLAG_FREE_CACHE_V2);
4304 } catch (InstallerException ignored) {
4306 if (file.getUsableSpace() >= bytes) return;
4308 // 5. Consider shared libraries with refcount=0 and age>min cache period
4309 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4310 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4311 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4312 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4316 // 6. Consider dexopt output (aggressive only)
4319 // 7. Consider installed instant apps unused longer than min cache period
4320 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4321 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4322 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4323 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4327 // 8. Consider cached app data (below quotas)
4329 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4330 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4331 } catch (InstallerException ignored) {
4333 if (file.getUsableSpace() >= bytes) return;
4335 // 9. Consider DropBox entries
4338 // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4339 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4340 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4341 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4342 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4347 mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4348 } catch (InstallerException ignored) {
4350 if (file.getUsableSpace() >= bytes) return;
4353 throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4356 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4357 throws IOException {
4358 final StorageManager storage = mContext.getSystemService(StorageManager.class);
4359 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4361 List<VersionedPackage> packagesToDelete = null;
4362 final long now = System.currentTimeMillis();
4364 synchronized (mPackages) {
4365 final int[] allUsers = sUserManager.getUserIds();
4366 final int libCount = mSharedLibraries.size();
4367 for (int i = 0; i < libCount; i++) {
4368 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4369 if (versionedLib == null) {
4372 final int versionCount = versionedLib.size();
4373 for (int j = 0; j < versionCount; j++) {
4374 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4375 // Skip packages that are not static shared libs.
4376 if (!libInfo.isStatic()) {
4379 // Important: We skip static shared libs used for some user since
4380 // in such a case we need to keep the APK on the device. The check for
4381 // a lib being used for any user is performed by the uninstall call.
4382 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4383 // Resolve the package name - we use synthetic package names internally
4384 final String internalPackageName = resolveInternalPackageNameLPr(
4385 declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4386 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4387 // Skip unused static shared libs cached less than the min period
4388 // to prevent pruning a lib needed by a subsequently installed package.
4389 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4392 if (packagesToDelete == null) {
4393 packagesToDelete = new ArrayList<>();
4395 packagesToDelete.add(new VersionedPackage(internalPackageName,
4396 declaringPackage.getVersionCode()));
4401 if (packagesToDelete != null) {
4402 final int packageCount = packagesToDelete.size();
4403 for (int i = 0; i < packageCount; i++) {
4404 final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4405 // Delete the package synchronously (will fail of the lib used for any user).
4406 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4407 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4408 == PackageManager.DELETE_SUCCEEDED) {
4409 if (volume.getUsableSpace() >= neededSpace) {
4420 * Update given flags based on encryption status of current user.
4422 private int updateFlags(int flags, int userId) {
4423 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4424 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4425 // Caller expressed an explicit opinion about what encryption
4426 // aware/unaware components they want to see, so fall through and
4427 // give them what they want
4429 // Caller expressed no opinion, so match based on user state
4430 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4431 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4433 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4439 private UserManagerInternal getUserManagerInternal() {
4440 if (mUserManagerInternal == null) {
4441 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4443 return mUserManagerInternal;
4446 private DeviceIdleController.LocalService getDeviceIdleController() {
4447 if (mDeviceIdleController == null) {
4448 mDeviceIdleController =
4449 LocalServices.getService(DeviceIdleController.LocalService.class);
4451 return mDeviceIdleController;
4455 * Update given flags when being used to request {@link PackageInfo}.
4457 private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4458 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4459 boolean triaged = true;
4460 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4461 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4462 // Caller is asking for component details, so they'd better be
4463 // asking for specific encryption matching behavior, or be triaged
4464 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4465 | PackageManager.MATCH_DIRECT_BOOT_AWARE
4466 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4470 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4471 | PackageManager.MATCH_SYSTEM_ONLY
4472 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4475 if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4476 // require the permission to be held; the calling uid and given user id referring
4477 // to the same user is not sufficient
4479 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, true,
4480 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4481 + Debug.getCallers(5));
4482 } catch (SecurityException se) {
4483 // For compatibility reasons, we can't throw a security exception here if we're
4484 // looking for applications in our own user id. Instead, unset the MATCH_ANY_USER
4485 // flag and move on.
4486 if (userId != UserHandle.getCallingUserId()) {
4489 flags &= ~PackageManager.MATCH_ANY_USER;
4491 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4492 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4493 // If the caller wants all packages and has a restricted profile associated with it,
4494 // then match all users. This is to make sure that launchers that need to access work
4495 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4496 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4497 flags |= PackageManager.MATCH_ANY_USER;
4499 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4500 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4501 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4503 return updateFlags(flags, userId);
4507 * Update given flags when being used to request {@link ApplicationInfo}.
4509 private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4510 return updateFlagsForPackage(flags, userId, cookie);
4514 * Update given flags when being used to request {@link ComponentInfo}.
4516 private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4517 if (cookie instanceof Intent) {
4518 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4519 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4523 boolean triaged = true;
4524 // Caller is asking for component details, so they'd better be
4525 // asking for specific encryption matching behavior, or be triaged
4526 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4527 | PackageManager.MATCH_DIRECT_BOOT_AWARE
4528 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4531 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4532 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4533 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4536 return updateFlags(flags, userId);
4540 * Update given intent when being used to request {@link ResolveInfo}.
4542 private Intent updateIntentForResolve(Intent intent) {
4543 if (intent.getSelector() != null) {
4544 intent = intent.getSelector();
4546 if (DEBUG_PREFERRED) {
4547 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4553 * Update given flags when being used to request {@link ResolveInfo}.
4554 * <p>Instant apps are resolved specially, depending upon context. Minimally,
4555 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4556 * flag set. However, this flag is only honoured in three circumstances:
4558 * <li>when called from a system process</li>
4559 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4560 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4561 * action and a {@code android.intent.category.BROWSABLE} category</li>
4564 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4565 return updateFlagsForResolve(flags, userId, intent, callingUid,
4566 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4568 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4569 boolean wantInstantApps) {
4570 return updateFlagsForResolve(flags, userId, intent, callingUid,
4571 wantInstantApps, false /*onlyExposedExplicitly*/);
4573 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4574 boolean wantInstantApps, boolean onlyExposedExplicitly) {
4575 // Safe mode means we shouldn't match any third-party components
4577 flags |= PackageManager.MATCH_SYSTEM_ONLY;
4579 if (getInstantAppPackageName(callingUid) != null) {
4580 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4581 if (onlyExposedExplicitly) {
4582 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4584 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4585 flags |= PackageManager.MATCH_INSTANT;
4587 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4588 final boolean allowMatchInstant =
4590 && Intent.ACTION_VIEW.equals(intent.getAction())
4591 && hasWebURI(intent))
4592 || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4593 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4594 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4595 if (!allowMatchInstant) {
4596 flags &= ~PackageManager.MATCH_INSTANT;
4599 return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4603 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4604 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4608 * Important: The provided filterCallingUid is used exclusively to filter out activities
4609 * that can be seen based on user state. It's typically the original caller uid prior
4610 * to clearing. Because it can only be provided by trusted code, it's value can be
4611 * trusted and will be used as-is; unlike userId which will be validated by this method.
4613 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4614 int filterCallingUid, int userId) {
4615 if (!sUserManager.exists(userId)) return null;
4616 flags = updateFlagsForComponent(flags, userId, component);
4617 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4618 false /* requireFullPermission */, false /* checkShell */, "get activity info");
4619 synchronized (mPackages) {
4620 PackageParser.Activity a = mActivities.mActivities.get(component);
4622 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4623 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4624 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4625 if (ps == null) return null;
4626 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4629 return PackageParser.generateActivityInfo(
4630 a, flags, ps.readUserState(userId), userId);
4632 if (mResolveComponentName.equals(component)) {
4633 return PackageParser.generateActivityInfo(
4634 mResolveActivity, flags, new PackageUserState(), userId);
4641 public boolean activitySupportsIntent(ComponentName component, Intent intent,
4642 String resolvedType) {
4643 synchronized (mPackages) {
4644 if (component.equals(mResolveComponentName)) {
4645 // The resolver supports EVERYTHING!
4648 final int callingUid = Binder.getCallingUid();
4649 final int callingUserId = UserHandle.getUserId(callingUid);
4650 PackageParser.Activity a = mActivities.mActivities.get(component);
4654 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4658 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4661 for (int i=0; i<a.intents.size(); i++) {
4662 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4663 intent.getData(), intent.getCategories(), TAG) >= 0) {
4672 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4673 if (!sUserManager.exists(userId)) return null;
4674 final int callingUid = Binder.getCallingUid();
4675 flags = updateFlagsForComponent(flags, userId, component);
4676 enforceCrossUserPermission(callingUid, userId,
4677 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4678 synchronized (mPackages) {
4679 PackageParser.Activity a = mReceivers.mActivities.get(component);
4680 if (DEBUG_PACKAGE_INFO) Log.v(
4681 TAG, "getReceiverInfo " + component + ": " + a);
4682 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4683 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4684 if (ps == null) return null;
4685 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4688 return PackageParser.generateActivityInfo(
4689 a, flags, ps.readUserState(userId), userId);
4696 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4697 int flags, int userId) {
4698 if (!sUserManager.exists(userId)) return null;
4699 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4700 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4704 flags = updateFlagsForPackage(flags, userId, null);
4706 final boolean canSeeStaticLibraries =
4707 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4708 == PERMISSION_GRANTED
4709 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4710 == PERMISSION_GRANTED
4711 || canRequestPackageInstallsInternal(packageName,
4712 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4713 false /* throwIfPermNotDeclared*/)
4714 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4715 == PERMISSION_GRANTED;
4717 synchronized (mPackages) {
4718 List<SharedLibraryInfo> result = null;
4720 final int libCount = mSharedLibraries.size();
4721 for (int i = 0; i < libCount; i++) {
4722 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4723 if (versionedLib == null) {
4727 final int versionCount = versionedLib.size();
4728 for (int j = 0; j < versionCount; j++) {
4729 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4730 if (!canSeeStaticLibraries && libInfo.isStatic()) {
4733 final long identity = Binder.clearCallingIdentity();
4735 PackageInfo packageInfo = getPackageInfoVersioned(
4736 libInfo.getDeclaringPackage(), flags
4737 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4738 if (packageInfo == null) {
4742 Binder.restoreCallingIdentity(identity);
4745 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4746 libInfo.getVersion(), libInfo.getType(),
4747 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4750 if (result == null) {
4751 result = new ArrayList<>();
4753 result.add(resLibInfo);
4757 return result != null ? new ParceledListSlice<>(result) : null;
4761 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4762 SharedLibraryInfo libInfo, int flags, int userId) {
4763 List<VersionedPackage> versionedPackages = null;
4764 final int packageCount = mSettings.mPackages.size();
4765 for (int i = 0; i < packageCount; i++) {
4766 PackageSetting ps = mSettings.mPackages.valueAt(i);
4772 if (!ps.getUserState().get(userId).isAvailable(flags)) {
4776 final String libName = libInfo.getName();
4777 if (libInfo.isStatic()) {
4778 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4782 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4785 if (versionedPackages == null) {
4786 versionedPackages = new ArrayList<>();
4788 // If the dependent is a static shared lib, use the public package name
4789 String dependentPackageName = ps.name;
4790 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4791 dependentPackageName = ps.pkg.manifestPackageName;
4793 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4794 } else if (ps.pkg != null) {
4795 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4796 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4797 if (versionedPackages == null) {
4798 versionedPackages = new ArrayList<>();
4800 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4805 return versionedPackages;
4809 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4810 if (!sUserManager.exists(userId)) return null;
4811 final int callingUid = Binder.getCallingUid();
4812 flags = updateFlagsForComponent(flags, userId, component);
4813 enforceCrossUserPermission(callingUid, userId,
4814 false /* requireFullPermission */, false /* checkShell */, "get service info");
4815 synchronized (mPackages) {
4816 PackageParser.Service s = mServices.mServices.get(component);
4817 if (DEBUG_PACKAGE_INFO) Log.v(
4818 TAG, "getServiceInfo " + component + ": " + s);
4819 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4820 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4821 if (ps == null) return null;
4822 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4825 return PackageParser.generateServiceInfo(
4826 s, flags, ps.readUserState(userId), userId);
4833 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4834 if (!sUserManager.exists(userId)) return null;
4835 final int callingUid = Binder.getCallingUid();
4836 flags = updateFlagsForComponent(flags, userId, component);
4837 enforceCrossUserPermission(callingUid, userId,
4838 false /* requireFullPermission */, false /* checkShell */, "get provider info");
4839 synchronized (mPackages) {
4840 PackageParser.Provider p = mProviders.mProviders.get(component);
4841 if (DEBUG_PACKAGE_INFO) Log.v(
4842 TAG, "getProviderInfo " + component + ": " + p);
4843 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4844 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4845 if (ps == null) return null;
4846 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4849 return PackageParser.generateProviderInfo(
4850 p, flags, ps.readUserState(userId), userId);
4857 public String[] getSystemSharedLibraryNames() {
4858 // allow instant applications
4859 synchronized (mPackages) {
4860 Set<String> libs = null;
4861 final int libCount = mSharedLibraries.size();
4862 for (int i = 0; i < libCount; i++) {
4863 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4864 if (versionedLib == null) {
4867 final int versionCount = versionedLib.size();
4868 for (int j = 0; j < versionCount; j++) {
4869 SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4870 if (!libEntry.info.isStatic()) {
4872 libs = new ArraySet<>();
4874 libs.add(libEntry.info.getName());
4877 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4878 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4879 UserHandle.getUserId(Binder.getCallingUid()),
4880 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4882 libs = new ArraySet<>();
4884 libs.add(libEntry.info.getName());
4891 String[] libsArray = new String[libs.size()];
4892 libs.toArray(libsArray);
4901 public @NonNull String getServicesSystemSharedLibraryPackageName() {
4902 // allow instant applications
4903 synchronized (mPackages) {
4904 return mServicesSystemSharedLibraryPackageName;
4909 public @NonNull String getSharedSystemSharedLibraryPackageName() {
4910 // allow instant applications
4911 synchronized (mPackages) {
4912 return mSharedSystemSharedLibraryPackageName;
4916 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4917 for (int i = userList.length - 1; i >= 0; --i) {
4918 final int userId = userList[i];
4919 // don't add instant app to the list of updates
4920 if (pkgSetting.getInstantApp(userId)) {
4923 SparseArray<String> changedPackages = mChangedPackages.get(userId);
4924 if (changedPackages == null) {
4925 changedPackages = new SparseArray<>();
4926 mChangedPackages.put(userId, changedPackages);
4928 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4929 if (sequenceNumbers == null) {
4930 sequenceNumbers = new HashMap<>();
4931 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4933 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4934 if (sequenceNumber != null) {
4935 changedPackages.remove(sequenceNumber);
4937 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4938 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4940 mChangedPackagesSequenceNumber++;
4944 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4945 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4948 synchronized (mPackages) {
4949 if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4952 final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4953 if (changedPackages == null) {
4956 final List<String> packageNames =
4957 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4958 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4959 final String packageName = changedPackages.get(i);
4960 if (packageName != null) {
4961 packageNames.add(packageName);
4964 return packageNames.isEmpty()
4965 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4970 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4971 // allow instant applications
4972 ArrayList<FeatureInfo> res;
4973 synchronized (mAvailableFeatures) {
4974 res = new ArrayList<>(mAvailableFeatures.size() + 1);
4975 res.addAll(mAvailableFeatures.values());
4977 final FeatureInfo fi = new FeatureInfo();
4978 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4979 FeatureInfo.GL_ES_VERSION_UNDEFINED);
4982 return new ParceledListSlice<>(res);
4986 public boolean hasSystemFeature(String name, int version) {
4987 // allow instant applications
4988 synchronized (mAvailableFeatures) {
4989 final FeatureInfo feat = mAvailableFeatures.get(name);
4993 return feat.version >= version;
4999 public int checkPermission(String permName, String pkgName, int userId) {
5000 if (!sUserManager.exists(userId)) {
5001 return PackageManager.PERMISSION_DENIED;
5003 final int callingUid = Binder.getCallingUid();
5005 synchronized (mPackages) {
5006 final PackageParser.Package p = mPackages.get(pkgName);
5007 if (p != null && p.mExtras != null) {
5008 final PackageSetting ps = (PackageSetting) p.mExtras;
5009 if (filterAppAccessLPr(ps, callingUid, userId)) {
5010 return PackageManager.PERMISSION_DENIED;
5012 final boolean instantApp = ps.getInstantApp(userId);
5013 final PermissionsState permissionsState = ps.getPermissionsState();
5014 if (permissionsState.hasPermission(permName, userId)) {
5016 BasePermission bp = mSettings.mPermissions.get(permName);
5017 if (bp != null && bp.isInstant()) {
5018 return PackageManager.PERMISSION_GRANTED;
5021 return PackageManager.PERMISSION_GRANTED;
5024 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5025 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5026 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5027 return PackageManager.PERMISSION_GRANTED;
5032 return PackageManager.PERMISSION_DENIED;
5036 public int checkUidPermission(String permName, int uid) {
5037 final int callingUid = Binder.getCallingUid();
5038 final int callingUserId = UserHandle.getUserId(callingUid);
5039 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5040 final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5041 final int userId = UserHandle.getUserId(uid);
5042 if (!sUserManager.exists(userId)) {
5043 return PackageManager.PERMISSION_DENIED;
5046 synchronized (mPackages) {
5047 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5049 if (obj instanceof SharedUserSetting) {
5050 if (isCallerInstantApp) {
5051 return PackageManager.PERMISSION_DENIED;
5053 } else if (obj instanceof PackageSetting) {
5054 final PackageSetting ps = (PackageSetting) obj;
5055 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5056 return PackageManager.PERMISSION_DENIED;
5059 final SettingBase settingBase = (SettingBase) obj;
5060 final PermissionsState permissionsState = settingBase.getPermissionsState();
5061 if (permissionsState.hasPermission(permName, userId)) {
5062 if (isUidInstantApp) {
5063 BasePermission bp = mSettings.mPermissions.get(permName);
5064 if (bp != null && bp.isInstant()) {
5065 return PackageManager.PERMISSION_GRANTED;
5068 return PackageManager.PERMISSION_GRANTED;
5071 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5072 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5073 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5074 return PackageManager.PERMISSION_GRANTED;
5077 ArraySet<String> perms = mSystemPermissions.get(uid);
5078 if (perms != null) {
5079 if (perms.contains(permName)) {
5080 return PackageManager.PERMISSION_GRANTED;
5082 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5083 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5084 return PackageManager.PERMISSION_GRANTED;
5090 return PackageManager.PERMISSION_DENIED;
5094 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5095 if (UserHandle.getCallingUserId() != userId) {
5096 mContext.enforceCallingPermission(
5097 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5098 "isPermissionRevokedByPolicy for user " + userId);
5101 if (checkPermission(permission, packageName, userId)
5102 == PackageManager.PERMISSION_GRANTED) {
5106 final int callingUid = Binder.getCallingUid();
5107 if (getInstantAppPackageName(callingUid) != null) {
5108 if (!isCallerSameApp(packageName, callingUid)) {
5112 if (isInstantApp(packageName, userId)) {
5117 final long identity = Binder.clearCallingIdentity();
5119 final int flags = getPermissionFlags(permission, packageName, userId);
5120 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5122 Binder.restoreCallingIdentity(identity);
5127 public String getPermissionControllerPackageName() {
5128 synchronized (mPackages) {
5129 return mRequiredInstallerPackage;
5134 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5135 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5136 * @param checkShell whether to prevent shell from access if there's a debugging restriction
5137 * @param message the message to log on security exception
5139 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5140 boolean checkShell, String message) {
5141 enforceCrossUserPermission(
5144 requireFullPermission,
5150 private void enforceCrossUserPermission(int callingUid, int userId,
5151 boolean requireFullPermission, boolean checkShell,
5152 boolean requirePermissionWhenSameUser, String message) {
5154 throw new IllegalArgumentException("Invalid userId " + userId);
5157 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5159 if (!requirePermissionWhenSameUser && userId == UserHandle.getUserId(callingUid)) return;
5160 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5161 if (requireFullPermission) {
5162 mContext.enforceCallingOrSelfPermission(
5163 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5166 mContext.enforceCallingOrSelfPermission(
5167 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5168 } catch (SecurityException se) {
5169 mContext.enforceCallingOrSelfPermission(
5170 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5176 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5177 if (callingUid == Process.SHELL_UID) {
5179 && sUserManager.hasUserRestriction(restriction, userHandle)) {
5180 throw new SecurityException("Shell does not have permission to access user "
5182 } else if (userHandle < 0) {
5183 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5184 + Debug.getCallers(3));
5189 private BasePermission findPermissionTreeLP(String permName) {
5190 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5191 if (permName.startsWith(bp.name) &&
5192 permName.length() > bp.name.length() &&
5193 permName.charAt(bp.name.length()) == '.') {
5200 private BasePermission checkPermissionTreeLP(String permName) {
5201 if (permName != null) {
5202 BasePermission bp = findPermissionTreeLP(permName);
5204 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5207 throw new SecurityException("Calling uid "
5208 + Binder.getCallingUid()
5209 + " is not allowed to add to permission tree "
5210 + bp.name + " owned by uid " + bp.uid);
5213 throw new SecurityException("No permission tree found for " + permName);
5216 static boolean compareStrings(CharSequence s1, CharSequence s2) {
5223 if (s1.getClass() != s2.getClass()) {
5226 return s1.equals(s2);
5229 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5230 if (pi1.icon != pi2.icon) return false;
5231 if (pi1.logo != pi2.logo) return false;
5232 if (pi1.protectionLevel != pi2.protectionLevel) return false;
5233 if (!compareStrings(pi1.name, pi2.name)) return false;
5234 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5235 // We'll take care of setting this one.
5236 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5237 // These are not currently stored in settings.
5238 //if (!compareStrings(pi1.group, pi2.group)) return false;
5239 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5240 //if (pi1.labelRes != pi2.labelRes) return false;
5241 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5245 int permissionInfoFootprint(PermissionInfo info) {
5246 int size = info.name.length();
5247 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5248 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5252 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5254 for (BasePermission perm : mSettings.mPermissions.values()) {
5255 if (perm.uid == tree.uid) {
5256 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5262 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5263 // We calculate the max size of permissions defined by this uid and throw
5264 // if that plus the size of 'info' would exceed our stated maximum.
5265 if (tree.uid != Process.SYSTEM_UID) {
5266 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5267 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5268 throw new SecurityException("Permission tree size cap exceeded");
5273 boolean addPermissionLocked(PermissionInfo info, boolean async) {
5274 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5275 throw new SecurityException("Instant apps can't add permissions");
5277 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5278 throw new SecurityException("Label must be specified in permission");
5280 BasePermission tree = checkPermissionTreeLP(info.name);
5281 BasePermission bp = mSettings.mPermissions.get(info.name);
5282 boolean added = bp == null;
5283 boolean changed = true;
5284 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5286 enforcePermissionCapLocked(info, tree);
5287 bp = new BasePermission(info.name, tree.sourcePackage,
5288 BasePermission.TYPE_DYNAMIC);
5289 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5290 throw new SecurityException(
5291 "Not allowed to modify non-dynamic permission "
5294 if (bp.protectionLevel == fixedLevel
5295 && bp.perm.owner.equals(tree.perm.owner)
5296 && bp.uid == tree.uid
5297 && comparePermissionInfos(bp.perm.info, info)) {
5301 bp.protectionLevel = fixedLevel;
5302 info = new PermissionInfo(info);
5303 info.protectionLevel = fixedLevel;
5304 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5305 bp.perm.info.packageName = tree.perm.info.packageName;
5308 mSettings.mPermissions.put(info.name, bp);
5312 mSettings.writeLPr();
5314 scheduleWriteSettingsLocked();
5321 public boolean addPermission(PermissionInfo info) {
5322 synchronized (mPackages) {
5323 return addPermissionLocked(info, false);
5328 public boolean addPermissionAsync(PermissionInfo info) {
5329 synchronized (mPackages) {
5330 return addPermissionLocked(info, true);
5335 public void removePermission(String name) {
5336 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5337 throw new SecurityException("Instant applications don't have access to this method");
5339 synchronized (mPackages) {
5340 checkPermissionTreeLP(name);
5341 BasePermission bp = mSettings.mPermissions.get(name);
5343 if (bp.type != BasePermission.TYPE_DYNAMIC) {
5344 throw new SecurityException(
5345 "Not allowed to modify non-dynamic permission "
5348 mSettings.mPermissions.remove(name);
5349 mSettings.writeLPr();
5354 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5355 PackageParser.Package pkg, BasePermission bp) {
5356 int index = pkg.requestedPermissions.indexOf(bp.name);
5358 throw new SecurityException("Package " + pkg.packageName
5359 + " has not requested permission " + bp.name);
5361 if (!bp.isRuntime() && !bp.isDevelopment()) {
5362 throw new SecurityException("Permission " + bp.name
5363 + " is not a changeable permission type");
5368 public void grantRuntimePermission(String packageName, String name, final int userId) {
5369 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5372 private void grantRuntimePermission(String packageName, String name, final int userId,
5373 boolean overridePolicy) {
5374 if (!sUserManager.exists(userId)) {
5375 Log.e(TAG, "No such user:" + userId);
5378 final int callingUid = Binder.getCallingUid();
5380 mContext.enforceCallingOrSelfPermission(
5381 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5382 "grantRuntimePermission");
5384 enforceCrossUserPermission(callingUid, userId,
5385 true /* requireFullPermission */, true /* checkShell */,
5386 "grantRuntimePermission");
5389 final PackageSetting ps;
5391 synchronized (mPackages) {
5392 final PackageParser.Package pkg = mPackages.get(packageName);
5394 throw new IllegalArgumentException("Unknown package: " + packageName);
5396 final BasePermission bp = mSettings.mPermissions.get(name);
5398 throw new IllegalArgumentException("Unknown permission: " + name);
5400 ps = (PackageSetting) pkg.mExtras;
5402 || filterAppAccessLPr(ps, callingUid, userId)) {
5403 throw new IllegalArgumentException("Unknown package: " + packageName);
5406 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5408 // If a permission review is required for legacy apps we represent
5409 // their permissions as always granted runtime ones since we need
5410 // to keep the review required permission flag per user while an
5411 // install permission's state is shared across all users.
5412 if (mPermissionReviewRequired
5413 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5414 && bp.isRuntime()) {
5418 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5420 final PermissionsState permissionsState = ps.getPermissionsState();
5422 final int flags = permissionsState.getPermissionFlags(name, userId);
5423 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5424 throw new SecurityException("Cannot grant system fixed permission "
5425 + name + " for package " + packageName);
5427 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5428 throw new SecurityException("Cannot grant policy fixed permission "
5429 + name + " for package " + packageName);
5432 if (bp.isDevelopment()) {
5433 // Development permissions must be handled specially, since they are not
5434 // normal runtime permissions. For now they apply to all users.
5435 if (permissionsState.grantInstallPermission(bp) !=
5436 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5437 scheduleWriteSettingsLocked();
5442 if (ps.getInstantApp(userId) && !bp.isInstant()) {
5443 throw new SecurityException("Cannot grant non-ephemeral permission"
5444 + name + " for package " + packageName);
5447 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5448 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5452 final int result = permissionsState.grantRuntimePermission(bp, userId);
5454 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5458 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5459 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5460 mHandler.post(new Runnable() {
5463 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5470 if (bp.isRuntime()) {
5471 logPermissionGranted(mContext, name, packageName);
5474 mOnPermissionChangeListeners.onPermissionsChanged(uid);
5476 // Not critical if that is lost - app has to request again.
5477 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5480 // Only need to do this if user is initialized. Otherwise it's a new user
5481 // and there are no processes running as the user yet and there's no need
5482 // to make an expensive call to remount processes for the changed permissions.
5483 if (READ_EXTERNAL_STORAGE.equals(name)
5484 || WRITE_EXTERNAL_STORAGE.equals(name)) {
5485 final long token = Binder.clearCallingIdentity();
5487 if (sUserManager.isInitialized(userId)) {
5488 StorageManagerInternal storageManagerInternal = LocalServices.getService(
5489 StorageManagerInternal.class);
5490 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5493 Binder.restoreCallingIdentity(token);
5499 public void revokeRuntimePermission(String packageName, String name, int userId) {
5500 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5503 private void revokeRuntimePermission(String packageName, String name, int userId,
5504 boolean overridePolicy) {
5505 if (!sUserManager.exists(userId)) {
5506 Log.e(TAG, "No such user:" + userId);
5510 mContext.enforceCallingOrSelfPermission(
5511 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5512 "revokeRuntimePermission");
5514 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5515 true /* requireFullPermission */, true /* checkShell */,
5516 "revokeRuntimePermission");
5520 synchronized (mPackages) {
5521 final PackageParser.Package pkg = mPackages.get(packageName);
5523 throw new IllegalArgumentException("Unknown package: " + packageName);
5525 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5527 || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5528 throw new IllegalArgumentException("Unknown package: " + packageName);
5530 final BasePermission bp = mSettings.mPermissions.get(name);
5532 throw new IllegalArgumentException("Unknown permission: " + name);
5535 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5537 // If a permission review is required for legacy apps we represent
5538 // their permissions as always granted runtime ones since we need
5539 // to keep the review required permission flag per user while an
5540 // install permission's state is shared across all users.
5541 if (mPermissionReviewRequired
5542 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5543 && bp.isRuntime()) {
5547 final PermissionsState permissionsState = ps.getPermissionsState();
5549 final int flags = permissionsState.getPermissionFlags(name, userId);
5550 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5551 throw new SecurityException("Cannot revoke system fixed permission "
5552 + name + " for package " + packageName);
5554 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5555 throw new SecurityException("Cannot revoke policy fixed permission "
5556 + name + " for package " + packageName);
5559 if (bp.isDevelopment()) {
5560 // Development permissions must be handled specially, since they are not
5561 // normal runtime permissions. For now they apply to all users.
5562 if (permissionsState.revokeInstallPermission(bp) !=
5563 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5564 scheduleWriteSettingsLocked();
5569 if (permissionsState.revokeRuntimePermission(bp, userId) ==
5570 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5574 if (bp.isRuntime()) {
5575 logPermissionRevoked(mContext, name, packageName);
5578 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5580 // Critical, after this call app should never have the permission.
5581 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5583 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5586 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5590 * We might auto-grant permissions if any permission of the group is already granted. Hence if
5591 * the group of a granted permission changes we need to revoke it to avoid having permissions of
5592 * the new group auto-granted.
5594 * @param newPackage The new package that was installed
5595 * @param oldPackage The old package that was updated
5596 * @param allPackageNames All package names
5598 private void revokeRuntimePermissionsIfGroupChanged(
5599 PackageParser.Package newPackage,
5600 PackageParser.Package oldPackage,
5601 ArrayList<String> allPackageNames) {
5602 final int numOldPackagePermissions = oldPackage.permissions.size();
5603 final ArrayMap<String, String> oldPermissionNameToGroupName
5604 = new ArrayMap<>(numOldPackagePermissions);
5606 for (int i = 0; i < numOldPackagePermissions; i++) {
5607 final PackageParser.Permission permission = oldPackage.permissions.get(i);
5609 if (permission.group != null) {
5610 oldPermissionNameToGroupName.put(permission.info.name,
5611 permission.group.info.name);
5615 final int numNewPackagePermissions = newPackage.permissions.size();
5616 for (int newPermissionNum = 0; newPermissionNum < numNewPackagePermissions;
5617 newPermissionNum++) {
5618 final PackageParser.Permission newPermission =
5619 newPackage.permissions.get(newPermissionNum);
5620 final int newProtection = newPermission.info.protectionLevel;
5622 if ((newProtection & PermissionInfo.PROTECTION_DANGEROUS) != 0) {
5623 final String permissionName = newPermission.info.name;
5624 final String newPermissionGroupName =
5625 newPermission.group == null ? null : newPermission.group.info.name;
5626 final String oldPermissionGroupName = oldPermissionNameToGroupName.get(
5629 if (newPermissionGroupName != null
5630 && !newPermissionGroupName.equals(oldPermissionGroupName)) {
5631 final List<UserInfo> users = mContext.getSystemService(UserManager.class)
5634 final int numUsers = users.size();
5635 for (int userNum = 0; userNum < numUsers; userNum++) {
5636 final int userId = users.get(userNum).id;
5637 final int numPackages = allPackageNames.size();
5639 for (int packageNum = 0; packageNum < numPackages; packageNum++) {
5640 final String packageName = allPackageNames.get(packageNum);
5642 if (checkPermission(permissionName, packageName, userId)
5643 == PackageManager.PERMISSION_GRANTED) {
5644 EventLog.writeEvent(0x534e4554, "72710897",
5645 newPackage.applicationInfo.uid,
5646 "Revoking permission", permissionName, "from package",
5647 packageName, "as the group changed from",
5648 oldPermissionGroupName, "to", newPermissionGroupName);
5651 revokeRuntimePermission(packageName, permissionName, userId,
5653 } catch (IllegalArgumentException e) {
5654 Slog.e(TAG, "Could not revoke " + permissionName + " from "
5667 * Get the first event id for the permission.
5669 * <p>There are four events for each permission: <ul>
5670 * <li>Request permission: first id + 0</li>
5671 * <li>Grant permission: first id + 1</li>
5672 * <li>Request for permission denied: first id + 2</li>
5673 * <li>Revoke permission: first id + 3</li>
5676 * @param name name of the permission
5678 * @return The first event id for the permission
5680 private static int getBaseEventId(@NonNull String name) {
5681 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5683 if (eventIdIndex == -1) {
5684 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5685 || "user".equals(Build.TYPE)) {
5686 Log.i(TAG, "Unknown permission " + name);
5688 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5690 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5693 // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5694 // - metrics_constants.proto
5695 throw new IllegalStateException("Unknown permission " + name);
5699 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5703 * Log that a permission was revoked.
5705 * @param context Context of the caller
5706 * @param name name of the permission
5707 * @param packageName package permission if for
5709 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5710 @NonNull String packageName) {
5711 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5715 * Log that a permission request was granted.
5717 * @param context Context of the caller
5718 * @param name name of the permission
5719 * @param packageName package permission if for
5721 private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5722 @NonNull String packageName) {
5723 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5727 public void resetRuntimePermissions() {
5728 mContext.enforceCallingOrSelfPermission(
5729 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5730 "revokeRuntimePermission");
5732 int callingUid = Binder.getCallingUid();
5733 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5734 mContext.enforceCallingOrSelfPermission(
5735 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5736 "resetRuntimePermissions");
5739 synchronized (mPackages) {
5740 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5741 for (int userId : UserManagerService.getInstance().getUserIds()) {
5742 final int packageCount = mPackages.size();
5743 for (int i = 0; i < packageCount; i++) {
5744 PackageParser.Package pkg = mPackages.valueAt(i);
5745 if (!(pkg.mExtras instanceof PackageSetting)) {
5748 PackageSetting ps = (PackageSetting) pkg.mExtras;
5749 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5756 public int getPermissionFlags(String name, String packageName, int userId) {
5757 if (!sUserManager.exists(userId)) {
5761 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5763 final int callingUid = Binder.getCallingUid();
5764 enforceCrossUserPermission(callingUid, userId,
5765 true /* requireFullPermission */, false /* checkShell */,
5766 "getPermissionFlags");
5768 synchronized (mPackages) {
5769 final PackageParser.Package pkg = mPackages.get(packageName);
5773 final BasePermission bp = mSettings.mPermissions.get(name);
5777 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5779 || filterAppAccessLPr(ps, callingUid, userId)) {
5782 PermissionsState permissionsState = ps.getPermissionsState();
5783 return permissionsState.getPermissionFlags(name, userId);
5788 public void updatePermissionFlags(String name, String packageName, int flagMask,
5789 int flagValues, int userId) {
5790 if (!sUserManager.exists(userId)) {
5794 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5796 final int callingUid = Binder.getCallingUid();
5797 enforceCrossUserPermission(callingUid, userId,
5798 true /* requireFullPermission */, true /* checkShell */,
5799 "updatePermissionFlags");
5801 // Only the system can change these flags and nothing else.
5802 if (getCallingUid() != Process.SYSTEM_UID) {
5803 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5804 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5805 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5806 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5807 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5810 synchronized (mPackages) {
5811 final PackageParser.Package pkg = mPackages.get(packageName);
5813 throw new IllegalArgumentException("Unknown package: " + packageName);
5815 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5817 || filterAppAccessLPr(ps, callingUid, userId)) {
5818 throw new IllegalArgumentException("Unknown package: " + packageName);
5821 final BasePermission bp = mSettings.mPermissions.get(name);
5823 throw new IllegalArgumentException("Unknown permission: " + name);
5826 PermissionsState permissionsState = ps.getPermissionsState();
5828 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5830 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5831 // Install and runtime permissions are stored in different places,
5832 // so figure out what permission changed and persist the change.
5833 if (permissionsState.getInstallPermissionState(name) != null) {
5834 scheduleWriteSettingsLocked();
5835 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5837 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5844 * Update the permission flags for all packages and runtime permissions of a user in order
5845 * to allow device or profile owner to remove POLICY_FIXED.
5848 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5849 if (!sUserManager.exists(userId)) {
5853 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5855 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5856 true /* requireFullPermission */, true /* checkShell */,
5857 "updatePermissionFlagsForAllApps");
5859 // Only the system can change system fixed flags.
5860 if (getCallingUid() != Process.SYSTEM_UID) {
5861 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5862 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5865 synchronized (mPackages) {
5866 boolean changed = false;
5867 final int packageCount = mPackages.size();
5868 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5869 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5870 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5874 PermissionsState permissionsState = ps.getPermissionsState();
5875 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5876 userId, flagMask, flagValues);
5879 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5884 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5885 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5886 != PackageManager.PERMISSION_GRANTED
5887 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5888 != PackageManager.PERMISSION_GRANTED) {
5889 throw new SecurityException(message + " requires "
5890 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5891 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5896 public boolean shouldShowRequestPermissionRationale(String permissionName,
5897 String packageName, int userId) {
5898 if (UserHandle.getCallingUserId() != userId) {
5899 mContext.enforceCallingPermission(
5900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5901 "canShowRequestPermissionRationale for user " + userId);
5904 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5905 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5909 if (checkPermission(permissionName, packageName, userId)
5910 == PackageManager.PERMISSION_GRANTED) {
5916 final long identity = Binder.clearCallingIdentity();
5918 flags = getPermissionFlags(permissionName,
5919 packageName, userId);
5921 Binder.restoreCallingIdentity(identity);
5924 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5925 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5926 | PackageManager.FLAG_PERMISSION_USER_FIXED;
5928 if ((flags & fixedFlags) != 0) {
5932 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5936 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5937 mContext.enforceCallingOrSelfPermission(
5938 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5939 "addOnPermissionsChangeListener");
5941 synchronized (mPackages) {
5942 mOnPermissionChangeListeners.addListenerLocked(listener);
5947 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5948 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5949 throw new SecurityException("Instant applications don't have access to this method");
5951 synchronized (mPackages) {
5952 mOnPermissionChangeListeners.removeListenerLocked(listener);
5957 public boolean isProtectedBroadcast(String actionName) {
5958 // allow instant applications
5959 synchronized (mPackages) {
5960 if (mProtectedBroadcasts.contains(actionName)) {
5962 } else if (actionName != null) {
5963 // TODO: remove these terrible hacks
5964 if (actionName.startsWith("android.net.netmon.lingerExpired")
5965 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5966 || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5967 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5976 public int checkSignatures(String pkg1, String pkg2) {
5977 synchronized (mPackages) {
5978 final PackageParser.Package p1 = mPackages.get(pkg1);
5979 final PackageParser.Package p2 = mPackages.get(pkg2);
5980 if (p1 == null || p1.mExtras == null
5981 || p2 == null || p2.mExtras == null) {
5982 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5984 final int callingUid = Binder.getCallingUid();
5985 final int callingUserId = UserHandle.getUserId(callingUid);
5986 final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5987 final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5988 if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5989 || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5990 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5992 return compareSignatures(p1.mSignatures, p2.mSignatures);
5997 public int checkUidSignatures(int uid1, int uid2) {
5998 final int callingUid = Binder.getCallingUid();
5999 final int callingUserId = UserHandle.getUserId(callingUid);
6000 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6001 // Map to base uids.
6002 uid1 = UserHandle.getAppId(uid1);
6003 uid2 = UserHandle.getAppId(uid2);
6005 synchronized (mPackages) {
6008 Object obj = mSettings.getUserIdLPr(uid1);
6010 if (obj instanceof SharedUserSetting) {
6011 if (isCallerInstantApp) {
6012 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6014 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6015 } else if (obj instanceof PackageSetting) {
6016 final PackageSetting ps = (PackageSetting) obj;
6017 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6018 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6020 s1 = ps.signatures.mSignatures;
6022 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6025 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6027 obj = mSettings.getUserIdLPr(uid2);
6029 if (obj instanceof SharedUserSetting) {
6030 if (isCallerInstantApp) {
6031 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6033 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6034 } else if (obj instanceof PackageSetting) {
6035 final PackageSetting ps = (PackageSetting) obj;
6036 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6037 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6039 s2 = ps.signatures.mSignatures;
6041 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6044 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6046 return compareSignatures(s1, s2);
6051 * This method should typically only be used when granting or revoking
6052 * permissions, since the app may immediately restart after this call.
6054 * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6055 * guard your work against the app being relaunched.
6057 private void killUid(int appId, int userId, String reason) {
6058 final long identity = Binder.clearCallingIdentity();
6060 IActivityManager am = ActivityManager.getService();
6063 am.killUid(appId, userId, reason);
6064 } catch (RemoteException e) {
6065 /* ignore - same process */
6069 Binder.restoreCallingIdentity(identity);
6074 * Compares two sets of signatures. Returns:
6076 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6078 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6080 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6082 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6084 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6086 static int compareSignatures(Signature[] s1, Signature[] s2) {
6089 ? PackageManager.SIGNATURE_NEITHER_SIGNED
6090 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6094 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6097 if (s1.length != s2.length) {
6098 return PackageManager.SIGNATURE_NO_MATCH;
6101 // Since both signature sets are of size 1, we can compare without HashSets.
6102 if (s1.length == 1) {
6103 return s1[0].equals(s2[0]) ?
6104 PackageManager.SIGNATURE_MATCH :
6105 PackageManager.SIGNATURE_NO_MATCH;
6108 ArraySet<Signature> set1 = new ArraySet<Signature>();
6109 for (Signature sig : s1) {
6112 ArraySet<Signature> set2 = new ArraySet<Signature>();
6113 for (Signature sig : s2) {
6116 // Make sure s2 contains all signatures in s1.
6117 if (set1.equals(set2)) {
6118 return PackageManager.SIGNATURE_MATCH;
6120 return PackageManager.SIGNATURE_NO_MATCH;
6124 * If the database version for this type of package (internal storage or
6125 * external storage) is less than the version where package signatures
6126 * were updated, return true.
6128 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6129 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6130 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6134 * Used for backward compatibility to make sure any packages with
6135 * certificate chains get upgraded to the new style. {@code existingSigs}
6136 * will be in the old format (since they were stored on disk from before the
6137 * system upgrade) and {@code scannedSigs} will be in the newer format.
6139 private int compareSignaturesCompat(PackageSignatures existingSigs,
6140 PackageParser.Package scannedPkg) {
6141 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6142 return PackageManager.SIGNATURE_NO_MATCH;
6145 ArraySet<Signature> existingSet = new ArraySet<Signature>();
6146 for (Signature sig : existingSigs.mSignatures) {
6147 existingSet.add(sig);
6149 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6150 for (Signature sig : scannedPkg.mSignatures) {
6152 Signature[] chainSignatures = sig.getChainSignatures();
6153 for (Signature chainSig : chainSignatures) {
6154 scannedCompatSet.add(chainSig);
6156 } catch (CertificateEncodingException e) {
6157 scannedCompatSet.add(sig);
6161 * Make sure the expanded scanned set contains all signatures in the
6164 if (scannedCompatSet.equals(existingSet)) {
6165 // Migrate the old signatures to the new scheme.
6166 existingSigs.assignSignatures(scannedPkg.mSignatures);
6167 // The new KeySets will be re-added later in the scanning process.
6168 synchronized (mPackages) {
6169 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6171 return PackageManager.SIGNATURE_MATCH;
6173 return PackageManager.SIGNATURE_NO_MATCH;
6176 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6177 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6178 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6181 private int compareSignaturesRecover(PackageSignatures existingSigs,
6182 PackageParser.Package scannedPkg) {
6183 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6184 return PackageManager.SIGNATURE_NO_MATCH;
6189 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6190 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6191 + scannedPkg.packageName);
6192 return PackageManager.SIGNATURE_MATCH;
6194 } catch (CertificateException e) {
6195 msg = e.getMessage();
6198 logCriticalInfo(Log.INFO,
6199 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6200 return PackageManager.SIGNATURE_NO_MATCH;
6204 public List<String> getAllPackages() {
6205 final int callingUid = Binder.getCallingUid();
6206 final int callingUserId = UserHandle.getUserId(callingUid);
6207 synchronized (mPackages) {
6208 if (canViewInstantApps(callingUid, callingUserId)) {
6209 return new ArrayList<String>(mPackages.keySet());
6211 final String instantAppPkgName = getInstantAppPackageName(callingUid);
6212 final List<String> result = new ArrayList<>();
6213 if (instantAppPkgName != null) {
6214 // caller is an instant application; filter unexposed applications
6215 for (PackageParser.Package pkg : mPackages.values()) {
6216 if (!pkg.visibleToInstantApps) {
6219 result.add(pkg.packageName);
6222 // caller is a normal application; filter instant applications
6223 for (PackageParser.Package pkg : mPackages.values()) {
6224 final PackageSetting ps =
6225 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6227 && ps.getInstantApp(callingUserId)
6228 && !mInstantAppRegistry.isInstantAccessGranted(
6229 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6232 result.add(pkg.packageName);
6240 public String[] getPackagesForUid(int uid) {
6241 final int callingUid = Binder.getCallingUid();
6242 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6243 final int userId = UserHandle.getUserId(uid);
6244 uid = UserHandle.getAppId(uid);
6246 synchronized (mPackages) {
6247 Object obj = mSettings.getUserIdLPr(uid);
6248 if (obj instanceof SharedUserSetting) {
6249 if (isCallerInstantApp) {
6252 final SharedUserSetting sus = (SharedUserSetting) obj;
6253 final int N = sus.packages.size();
6254 String[] res = new String[N];
6255 final Iterator<PackageSetting> it = sus.packages.iterator();
6257 while (it.hasNext()) {
6258 PackageSetting ps = it.next();
6259 if (ps.getInstalled(userId)) {
6262 res = ArrayUtils.removeElement(String.class, res, res[i]);
6266 } else if (obj instanceof PackageSetting) {
6267 final PackageSetting ps = (PackageSetting) obj;
6268 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6269 return new String[]{ps.name};
6277 public String getNameForUid(int uid) {
6278 final int callingUid = Binder.getCallingUid();
6279 if (getInstantAppPackageName(callingUid) != null) {
6282 synchronized (mPackages) {
6283 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6284 if (obj instanceof SharedUserSetting) {
6285 final SharedUserSetting sus = (SharedUserSetting) obj;
6286 return sus.name + ":" + sus.userId;
6287 } else if (obj instanceof PackageSetting) {
6288 final PackageSetting ps = (PackageSetting) obj;
6289 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6299 public int getUidForSharedUser(String sharedUserName) {
6300 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6303 if (sharedUserName == null) {
6307 synchronized (mPackages) {
6308 SharedUserSetting suid;
6310 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6314 } catch (PackageManagerException ignore) {
6315 // can't happen, but, still need to catch it
6322 public int getFlagsForUid(int uid) {
6323 final int callingUid = Binder.getCallingUid();
6324 if (getInstantAppPackageName(callingUid) != null) {
6327 synchronized (mPackages) {
6328 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6329 if (obj instanceof SharedUserSetting) {
6330 final SharedUserSetting sus = (SharedUserSetting) obj;
6331 return sus.pkgFlags;
6332 } else if (obj instanceof PackageSetting) {
6333 final PackageSetting ps = (PackageSetting) obj;
6334 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6344 public int getPrivateFlagsForUid(int uid) {
6345 final int callingUid = Binder.getCallingUid();
6346 if (getInstantAppPackageName(callingUid) != null) {
6349 synchronized (mPackages) {
6350 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6351 if (obj instanceof SharedUserSetting) {
6352 final SharedUserSetting sus = (SharedUserSetting) obj;
6353 return sus.pkgPrivateFlags;
6354 } else if (obj instanceof PackageSetting) {
6355 final PackageSetting ps = (PackageSetting) obj;
6356 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6359 return ps.pkgPrivateFlags;
6366 public boolean isUidPrivileged(int uid) {
6367 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6370 uid = UserHandle.getAppId(uid);
6372 synchronized (mPackages) {
6373 Object obj = mSettings.getUserIdLPr(uid);
6374 if (obj instanceof SharedUserSetting) {
6375 final SharedUserSetting sus = (SharedUserSetting) obj;
6376 final Iterator<PackageSetting> it = sus.packages.iterator();
6377 while (it.hasNext()) {
6378 if (it.next().isPrivileged()) {
6382 } else if (obj instanceof PackageSetting) {
6383 final PackageSetting ps = (PackageSetting) obj;
6384 return ps.isPrivileged();
6391 public String[] getAppOpPermissionPackages(String permissionName) {
6392 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6395 synchronized (mPackages) {
6396 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6400 return pkgs.toArray(new String[pkgs.size()]);
6405 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6406 int flags, int userId) {
6407 return resolveIntentInternal(
6408 intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6411 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6412 int flags, int userId, boolean resolveForStart) {
6414 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6416 if (!sUserManager.exists(userId)) return null;
6417 final int callingUid = Binder.getCallingUid();
6418 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6419 enforceCrossUserPermission(callingUid, userId,
6420 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6423 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6424 flags, callingUid, userId, resolveForStart);
6425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6427 final ResolveInfo bestChoice =
6428 chooseBestActivity(intent, resolvedType, flags, query, userId);
6431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6436 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6437 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6438 throw new SecurityException(
6439 "findPersistentPreferredActivity can only be run by the system");
6441 if (!sUserManager.exists(userId)) {
6444 final int callingUid = Binder.getCallingUid();
6445 intent = updateIntentForResolve(intent);
6446 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6447 final int flags = updateFlagsForResolve(
6448 0, userId, intent, callingUid, false /*includeInstantApps*/);
6449 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6451 synchronized (mPackages) {
6452 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6458 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6459 IntentFilter filter, int match, ComponentName activity) {
6460 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6463 final int userId = UserHandle.getCallingUserId();
6464 if (DEBUG_PREFERRED) {
6465 Log.v(TAG, "setLastChosenActivity intent=" + intent
6466 + " resolvedType=" + resolvedType
6468 + " filter=" + filter
6470 + " activity=" + activity);
6471 filter.dump(new PrintStreamPrinter(System.out), " ");
6473 intent.setComponent(null);
6474 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6476 // Find any earlier preferred or last chosen entries and nuke them
6477 findPreferredActivity(intent, resolvedType,
6478 flags, query, 0, false, true, false, userId);
6479 // Add the new activity as the last chosen for this filter
6480 addPreferredActivityInternal(filter, match, null, activity, false, userId,
6481 "Setting last chosen");
6485 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6486 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6489 final int userId = UserHandle.getCallingUserId();
6490 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6491 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6493 return findPreferredActivity(intent, resolvedType, flags, query, 0,
6494 false, false, false, userId);
6498 * Returns whether or not instant apps have been disabled remotely.
6500 private boolean isEphemeralDisabled() {
6501 return mEphemeralAppsDisabled;
6504 private boolean isInstantAppAllowed(
6505 Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6506 boolean skipPackageCheck) {
6507 if (mInstantAppResolverConnection == null) {
6510 if (mInstantAppInstallerActivity == null) {
6513 if (intent.getComponent() != null) {
6516 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6519 if (!skipPackageCheck && intent.getPackage() != null) {
6522 final boolean isWebUri = hasWebURI(intent);
6523 if (!isWebUri || intent.getData().getHost() == null) {
6526 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6527 // Or if there's already an ephemeral app installed that handles the action
6528 synchronized (mPackages) {
6529 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6530 for (int n = 0; n < count; n++) {
6531 final ResolveInfo info = resolvedActivities.get(n);
6532 final String packageName = info.activityInfo.packageName;
6533 final PackageSetting ps = mSettings.mPackages.get(packageName);
6535 // only check domain verification status if the app is not a browser
6536 if (!info.handleAllWebDataURI) {
6537 // Try to get the status from User settings first
6538 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6539 final int status = (int) (packedStatus >> 32);
6540 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6541 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6542 if (DEBUG_EPHEMERAL) {
6543 Slog.v(TAG, "DENY instant app;"
6544 + " pkg: " + packageName + ", status: " + status);
6549 if (ps.getInstantApp(userId)) {
6550 if (DEBUG_EPHEMERAL) {
6551 Slog.v(TAG, "DENY instant app installed;"
6552 + " pkg: " + packageName);
6559 // We've exhausted all ways to deny ephemeral application; let the system look for them.
6563 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6564 Intent origIntent, String resolvedType, String callingPackage,
6565 Bundle verificationBundle, int userId) {
6566 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6567 new InstantAppRequest(responseObj, origIntent, resolvedType,
6568 callingPackage, userId, verificationBundle));
6569 mHandler.sendMessage(msg);
6572 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6573 int flags, List<ResolveInfo> query, int userId) {
6574 if (query != null) {
6575 final int N = query.size();
6577 return query.get(0);
6579 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6580 // If there is more than one activity with the same priority,
6581 // then let the user decide between them.
6582 ResolveInfo r0 = query.get(0);
6583 ResolveInfo r1 = query.get(1);
6584 if (DEBUG_INTENT_MATCHING || debug) {
6585 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6586 + r1.activityInfo.name + "=" + r1.priority);
6588 // If the first activity has a higher priority, or a different
6589 // default, then it is always desirable to pick it.
6590 if (r0.priority != r1.priority
6591 || r0.preferredOrder != r1.preferredOrder
6592 || r0.isDefault != r1.isDefault) {
6593 return query.get(0);
6595 // If we have saved a preference for a preferred activity for
6596 // this Intent, use that.
6597 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6598 flags, query, r0.priority, true, false, debug, userId);
6602 // If we have an ephemeral app, use it
6603 for (int i = 0; i < N; i++) {
6605 if (ri.activityInfo.applicationInfo.isInstantApp()) {
6606 final String packageName = ri.activityInfo.packageName;
6607 final PackageSetting ps = mSettings.mPackages.get(packageName);
6608 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6609 final int status = (int)(packedStatus >> 32);
6610 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6615 ri = new ResolveInfo(mResolveInfo);
6616 ri.activityInfo = new ActivityInfo(ri.activityInfo);
6617 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6618 // If all of the options come from the same package, show the application's
6619 // label and icon instead of the generic resolver's.
6620 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6621 // and then throw away the ResolveInfo itself, meaning that the caller loses
6622 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6623 // a fallback for this case; we only set the target package's resources on
6624 // the ResolveInfo, not the ActivityInfo.
6625 final String intentPackage = intent.getPackage();
6626 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6627 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6628 ri.resolvePackageName = intentPackage;
6629 if (userNeedsBadging(userId)) {
6630 ri.noResourceId = true;
6632 ri.icon = appi.icon;
6634 ri.iconResourceId = appi.icon;
6635 ri.labelRes = appi.labelRes;
6637 ri.activityInfo.applicationInfo = new ApplicationInfo(
6638 ri.activityInfo.applicationInfo);
6640 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6641 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6643 // Make sure that the resolver is displayable in car mode
6644 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6645 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6653 * Return true if the given list is not empty and all of its contents have
6654 * an activityInfo with the given package name.
6656 private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6657 if (ArrayUtils.isEmpty(list)) {
6660 for (int i = 0, N = list.size(); i < N; i++) {
6661 final ResolveInfo ri = list.get(i);
6662 final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6663 if (ai == null || !packageName.equals(ai.packageName)) {
6670 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6671 int flags, List<ResolveInfo> query, boolean debug, int userId) {
6672 final int N = query.size();
6673 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6675 // Get the list of persistent preferred activities that handle the intent
6676 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6677 List<PersistentPreferredActivity> pprefs = ppir != null
6678 ? ppir.queryIntent(intent, resolvedType,
6679 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6682 if (pprefs != null && pprefs.size() > 0) {
6683 final int M = pprefs.size();
6684 for (int i=0; i<M; i++) {
6685 final PersistentPreferredActivity ppa = pprefs.get(i);
6686 if (DEBUG_PREFERRED || debug) {
6687 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6688 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6689 + "\n component=" + ppa.mComponent);
6690 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6692 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6693 flags | MATCH_DISABLED_COMPONENTS, userId);
6694 if (DEBUG_PREFERRED || debug) {
6695 Slog.v(TAG, "Found persistent preferred activity:");
6697 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6699 Slog.v(TAG, " null");
6703 // This previously registered persistent preferred activity
6704 // component is no longer known. Ignore it and do NOT remove it.
6707 for (int j=0; j<N; j++) {
6708 final ResolveInfo ri = query.get(j);
6709 if (!ri.activityInfo.applicationInfo.packageName
6710 .equals(ai.applicationInfo.packageName)) {
6713 if (!ri.activityInfo.name.equals(ai.name)) {
6716 // Found a persistent preference that can handle the intent.
6717 if (DEBUG_PREFERRED || debug) {
6718 Slog.v(TAG, "Returning persistent preferred activity: " +
6719 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6728 // TODO: handle preferred activities missing while user has amnesia
6729 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6730 List<ResolveInfo> query, int priority, boolean always,
6731 boolean removeMatches, boolean debug, int userId) {
6732 if (!sUserManager.exists(userId)) return null;
6733 final int callingUid = Binder.getCallingUid();
6734 flags = updateFlagsForResolve(
6735 flags, userId, intent, callingUid, false /*includeInstantApps*/);
6736 intent = updateIntentForResolve(intent);
6738 synchronized (mPackages) {
6739 // Try to find a matching persistent preferred activity.
6740 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6743 // If a persistent preferred activity matched, use it.
6748 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6749 // Get the list of preferred activities that handle the intent
6750 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6751 List<PreferredActivity> prefs = pir != null
6752 ? pir.queryIntent(intent, resolvedType,
6753 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6756 if (prefs != null && prefs.size() > 0) {
6757 boolean changed = false;
6759 // First figure out how good the original match set is.
6760 // We will only allow preferred activities that came
6761 // from the same match quality.
6764 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6766 final int N = query.size();
6767 for (int j=0; j<N; j++) {
6768 final ResolveInfo ri = query.get(j);
6769 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6770 + ": 0x" + Integer.toHexString(match));
6771 if (ri.match > match) {
6776 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6777 + Integer.toHexString(match));
6779 match &= IntentFilter.MATCH_CATEGORY_MASK;
6780 final int M = prefs.size();
6781 for (int i=0; i<M; i++) {
6782 final PreferredActivity pa = prefs.get(i);
6783 if (DEBUG_PREFERRED || debug) {
6784 Slog.v(TAG, "Checking PreferredActivity ds="
6785 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6786 + "\n component=" + pa.mPref.mComponent);
6787 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6789 if (pa.mPref.mMatch != match) {
6790 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6791 + Integer.toHexString(pa.mPref.mMatch));
6794 // If it's not an "always" type preferred activity and that's what we're
6795 // looking for, skip it.
6796 if (always && !pa.mPref.mAlways) {
6797 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6800 final ActivityInfo ai = getActivityInfo(
6801 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6802 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6804 if (DEBUG_PREFERRED || debug) {
6805 Slog.v(TAG, "Found preferred activity:");
6807 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6809 Slog.v(TAG, " null");
6813 // This previously registered preferred activity
6814 // component is no longer known. Most likely an update
6815 // to the app was installed and in the new version this
6816 // component no longer exists. Clean it up by removing
6817 // it from the preferred activities list, and skip it.
6818 Slog.w(TAG, "Removing dangling preferred activity: "
6819 + pa.mPref.mComponent);
6820 pir.removeFilter(pa);
6824 for (int j=0; j<N; j++) {
6825 final ResolveInfo ri = query.get(j);
6826 if (!ri.activityInfo.applicationInfo.packageName
6827 .equals(ai.applicationInfo.packageName)) {
6830 if (!ri.activityInfo.name.equals(ai.name)) {
6834 if (removeMatches) {
6835 pir.removeFilter(pa);
6837 if (DEBUG_PREFERRED) {
6838 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6843 // Okay we found a previously set preferred or last chosen app.
6844 // If the result set is different from when this
6845 // was created, we need to clear it and re-ask the
6846 // user their preference, if we're looking for an "always" type entry.
6847 if (always && !pa.mPref.sameSet(query)) {
6848 Slog.i(TAG, "Result set changed, dropping preferred activity for "
6849 + intent + " type " + resolvedType);
6850 if (DEBUG_PREFERRED) {
6851 Slog.v(TAG, "Removing preferred activity since set changed "
6852 + pa.mPref.mComponent);
6854 pir.removeFilter(pa);
6855 // Re-add the filter as a "last chosen" entry (!always)
6856 PreferredActivity lastChosen = new PreferredActivity(
6857 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6858 pir.addFilter(lastChosen);
6863 // Yay! Either the set matched or we're looking for the last chosen
6864 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6865 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6871 if (DEBUG_PREFERRED) {
6872 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6874 scheduleWritePackageRestrictionsLocked(userId);
6879 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6884 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6887 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6889 mContext.enforceCallingOrSelfPermission(
6890 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6891 List<CrossProfileIntentFilter> matches =
6892 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6893 if (matches != null) {
6894 int size = matches.size();
6895 for (int i = 0; i < size; i++) {
6896 if (matches.get(i).getTargetUserId() == targetUserId) return true;
6899 if (hasWebURI(intent)) {
6900 // cross-profile app linking works only towards the parent.
6901 final int callingUid = Binder.getCallingUid();
6902 final UserInfo parent = getProfileParent(sourceUserId);
6903 synchronized(mPackages) {
6904 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6905 false /*includeInstantApps*/);
6906 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6907 intent, resolvedType, flags, sourceUserId, parent.id);
6908 return xpDomainInfo != null;
6914 private UserInfo getProfileParent(int userId) {
6915 final long identity = Binder.clearCallingIdentity();
6917 return sUserManager.getProfileParent(userId);
6919 Binder.restoreCallingIdentity(identity);
6923 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6924 String resolvedType, int userId) {
6925 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6926 if (resolver != null) {
6927 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6933 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6934 String resolvedType, int flags, int userId) {
6936 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6938 return new ParceledListSlice<>(
6939 queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6946 * Returns the package name of the calling Uid if it's an instant app. If it isn't
6947 * instant, returns {@code null}.
6949 private String getInstantAppPackageName(int callingUid) {
6950 synchronized (mPackages) {
6951 // If the caller is an isolated app use the owner's uid for the lookup.
6952 if (Process.isIsolated(callingUid)) {
6953 callingUid = mIsolatedOwners.get(callingUid);
6955 final int appId = UserHandle.getAppId(callingUid);
6956 final Object obj = mSettings.getUserIdLPr(appId);
6957 if (obj instanceof PackageSetting) {
6958 final PackageSetting ps = (PackageSetting) obj;
6959 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6960 return isInstantApp ? ps.pkg.packageName : null;
6966 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6967 String resolvedType, int flags, int userId) {
6968 return queryIntentActivitiesInternal(
6969 intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6972 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6973 String resolvedType, int flags, int filterCallingUid, int userId,
6974 boolean resolveForStart) {
6975 if (!sUserManager.exists(userId)) return Collections.emptyList();
6976 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6977 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6978 false /* requireFullPermission */, false /* checkShell */,
6979 "query intent activities");
6980 final String pkgName = intent.getPackage();
6981 ComponentName comp = intent.getComponent();
6983 if (intent.getSelector() != null) {
6984 intent = intent.getSelector();
6985 comp = intent.getComponent();
6989 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6990 comp != null || pkgName != null /*onlyExposedExplicitly*/);
6992 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6993 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6995 // When specifying an explicit component, we prevent the activity from being
6996 // used when either 1) the calling package is normal and the activity is within
6997 // an ephemeral application or 2) the calling package is ephemeral and the
6998 // activity is not visible to ephemeral applications.
6999 final boolean matchInstantApp =
7000 (flags & PackageManager.MATCH_INSTANT) != 0;
7001 final boolean matchVisibleToInstantAppOnly =
7002 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7003 final boolean matchExplicitlyVisibleOnly =
7004 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7005 final boolean isCallerInstantApp =
7006 instantAppPkgName != null;
7007 final boolean isTargetSameInstantApp =
7008 comp.getPackageName().equals(instantAppPkgName);
7009 final boolean isTargetInstantApp =
7010 (ai.applicationInfo.privateFlags
7011 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7012 final boolean isTargetVisibleToInstantApp =
7013 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7014 final boolean isTargetExplicitlyVisibleToInstantApp =
7015 isTargetVisibleToInstantApp
7016 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7017 final boolean isTargetHiddenFromInstantApp =
7018 !isTargetVisibleToInstantApp
7019 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7020 final boolean blockResolution =
7021 !isTargetSameInstantApp
7022 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7023 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7024 && isTargetHiddenFromInstantApp));
7025 if (!blockResolution) {
7026 final ResolveInfo ri = new ResolveInfo();
7027 ri.activityInfo = ai;
7031 return applyPostResolutionFilter(list, instantAppPkgName);
7035 boolean sortResult = false;
7036 boolean addEphemeral = false;
7037 List<ResolveInfo> result;
7038 final boolean ephemeralDisabled = isEphemeralDisabled();
7039 synchronized (mPackages) {
7040 if (pkgName == null) {
7041 List<CrossProfileIntentFilter> matchingFilters =
7042 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7043 // Check for results that need to skip the current profile.
7044 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
7045 resolvedType, flags, userId);
7046 if (xpResolveInfo != null) {
7047 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7048 xpResult.add(xpResolveInfo);
7049 return applyPostResolutionFilter(
7050 filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7053 // Check for results in the current profile.
7054 result = filterIfNotSystemUser(mActivities.queryIntent(
7055 intent, resolvedType, flags, userId), userId);
7056 addEphemeral = !ephemeralDisabled
7057 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7058 // Check for cross profile results.
7059 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7060 xpResolveInfo = queryCrossProfileIntents(
7061 matchingFilters, intent, resolvedType, flags, userId,
7062 hasNonNegativePriorityResult);
7063 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7064 boolean isVisibleToUser = filterIfNotSystemUser(
7065 Collections.singletonList(xpResolveInfo), userId).size() > 0;
7066 if (isVisibleToUser) {
7067 result.add(xpResolveInfo);
7071 if (hasWebURI(intent)) {
7072 CrossProfileDomainInfo xpDomainInfo = null;
7073 final UserInfo parent = getProfileParent(userId);
7074 if (parent != null) {
7075 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7076 flags, userId, parent.id);
7078 if (xpDomainInfo != null) {
7079 if (xpResolveInfo != null) {
7080 // If we didn't remove it, the cross-profile ResolveInfo would be twice
7082 result.remove(xpResolveInfo);
7084 if (result.size() == 0 && !addEphemeral) {
7085 // No result in current profile, but found candidate in parent user.
7086 // And we are not going to add emphemeral app, so we can return the
7087 // result straight away.
7088 result.add(xpDomainInfo.resolveInfo);
7089 return applyPostResolutionFilter(result, instantAppPkgName);
7091 } else if (result.size() <= 1 && !addEphemeral) {
7092 // No result in parent user and <= 1 result in current profile, and we
7093 // are not going to add emphemeral app, so we can return the result without
7094 // further processing.
7095 return applyPostResolutionFilter(result, instantAppPkgName);
7097 // We have more than one candidate (combining results from current and parent
7098 // profile), so we need filtering and sorting.
7099 result = filterCandidatesWithDomainPreferredActivitiesLPr(
7100 intent, flags, result, xpDomainInfo, userId);
7104 final PackageParser.Package pkg = mPackages.get(pkgName);
7107 result = filterIfNotSystemUser(
7108 mActivities.queryIntentForPackage(
7109 intent, resolvedType, flags, pkg.activities, userId),
7112 if (result == null || result.size() == 0) {
7113 // the caller wants to resolve for a particular package; however, there
7114 // were no installed results, so, try to find an ephemeral result
7115 addEphemeral = !ephemeralDisabled
7116 && isInstantAppAllowed(
7117 intent, null /*result*/, userId, true /*skipPackageCheck*/);
7118 if (result == null) {
7119 result = new ArrayList<>();
7125 result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7128 Collections.sort(result, mResolvePrioritySorter);
7130 return applyPostResolutionFilter(result, instantAppPkgName);
7133 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7134 String resolvedType, int flags, int userId) {
7135 // first, check to see if we've got an instant app already installed
7136 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7137 ResolveInfo localInstantApp = null;
7138 boolean blockResolution = false;
7139 if (!alreadyResolvedLocally) {
7140 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7142 | PackageManager.GET_RESOLVED_FILTER
7143 | PackageManager.MATCH_INSTANT
7144 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7146 for (int i = instantApps.size() - 1; i >= 0; --i) {
7147 final ResolveInfo info = instantApps.get(i);
7148 final String packageName = info.activityInfo.packageName;
7149 final PackageSetting ps = mSettings.mPackages.get(packageName);
7150 if (ps.getInstantApp(userId)) {
7151 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7152 final int status = (int)(packedStatus >> 32);
7153 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7154 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7155 // there's a local instant application installed, but, the user has
7156 // chosen to never use it; skip resolution and don't acknowledge
7157 // an instant application is even available
7158 if (DEBUG_EPHEMERAL) {
7159 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7161 blockResolution = true;
7164 // we have a locally installed instant application; skip resolution
7165 // but acknowledge there's an instant application available
7166 if (DEBUG_EPHEMERAL) {
7167 Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7169 localInstantApp = info;
7175 // no app installed, let's see if one's available
7176 AuxiliaryResolveInfo auxiliaryResponse = null;
7177 if (!blockResolution) {
7178 if (localInstantApp == null) {
7179 // we don't have an instant app locally, resolve externally
7180 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7181 final InstantAppRequest requestObject = new InstantAppRequest(
7182 null /*responseObj*/, intent /*origIntent*/, resolvedType,
7183 null /*callingPackage*/, userId, null /*verificationBundle*/);
7185 InstantAppResolver.doInstantAppResolutionPhaseOne(
7186 mContext, mInstantAppResolverConnection, requestObject);
7187 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7189 // we have an instant application locally, but, we can't admit that since
7190 // callers shouldn't be able to determine prior browsing. create a dummy
7191 // auxiliary response so the downstream code behaves as if there's an
7192 // instant application available externally. when it comes time to start
7193 // the instant application, we'll do the right thing.
7194 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7195 auxiliaryResponse = new AuxiliaryResolveInfo(
7196 ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7199 if (auxiliaryResponse != null) {
7200 if (DEBUG_EPHEMERAL) {
7201 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7203 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7204 final PackageSetting ps =
7205 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7207 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7208 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7209 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7210 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7211 // make sure this resolver is the default
7212 ephemeralInstaller.isDefault = true;
7213 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7214 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7215 // add a non-generic filter
7216 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7217 ephemeralInstaller.filter.addDataPath(
7218 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7219 ephemeralInstaller.isInstantAppAvailable = true;
7220 result.add(ephemeralInstaller);
7226 private static class CrossProfileDomainInfo {
7227 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7228 ResolveInfo resolveInfo;
7229 /* Best domain verification status of the activities found in the other profile */
7230 int bestDomainVerificationStatus;
7233 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7234 String resolvedType, int flags, int sourceUserId, int parentUserId) {
7235 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7239 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7240 resolvedType, flags, parentUserId);
7242 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7245 CrossProfileDomainInfo result = null;
7246 int size = resultTargetUser.size();
7247 for (int i = 0; i < size; i++) {
7248 ResolveInfo riTargetUser = resultTargetUser.get(i);
7249 // Intent filter verification is only for filters that specify a host. So don't return
7250 // those that handle all web uris.
7251 if (riTargetUser.handleAllWebDataURI) {
7254 String packageName = riTargetUser.activityInfo.packageName;
7255 PackageSetting ps = mSettings.mPackages.get(packageName);
7259 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7260 int status = (int)(verificationState >> 32);
7261 if (result == null) {
7262 result = new CrossProfileDomainInfo();
7263 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7264 sourceUserId, parentUserId);
7265 result.bestDomainVerificationStatus = status;
7267 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7268 result.bestDomainVerificationStatus);
7271 // Don't consider matches with status NEVER across profiles.
7272 if (result != null && result.bestDomainVerificationStatus
7273 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7280 * Verification statuses are ordered from the worse to the best, except for
7281 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7283 private int bestDomainVerificationStatus(int status1, int status2) {
7284 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7287 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7290 return (int) MathUtils.max(status1, status2);
7293 private boolean isUserEnabled(int userId) {
7294 long callingId = Binder.clearCallingIdentity();
7296 UserInfo userInfo = sUserManager.getUserInfo(userId);
7297 return userInfo != null && userInfo.isEnabled();
7299 Binder.restoreCallingIdentity(callingId);
7304 * Filter out activities with systemUserOnly flag set, when current user is not System.
7306 * @return filtered list
7308 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7309 if (userId == UserHandle.USER_SYSTEM) {
7310 return resolveInfos;
7312 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7313 ResolveInfo info = resolveInfos.get(i);
7314 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7315 resolveInfos.remove(i);
7318 return resolveInfos;
7322 * Filters out ephemeral activities.
7323 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7324 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7326 * @param resolveInfos The pre-filtered list of resolved activities
7327 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7329 * @return A filtered list of resolved activities.
7331 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7332 String ephemeralPkgName) {
7333 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7334 final ResolveInfo info = resolveInfos.get(i);
7335 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7336 // TODO: When adding on-demand split support for non-instant apps, remove this check
7337 // and always apply post filtering
7338 // allow activities that are defined in the provided package
7339 if (isEphemeralApp) {
7340 if (info.activityInfo.splitName != null
7341 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7342 info.activityInfo.splitName)) {
7343 // requested activity is defined in a split that hasn't been installed yet.
7344 // add the installer to the resolve list
7345 if (DEBUG_EPHEMERAL) {
7346 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7348 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7349 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7350 info.activityInfo.packageName, info.activityInfo.splitName,
7351 info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7352 // make sure this resolver is the default
7353 installerInfo.isDefault = true;
7354 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7355 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7356 // add a non-generic filter
7357 installerInfo.filter = new IntentFilter();
7358 // load resources from the correct package
7359 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7360 resolveInfos.set(i, installerInfo);
7364 // caller is a full app, don't need to apply any other filtering
7365 if (ephemeralPkgName == null) {
7367 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7368 // caller is same app; don't need to apply any other filtering
7371 // allow activities that have been explicitly exposed to ephemeral apps
7373 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7376 resolveInfos.remove(i);
7378 return resolveInfos;
7382 * @param resolveInfos list of resolve infos in descending priority order
7383 * @return if the list contains a resolve info with non-negative priority
7385 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7386 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7389 private static boolean hasWebURI(Intent intent) {
7390 if (intent.getData() == null) {
7393 final String scheme = intent.getScheme();
7394 if (TextUtils.isEmpty(scheme)) {
7397 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7400 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7401 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7403 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7405 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7406 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7410 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7411 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7412 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7413 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7414 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7415 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7417 synchronized (mPackages) {
7418 final int count = candidates.size();
7419 // First, try to use linked apps. Partition the candidates into four lists:
7420 // one for the final results, one for the "do not use ever", one for "undefined status"
7421 // and finally one for "browser app type".
7422 for (int n=0; n<count; n++) {
7423 ResolveInfo info = candidates.get(n);
7424 String packageName = info.activityInfo.packageName;
7425 PackageSetting ps = mSettings.mPackages.get(packageName);
7427 // Add to the special match all list (Browser use case)
7428 if (info.handleAllWebDataURI) {
7429 matchAllList.add(info);
7432 // Try to get the status from User settings first
7433 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7434 int status = (int)(packedStatus >> 32);
7435 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7436 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7437 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7438 Slog.i(TAG, " + always: " + info.activityInfo.packageName
7439 + " : linkgen=" + linkGeneration);
7441 // Use link-enabled generation as preferredOrder, i.e.
7442 // prefer newly-enabled over earlier-enabled.
7443 info.preferredOrder = linkGeneration;
7444 alwaysList.add(info);
7445 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7446 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7447 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
7449 neverList.add(info);
7450 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7451 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7452 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
7454 alwaysAskList.add(info);
7455 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7456 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7457 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7458 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
7460 undefinedList.add(info);
7465 // We'll want to include browser possibilities in a few cases
7466 boolean includeBrowser = false;
7468 // First try to add the "always" resolution(s) for the current user, if any
7469 if (alwaysList.size() > 0) {
7470 result.addAll(alwaysList);
7472 // Add all undefined apps as we want them to appear in the disambiguation dialog.
7473 result.addAll(undefinedList);
7474 // Maybe add one for the other profile.
7475 if (xpDomainInfo != null && (
7476 xpDomainInfo.bestDomainVerificationStatus
7477 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7478 result.add(xpDomainInfo.resolveInfo);
7480 includeBrowser = true;
7483 // The presence of any 'always ask' alternatives means we'll also offer browsers.
7484 // If there were 'always' entries their preferred order has been set, so we also
7485 // back that off to make the alternatives equivalent
7486 if (alwaysAskList.size() > 0) {
7487 for (ResolveInfo i : result) {
7488 i.preferredOrder = 0;
7490 result.addAll(alwaysAskList);
7491 includeBrowser = true;
7494 if (includeBrowser) {
7495 // Also add browsers (all of them or only the default one)
7496 if (DEBUG_DOMAIN_VERIFICATION) {
7497 Slog.v(TAG, " ...including browsers in candidate set");
7499 if ((matchFlags & MATCH_ALL) != 0) {
7500 result.addAll(matchAllList);
7502 // Browser/generic handling case. If there's a default browser, go straight
7503 // to that (but only if there is no other higher-priority match).
7504 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7505 int maxMatchPrio = 0;
7506 ResolveInfo defaultBrowserMatch = null;
7507 final int numCandidates = matchAllList.size();
7508 for (int n = 0; n < numCandidates; n++) {
7509 ResolveInfo info = matchAllList.get(n);
7510 // track the highest overall match priority...
7511 if (info.priority > maxMatchPrio) {
7512 maxMatchPrio = info.priority;
7514 // ...and the highest-priority default browser match
7515 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7516 if (defaultBrowserMatch == null
7517 || (defaultBrowserMatch.priority < info.priority)) {
7519 Slog.v(TAG, "Considering default browser match " + info);
7521 defaultBrowserMatch = info;
7525 if (defaultBrowserMatch != null
7526 && defaultBrowserMatch.priority >= maxMatchPrio
7527 && !TextUtils.isEmpty(defaultBrowserPackageName))
7530 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7532 result.add(defaultBrowserMatch);
7534 result.addAll(matchAllList);
7538 // If there is nothing selected, add all candidates and remove the ones that the user
7539 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7540 if (result.size() == 0) {
7541 result.addAll(candidates);
7542 result.removeAll(neverList);
7546 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7547 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7549 for (ResolveInfo info : result) {
7550 Slog.v(TAG, " + " + info.activityInfo);
7556 // Returns a packed value as a long:
7558 // high 'int'-sized word: link status: undefined/ask/never/always.
7559 // low 'int'-sized word: relative priority among 'always' results.
7560 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7561 long result = ps.getDomainVerificationStatusForUser(userId);
7562 // if none available, get the master status
7563 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7564 if (ps.getIntentFilterVerificationInfo() != null) {
7565 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7571 private ResolveInfo querySkipCurrentProfileIntents(
7572 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7573 int flags, int sourceUserId) {
7574 if (matchingFilters != null) {
7575 int size = matchingFilters.size();
7576 for (int i = 0; i < size; i ++) {
7577 CrossProfileIntentFilter filter = matchingFilters.get(i);
7578 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7579 // Checking if there are activities in the target user that can handle the
7581 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7582 resolvedType, flags, sourceUserId);
7583 if (resolveInfo != null) {
7592 // Return matching ResolveInfo in target user if any.
7593 private ResolveInfo queryCrossProfileIntents(
7594 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7595 int flags, int sourceUserId, boolean matchInCurrentProfile) {
7596 if (matchingFilters != null) {
7597 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7598 // match the same intent. For performance reasons, it is better not to
7599 // run queryIntent twice for the same userId
7600 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7601 int size = matchingFilters.size();
7602 for (int i = 0; i < size; i++) {
7603 CrossProfileIntentFilter filter = matchingFilters.get(i);
7604 int targetUserId = filter.getTargetUserId();
7605 boolean skipCurrentProfile =
7606 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7607 boolean skipCurrentProfileIfNoMatchFound =
7608 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7609 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7610 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7611 // Checking if there are activities in the target user that can handle the
7613 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7614 resolvedType, flags, sourceUserId);
7615 if (resolveInfo != null) return resolveInfo;
7616 alreadyTriedUserIds.put(targetUserId, true);
7624 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7625 * will forward the intent to the filter's target user.
7626 * Otherwise, returns null.
7628 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7629 String resolvedType, int flags, int sourceUserId) {
7630 int targetUserId = filter.getTargetUserId();
7631 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7632 resolvedType, flags, targetUserId);
7633 if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7634 // If all the matches in the target profile are suspended, return null.
7635 for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7636 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7637 & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7638 return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7646 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7647 int sourceUserId, int targetUserId) {
7648 ResolveInfo forwardingResolveInfo = new ResolveInfo();
7649 long ident = Binder.clearCallingIdentity();
7650 boolean targetIsProfile;
7652 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7654 Binder.restoreCallingIdentity(ident);
7657 if (targetIsProfile) {
7658 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7660 className = FORWARD_INTENT_TO_PARENT;
7662 ComponentName forwardingActivityComponentName = new ComponentName(
7663 mAndroidApplication.packageName, className);
7664 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7666 if (!targetIsProfile) {
7667 forwardingActivityInfo.showUserIcon = targetUserId;
7668 forwardingResolveInfo.noResourceId = true;
7670 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7671 forwardingResolveInfo.priority = 0;
7672 forwardingResolveInfo.preferredOrder = 0;
7673 forwardingResolveInfo.match = 0;
7674 forwardingResolveInfo.isDefault = true;
7675 forwardingResolveInfo.filter = filter;
7676 forwardingResolveInfo.targetUserId = targetUserId;
7677 return forwardingResolveInfo;
7681 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7682 Intent[] specifics, String[] specificTypes, Intent intent,
7683 String resolvedType, int flags, int userId) {
7684 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7685 specificTypes, intent, resolvedType, flags, userId));
7688 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7689 Intent[] specifics, String[] specificTypes, Intent intent,
7690 String resolvedType, int flags, int userId) {
7691 if (!sUserManager.exists(userId)) return Collections.emptyList();
7692 final int callingUid = Binder.getCallingUid();
7693 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7694 false /*includeInstantApps*/);
7695 enforceCrossUserPermission(callingUid, userId,
7696 false /*requireFullPermission*/, false /*checkShell*/,
7697 "query intent activity options");
7698 final String resultsAction = intent.getAction();
7700 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7701 | PackageManager.GET_RESOLVED_FILTER, userId);
7703 if (DEBUG_INTENT_MATCHING) {
7704 Log.v(TAG, "Query " + intent + ": " + results);
7707 int specificsPos = 0;
7710 // todo: note that the algorithm used here is O(N^2). This
7711 // isn't a problem in our current environment, but if we start running
7712 // into situations where we have more than 5 or 10 matches then this
7713 // should probably be changed to something smarter...
7715 // First we go through and resolve each of the specific items
7716 // that were supplied, taking care of removing any corresponding
7717 // duplicate items in the generic resolve list.
7718 if (specifics != null) {
7719 for (int i=0; i<specifics.length; i++) {
7720 final Intent sintent = specifics[i];
7721 if (sintent == null) {
7725 if (DEBUG_INTENT_MATCHING) {
7726 Log.v(TAG, "Specific #" + i + ": " + sintent);
7729 String action = sintent.getAction();
7730 if (resultsAction != null && resultsAction.equals(action)) {
7731 // If this action was explicitly requested, then don't
7732 // remove things that have it.
7736 ResolveInfo ri = null;
7737 ActivityInfo ai = null;
7739 ComponentName comp = sintent.getComponent();
7743 specificTypes != null ? specificTypes[i] : null,
7748 if (ri == mResolveInfo) {
7749 // ACK! Must do something better with this.
7751 ai = ri.activityInfo;
7752 comp = new ComponentName(ai.applicationInfo.packageName,
7755 ai = getActivityInfo(comp, flags, userId);
7761 // Look for any generic query activities that are duplicates
7762 // of this specific one, and remove them from the results.
7763 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7766 for (j=specificsPos; j<N; j++) {
7767 ResolveInfo sri = results.get(j);
7768 if ((sri.activityInfo.name.equals(comp.getClassName())
7769 && sri.activityInfo.applicationInfo.packageName.equals(
7770 comp.getPackageName()))
7771 || (action != null && sri.filter.matchAction(action))) {
7773 if (DEBUG_INTENT_MATCHING) Log.v(
7774 TAG, "Removing duplicate item from " + j
7775 + " due to specific " + specificsPos);
7784 // Add this specific item to its proper place.
7786 ri = new ResolveInfo();
7787 ri.activityInfo = ai;
7789 results.add(specificsPos, ri);
7790 ri.specificIndex = i;
7795 // Now we go through the remaining generic results and remove any
7796 // duplicate actions that are found here.
7798 for (int i=specificsPos; i<N-1; i++) {
7799 final ResolveInfo rii = results.get(i);
7800 if (rii.filter == null) {
7804 // Iterate over all of the actions of this result's intent
7805 // filter... typically this should be just one.
7806 final Iterator<String> it = rii.filter.actionsIterator();
7810 while (it.hasNext()) {
7811 final String action = it.next();
7812 if (resultsAction != null && resultsAction.equals(action)) {
7813 // If this action was explicitly requested, then don't
7814 // remove things that have it.
7817 for (int j=i+1; j<N; j++) {
7818 final ResolveInfo rij = results.get(j);
7819 if (rij.filter != null && rij.filter.hasAction(action)) {
7821 if (DEBUG_INTENT_MATCHING) Log.v(
7822 TAG, "Removing duplicate item from " + j
7823 + " due to action " + action + " at " + i);
7830 // If the caller didn't request filter information, drop it now
7831 // so we don't have to marshall/unmarshall it.
7832 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7837 // Filter out the caller activity if so requested.
7838 if (caller != null) {
7840 for (int i=0; i<N; i++) {
7841 ActivityInfo ainfo = results.get(i).activityInfo;
7842 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7843 && caller.getClassName().equals(ainfo.name)) {
7850 // If the caller didn't request filter information,
7851 // drop them now so we don't have to
7852 // marshall/unmarshall it.
7853 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7855 for (int i=0; i<N; i++) {
7856 results.get(i).filter = null;
7860 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7865 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7866 String resolvedType, int flags, int userId) {
7867 return new ParceledListSlice<>(
7868 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7871 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7872 String resolvedType, int flags, int userId) {
7873 if (!sUserManager.exists(userId)) return Collections.emptyList();
7874 final int callingUid = Binder.getCallingUid();
7875 final String instantAppPkgName = getInstantAppPackageName(callingUid);
7876 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7877 false /*includeInstantApps*/);
7878 ComponentName comp = intent.getComponent();
7880 if (intent.getSelector() != null) {
7881 intent = intent.getSelector();
7882 comp = intent.getComponent();
7886 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7887 final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7889 // When specifying an explicit component, we prevent the activity from being
7890 // used when either 1) the calling package is normal and the activity is within
7891 // an instant application or 2) the calling package is ephemeral and the
7892 // activity is not visible to instant applications.
7893 final boolean matchInstantApp =
7894 (flags & PackageManager.MATCH_INSTANT) != 0;
7895 final boolean matchVisibleToInstantAppOnly =
7896 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7897 final boolean matchExplicitlyVisibleOnly =
7898 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7899 final boolean isCallerInstantApp =
7900 instantAppPkgName != null;
7901 final boolean isTargetSameInstantApp =
7902 comp.getPackageName().equals(instantAppPkgName);
7903 final boolean isTargetInstantApp =
7904 (ai.applicationInfo.privateFlags
7905 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7906 final boolean isTargetVisibleToInstantApp =
7907 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7908 final boolean isTargetExplicitlyVisibleToInstantApp =
7909 isTargetVisibleToInstantApp
7910 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7911 final boolean isTargetHiddenFromInstantApp =
7912 !isTargetVisibleToInstantApp
7913 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7914 final boolean blockResolution =
7915 !isTargetSameInstantApp
7916 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7917 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7918 && isTargetHiddenFromInstantApp));
7919 if (!blockResolution) {
7920 ResolveInfo ri = new ResolveInfo();
7921 ri.activityInfo = ai;
7925 return applyPostResolutionFilter(list, instantAppPkgName);
7929 synchronized (mPackages) {
7930 String pkgName = intent.getPackage();
7931 if (pkgName == null) {
7932 final List<ResolveInfo> result =
7933 mReceivers.queryIntent(intent, resolvedType, flags, userId);
7934 return applyPostResolutionFilter(result, instantAppPkgName);
7936 final PackageParser.Package pkg = mPackages.get(pkgName);
7938 final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7939 intent, resolvedType, flags, pkg.receivers, userId);
7940 return applyPostResolutionFilter(result, instantAppPkgName);
7942 return Collections.emptyList();
7947 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7948 final int callingUid = Binder.getCallingUid();
7949 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7952 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7953 int userId, int callingUid) {
7954 if (!sUserManager.exists(userId)) return null;
7955 flags = updateFlagsForResolve(
7956 flags, userId, intent, callingUid, false /*includeInstantApps*/);
7957 List<ResolveInfo> query = queryIntentServicesInternal(
7958 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7959 if (query != null) {
7960 if (query.size() >= 1) {
7961 // If there is more than one service with the same priority,
7962 // just arbitrarily pick the first one.
7963 return query.get(0);
7970 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7971 String resolvedType, int flags, int userId) {
7972 final int callingUid = Binder.getCallingUid();
7973 return new ParceledListSlice<>(queryIntentServicesInternal(
7974 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7977 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7978 String resolvedType, int flags, int userId, int callingUid,
7979 boolean includeInstantApps) {
7980 if (!sUserManager.exists(userId)) return Collections.emptyList();
7981 final String instantAppPkgName = getInstantAppPackageName(callingUid);
7982 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7983 ComponentName comp = intent.getComponent();
7985 if (intent.getSelector() != null) {
7986 intent = intent.getSelector();
7987 comp = intent.getComponent();
7991 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7992 final ServiceInfo si = getServiceInfo(comp, flags, userId);
7994 // When specifying an explicit component, we prevent the service from being
7995 // used when either 1) the service is in an instant application and the
7996 // caller is not the same instant application or 2) the calling package is
7997 // ephemeral and the activity is not visible to ephemeral applications.
7998 final boolean matchInstantApp =
7999 (flags & PackageManager.MATCH_INSTANT) != 0;
8000 final boolean matchVisibleToInstantAppOnly =
8001 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8002 final boolean isCallerInstantApp =
8003 instantAppPkgName != null;
8004 final boolean isTargetSameInstantApp =
8005 comp.getPackageName().equals(instantAppPkgName);
8006 final boolean isTargetInstantApp =
8007 (si.applicationInfo.privateFlags
8008 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8009 final boolean isTargetHiddenFromInstantApp =
8010 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8011 final boolean blockResolution =
8012 !isTargetSameInstantApp
8013 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8014 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8015 && isTargetHiddenFromInstantApp));
8016 if (!blockResolution) {
8017 final ResolveInfo ri = new ResolveInfo();
8018 ri.serviceInfo = si;
8026 synchronized (mPackages) {
8027 String pkgName = intent.getPackage();
8028 if (pkgName == null) {
8029 return applyPostServiceResolutionFilter(
8030 mServices.queryIntent(intent, resolvedType, flags, userId),
8033 final PackageParser.Package pkg = mPackages.get(pkgName);
8035 return applyPostServiceResolutionFilter(
8036 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8040 return Collections.emptyList();
8044 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8045 String instantAppPkgName) {
8046 // TODO: When adding on-demand split support for non-instant apps, remove this check
8047 // and always apply post filtering
8048 if (instantAppPkgName == null) {
8049 return resolveInfos;
8051 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8052 final ResolveInfo info = resolveInfos.get(i);
8053 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8054 // allow services that are defined in the provided package
8055 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8056 if (info.serviceInfo.splitName != null
8057 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8058 info.serviceInfo.splitName)) {
8059 // requested service is defined in a split that hasn't been installed yet.
8060 // add the installer to the resolve list
8061 if (DEBUG_EPHEMERAL) {
8062 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8064 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8065 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8066 info.serviceInfo.packageName, info.serviceInfo.splitName,
8067 info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8068 // make sure this resolver is the default
8069 installerInfo.isDefault = true;
8070 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8071 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8072 // add a non-generic filter
8073 installerInfo.filter = new IntentFilter();
8074 // load resources from the correct package
8075 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8076 resolveInfos.set(i, installerInfo);
8080 // allow services that have been explicitly exposed to ephemeral apps
8082 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8085 resolveInfos.remove(i);
8087 return resolveInfos;
8091 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8092 String resolvedType, int flags, int userId) {
8093 return new ParceledListSlice<>(
8094 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8097 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8098 Intent intent, String resolvedType, int flags, int userId) {
8099 if (!sUserManager.exists(userId)) return Collections.emptyList();
8100 final int callingUid = Binder.getCallingUid();
8101 final String instantAppPkgName = getInstantAppPackageName(callingUid);
8102 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8103 false /*includeInstantApps*/);
8104 ComponentName comp = intent.getComponent();
8106 if (intent.getSelector() != null) {
8107 intent = intent.getSelector();
8108 comp = intent.getComponent();
8112 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8113 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8115 // When specifying an explicit component, we prevent the provider from being
8116 // used when either 1) the provider is in an instant application and the
8117 // caller is not the same instant application or 2) the calling package is an
8118 // instant application and the provider is not visible to instant applications.
8119 final boolean matchInstantApp =
8120 (flags & PackageManager.MATCH_INSTANT) != 0;
8121 final boolean matchVisibleToInstantAppOnly =
8122 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8123 final boolean isCallerInstantApp =
8124 instantAppPkgName != null;
8125 final boolean isTargetSameInstantApp =
8126 comp.getPackageName().equals(instantAppPkgName);
8127 final boolean isTargetInstantApp =
8128 (pi.applicationInfo.privateFlags
8129 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8130 final boolean isTargetHiddenFromInstantApp =
8131 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8132 final boolean blockResolution =
8133 !isTargetSameInstantApp
8134 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8135 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8136 && isTargetHiddenFromInstantApp));
8137 if (!blockResolution) {
8138 final ResolveInfo ri = new ResolveInfo();
8139 ri.providerInfo = pi;
8147 synchronized (mPackages) {
8148 String pkgName = intent.getPackage();
8149 if (pkgName == null) {
8150 return applyPostContentProviderResolutionFilter(
8151 mProviders.queryIntent(intent, resolvedType, flags, userId),
8154 final PackageParser.Package pkg = mPackages.get(pkgName);
8156 return applyPostContentProviderResolutionFilter(
8157 mProviders.queryIntentForPackage(
8158 intent, resolvedType, flags, pkg.providers, userId),
8161 return Collections.emptyList();
8165 private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8166 List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8167 // TODO: When adding on-demand split support for non-instant applications, remove
8168 // this check and always apply post filtering
8169 if (instantAppPkgName == null) {
8170 return resolveInfos;
8172 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8173 final ResolveInfo info = resolveInfos.get(i);
8174 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8175 // allow providers that are defined in the provided package
8176 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8177 if (info.providerInfo.splitName != null
8178 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8179 info.providerInfo.splitName)) {
8180 // requested provider is defined in a split that hasn't been installed yet.
8181 // add the installer to the resolve list
8182 if (DEBUG_EPHEMERAL) {
8183 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8185 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8186 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8187 info.providerInfo.packageName, info.providerInfo.splitName,
8188 info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8189 // make sure this resolver is the default
8190 installerInfo.isDefault = true;
8191 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8192 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8193 // add a non-generic filter
8194 installerInfo.filter = new IntentFilter();
8195 // load resources from the correct package
8196 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8197 resolveInfos.set(i, installerInfo);
8201 // allow providers that have been explicitly exposed to instant applications
8203 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8206 resolveInfos.remove(i);
8208 return resolveInfos;
8212 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8213 final int callingUid = Binder.getCallingUid();
8214 if (getInstantAppPackageName(callingUid) != null) {
8215 return ParceledListSlice.emptyList();
8217 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8218 flags = updateFlagsForPackage(flags, userId, null);
8219 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8220 enforceCrossUserPermission(callingUid, userId,
8221 false /* requireFullPermission */, false /* checkShell */,
8222 "get installed packages");
8225 synchronized (mPackages) {
8226 ArrayList<PackageInfo> list;
8227 if (listUninstalled) {
8228 list = new ArrayList<>(mSettings.mPackages.size());
8229 for (PackageSetting ps : mSettings.mPackages.values()) {
8230 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8233 if (filterAppAccessLPr(ps, callingUid, userId)) {
8236 final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8242 list = new ArrayList<>(mPackages.size());
8243 for (PackageParser.Package p : mPackages.values()) {
8244 final PackageSetting ps = (PackageSetting) p.mExtras;
8245 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8248 if (filterAppAccessLPr(ps, callingUid, userId)) {
8251 final PackageInfo pi = generatePackageInfo((PackageSetting)
8252 p.mExtras, flags, userId);
8259 return new ParceledListSlice<>(list);
8263 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8264 String[] permissions, boolean[] tmp, int flags, int userId) {
8266 final PermissionsState permissionsState = ps.getPermissionsState();
8267 for (int i=0; i<permissions.length; i++) {
8268 final String permission = permissions[i];
8269 if (permissionsState.hasPermission(permission, userId)) {
8276 if (numMatch == 0) {
8279 final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8281 // The above might return null in cases of uninstalled apps or install-state
8282 // skew across users/profiles.
8284 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8285 if (numMatch == permissions.length) {
8286 pi.requestedPermissions = permissions;
8288 pi.requestedPermissions = new String[numMatch];
8290 for (int i=0; i<permissions.length; i++) {
8292 pi.requestedPermissions[numMatch] = permissions[i];
8303 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8304 String[] permissions, int flags, int userId) {
8305 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8306 flags = updateFlagsForPackage(flags, userId, permissions);
8307 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8308 true /* requireFullPermission */, false /* checkShell */,
8309 "get packages holding permissions");
8310 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8313 synchronized (mPackages) {
8314 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8315 boolean[] tmpBools = new boolean[permissions.length];
8316 if (listUninstalled) {
8317 for (PackageSetting ps : mSettings.mPackages.values()) {
8318 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8322 for (PackageParser.Package pkg : mPackages.values()) {
8323 PackageSetting ps = (PackageSetting)pkg.mExtras;
8325 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8331 return new ParceledListSlice<PackageInfo>(list);
8336 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8337 final int callingUid = Binder.getCallingUid();
8338 if (getInstantAppPackageName(callingUid) != null) {
8339 return ParceledListSlice.emptyList();
8341 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8342 flags = updateFlagsForApplication(flags, userId, null);
8343 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8345 enforceCrossUserPermission(
8348 false /* requireFullPermission */,
8349 false /* checkShell */,
8350 "get installed application info");
8353 synchronized (mPackages) {
8354 ArrayList<ApplicationInfo> list;
8355 if (listUninstalled) {
8356 list = new ArrayList<>(mSettings.mPackages.size());
8357 for (PackageSetting ps : mSettings.mPackages.values()) {
8359 int effectiveFlags = flags;
8360 if (ps.isSystem()) {
8361 effectiveFlags |= PackageManager.MATCH_ANY_USER;
8363 if (ps.pkg != null) {
8364 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8367 if (filterAppAccessLPr(ps, callingUid, userId)) {
8370 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8371 ps.readUserState(userId), userId);
8373 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8376 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8377 // and already converts to externally visible package name
8378 ai = generateApplicationInfoFromSettingsLPw(ps.name,
8379 callingUid, effectiveFlags, userId);
8386 list = new ArrayList<>(mPackages.size());
8387 for (PackageParser.Package p : mPackages.values()) {
8388 if (p.mExtras != null) {
8389 PackageSetting ps = (PackageSetting) p.mExtras;
8390 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8393 if (filterAppAccessLPr(ps, callingUid, userId)) {
8396 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8397 ps.readUserState(userId), userId);
8399 ai.packageName = resolveExternalPackageNameLPr(p);
8406 return new ParceledListSlice<>(list);
8411 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8412 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8415 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8416 "getEphemeralApplications");
8417 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8418 true /* requireFullPermission */, false /* checkShell */,
8419 "getEphemeralApplications");
8420 synchronized (mPackages) {
8421 List<InstantAppInfo> instantApps = mInstantAppRegistry
8422 .getInstantAppsLPr(userId);
8423 if (instantApps != null) {
8424 return new ParceledListSlice<>(instantApps);
8431 public boolean isInstantApp(String packageName, int userId) {
8432 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8433 true /* requireFullPermission */, false /* checkShell */,
8435 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8438 int callingUid = Binder.getCallingUid();
8439 if (Process.isIsolated(callingUid)) {
8440 callingUid = mIsolatedOwners.get(callingUid);
8443 synchronized (mPackages) {
8444 final PackageSetting ps = mSettings.mPackages.get(packageName);
8445 PackageParser.Package pkg = mPackages.get(packageName);
8446 final boolean returnAllowed =
8448 && (isCallerSameApp(packageName, callingUid)
8449 || canViewInstantApps(callingUid, userId)
8450 || mInstantAppRegistry.isInstantAccessGranted(
8451 userId, UserHandle.getAppId(callingUid), ps.appId));
8452 if (returnAllowed) {
8453 return ps.getInstantApp(userId);
8460 public byte[] getInstantAppCookie(String packageName, int userId) {
8461 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8465 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8466 true /* requireFullPermission */, false /* checkShell */,
8467 "getInstantAppCookie");
8468 if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8471 synchronized (mPackages) {
8472 return mInstantAppRegistry.getInstantAppCookieLPw(
8473 packageName, userId);
8478 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8479 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8483 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8484 true /* requireFullPermission */, true /* checkShell */,
8485 "setInstantAppCookie");
8486 if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8489 synchronized (mPackages) {
8490 return mInstantAppRegistry.setInstantAppCookieLPw(
8491 packageName, cookie, userId);
8496 public Bitmap getInstantAppIcon(String packageName, int userId) {
8497 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8501 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8502 "getInstantAppIcon");
8504 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8505 true /* requireFullPermission */, false /* checkShell */,
8506 "getInstantAppIcon");
8508 synchronized (mPackages) {
8509 return mInstantAppRegistry.getInstantAppIconLPw(
8510 packageName, userId);
8514 private boolean isCallerSameApp(String packageName, int uid) {
8515 PackageParser.Package pkg = mPackages.get(packageName);
8517 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8521 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8522 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8523 return ParceledListSlice.emptyList();
8525 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8528 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8529 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8532 synchronized (mPackages) {
8533 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8534 final int userId = UserHandle.getCallingUserId();
8535 while (i.hasNext()) {
8536 final PackageParser.Package p = i.next();
8537 if (p.applicationInfo == null) continue;
8539 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8540 && !p.applicationInfo.isDirectBootAware();
8541 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8542 && p.applicationInfo.isDirectBootAware();
8544 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8545 && (!mSafeMode || isSystemApp(p))
8546 && (matchesUnaware || matchesAware)) {
8547 PackageSetting ps = mSettings.mPackages.get(p.packageName);
8549 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8550 ps.readUserState(userId), userId);
8563 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8564 if (!sUserManager.exists(userId)) return null;
8565 flags = updateFlagsForComponent(flags, userId, name);
8566 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8568 synchronized (mPackages) {
8569 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8570 PackageSetting ps = provider != null
8571 ? mSettings.mPackages.get(provider.owner.packageName)
8574 final boolean isInstantApp = ps.getInstantApp(userId);
8575 // normal application; filter out instant application provider
8576 if (instantAppPkgName == null && isInstantApp) {
8579 // instant application; filter out other instant applications
8580 if (instantAppPkgName != null
8582 && !provider.owner.packageName.equals(instantAppPkgName)) {
8585 // instant application; filter out non-exposed provider
8586 if (instantAppPkgName != null
8588 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8591 // provider not enabled
8592 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8595 return PackageParser.generateProviderInfo(
8596 provider, flags, ps.readUserState(userId), userId);
8606 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8607 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8611 synchronized (mPackages) {
8612 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8613 .entrySet().iterator();
8614 final int userId = UserHandle.getCallingUserId();
8615 while (i.hasNext()) {
8616 Map.Entry<String, PackageParser.Provider> entry = i.next();
8617 PackageParser.Provider p = entry.getValue();
8618 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8620 if (ps != null && p.syncable
8621 && (!mSafeMode || (p.info.applicationInfo.flags
8622 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8623 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8624 ps.readUserState(userId), userId);
8626 outNames.add(entry.getKey());
8635 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8636 int uid, int flags, String metaDataKey) {
8637 final int callingUid = Binder.getCallingUid();
8638 final int userId = processName != null ? UserHandle.getUserId(uid)
8639 : UserHandle.getCallingUserId();
8640 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8641 flags = updateFlagsForComponent(flags, userId, processName);
8642 ArrayList<ProviderInfo> finalList = null;
8644 synchronized (mPackages) {
8645 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8646 while (i.hasNext()) {
8647 final PackageParser.Provider p = i.next();
8648 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8649 if (ps != null && p.info.authority != null
8650 && (processName == null
8651 || (p.info.processName.equals(processName)
8652 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8653 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8655 // See PM.queryContentProviders()'s javadoc for why we have the metaData
8657 if (metaDataKey != null
8658 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8661 final ComponentName component =
8662 new ComponentName(p.info.packageName, p.info.name);
8663 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8666 if (finalList == null) {
8667 finalList = new ArrayList<ProviderInfo>(3);
8669 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8670 ps.readUserState(userId), userId);
8672 finalList.add(info);
8678 if (finalList != null) {
8679 Collections.sort(finalList, mProviderInitOrderSorter);
8680 return new ParceledListSlice<ProviderInfo>(finalList);
8683 return ParceledListSlice.emptyList();
8687 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8689 synchronized (mPackages) {
8690 final int callingUid = Binder.getCallingUid();
8691 final int callingUserId = UserHandle.getUserId(callingUid);
8692 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8693 if (ps == null) return null;
8694 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8697 final PackageParser.Instrumentation i = mInstrumentation.get(component);
8698 return PackageParser.generateInstrumentationInfo(i, flags);
8703 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8704 String targetPackage, int flags) {
8705 final int callingUid = Binder.getCallingUid();
8706 final int callingUserId = UserHandle.getUserId(callingUid);
8707 final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8708 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8709 return ParceledListSlice.emptyList();
8711 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8714 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8716 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8719 synchronized (mPackages) {
8720 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8721 while (i.hasNext()) {
8722 final PackageParser.Instrumentation p = i.next();
8723 if (targetPackage == null
8724 || targetPackage.equals(p.info.targetPackage)) {
8725 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8737 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8738 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8740 scanDirLI(dir, parseFlags, scanFlags, currentTime);
8742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8746 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8747 final File[] files = dir.listFiles();
8748 if (ArrayUtils.isEmpty(files)) {
8749 Log.d(TAG, "No files in app dir " + dir);
8753 if (DEBUG_PACKAGE_SCANNING) {
8754 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8755 + " flags=0x" + Integer.toHexString(parseFlags));
8757 ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8758 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8759 mParallelPackageParserCallback);
8761 // Submit files for parsing in parallel
8763 for (File file : files) {
8764 final boolean isPackage = (isApkFile(file) || file.isDirectory())
8765 && !PackageInstallerService.isStageName(file.getName());
8767 // Ignore entries which are not packages
8770 parallelPackageParser.submit(file, parseFlags);
8774 // Process results one by one
8775 for (; fileCount > 0; fileCount--) {
8776 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8777 Throwable throwable = parseResult.throwable;
8778 int errorCode = PackageManager.INSTALL_SUCCEEDED;
8780 if (throwable == null) {
8781 // Static shared libraries have synthetic package names
8782 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8783 renameStaticSharedLibraryPackage(parseResult.pkg);
8786 if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8787 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8790 } catch (PackageManagerException e) {
8791 errorCode = e.error;
8792 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8794 } else if (throwable instanceof PackageParser.PackageParserException) {
8795 PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8797 errorCode = e.error;
8798 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8800 throw new IllegalStateException("Unexpected exception occurred while parsing "
8801 + parseResult.scanFile, throwable);
8804 // Delete invalid userdata apps
8805 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8806 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8807 logCriticalInfo(Log.WARN,
8808 "Deleting invalid package at " + parseResult.scanFile);
8809 removeCodePathLI(parseResult.scanFile);
8812 parallelPackageParser.close();
8815 private static File getSettingsProblemFile() {
8816 File dataDir = Environment.getDataDirectory();
8817 File systemDir = new File(dataDir, "system");
8818 File fname = new File(systemDir, "uiderrors.txt");
8822 static void reportSettingsProblem(int priority, String msg) {
8823 logCriticalInfo(priority, msg);
8826 public static void logCriticalInfo(int priority, String msg) {
8827 Slog.println(priority, TAG, msg);
8828 EventLogTags.writePmCriticalInfo(msg);
8830 File fname = getSettingsProblemFile();
8831 FileOutputStream out = new FileOutputStream(fname, true);
8832 PrintWriter pw = new FastPrintWriter(out);
8833 SimpleDateFormat formatter = new SimpleDateFormat();
8834 String dateString = formatter.format(new Date(System.currentTimeMillis()));
8835 pw.println(dateString + ": " + msg);
8837 FileUtils.setPermissions(
8839 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8841 } catch (java.io.IOException e) {
8845 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8846 if (srcFile.isDirectory()) {
8847 final File baseFile = new File(pkg.baseCodePath);
8848 long maxModifiedTime = baseFile.lastModified();
8849 if (pkg.splitCodePaths != null) {
8850 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8851 final File splitFile = new File(pkg.splitCodePaths[i]);
8852 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8855 return maxModifiedTime;
8857 return srcFile.lastModified();
8860 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8861 final int policyFlags) throws PackageManagerException {
8862 // When upgrading from pre-N MR1, verify the package time stamp using the package
8863 // directory and not the APK file.
8864 final long lastModifiedTime = mIsPreNMR1Upgrade
8865 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8867 && ps.codePath.equals(srcFile)
8868 && ps.timeStamp == lastModifiedTime
8869 && !isCompatSignatureUpdateNeeded(pkg)
8870 && !isRecoverSignatureUpdateNeeded(pkg)) {
8871 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8872 KeySetManagerService ksms = mSettings.mKeySetManagerService;
8873 ArraySet<PublicKey> signingKs;
8874 synchronized (mPackages) {
8875 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8877 if (ps.signatures.mSignatures != null
8878 && ps.signatures.mSignatures.length != 0
8879 && signingKs != null) {
8880 // Optimization: reuse the existing cached certificates
8881 // if the package appears to be unchanged.
8882 pkg.mSignatures = ps.signatures.mSignatures;
8883 pkg.mSigningKeys = signingKs;
8887 Slog.w(TAG, "PackageSetting for " + ps.name
8888 + " is missing signatures. Collecting certs again to recover them.");
8890 Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8894 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8895 PackageParser.collectCertificates(pkg, policyFlags);
8896 } catch (PackageParserException e) {
8897 throw PackageManagerException.from(e);
8899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8904 * Traces a package scan.
8905 * @see #scanPackageLI(File, int, int, long, UserHandle)
8907 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8908 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8909 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8911 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8913 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8918 * Scans a package and returns the newly parsed package.
8919 * Returns {@code null} in case of errors and the error code is stored in mLastScanError
8921 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8922 long currentTime, UserHandle user) throws PackageManagerException {
8923 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8924 PackageParser pp = new PackageParser();
8925 pp.setSeparateProcesses(mSeparateProcesses);
8926 pp.setOnlyCoreApps(mOnlyCore);
8927 pp.setDisplayMetrics(mMetrics);
8928 pp.setCallback(mPackageParserCallback);
8930 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8931 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8934 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8935 final PackageParser.Package pkg;
8937 pkg = pp.parsePackage(scanFile, parseFlags);
8938 } catch (PackageParserException e) {
8939 throw PackageManagerException.from(e);
8941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8944 // Static shared libraries have synthetic package names
8945 if (pkg.applicationInfo.isStaticSharedLibrary()) {
8946 renameStaticSharedLibraryPackage(pkg);
8949 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8953 * Scans a package and returns the newly parsed package.
8954 * @throws PackageManagerException on a parse error.
8956 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8957 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8958 throws PackageManagerException {
8959 // If the package has children and this is the first dive in the function
8960 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8961 // packages (parent and children) would be successfully scanned before the
8962 // actual scan since scanning mutates internal state and we want to atomically
8963 // install the package and its children.
8964 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8965 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8966 scanFlags |= SCAN_CHECK_ONLY;
8969 scanFlags &= ~SCAN_CHECK_ONLY;
8973 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8974 scanFlags, currentTime, user);
8976 // Scan the children
8977 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8978 for (int i = 0; i < childCount; i++) {
8979 PackageParser.Package childPackage = pkg.childPackages.get(i);
8980 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8985 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8986 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8993 * Scans a package and returns the newly parsed package.
8994 * @throws PackageManagerException on a parse error.
8996 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8997 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8998 throws PackageManagerException {
8999 PackageSetting ps = null;
9000 PackageSetting updatedPkg;
9002 synchronized (mPackages) {
9003 // Look to see if we already know about this package.
9004 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9005 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9006 // This package has been renamed to its original name. Let's
9008 ps = mSettings.getPackageLPr(oldName);
9010 // If there was no original package, see one for the real package name.
9012 ps = mSettings.getPackageLPr(pkg.packageName);
9014 // Check to see if this package could be hiding/updating a system
9015 // package. Must look for it either under the original or real
9016 // package name depending on our state.
9017 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9018 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9020 // If this is a package we don't know about on the system partition, we
9021 // may need to remove disabled child packages on the system partition
9022 // or may need to not add child packages if the parent apk is updated
9023 // on the data partition and no longer defines this child package.
9024 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9025 // If this is a parent package for an updated system app and this system
9026 // app got an OTA update which no longer defines some of the child packages
9027 // we have to prune them from the disabled system packages.
9028 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9029 if (disabledPs != null) {
9030 final int scannedChildCount = (pkg.childPackages != null)
9031 ? pkg.childPackages.size() : 0;
9032 final int disabledChildCount = disabledPs.childPackageNames != null
9033 ? disabledPs.childPackageNames.size() : 0;
9034 for (int i = 0; i < disabledChildCount; i++) {
9035 String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9036 boolean disabledPackageAvailable = false;
9037 for (int j = 0; j < scannedChildCount; j++) {
9038 PackageParser.Package childPkg = pkg.childPackages.get(j);
9039 if (childPkg.packageName.equals(disabledChildPackageName)) {
9040 disabledPackageAvailable = true;
9044 if (!disabledPackageAvailable) {
9045 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9052 boolean updatedPkgBetter = false;
9053 // First check if this is a system package that may involve an update
9054 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9055 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9056 // it needs to drop FLAG_PRIVILEGED.
9057 if (locationIsPrivileged(scanFile)) {
9058 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9060 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9063 if (ps != null && !ps.codePath.equals(scanFile)) {
9064 // The path has changed from what was last scanned... check the
9065 // version of the new path against what we have stored to determine
9067 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9068 if (pkg.mVersionCode <= ps.versionCode) {
9069 // The system package has been updated and the code path does not match
9070 // Ignore entry. Skip it.
9071 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9072 + " ignored: updated version " + ps.versionCode
9073 + " better than this " + pkg.mVersionCode);
9074 if (!updatedPkg.codePath.equals(scanFile)) {
9075 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9076 + ps.name + " changing from " + updatedPkg.codePathString
9077 + " to " + scanFile);
9078 updatedPkg.codePath = scanFile;
9079 updatedPkg.codePathString = scanFile.toString();
9080 updatedPkg.resourcePath = scanFile;
9081 updatedPkg.resourcePathString = scanFile.toString();
9083 updatedPkg.pkg = pkg;
9084 updatedPkg.versionCode = pkg.mVersionCode;
9086 // Update the disabled system child packages to point to the package too.
9087 final int childCount = updatedPkg.childPackageNames != null
9088 ? updatedPkg.childPackageNames.size() : 0;
9089 for (int i = 0; i < childCount; i++) {
9090 String childPackageName = updatedPkg.childPackageNames.get(i);
9091 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9093 if (updatedChildPkg != null) {
9094 updatedChildPkg.pkg = pkg;
9095 updatedChildPkg.versionCode = pkg.mVersionCode;
9099 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9100 + scanFile + " ignored: updated version " + ps.versionCode
9101 + " better than this " + pkg.mVersionCode);
9103 // The current app on the system partition is better than
9104 // what we have updated to on the data partition; switch
9105 // back to the system partition version.
9106 // At this point, its safely assumed that package installation for
9107 // apps in system partition will go through. If not there won't be a working
9108 // version of the app
9110 synchronized (mPackages) {
9111 // Just remove the loaded entries from package lists.
9112 mPackages.remove(ps.name);
9115 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9116 + " reverting from " + ps.codePathString
9117 + ": new version " + pkg.mVersionCode
9118 + " better than installed " + ps.versionCode);
9120 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9121 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9122 synchronized (mInstallLock) {
9123 args.cleanUpResourcesLI();
9125 synchronized (mPackages) {
9126 mSettings.enableSystemPackageLPw(ps.name);
9128 updatedPkgBetter = true;
9133 if (updatedPkg != null) {
9134 // An updated system app will not have the PARSE_IS_SYSTEM flag set
9136 policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9138 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9139 // flag set initially
9140 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9141 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9145 // Verify certificates against what was last scanned
9146 collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9149 * A new system app appeared, but we already had a non-system one of the
9150 * same name installed earlier.
9152 boolean shouldHideSystemApp = false;
9153 if (updatedPkg == null && ps != null
9154 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9156 * Check to make sure the signatures match first. If they don't,
9157 * wipe the installed application and its data.
9159 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9160 != PackageManager.SIGNATURE_MATCH) {
9161 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9162 + " signatures don't match existing userdata copy; removing");
9163 try (PackageFreezer freezer = freezePackage(pkg.packageName,
9164 "scanPackageInternalLI")) {
9165 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9170 * If the newly-added system app is an older version than the
9171 * already installed version, hide it. It will be scanned later
9172 * and re-added like an update.
9174 if (pkg.mVersionCode <= ps.versionCode) {
9175 shouldHideSystemApp = true;
9176 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9177 + " but new version " + pkg.mVersionCode + " better than installed "
9178 + ps.versionCode + "; hiding system");
9181 * The newly found system app is a newer version that the
9182 * one previously installed. Simply remove the
9183 * already-installed application and replace it with our own
9184 * while keeping the application data.
9186 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9187 + " reverting from " + ps.codePathString + ": new version "
9188 + pkg.mVersionCode + " better than installed " + ps.versionCode);
9189 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9190 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9191 synchronized (mInstallLock) {
9192 args.cleanUpResourcesLI();
9198 // The apk is forward locked (not public) if its code and resources
9199 // are kept in different files. (except for app in either system or
9201 // TODO grab this value from PackageSettings
9202 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9203 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9204 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9208 // TODO: extend to support forward-locked splits
9209 String resourcePath = null;
9210 String baseResourcePath = null;
9211 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9212 if (ps != null && ps.resourcePathString != null) {
9213 resourcePath = ps.resourcePathString;
9214 baseResourcePath = ps.resourcePathString;
9216 // Should not happen at all. Just log an error.
9217 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9220 resourcePath = pkg.codePath;
9221 baseResourcePath = pkg.baseCodePath;
9224 // Set application objects path explicitly.
9225 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9226 pkg.setApplicationInfoCodePath(pkg.codePath);
9227 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9228 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9229 pkg.setApplicationInfoResourcePath(resourcePath);
9230 pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9231 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9233 final int userId = ((user == null) ? 0 : user.getIdentifier());
9234 if (ps != null && ps.getInstantApp(userId)) {
9235 scanFlags |= SCAN_AS_INSTANT_APP;
9238 // Note that we invoke the following method only if we are about to unpack an application
9239 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9240 | SCAN_UPDATE_SIGNATURE, currentTime, user);
9243 * If the system app should be overridden by a previously installed
9244 * data, hide the system app now and let the /data/app scan pick it up
9247 if (shouldHideSystemApp) {
9248 synchronized (mPackages) {
9249 mSettings.disableSystemPackageLPw(pkg.packageName, true);
9256 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9257 // Derive the new package synthetic package name
9258 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9259 + pkg.staticSharedLibVersion);
9262 private static String fixProcessName(String defProcessName,
9263 String processName) {
9264 if (processName == null) {
9265 return defProcessName;
9270 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9271 throws PackageManagerException {
9272 if (pkgSetting.signatures.mSignatures != null) {
9273 // Already existing package. Make sure signatures match
9274 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9275 == PackageManager.SIGNATURE_MATCH;
9277 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9278 == PackageManager.SIGNATURE_MATCH;
9281 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9282 == PackageManager.SIGNATURE_MATCH;
9285 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9286 + pkg.packageName + " signatures do not match the "
9287 + "previously installed version; ignoring!");
9291 // Check for shared user signatures
9292 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9293 // Already existing package. Make sure signatures match
9294 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9295 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9297 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9298 == PackageManager.SIGNATURE_MATCH;
9301 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9302 == PackageManager.SIGNATURE_MATCH;
9305 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9306 "Package " + pkg.packageName
9307 + " has no signatures that match those in shared user "
9308 + pkgSetting.sharedUser.name + "; ignoring!");
9314 * Enforces that only the system UID or root's UID can call a method exposed
9317 * @param message used as message if SecurityException is thrown
9318 * @throws SecurityException if the caller is not system or root
9320 private static final void enforceSystemOrRoot(String message) {
9321 final int uid = Binder.getCallingUid();
9322 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9323 throw new SecurityException(message);
9328 public void performFstrimIfNeeded() {
9329 enforceSystemOrRoot("Only the system can request fstrim");
9331 // Before everything else, see whether we need to fstrim.
9333 IStorageManager sm = PackageHelper.getStorageManager();
9335 boolean doTrim = false;
9336 final long interval = android.provider.Settings.Global.getLong(
9337 mContext.getContentResolver(),
9338 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9339 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9341 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9342 if (timeSinceLast > interval) {
9344 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9345 + "; running immediately");
9349 final boolean dexOptDialogShown;
9350 synchronized (mPackages) {
9351 dexOptDialogShown = mDexOptDialogShown;
9353 if (!isFirstBoot() && dexOptDialogShown) {
9355 ActivityManager.getService().showBootMessage(
9356 mContext.getResources().getString(
9357 R.string.android_upgrading_fstrim), true);
9358 } catch (RemoteException e) {
9361 sm.runMaintenance();
9364 Slog.e(TAG, "storageManager service unavailable!");
9366 } catch (RemoteException e) {
9367 // Can't happen; StorageManagerService is local
9372 public void updatePackagesIfNeeded() {
9373 enforceSystemOrRoot("Only the system can request package update");
9375 // We need to re-extract after an OTA.
9376 boolean causeUpgrade = isUpgrade();
9378 // First boot or factory reset.
9379 // Note: we also handle devices that are upgrading to N right now as if it is their
9380 // first boot, as they do not have profile data.
9381 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9383 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9384 boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9386 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9390 List<PackageParser.Package> pkgs;
9391 synchronized (mPackages) {
9392 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9395 final long startTime = System.nanoTime();
9396 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9397 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9399 final int elapsedTimeSeconds =
9400 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9402 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9403 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9404 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9405 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9406 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9410 * Performs dexopt on the set of packages in {@code packages} and returns an int array
9411 * containing statistics about the invocation. The array consists of three elements,
9412 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9413 * and {@code numberOfPackagesFailed}.
9415 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9416 String compilerFilter) {
9418 int numberOfPackagesVisited = 0;
9419 int numberOfPackagesOptimized = 0;
9420 int numberOfPackagesSkipped = 0;
9421 int numberOfPackagesFailed = 0;
9422 final int numberOfPackagesToDexopt = pkgs.size();
9424 for (PackageParser.Package pkg : pkgs) {
9425 numberOfPackagesVisited++;
9427 if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9429 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9431 numberOfPackagesSkipped++;
9436 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9437 numberOfPackagesToDexopt + ": " + pkg.packageName);
9442 ActivityManager.getService().showBootMessage(
9443 mContext.getResources().getString(R.string.android_upgrading_apk,
9444 numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9445 } catch (RemoteException e) {
9447 synchronized (mPackages) {
9448 mDexOptDialogShown = true;
9452 // If the OTA updates a system app which was previously preopted to a non-preopted state
9453 // the app might end up being verified at runtime. That's because by default the apps
9454 // are verify-profile but for preopted apps there's no profile.
9455 // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9456 // that before the OTA the app was preopted) the app gets compiled with a non-profile
9457 // filter (by default 'quicken').
9458 // Note that at this stage unused apps are already filtered.
9459 if (isSystemApp(pkg) &&
9460 DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9461 !Environment.getReferenceProfile(pkg.packageName).exists()) {
9462 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9465 // checkProfiles is false to avoid merging profiles during boot which
9466 // might interfere with background compilation (b/28612421).
9467 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9468 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9469 // trade-off worth doing to save boot time work.
9470 int dexOptStatus = performDexOptTraced(pkg.packageName,
9471 false /* checkProfiles */,
9474 switch (dexOptStatus) {
9475 case PackageDexOptimizer.DEX_OPT_PERFORMED:
9476 numberOfPackagesOptimized++;
9478 case PackageDexOptimizer.DEX_OPT_SKIPPED:
9479 numberOfPackagesSkipped++;
9481 case PackageDexOptimizer.DEX_OPT_FAILED:
9482 numberOfPackagesFailed++;
9485 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9490 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9491 numberOfPackagesFailed };
9495 public void notifyPackageUse(String packageName, int reason) {
9496 synchronized (mPackages) {
9497 final int callingUid = Binder.getCallingUid();
9498 final int callingUserId = UserHandle.getUserId(callingUid);
9499 if (getInstantAppPackageName(callingUid) != null) {
9500 if (!isCallerSameApp(packageName, callingUid)) {
9504 if (isInstantApp(packageName, callingUserId)) {
9508 final PackageParser.Package p = mPackages.get(packageName);
9512 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9517 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9518 int userId = UserHandle.getCallingUserId();
9519 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9521 Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9522 + loadingPackageName + ", user=" + userId);
9525 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9529 public boolean performDexOpt(String packageName,
9530 boolean checkProfiles, int compileReason, boolean force) {
9531 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9533 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9536 return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9537 PackageDexOptimizer.DEX_OPT_FAILED;
9541 * Perform dexopt on the given package and return one of following result:
9542 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9543 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9544 * {@link PackageDexOptimizer#DEX_OPT_FAILED}
9546 /* package */ int performDexOptWithStatus(String packageName,
9547 boolean checkProfiles, int compileReason, boolean force) {
9548 return performDexOptTraced(packageName, checkProfiles,
9549 getCompilerFilterForReason(compileReason), force);
9553 public boolean performDexOptMode(String packageName,
9554 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9555 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9557 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9560 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9561 targetCompilerFilter, force);
9562 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9565 private int performDexOptTraced(String packageName,
9566 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9567 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9569 return performDexOptInternal(packageName, checkProfiles,
9570 targetCompilerFilter, force);
9572 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9576 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9577 // if the package can now be considered up to date for the given filter.
9578 private int performDexOptInternal(String packageName,
9579 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9580 PackageParser.Package p;
9581 synchronized (mPackages) {
9582 p = mPackages.get(packageName);
9584 // Package could not be found. Report failure.
9585 return PackageDexOptimizer.DEX_OPT_FAILED;
9587 mPackageUsage.maybeWriteAsync(mPackages);
9588 mCompilerStats.maybeWriteAsync();
9590 long callingId = Binder.clearCallingIdentity();
9592 synchronized (mInstallLock) {
9593 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9594 targetCompilerFilter, force);
9597 Binder.restoreCallingIdentity(callingId);
9601 public ArraySet<String> getOptimizablePackages() {
9602 ArraySet<String> pkgs = new ArraySet<String>();
9603 synchronized (mPackages) {
9604 for (PackageParser.Package p : mPackages.values()) {
9605 if (PackageDexOptimizer.canOptimizePackage(p)) {
9606 pkgs.add(p.packageName);
9613 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9614 boolean checkProfiles, String targetCompilerFilter,
9616 // Select the dex optimizer based on the force parameter.
9617 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9618 // allocate an object here.
9619 PackageDexOptimizer pdo = force
9620 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9621 : mPackageDexOptimizer;
9623 // Dexopt all dependencies first. Note: we ignore the return value and march on
9625 // Note that we are going to call performDexOpt on those libraries as many times as
9626 // they are referenced in packages. When we do a batch of performDexOpt (for example
9627 // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9628 // and the first package that uses the library will dexopt it. The
9629 // others will see that the compiled code for the library is up to date.
9630 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9631 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9632 if (!deps.isEmpty()) {
9633 for (PackageParser.Package depPackage : deps) {
9634 // TODO: Analyze and investigate if we (should) profile libraries.
9635 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9636 false /* checkProfiles */,
9637 targetCompilerFilter,
9638 getOrCreateCompilerPackageStats(depPackage),
9639 true /* isUsedByOtherApps */);
9642 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9643 targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9644 mDexManager.isUsedByOtherApps(p.packageName));
9647 // Performs dexopt on the used secondary dex files belonging to the given package.
9648 // Returns true if all dex files were process successfully (which could mean either dexopt or
9649 // skip). Returns false if any of the files caused errors.
9651 public boolean performDexOptSecondary(String packageName, String compilerFilter,
9653 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9655 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9658 mDexManager.reconcileSecondaryDexFiles(packageName);
9659 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9662 public boolean performDexOptSecondary(String packageName, int compileReason,
9664 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9668 * Reconcile the information we have about the secondary dex files belonging to
9669 * {@code packagName} and the actual dex files. For all dex files that were
9670 * deleted, update the internal records and delete the generated oat files.
9673 public void reconcileSecondaryDexFiles(String packageName) {
9674 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9676 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9679 mDexManager.reconcileSecondaryDexFiles(packageName);
9682 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9683 // a reference there.
9684 /*package*/ DexManager getDexManager() {
9689 * Execute the background dexopt job immediately.
9692 public boolean runBackgroundDexoptJob() {
9693 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9696 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9699 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9700 if (p.usesLibraries != null || p.usesOptionalLibraries != null
9701 || p.usesStaticLibraries != null) {
9702 ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9703 Set<String> collectedNames = new HashSet<>();
9704 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9710 return Collections.emptyList();
9714 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9715 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9716 if (!collectedNames.contains(p.packageName)) {
9717 collectedNames.add(p.packageName);
9720 if (p.usesLibraries != null) {
9721 findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9722 null, collected, collectedNames);
9724 if (p.usesOptionalLibraries != null) {
9725 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9726 null, collected, collectedNames);
9728 if (p.usesStaticLibraries != null) {
9729 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9730 p.usesStaticLibrariesVersions, collected, collectedNames);
9735 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9736 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9737 final int libNameCount = libs.size();
9738 for (int i = 0; i < libNameCount; i++) {
9739 String libName = libs.get(i);
9740 int version = (versions != null && versions.length == libNameCount)
9741 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9742 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9743 if (libPkg != null) {
9744 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9749 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9750 synchronized (mPackages) {
9751 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9752 if (libEntry != null) {
9753 return mPackages.get(libEntry.apk);
9759 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9760 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9761 if (versionedLib == null) {
9764 return versionedLib.get(version);
9767 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9768 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9769 pkg.staticSharedLibName);
9770 if (versionedLib == null) {
9773 int previousLibVersion = -1;
9774 final int versionCount = versionedLib.size();
9775 for (int i = 0; i < versionCount; i++) {
9776 final int libVersion = versionedLib.keyAt(i);
9777 if (libVersion < pkg.staticSharedLibVersion) {
9778 previousLibVersion = Math.max(previousLibVersion, libVersion);
9781 if (previousLibVersion >= 0) {
9782 return versionedLib.get(previousLibVersion);
9787 public void shutdown() {
9788 mPackageUsage.writeNow(mPackages);
9789 mCompilerStats.writeNow();
9793 public void dumpProfiles(String packageName) {
9794 PackageParser.Package pkg;
9795 synchronized (mPackages) {
9796 pkg = mPackages.get(packageName);
9798 throw new IllegalArgumentException("Unknown package: " + packageName);
9801 /* Only the shell, root, or the app user should be able to dump profiles. */
9802 int callingUid = Binder.getCallingUid();
9803 if (callingUid != Process.SHELL_UID &&
9804 callingUid != Process.ROOT_UID &&
9805 callingUid != pkg.applicationInfo.uid) {
9806 throw new SecurityException("dumpProfiles");
9809 synchronized (mInstallLock) {
9810 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9811 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9813 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9814 String codePaths = TextUtils.join(";", allCodePaths);
9815 mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9816 } catch (InstallerException e) {
9817 Slog.w(TAG, "Failed to dump profiles", e);
9819 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9824 public void forceDexOpt(String packageName) {
9825 enforceSystemOrRoot("forceDexOpt");
9827 PackageParser.Package pkg;
9828 synchronized (mPackages) {
9829 pkg = mPackages.get(packageName);
9831 throw new IllegalArgumentException("Unknown package: " + packageName);
9835 synchronized (mInstallLock) {
9836 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9838 // Whoever is calling forceDexOpt wants a compiled package.
9839 // Don't use profiles since that may cause compilation to be skipped.
9840 final int res = performDexOptInternalWithDependenciesLI(pkg,
9841 false /* checkProfiles */, getDefaultCompilerFilter(),
9844 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9845 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9846 throw new IllegalStateException("Failed to dexopt: " + res);
9851 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9852 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9853 Slog.w(TAG, "Unable to update from " + oldPkg.name
9854 + " to " + newPkg.packageName
9855 + ": old package not in system partition");
9857 } else if (mPackages.get(oldPkg.name) != null) {
9858 Slog.w(TAG, "Unable to update from " + oldPkg.name
9859 + " to " + newPkg.packageName
9860 + ": old package still exists");
9866 void removeCodePathLI(File codePath) {
9867 if (codePath.isDirectory()) {
9869 mInstaller.rmPackageDir(codePath.getAbsolutePath());
9870 } catch (InstallerException e) {
9871 Slog.w(TAG, "Failed to remove code path", e);
9878 private int[] resolveUserIds(int userId) {
9879 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9882 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9884 Slog.wtf(TAG, "Package was null!", new Throwable());
9887 clearAppDataLeafLIF(pkg, userId, flags);
9888 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9889 for (int i = 0; i < childCount; i++) {
9890 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9894 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9895 final PackageSetting ps;
9896 synchronized (mPackages) {
9897 ps = mSettings.mPackages.get(pkg.packageName);
9899 for (int realUserId : resolveUserIds(userId)) {
9900 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9902 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9904 } catch (InstallerException e) {
9905 Slog.w(TAG, String.valueOf(e));
9910 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9912 Slog.wtf(TAG, "Package was null!", new Throwable());
9915 destroyAppDataLeafLIF(pkg, userId, flags);
9916 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9917 for (int i = 0; i < childCount; i++) {
9918 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9922 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9923 final PackageSetting ps;
9924 synchronized (mPackages) {
9925 ps = mSettings.mPackages.get(pkg.packageName);
9927 for (int realUserId : resolveUserIds(userId)) {
9928 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9930 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9932 } catch (InstallerException e) {
9933 Slog.w(TAG, String.valueOf(e));
9935 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9939 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9941 Slog.wtf(TAG, "Package was null!", new Throwable());
9944 destroyAppProfilesLeafLIF(pkg);
9945 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9946 for (int i = 0; i < childCount; i++) {
9947 destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9951 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9953 mInstaller.destroyAppProfiles(pkg.packageName);
9954 } catch (InstallerException e) {
9955 Slog.w(TAG, String.valueOf(e));
9959 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9961 Slog.wtf(TAG, "Package was null!", new Throwable());
9964 clearAppProfilesLeafLIF(pkg);
9965 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9966 for (int i = 0; i < childCount; i++) {
9967 clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9971 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9973 mInstaller.clearAppProfiles(pkg.packageName);
9974 } catch (InstallerException e) {
9975 Slog.w(TAG, String.valueOf(e));
9979 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9980 long lastUpdateTime) {
9981 // Set parent install/update time
9982 PackageSetting ps = (PackageSetting) pkg.mExtras;
9984 ps.firstInstallTime = firstInstallTime;
9985 ps.lastUpdateTime = lastUpdateTime;
9987 // Set children install/update time
9988 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9989 for (int i = 0; i < childCount; i++) {
9990 PackageParser.Package childPkg = pkg.childPackages.get(i);
9991 ps = (PackageSetting) childPkg.mExtras;
9993 ps.firstInstallTime = firstInstallTime;
9994 ps.lastUpdateTime = lastUpdateTime;
9999 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10000 PackageParser.Package changingLib) {
10001 if (file.path != null) {
10002 usesLibraryFiles.add(file.path);
10005 PackageParser.Package p = mPackages.get(file.apk);
10006 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10007 // If we are doing this while in the middle of updating a library apk,
10008 // then we need to make sure to use that new apk for determining the
10009 // dependencies here. (We haven't yet finished committing the new apk
10010 // to the package manager state.)
10011 if (p == null || p.packageName.equals(changingLib.packageName)) {
10016 usesLibraryFiles.addAll(p.getAllCodePaths());
10017 if (p.usesLibraryFiles != null) {
10018 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10023 private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10024 PackageParser.Package changingLib) throws PackageManagerException {
10028 ArraySet<String> usesLibraryFiles = null;
10029 if (pkg.usesLibraries != null) {
10030 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10031 null, null, pkg.packageName, changingLib, true, null);
10033 if (pkg.usesStaticLibraries != null) {
10034 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10035 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10036 pkg.packageName, changingLib, true, usesLibraryFiles);
10038 if (pkg.usesOptionalLibraries != null) {
10039 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10040 null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10042 if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10043 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10045 pkg.usesLibraryFiles = null;
10049 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10050 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10051 @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10052 boolean required, @Nullable ArraySet<String> outUsedLibraries)
10053 throws PackageManagerException {
10054 final int libCount = requestedLibraries.size();
10055 for (int i = 0; i < libCount; i++) {
10056 final String libName = requestedLibraries.get(i);
10057 final int libVersion = requiredVersions != null ? requiredVersions[i]
10058 : SharedLibraryInfo.VERSION_UNDEFINED;
10059 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10060 if (libEntry == null) {
10062 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10063 "Package " + packageName + " requires unavailable shared library "
10064 + libName + "; failing!");
10065 } else if (DEBUG_SHARED_LIBRARIES) {
10066 Slog.i(TAG, "Package " + packageName
10067 + " desires unavailable shared library "
10068 + libName + "; ignoring!");
10071 if (requiredVersions != null && requiredCertDigests != null) {
10072 if (libEntry.info.getVersion() != requiredVersions[i]) {
10073 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10074 "Package " + packageName + " requires unavailable static shared"
10075 + " library " + libName + " version "
10076 + libEntry.info.getVersion() + "; failing!");
10079 PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10080 if (libPkg == null) {
10081 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10082 "Package " + packageName + " requires unavailable static shared"
10083 + " library; failing!");
10086 String expectedCertDigest = requiredCertDigests[i];
10087 String libCertDigest = PackageUtils.computeCertSha256Digest(
10088 libPkg.mSignatures[0]);
10089 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10090 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10091 "Package " + packageName + " requires differently signed" +
10092 " static shared library; failing!");
10096 if (outUsedLibraries == null) {
10097 outUsedLibraries = new ArraySet<>();
10099 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10102 return outUsedLibraries;
10105 private static boolean hasString(List<String> list, List<String> which) {
10106 if (list == null) {
10109 for (int i=list.size()-1; i>=0; i--) {
10110 for (int j=which.size()-1; j>=0; j--) {
10111 if (which.get(j).equals(list.get(i))) {
10119 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10120 PackageParser.Package changingPkg) {
10121 ArrayList<PackageParser.Package> res = null;
10122 for (PackageParser.Package pkg : mPackages.values()) {
10123 if (changingPkg != null
10124 && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10125 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10126 && !ArrayUtils.contains(pkg.usesStaticLibraries,
10127 changingPkg.staticSharedLibName)) {
10131 res = new ArrayList<>();
10135 updateSharedLibrariesLPr(pkg, changingPkg);
10136 } catch (PackageManagerException e) {
10137 // If a system app update or an app and a required lib missing we
10138 // delete the package and for updated system apps keep the data as
10139 // it is better for the user to reinstall than to be in an limbo
10140 // state. Also libs disappearing under an app should never happen
10142 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10143 final int flags = pkg.isUpdatedSystemApp()
10144 ? PackageManager.DELETE_KEEP_DATA : 0;
10145 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10146 flags , null, true, null);
10148 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10155 * Derive the value of the {@code cpuAbiOverride} based on the provided
10156 * value and an optional stored value from the package settings.
10158 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10159 String cpuAbiOverride = null;
10161 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10162 cpuAbiOverride = null;
10163 } else if (abiOverride != null) {
10164 cpuAbiOverride = abiOverride;
10165 } else if (settings != null) {
10166 cpuAbiOverride = settings.cpuAbiOverrideString;
10169 return cpuAbiOverride;
10172 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10173 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10174 throws PackageManagerException {
10175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10176 // If the package has children and this is the first dive in the function
10177 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10178 // whether all packages (parent and children) would be successfully scanned
10179 // before the actual scan since scanning mutates internal state and we want
10180 // to atomically install the package and its children.
10181 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10182 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10183 scanFlags |= SCAN_CHECK_ONLY;
10186 scanFlags &= ~SCAN_CHECK_ONLY;
10189 final PackageParser.Package scannedPkg;
10192 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10193 // Scan the children
10194 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10195 for (int i = 0; i < childCount; i++) {
10196 PackageParser.Package childPkg = pkg.childPackages.get(i);
10197 scanPackageLI(childPkg, policyFlags,
10198 scanFlags, currentTime, user);
10201 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10204 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10205 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10211 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10212 int scanFlags, long currentTime, @Nullable UserHandle user)
10213 throws PackageManagerException {
10214 boolean success = false;
10216 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10217 currentTime, user);
10221 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10222 // DELETE_DATA_ON_FAILURES is only used by frozen paths
10223 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10224 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10225 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10231 * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10233 private static boolean apkHasCode(String fileName) {
10234 StrictJarFile jarFile = null;
10236 jarFile = new StrictJarFile(fileName,
10237 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10238 return jarFile.findEntry("classes.dex") != null;
10239 } catch (IOException ignore) {
10242 if (jarFile != null) {
10245 } catch (IOException ignore) {}
10251 * Enforces code policy for the package. This ensures that if an APK has
10252 * declared hasCode="true" in its manifest that the APK actually contains
10255 * @throws PackageManagerException If bytecode could not be found when it should exist
10257 private static void assertCodePolicy(PackageParser.Package pkg)
10258 throws PackageManagerException {
10259 final boolean shouldHaveCode =
10260 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10261 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10262 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10263 "Package " + pkg.baseCodePath + " code is missing");
10266 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10267 for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10268 final boolean splitShouldHaveCode =
10269 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10270 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10271 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10272 "Package " + pkg.splitCodePaths[i] + " code is missing");
10278 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10279 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10280 throws PackageManagerException {
10281 if (DEBUG_PACKAGE_SCANNING) {
10282 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10283 Log.d(TAG, "Scanning package " + pkg.packageName);
10286 applyPolicy(pkg, policyFlags);
10288 assertPackageIsValid(pkg, policyFlags, scanFlags);
10290 // Initialize package source and resource directories
10291 final File scanFile = new File(pkg.codePath);
10292 final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10293 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10295 SharedUserSetting suid = null;
10296 PackageSetting pkgSetting = null;
10298 // Getting the package setting may have a side-effect, so if we
10299 // are only checking if scan would succeed, stash a copy of the
10300 // old setting to restore at the end.
10301 PackageSetting nonMutatedPs = null;
10303 // We keep references to the derived CPU Abis from settings in oder to reuse
10304 // them in the case where we're not upgrading or booting for the first time.
10305 String primaryCpuAbiFromSettings = null;
10306 String secondaryCpuAbiFromSettings = null;
10308 final PackageParser.Package oldPkg;
10311 synchronized (mPackages) {
10312 if (pkg.mSharedUserId != null) {
10313 // SIDE EFFECTS; may potentially allocate a new shared user
10314 suid = mSettings.getSharedUserLPw(
10315 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10316 if (DEBUG_PACKAGE_SCANNING) {
10317 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10318 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10319 + "): packages=" + suid.packages);
10323 // Check if we are renaming from an original package name.
10324 PackageSetting origPackage = null;
10325 String realName = null;
10326 if (pkg.mOriginalPackages != null) {
10327 // This package may need to be renamed to a previously
10328 // installed name. Let's check on that...
10329 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10330 if (pkg.mOriginalPackages.contains(renamed)) {
10331 // This package had originally been installed as the
10332 // original name, and we have already taken care of
10333 // transitioning to the new one. Just update the new
10334 // one to continue using the old name.
10335 realName = pkg.mRealPackage;
10336 if (!pkg.packageName.equals(renamed)) {
10337 // Callers into this function may have already taken
10338 // care of renaming the package; only do it here if
10339 // it is not already done.
10340 pkg.setPackageName(renamed);
10343 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10344 if ((origPackage = mSettings.getPackageLPr(
10345 pkg.mOriginalPackages.get(i))) != null) {
10346 // We do have the package already installed under its
10347 // original name... should we use it?
10348 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10349 // New package is not compatible with original.
10350 origPackage = null;
10352 } else if (origPackage.sharedUser != null) {
10353 // Make sure uid is compatible between packages.
10354 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10355 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10356 + " to " + pkg.packageName + ": old uid "
10357 + origPackage.sharedUser.name
10358 + " differs from " + pkg.mSharedUserId);
10359 origPackage = null;
10362 // TODO: Add case when shared user id is added [b/28144775]
10364 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10365 + pkg.packageName + " to old name " + origPackage.name);
10373 if (mTransferedPackages.contains(pkg.packageName)) {
10374 Slog.w(TAG, "Package " + pkg.packageName
10375 + " was transferred to another, but its .apk remains");
10378 // See comments in nonMutatedPs declaration
10379 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10380 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10381 if (foundPs != null) {
10382 nonMutatedPs = new PackageSetting(foundPs);
10386 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10387 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10388 if (foundPs != null) {
10389 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10390 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10394 pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10395 if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10396 PackageManagerService.reportSettingsProblem(Log.WARN,
10397 "Package " + pkg.packageName + " shared user changed from "
10398 + (pkgSetting.sharedUser != null
10399 ? pkgSetting.sharedUser.name : "<nothing>")
10401 + (suid != null ? suid.name : "<nothing>")
10402 + "; replacing with new");
10405 final PackageSetting oldPkgSetting =
10406 pkgSetting == null ? null : new PackageSetting(pkgSetting);
10407 final PackageSetting disabledPkgSetting =
10408 mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10410 if (oldPkgSetting == null) {
10413 oldPkg = oldPkgSetting.pkg;
10416 String[] usesStaticLibraries = null;
10417 if (pkg.usesStaticLibraries != null) {
10418 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10419 pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10422 if (pkgSetting == null) {
10423 final String parentPackageName = (pkg.parentPackage != null)
10424 ? pkg.parentPackage.packageName : null;
10425 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10426 // REMOVE SharedUserSetting from method; update in a separate call
10427 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10428 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10429 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10430 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10431 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10432 true /*allowInstall*/, instantApp, parentPackageName,
10433 pkg.getChildPackageNames(), UserManagerService.getInstance(),
10434 usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10435 // SIDE EFFECTS; updates system state; move elsewhere
10436 if (origPackage != null) {
10437 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10439 mSettings.addUserToSettingLPw(pkgSetting);
10441 // REMOVE SharedUserSetting from method; update in a separate call.
10443 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10444 // secondaryCpuAbi are not known at this point so we always update them
10445 // to null here, only to reset them at a later point.
10446 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10447 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10448 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10449 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10450 UserManagerService.getInstance(), usesStaticLibraries,
10451 pkg.usesStaticLibrariesVersions);
10453 // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10454 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10456 // SIDE EFFECTS; modifies system state; move elsewhere
10457 if (pkgSetting.origPackage != null) {
10458 // If we are first transitioning from an original package,
10459 // fix up the new package's name now. We need to do this after
10460 // looking up the package under its new name, so getPackageLP
10461 // can take care of fiddling things correctly.
10462 pkg.setPackageName(origPackage.name);
10464 // File a report about this.
10465 String msg = "New package " + pkgSetting.realName
10466 + " renamed to replace old package " + pkgSetting.name;
10467 reportSettingsProblem(Log.WARN, msg);
10469 // Make a note of it.
10470 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10471 mTransferedPackages.add(origPackage.name);
10474 // No longer need to retain this.
10475 pkgSetting.origPackage = null;
10478 // SIDE EFFECTS; modifies system state; move elsewhere
10479 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10480 // Make a note of it.
10481 mTransferedPackages.add(pkg.packageName);
10484 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10485 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10488 if ((scanFlags & SCAN_BOOTING) == 0
10489 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10490 // Check all shared libraries and map to their actual file path.
10491 // We only do this here for apps not on a system dir, because those
10492 // are the only ones that can fail an install due to this. We
10493 // will take care of the system apps by updating all of their
10494 // library paths after the scan is done. Also during the initial
10495 // scan don't update any libs as we do this wholesale after all
10496 // apps are scanned to avoid dependency based scanning.
10497 updateSharedLibrariesLPr(pkg, null);
10500 if (mFoundPolicyFile) {
10501 SELinuxMMAC.assignSeInfoValue(pkg);
10503 pkg.applicationInfo.uid = pkgSetting.appId;
10504 pkg.mExtras = pkgSetting;
10507 // Static shared libs have same package with different versions where
10508 // we internally use a synthetic package name to allow multiple versions
10509 // of the same package, therefore we need to compare signatures against
10510 // the package setting for the latest library version.
10511 PackageSetting signatureCheckPs = pkgSetting;
10512 if (pkg.applicationInfo.isStaticSharedLibrary()) {
10513 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10514 if (libraryEntry != null) {
10515 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10519 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10520 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10521 // We just determined the app is signed correctly, so bring
10522 // over the latest parsed certs.
10523 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10525 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10526 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10527 "Package " + pkg.packageName + " upgrade keys do not match the "
10528 + "previously installed version");
10530 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10531 String msg = "System package " + pkg.packageName
10532 + " signature changed; retaining data.";
10533 reportSettingsProblem(Log.WARN, msg);
10538 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10539 verifySignaturesLP(signatureCheckPs, pkg);
10540 // We just determined the app is signed correctly, so bring
10541 // over the latest parsed certs.
10542 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10543 } catch (PackageManagerException e) {
10544 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10547 // The signature has changed, but this package is in the system
10548 // image... let's recover!
10549 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10550 // However... if this package is part of a shared user, but it
10551 // doesn't match the signature of the shared user, let's fail.
10552 // What this means is that you can't change the signatures
10553 // associated with an overall shared user, which doesn't seem all
10554 // that unreasonable.
10555 if (signatureCheckPs.sharedUser != null) {
10556 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10557 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10558 throw new PackageManagerException(
10559 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10560 "Signature mismatch for shared user: "
10561 + pkgSetting.sharedUser);
10564 // File a report about this.
10565 String msg = "System package " + pkg.packageName
10566 + " signature changed; retaining data.";
10567 reportSettingsProblem(Log.WARN, msg);
10571 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10572 // This package wants to adopt ownership of permissions from
10573 // another package.
10574 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10575 final String origName = pkg.mAdoptPermissions.get(i);
10576 final PackageSetting orig = mSettings.getPackageLPr(origName);
10577 if (orig != null) {
10578 if (verifyPackageUpdateLPr(orig, pkg)) {
10579 Slog.i(TAG, "Adopting permissions from " + origName + " to "
10580 + pkg.packageName);
10581 // SIDE EFFECTS; updates permissions system state; move elsewhere
10582 mSettings.transferPermissionsLPw(origName, pkg.packageName);
10589 pkg.applicationInfo.processName = fixProcessName(
10590 pkg.applicationInfo.packageName,
10591 pkg.applicationInfo.processName);
10593 if (pkg != mPlatformPackage) {
10594 // Get all of our default paths setup
10595 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10598 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10600 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10601 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10602 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10603 final boolean extractNativeLibs = !pkg.isLibrary();
10604 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10605 mAppLib32InstallDir);
10606 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10608 // Some system apps still use directory structure for native libraries
10609 // in which case we might end up not detecting abi solely based on apk
10610 // structure. Try to detect abi based on directory structure.
10611 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10612 pkg.applicationInfo.primaryCpuAbi == null) {
10613 setBundledAppAbisAndRoots(pkg, pkgSetting);
10614 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10617 // This is not a first boot or an upgrade, don't bother deriving the
10618 // ABI during the scan. Instead, trust the value that was stored in the
10619 // package setting.
10620 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10621 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10623 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10625 if (DEBUG_ABI_SELECTION) {
10626 Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10627 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10628 pkg.applicationInfo.secondaryCpuAbi);
10632 if ((scanFlags & SCAN_MOVE) != 0) {
10633 // We haven't run dex-opt for this move (since we've moved the compiled output too)
10634 // but we already have this packages package info in the PackageSetting. We just
10635 // use that and derive the native library path based on the new codepath.
10636 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10637 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10640 // Set native library paths again. For moves, the path will be updated based on the
10641 // ABIs we've determined above. For non-moves, the path will be updated based on the
10642 // ABIs we determined during compilation, but the path will depend on the final
10643 // package path (after the rename away from the stage path).
10644 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10647 // This is a special case for the "system" package, where the ABI is
10648 // dictated by the zygote configuration (and init.rc). We should keep track
10649 // of this ABI so that we can deal with "normal" applications that run under
10650 // the same UID correctly.
10651 if (mPlatformPackage == pkg) {
10652 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10653 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10656 // If there's a mismatch between the abi-override in the package setting
10657 // and the abiOverride specified for the install. Warn about this because we
10658 // would've already compiled the app without taking the package setting into
10660 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10661 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10662 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10663 " for package " + pkg.packageName);
10667 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10668 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10669 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10671 // Copy the derived override back to the parsed package, so that we can
10672 // update the package settings accordingly.
10673 pkg.cpuAbiOverride = cpuAbiOverride;
10675 if (DEBUG_ABI_SELECTION) {
10676 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10677 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10678 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10681 // Push the derived path down into PackageSettings so we know what to
10682 // clean up at uninstall time.
10683 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10685 if (DEBUG_ABI_SELECTION) {
10686 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10687 " primary=" + pkg.applicationInfo.primaryCpuAbi +
10688 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10691 // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10692 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10693 // We don't do this here during boot because we can do it all
10694 // at once after scanning all existing packages.
10696 // We also do this *before* we perform dexopt on this package, so that
10697 // we can avoid redundant dexopts, and also to make sure we've got the
10698 // code and package path correct.
10699 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10702 if (mFactoryTest && pkg.requestedPermissions.contains(
10703 android.Manifest.permission.FACTORY_TEST)) {
10704 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10707 if (isSystemApp(pkg)) {
10708 pkgSetting.isOrphaned = true;
10711 // Take care of first install / last update times.
10712 final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10713 if (currentTime != 0) {
10714 if (pkgSetting.firstInstallTime == 0) {
10715 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10716 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10717 pkgSetting.lastUpdateTime = currentTime;
10719 } else if (pkgSetting.firstInstallTime == 0) {
10720 // We need *something*. Take time time stamp of the file.
10721 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10722 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10723 if (scanFileTime != pkgSetting.timeStamp) {
10724 // A package on the system image has changed; consider this
10725 // to be an update.
10726 pkgSetting.lastUpdateTime = scanFileTime;
10729 pkgSetting.setTimeStamp(scanFileTime);
10731 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10732 if (nonMutatedPs != null) {
10733 synchronized (mPackages) {
10734 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10738 final int userId = user == null ? 0 : user.getIdentifier();
10739 // Modify state for the given package setting
10740 commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10741 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10742 if (pkgSetting.getInstantApp(userId)) {
10743 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10747 if (oldPkg != null) {
10748 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
10749 // revokation from this method might need to kill apps which need the
10750 // mPackages lock on a different thread. This would dead lock.
10752 // Hence create a copy of all package names and pass it into
10753 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
10754 // revoked. If a new package is added before the async code runs the permission
10755 // won't be granted yet, hence new packages are no problem.
10756 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
10758 AsyncTask.execute(new Runnable() {
10759 public void run() {
10760 revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg, allPackageNames);
10769 * Applies policy to the parsed package based upon the given policy flags.
10770 * Ensures the package is in a good state.
10772 * Implementation detail: This method must NOT have any side effect. It would
10773 * ideally be static, but, it requires locks to read system state.
10775 private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10776 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10777 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10778 if (pkg.applicationInfo.isDirectBootAware()) {
10779 // we're direct boot aware; set for all components
10780 for (PackageParser.Service s : pkg.services) {
10781 s.info.encryptionAware = s.info.directBootAware = true;
10783 for (PackageParser.Provider p : pkg.providers) {
10784 p.info.encryptionAware = p.info.directBootAware = true;
10786 for (PackageParser.Activity a : pkg.activities) {
10787 a.info.encryptionAware = a.info.directBootAware = true;
10789 for (PackageParser.Activity r : pkg.receivers) {
10790 r.info.encryptionAware = r.info.directBootAware = true;
10794 // Only allow system apps to be flagged as core apps.
10795 pkg.coreApp = false;
10796 // clear flags not applicable to regular apps
10797 pkg.applicationInfo.privateFlags &=
10798 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10799 pkg.applicationInfo.privateFlags &=
10800 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10802 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10804 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10805 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10808 if (!isSystemApp(pkg)) {
10809 // Only system apps can use these features.
10810 pkg.mOriginalPackages = null;
10811 pkg.mRealPackage = null;
10812 pkg.mAdoptPermissions = null;
10817 * Asserts the parsed package is valid according to the given policy. If the
10818 * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10820 * Implementation detail: This method must NOT have any side effects. It would
10821 * ideally be static, but, it requires locks to read system state.
10823 * @throws PackageManagerException If the package fails any of the validation checks
10825 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10826 throws PackageManagerException {
10827 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10828 assertCodePolicy(pkg);
10831 if (pkg.applicationInfo.getCodePath() == null ||
10832 pkg.applicationInfo.getResourcePath() == null) {
10833 // Bail out. The resource and code paths haven't been set.
10834 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10835 "Code and resource paths haven't been set correctly");
10838 // Make sure we're not adding any bogus keyset info
10839 KeySetManagerService ksms = mSettings.mKeySetManagerService;
10840 ksms.assertScannedPackageValid(pkg);
10842 synchronized (mPackages) {
10843 // The special "android" package can only be defined once
10844 if (pkg.packageName.equals("android")) {
10845 if (mAndroidApplication != null) {
10846 Slog.w(TAG, "*************************************************");
10847 Slog.w(TAG, "Core android package being redefined. Skipping.");
10848 Slog.w(TAG, " codePath=" + pkg.codePath);
10849 Slog.w(TAG, "*************************************************");
10850 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10851 "Core android package being redefined. Skipping.");
10855 // A package name must be unique; don't allow duplicates
10856 if (mPackages.containsKey(pkg.packageName)) {
10857 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10858 "Application package " + pkg.packageName
10859 + " already installed. Skipping duplicate.");
10862 if (pkg.applicationInfo.isStaticSharedLibrary()) {
10863 // Static libs have a synthetic package name containing the version
10864 // but we still want the base name to be unique.
10865 if (mPackages.containsKey(pkg.manifestPackageName)) {
10866 throw new PackageManagerException(
10867 "Duplicate static shared lib provider package");
10870 // Static shared libraries should have at least O target SDK
10871 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10872 throw new PackageManagerException(
10873 "Packages declaring static-shared libs must target O SDK or higher");
10876 // Package declaring static a shared lib cannot be instant apps
10877 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10878 throw new PackageManagerException(
10879 "Packages declaring static-shared libs cannot be instant apps");
10882 // Package declaring static a shared lib cannot be renamed since the package
10883 // name is synthetic and apps can't code around package manager internals.
10884 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10885 throw new PackageManagerException(
10886 "Packages declaring static-shared libs cannot be renamed");
10889 // Package declaring static a shared lib cannot declare child packages
10890 if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10891 throw new PackageManagerException(
10892 "Packages declaring static-shared libs cannot have child packages");
10895 // Package declaring static a shared lib cannot declare dynamic libs
10896 if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10897 throw new PackageManagerException(
10898 "Packages declaring static-shared libs cannot declare dynamic libs");
10901 // Package declaring static a shared lib cannot declare shared users
10902 if (pkg.mSharedUserId != null) {
10903 throw new PackageManagerException(
10904 "Packages declaring static-shared libs cannot declare shared users");
10907 // Static shared libs cannot declare activities
10908 if (!pkg.activities.isEmpty()) {
10909 throw new PackageManagerException(
10910 "Static shared libs cannot declare activities");
10913 // Static shared libs cannot declare services
10914 if (!pkg.services.isEmpty()) {
10915 throw new PackageManagerException(
10916 "Static shared libs cannot declare services");
10919 // Static shared libs cannot declare providers
10920 if (!pkg.providers.isEmpty()) {
10921 throw new PackageManagerException(
10922 "Static shared libs cannot declare content providers");
10925 // Static shared libs cannot declare receivers
10926 if (!pkg.receivers.isEmpty()) {
10927 throw new PackageManagerException(
10928 "Static shared libs cannot declare broadcast receivers");
10931 // Static shared libs cannot declare permission groups
10932 if (!pkg.permissionGroups.isEmpty()) {
10933 throw new PackageManagerException(
10934 "Static shared libs cannot declare permission groups");
10937 // Static shared libs cannot declare permissions
10938 if (!pkg.permissions.isEmpty()) {
10939 throw new PackageManagerException(
10940 "Static shared libs cannot declare permissions");
10943 // Static shared libs cannot declare protected broadcasts
10944 if (pkg.protectedBroadcasts != null) {
10945 throw new PackageManagerException(
10946 "Static shared libs cannot declare protected broadcasts");
10949 // Static shared libs cannot be overlay targets
10950 if (pkg.mOverlayTarget != null) {
10951 throw new PackageManagerException(
10952 "Static shared libs cannot be overlay targets");
10955 // The version codes must be ordered as lib versions
10956 int minVersionCode = Integer.MIN_VALUE;
10957 int maxVersionCode = Integer.MAX_VALUE;
10959 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10960 pkg.staticSharedLibName);
10961 if (versionedLib != null) {
10962 final int versionCount = versionedLib.size();
10963 for (int i = 0; i < versionCount; i++) {
10964 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10965 final int libVersionCode = libInfo.getDeclaringPackage()
10967 if (libInfo.getVersion() < pkg.staticSharedLibVersion) {
10968 minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10969 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) {
10970 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10972 minVersionCode = maxVersionCode = libVersionCode;
10977 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10978 throw new PackageManagerException("Static shared"
10979 + " lib version codes must be ordered as lib versions");
10983 // Only privileged apps and updated privileged apps can add child packages.
10984 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10985 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10986 throw new PackageManagerException("Only privileged apps can add child "
10987 + "packages. Ignoring package " + pkg.packageName);
10989 final int childCount = pkg.childPackages.size();
10990 for (int i = 0; i < childCount; i++) {
10991 PackageParser.Package childPkg = pkg.childPackages.get(i);
10992 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10993 childPkg.packageName)) {
10994 throw new PackageManagerException("Can't override child of "
10995 + "another disabled app. Ignoring package " + pkg.packageName);
11000 // If we're only installing presumed-existing packages, require that the
11001 // scanned APK is both already known and at the path previously established
11002 // for it. Previously unknown packages we pick up normally, but if we have an
11003 // a priori expectation about this package's install presence, enforce it.
11004 // With a singular exception for new system packages. When an OTA contains
11005 // a new system package, we allow the codepath to change from a system location
11006 // to the user-installed location. If we don't allow this change, any newer,
11007 // user-installed version of the application will be ignored.
11008 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11009 if (mExpectingBetter.containsKey(pkg.packageName)) {
11010 logCriticalInfo(Log.WARN,
11011 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11013 PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11014 if (known != null) {
11015 if (DEBUG_PACKAGE_SCANNING) {
11016 Log.d(TAG, "Examining " + pkg.codePath
11017 + " and requiring known paths " + known.codePathString
11018 + " & " + known.resourcePathString);
11020 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11021 || !pkg.applicationInfo.getResourcePath().equals(
11022 known.resourcePathString)) {
11023 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11024 "Application package " + pkg.packageName
11025 + " found at " + pkg.applicationInfo.getCodePath()
11026 + " but expected at " + known.codePathString
11033 // Verify that this new package doesn't have any content providers
11034 // that conflict with existing packages. Only do this if the
11035 // package isn't already installed, since we don't want to break
11036 // things that are installed.
11037 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11038 final int N = pkg.providers.size();
11040 for (i=0; i<N; i++) {
11041 PackageParser.Provider p = pkg.providers.get(i);
11042 if (p.info.authority != null) {
11043 String names[] = p.info.authority.split(";");
11044 for (int j = 0; j < names.length; j++) {
11045 if (mProvidersByAuthority.containsKey(names[j])) {
11046 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11047 final String otherPackageName =
11048 ((other != null && other.getComponentName() != null) ?
11049 other.getComponentName().getPackageName() : "?");
11050 throw new PackageManagerException(
11051 INSTALL_FAILED_CONFLICTING_PROVIDER,
11052 "Can't install because provider name " + names[j]
11053 + " (in package " + pkg.applicationInfo.packageName
11054 + ") is already used by " + otherPackageName);
11063 private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11064 int type, String declaringPackageName, int declaringVersionCode) {
11065 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11066 if (versionedLib == null) {
11067 versionedLib = new SparseArray<>();
11068 mSharedLibraries.put(name, versionedLib);
11069 if (type == SharedLibraryInfo.TYPE_STATIC) {
11070 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11072 } else if (versionedLib.indexOfKey(version) >= 0) {
11075 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11076 version, type, declaringPackageName, declaringVersionCode);
11077 versionedLib.put(version, libEntry);
11081 private boolean removeSharedLibraryLPw(String name, int version) {
11082 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11083 if (versionedLib == null) {
11086 final int libIdx = versionedLib.indexOfKey(version);
11090 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11091 versionedLib.remove(version);
11092 if (versionedLib.size() <= 0) {
11093 mSharedLibraries.remove(name);
11094 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11095 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11096 .getPackageName());
11103 * Adds a scanned package to the system. When this method is finished, the package will
11104 * be available for query, resolution, etc...
11106 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11107 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11108 final String pkgName = pkg.packageName;
11109 if (mCustomResolverComponentName != null &&
11110 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11111 setUpCustomResolverActivity(pkg);
11114 if (pkg.packageName.equals("android")) {
11115 synchronized (mPackages) {
11116 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11117 // Set up information for our fall-back user intent resolution activity.
11118 mPlatformPackage = pkg;
11119 pkg.mVersionCode = mSdkVersion;
11120 mAndroidApplication = pkg.applicationInfo;
11121 if (!mResolverReplaced) {
11122 mResolveActivity.applicationInfo = mAndroidApplication;
11123 mResolveActivity.name = ResolverActivity.class.getName();
11124 mResolveActivity.packageName = mAndroidApplication.packageName;
11125 mResolveActivity.processName = "system:ui";
11126 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11127 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11128 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11129 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11130 mResolveActivity.exported = true;
11131 mResolveActivity.enabled = true;
11132 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11133 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11134 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11135 | ActivityInfo.CONFIG_SCREEN_LAYOUT
11136 | ActivityInfo.CONFIG_ORIENTATION
11137 | ActivityInfo.CONFIG_KEYBOARD
11138 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11139 mResolveInfo.activityInfo = mResolveActivity;
11140 mResolveInfo.priority = 0;
11141 mResolveInfo.preferredOrder = 0;
11142 mResolveInfo.match = 0;
11143 mResolveComponentName = new ComponentName(
11144 mAndroidApplication.packageName, mResolveActivity.name);
11150 ArrayList<PackageParser.Package> clientLibPkgs = null;
11152 synchronized (mPackages) {
11153 boolean hasStaticSharedLibs = false;
11155 // Any app can add new static shared libraries
11156 if (pkg.staticSharedLibName != null) {
11157 // Static shared libs don't allow renaming as they have synthetic package
11158 // names to allow install of multiple versions, so use name from manifest.
11159 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11160 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11161 pkg.manifestPackageName, pkg.mVersionCode)) {
11162 hasStaticSharedLibs = true;
11164 Slog.w(TAG, "Package " + pkg.packageName + " library "
11165 + pkg.staticSharedLibName + " already exists; skipping");
11167 // Static shared libs cannot be updated once installed since they
11168 // use synthetic package name which includes the version code, so
11169 // not need to update other packages's shared lib dependencies.
11172 if (!hasStaticSharedLibs
11173 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11174 // Only system apps can add new dynamic shared libraries.
11175 if (pkg.libraryNames != null) {
11176 for (int i = 0; i < pkg.libraryNames.size(); i++) {
11177 String name = pkg.libraryNames.get(i);
11178 boolean allowed = false;
11179 if (pkg.isUpdatedSystemApp()) {
11180 // New library entries can only be added through the
11181 // system image. This is important to get rid of a lot
11182 // of nasty edge cases: for example if we allowed a non-
11183 // system update of the app to add a library, then uninstalling
11184 // the update would make the library go away, and assumptions
11185 // we made such as through app install filtering would now
11186 // have allowed apps on the device which aren't compatible
11187 // with it. Better to just have the restriction here, be
11188 // conservative, and create many fewer cases that can negatively
11189 // impact the user experience.
11190 final PackageSetting sysPs = mSettings
11191 .getDisabledSystemPkgLPr(pkg.packageName);
11192 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11193 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11194 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11204 if (!addSharedLibraryLPw(null, pkg.packageName, name,
11205 SharedLibraryInfo.VERSION_UNDEFINED,
11206 SharedLibraryInfo.TYPE_DYNAMIC,
11207 pkg.packageName, pkg.mVersionCode)) {
11208 Slog.w(TAG, "Package " + pkg.packageName + " library "
11209 + name + " already exists; skipping");
11212 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11213 + name + " that is not declared on system image; skipping");
11217 if ((scanFlags & SCAN_BOOTING) == 0) {
11218 // If we are not booting, we need to update any applications
11219 // that are clients of our shared library. If we are booting,
11220 // this will all be done once the scan is complete.
11221 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11227 if ((scanFlags & SCAN_BOOTING) != 0) {
11228 // No apps can run during boot scan, so they don't need to be frozen
11229 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11230 // Caller asked to not kill app, so it's probably not frozen
11231 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11232 // Caller asked us to ignore frozen check for some reason; they
11233 // probably didn't know the package name
11235 // We're doing major surgery on this package, so it better be frozen
11236 // right now to keep it from launching
11237 checkPackageFrozen(pkgName);
11240 // Also need to kill any apps that are dependent on the library.
11241 if (clientLibPkgs != null) {
11242 for (int i=0; i<clientLibPkgs.size(); i++) {
11243 PackageParser.Package clientPkg = clientLibPkgs.get(i);
11244 killApplication(clientPkg.applicationInfo.packageName,
11245 clientPkg.applicationInfo.uid, "update lib");
11250 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11252 synchronized (mPackages) {
11253 // We don't expect installation to fail beyond this point
11255 // Add the new setting to mSettings
11256 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11257 // Add the new setting to mPackages
11258 mPackages.put(pkg.applicationInfo.packageName, pkg);
11259 // Make sure we don't accidentally delete its data.
11260 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11261 while (iter.hasNext()) {
11262 PackageCleanItem item = iter.next();
11263 if (pkgName.equals(item.packageName)) {
11268 // Add the package's KeySets to the global KeySetManagerService
11269 KeySetManagerService ksms = mSettings.mKeySetManagerService;
11270 ksms.addScannedPackageLPw(pkg);
11272 int N = pkg.providers.size();
11273 StringBuilder r = null;
11275 for (i=0; i<N; i++) {
11276 PackageParser.Provider p = pkg.providers.get(i);
11277 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11278 p.info.processName);
11279 mProviders.addProvider(p);
11280 p.syncable = p.info.isSyncable;
11281 if (p.info.authority != null) {
11282 String names[] = p.info.authority.split(";");
11283 p.info.authority = null;
11284 for (int j = 0; j < names.length; j++) {
11285 if (j == 1 && p.syncable) {
11286 // We only want the first authority for a provider to possibly be
11287 // syncable, so if we already added this provider using a different
11288 // authority clear the syncable flag. We copy the provider before
11289 // changing it because the mProviders object contains a reference
11290 // to a provider that we don't want to change.
11291 // Only do this for the second authority since the resulting provider
11292 // object can be the same for all future authorities for this provider.
11293 p = new PackageParser.Provider(p);
11294 p.syncable = false;
11296 if (!mProvidersByAuthority.containsKey(names[j])) {
11297 mProvidersByAuthority.put(names[j], p);
11298 if (p.info.authority == null) {
11299 p.info.authority = names[j];
11301 p.info.authority = p.info.authority + ";" + names[j];
11303 if (DEBUG_PACKAGE_SCANNING) {
11305 Log.d(TAG, "Registered content provider: " + names[j]
11306 + ", className = " + p.info.name + ", isSyncable = "
11307 + p.info.isSyncable);
11310 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11311 Slog.w(TAG, "Skipping provider name " + names[j] +
11312 " (in package " + pkg.applicationInfo.packageName +
11313 "): name already used by "
11314 + ((other != null && other.getComponentName() != null)
11315 ? other.getComponentName().getPackageName() : "?"));
11321 r = new StringBuilder(256);
11325 r.append(p.info.name);
11329 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
11332 N = pkg.services.size();
11334 for (i=0; i<N; i++) {
11335 PackageParser.Service s = pkg.services.get(i);
11336 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11337 s.info.processName);
11338 mServices.addService(s);
11341 r = new StringBuilder(256);
11345 r.append(s.info.name);
11349 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
11352 N = pkg.receivers.size();
11354 for (i=0; i<N; i++) {
11355 PackageParser.Activity a = pkg.receivers.get(i);
11356 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11357 a.info.processName);
11358 mReceivers.addActivity(a, "receiver");
11361 r = new StringBuilder(256);
11365 r.append(a.info.name);
11369 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
11372 N = pkg.activities.size();
11374 for (i=0; i<N; i++) {
11375 PackageParser.Activity a = pkg.activities.get(i);
11376 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11377 a.info.processName);
11378 mActivities.addActivity(a, "activity");
11381 r = new StringBuilder(256);
11385 r.append(a.info.name);
11389 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
11392 N = pkg.permissionGroups.size();
11394 for (i=0; i<N; i++) {
11395 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11396 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11397 final String curPackageName = cur == null ? null : cur.info.packageName;
11398 // Dont allow ephemeral apps to define new permission groups.
11399 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11400 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11401 + pg.info.packageName
11402 + " ignored: instant apps cannot define new permission groups.");
11405 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11406 if (cur == null || isPackageUpdate) {
11407 mPermissionGroups.put(pg.info.name, pg);
11410 r = new StringBuilder(256);
11414 if (isPackageUpdate) {
11417 r.append(pg.info.name);
11420 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11421 + pg.info.packageName + " ignored: original from "
11422 + cur.info.packageName);
11425 r = new StringBuilder(256);
11430 r.append(pg.info.name);
11435 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
11438 N = pkg.permissions.size();
11440 for (i=0; i<N; i++) {
11441 PackageParser.Permission p = pkg.permissions.get(i);
11443 // Dont allow ephemeral apps to define new permissions.
11444 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11445 Slog.w(TAG, "Permission " + p.info.name + " from package "
11446 + p.info.packageName
11447 + " ignored: instant apps cannot define new permissions.");
11451 // Assume by default that we did not install this permission into the system.
11452 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11454 // Now that permission groups have a special meaning, we ignore permission
11455 // groups for legacy apps to prevent unexpected behavior. In particular,
11456 // permissions for one app being granted to someone just because they happen
11457 // to be in a group defined by another app (before this had no implications).
11458 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11459 p.group = mPermissionGroups.get(p.info.group);
11460 // Warn for a permission in an unknown group.
11461 if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11462 Slog.i(TAG, "Permission " + p.info.name + " from package "
11463 + p.info.packageName + " in an unknown group " + p.info.group);
11467 ArrayMap<String, BasePermission> permissionMap =
11468 p.tree ? mSettings.mPermissionTrees
11469 : mSettings.mPermissions;
11470 BasePermission bp = permissionMap.get(p.info.name);
11472 // Allow system apps to redefine non-system permissions
11473 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11474 final boolean currentOwnerIsSystem = (bp.perm != null
11475 && isSystemApp(bp.perm.owner));
11476 if (isSystemApp(p.owner)) {
11477 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11478 // It's a built-in permission and no owner, take ownership now
11479 bp.packageSetting = pkgSetting;
11481 bp.uid = pkg.applicationInfo.uid;
11482 bp.sourcePackage = p.info.packageName;
11483 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11484 } else if (!currentOwnerIsSystem) {
11485 String msg = "New decl " + p.owner + " of permission "
11486 + p.info.name + " is system; overriding " + bp.sourcePackage;
11487 reportSettingsProblem(Log.WARN, msg);
11494 bp = new BasePermission(p.info.name, p.info.packageName,
11495 BasePermission.TYPE_NORMAL);
11496 permissionMap.put(p.info.name, bp);
11499 if (bp.perm == null) {
11500 if (bp.sourcePackage == null
11501 || bp.sourcePackage.equals(p.info.packageName)) {
11502 BasePermission tree = findPermissionTreeLP(p.info.name);
11504 || tree.sourcePackage.equals(p.info.packageName)) {
11505 bp.packageSetting = pkgSetting;
11507 bp.uid = pkg.applicationInfo.uid;
11508 bp.sourcePackage = p.info.packageName;
11509 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11512 r = new StringBuilder(256);
11516 r.append(p.info.name);
11519 Slog.w(TAG, "Permission " + p.info.name + " from package "
11520 + p.info.packageName + " ignored: base tree "
11521 + tree.name + " is from package "
11522 + tree.sourcePackage);
11525 Slog.w(TAG, "Permission " + p.info.name + " from package "
11526 + p.info.packageName + " ignored: original from "
11527 + bp.sourcePackage);
11529 } else if (chatty) {
11531 r = new StringBuilder(256);
11536 r.append(p.info.name);
11538 if (bp.perm == p) {
11539 bp.protectionLevel = p.info.protectionLevel;
11544 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
11547 N = pkg.instrumentation.size();
11549 for (i=0; i<N; i++) {
11550 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11551 a.info.packageName = pkg.applicationInfo.packageName;
11552 a.info.sourceDir = pkg.applicationInfo.sourceDir;
11553 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11554 a.info.splitNames = pkg.splitNames;
11555 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11556 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11557 a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11558 a.info.dataDir = pkg.applicationInfo.dataDir;
11559 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11560 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11561 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11562 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11563 mInstrumentation.put(a.getComponentName(), a);
11566 r = new StringBuilder(256);
11570 r.append(a.info.name);
11574 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
11577 if (pkg.protectedBroadcasts != null) {
11578 N = pkg.protectedBroadcasts.size();
11579 for (i=0; i<N; i++) {
11580 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11585 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11589 * Derive the ABI of a non-system package located at {@code scanFile}. This information
11590 * is derived purely on the basis of the contents of {@code scanFile} and
11591 * {@code cpuAbiOverride}.
11593 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11595 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11596 String cpuAbiOverride, boolean extractLibs,
11597 File appLib32InstallDir)
11598 throws PackageManagerException {
11599 // Give ourselves some initial paths; we'll come back for another
11600 // pass once we've determined ABI below.
11601 setNativeLibraryPaths(pkg, appLib32InstallDir);
11603 // We would never need to extract libs for forward-locked and external packages,
11604 // since the container service will do it for us. We shouldn't attempt to
11605 // extract libs from system app when it was not updated.
11606 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11607 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11608 extractLibs = false;
11611 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11612 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11614 NativeLibraryHelper.Handle handle = null;
11616 handle = NativeLibraryHelper.Handle.create(pkg);
11617 // TODO(multiArch): This can be null for apps that didn't go through the
11618 // usual installation process. We can calculate it again, like we
11619 // do during install time.
11621 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11623 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11625 // Null out the abis so that they can be recalculated.
11626 pkg.applicationInfo.primaryCpuAbi = null;
11627 pkg.applicationInfo.secondaryCpuAbi = null;
11628 if (isMultiArch(pkg.applicationInfo)) {
11629 // Warn if we've set an abiOverride for multi-lib packages..
11630 // By definition, we need to copy both 32 and 64 bit libraries for
11632 if (pkg.cpuAbiOverride != null
11633 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11634 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11637 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11638 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11639 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11641 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11642 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11643 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11644 useIsaSpecificSubdirs);
11646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11647 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11652 // Shared library native code should be in the APK zip aligned
11653 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11654 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11655 "Shared library native lib extraction not supported");
11658 maybeThrowExceptionForMultiArchCopy(
11659 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11661 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11663 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11664 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11665 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11666 useIsaSpecificSubdirs);
11668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11669 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11671 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11674 maybeThrowExceptionForMultiArchCopy(
11675 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11678 // Shared library native libs should be in the APK zip aligned
11679 if (extractLibs && pkg.isLibrary()) {
11680 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11681 "Shared library native lib extraction not supported");
11683 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11687 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11689 if (pkg.use32bitAbi) {
11690 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11691 pkg.applicationInfo.primaryCpuAbi = abi;
11693 pkg.applicationInfo.secondaryCpuAbi = abi;
11696 pkg.applicationInfo.primaryCpuAbi = abi;
11700 String[] abiList = (cpuAbiOverride != null) ?
11701 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11703 // Enable gross and lame hacks for apps that are built with old
11704 // SDK tools. We must scan their APKs for renderscript bitcode and
11705 // not launch them if it's present. Don't bother checking on devices
11706 // that don't have 64 bit support.
11707 boolean needsRenderScriptOverride = false;
11708 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11709 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11710 abiList = Build.SUPPORTED_32_BIT_ABIS;
11711 needsRenderScriptOverride = true;
11716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11717 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11718 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11721 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11723 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11725 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11726 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11727 "Error unpackaging native libs for app, errorCode=" + copyRet);
11730 if (copyRet >= 0) {
11731 // Shared libraries that have native libs must be multi-architecture
11732 if (pkg.isLibrary()) {
11733 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11734 "Shared library with native libs must be multiarch");
11736 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11737 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11738 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11739 } else if (needsRenderScriptOverride) {
11740 pkg.applicationInfo.primaryCpuAbi = abiList[0];
11743 } catch (IOException ioe) {
11744 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11746 IoUtils.closeQuietly(handle);
11749 // Now that we've calculated the ABIs and determined if it's an internal app,
11750 // we will go ahead and populate the nativeLibraryPath.
11751 setNativeLibraryPaths(pkg, appLib32InstallDir);
11755 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11756 * i.e, so that all packages can be run inside a single process if required.
11758 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11759 * this function will either try and make the ABI for all packages in {@code packagesForUser}
11760 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11761 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11762 * updating a package that belongs to a shared user.
11764 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11765 * adds unnecessary complexity.
11767 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11768 PackageParser.Package scannedPackage) {
11769 String requiredInstructionSet = null;
11770 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11771 requiredInstructionSet = VMRuntime.getInstructionSet(
11772 scannedPackage.applicationInfo.primaryCpuAbi);
11775 PackageSetting requirer = null;
11776 for (PackageSetting ps : packagesForUser) {
11777 // If packagesForUser contains scannedPackage, we skip it. This will happen
11778 // when scannedPackage is an update of an existing package. Without this check,
11779 // we will never be able to change the ABI of any package belonging to a shared
11780 // user, even if it's compatible with other packages.
11781 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11782 if (ps.primaryCpuAbiString == null) {
11786 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11787 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11788 // We have a mismatch between instruction sets (say arm vs arm64) warn about
11789 // this but there's not much we can do.
11790 String errorMessage = "Instruction set mismatch, "
11791 + ((requirer == null) ? "[caller]" : requirer)
11792 + " requires " + requiredInstructionSet + " whereas " + ps
11793 + " requires " + instructionSet;
11794 Slog.w(TAG, errorMessage);
11797 if (requiredInstructionSet == null) {
11798 requiredInstructionSet = instructionSet;
11804 if (requiredInstructionSet != null) {
11805 String adjustedAbi;
11806 if (requirer != null) {
11807 // requirer != null implies that either scannedPackage was null or that scannedPackage
11808 // did not require an ABI, in which case we have to adjust scannedPackage to match
11809 // the ABI of the set (which is the same as requirer's ABI)
11810 adjustedAbi = requirer.primaryCpuAbiString;
11811 if (scannedPackage != null) {
11812 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11815 // requirer == null implies that we're updating all ABIs in the set to
11816 // match scannedPackage.
11817 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
11820 for (PackageSetting ps : packagesForUser) {
11821 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11822 if (ps.primaryCpuAbiString != null) {
11826 ps.primaryCpuAbiString = adjustedAbi;
11827 if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11828 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11829 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11830 if (DEBUG_ABI_SELECTION) {
11831 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11833 + (requirer != null ? requirer.pkg : "null")
11834 + ", scannedPackage="
11835 + (scannedPackage != null ? scannedPackage : "null")
11839 mInstaller.rmdex(ps.codePathString,
11840 getDexCodeInstructionSet(getPreferredInstructionSet()));
11841 } catch (InstallerException ignored) {
11849 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11850 synchronized (mPackages) {
11851 mResolverReplaced = true;
11852 // Set up information for custom user intent resolution activity.
11853 mResolveActivity.applicationInfo = pkg.applicationInfo;
11854 mResolveActivity.name = mCustomResolverComponentName.getClassName();
11855 mResolveActivity.packageName = pkg.applicationInfo.packageName;
11856 mResolveActivity.processName = pkg.applicationInfo.packageName;
11857 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11858 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11859 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11860 mResolveActivity.theme = 0;
11861 mResolveActivity.exported = true;
11862 mResolveActivity.enabled = true;
11863 mResolveInfo.activityInfo = mResolveActivity;
11864 mResolveInfo.priority = 0;
11865 mResolveInfo.preferredOrder = 0;
11866 mResolveInfo.match = 0;
11867 mResolveComponentName = mCustomResolverComponentName;
11868 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11869 mResolveComponentName);
11873 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11874 if (installerActivity == null) {
11875 if (DEBUG_EPHEMERAL) {
11876 Slog.d(TAG, "Clear ephemeral installer activity");
11878 mInstantAppInstallerActivity = null;
11882 if (DEBUG_EPHEMERAL) {
11883 Slog.d(TAG, "Set ephemeral installer activity: "
11884 + installerActivity.getComponentName());
11886 // Set up information for ephemeral installer activity
11887 mInstantAppInstallerActivity = installerActivity;
11888 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11889 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11890 mInstantAppInstallerActivity.exported = true;
11891 mInstantAppInstallerActivity.enabled = true;
11892 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11893 mInstantAppInstallerInfo.priority = 0;
11894 mInstantAppInstallerInfo.preferredOrder = 1;
11895 mInstantAppInstallerInfo.isDefault = true;
11896 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11897 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11900 private static String calculateBundledApkRoot(final String codePathString) {
11901 final File codePath = new File(codePathString);
11902 final File codeRoot;
11903 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11904 codeRoot = Environment.getRootDirectory();
11905 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11906 codeRoot = Environment.getOemDirectory();
11907 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11908 codeRoot = Environment.getVendorDirectory();
11910 // Unrecognized code path; take its top real segment as the apk root:
11911 // e.g. /something/app/blah.apk => /something
11913 File f = codePath.getCanonicalFile();
11914 File parent = f.getParentFile(); // non-null because codePath is a file
11916 while ((tmp = parent.getParentFile()) != null) {
11921 Slog.w(TAG, "Unrecognized code path "
11922 + codePath + " - using " + codeRoot);
11923 } catch (IOException e) {
11924 // Can't canonicalize the code path -- shenanigans?
11925 Slog.w(TAG, "Can't canonicalize code path " + codePath);
11926 return Environment.getRootDirectory().getPath();
11929 return codeRoot.getPath();
11933 * Derive and set the location of native libraries for the given package,
11934 * which varies depending on where and how the package was installed.
11936 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11937 final ApplicationInfo info = pkg.applicationInfo;
11938 final String codePath = pkg.codePath;
11939 final File codeFile = new File(codePath);
11940 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11941 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11943 info.nativeLibraryRootDir = null;
11944 info.nativeLibraryRootRequiresIsa = false;
11945 info.nativeLibraryDir = null;
11946 info.secondaryNativeLibraryDir = null;
11948 if (isApkFile(codeFile)) {
11949 // Monolithic install
11951 // If "/system/lib64/apkname" exists, assume that is the per-package
11952 // native library directory to use; otherwise use "/system/lib/apkname".
11953 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11954 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11955 getPrimaryInstructionSet(info));
11957 // This is a bundled system app so choose the path based on the ABI.
11958 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11959 // is just the default path.
11960 final String apkName = deriveCodePathName(codePath);
11961 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11962 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11963 apkName).getAbsolutePath();
11965 if (info.secondaryCpuAbi != null) {
11966 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11967 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11968 secondaryLibDir, apkName).getAbsolutePath();
11970 } else if (asecApp) {
11971 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11972 .getAbsolutePath();
11974 final String apkName = deriveCodePathName(codePath);
11975 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11976 .getAbsolutePath();
11979 info.nativeLibraryRootRequiresIsa = false;
11980 info.nativeLibraryDir = info.nativeLibraryRootDir;
11983 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11984 info.nativeLibraryRootRequiresIsa = true;
11986 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11987 getPrimaryInstructionSet(info)).getAbsolutePath();
11989 if (info.secondaryCpuAbi != null) {
11990 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11991 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11997 * Calculate the abis and roots for a bundled app. These can uniquely
11998 * be determined from the contents of the system partition, i.e whether
11999 * it contains 64 or 32 bit shared libraries etc. We do not validate any
12000 * of this information, and instead assume that the system was built
12003 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12004 PackageSetting pkgSetting) {
12005 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12007 // If "/system/lib64/apkname" exists, assume that is the per-package
12008 // native library directory to use; otherwise use "/system/lib/apkname".
12009 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12010 setBundledAppAbi(pkg, apkRoot, apkName);
12011 // pkgSetting might be null during rescan following uninstall of updates
12012 // to a bundled app, so accommodate that possibility. The settings in
12013 // that case will be established later from the parsed package.
12015 // If the settings aren't null, sync them up with what we've just derived.
12016 // note that apkRoot isn't stored in the package settings.
12017 if (pkgSetting != null) {
12018 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12019 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12024 * Deduces the ABI of a bundled app and sets the relevant fields on the
12025 * parsed pkg object.
12027 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12028 * under which system libraries are installed.
12029 * @param apkName the name of the installed package.
12031 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12032 final File codeFile = new File(pkg.codePath);
12034 final boolean has64BitLibs;
12035 final boolean has32BitLibs;
12036 if (isApkFile(codeFile)) {
12037 // Monolithic install
12038 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12039 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12042 final File rootDir = new File(codeFile, LIB_DIR_NAME);
12043 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12044 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12045 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12046 has64BitLibs = (new File(rootDir, isa)).exists();
12048 has64BitLibs = false;
12050 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12051 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12052 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12053 has32BitLibs = (new File(rootDir, isa)).exists();
12055 has32BitLibs = false;
12059 if (has64BitLibs && !has32BitLibs) {
12060 // The package has 64 bit libs, but not 32 bit libs. Its primary
12061 // ABI should be 64 bit. We can safely assume here that the bundled
12062 // native libraries correspond to the most preferred ABI in the list.
12064 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12065 pkg.applicationInfo.secondaryCpuAbi = null;
12066 } else if (has32BitLibs && !has64BitLibs) {
12067 // The package has 32 bit libs but not 64 bit libs. Its primary
12068 // ABI should be 32 bit.
12070 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12071 pkg.applicationInfo.secondaryCpuAbi = null;
12072 } else if (has32BitLibs && has64BitLibs) {
12073 // The application has both 64 and 32 bit bundled libraries. We check
12074 // here that the app declares multiArch support, and warn if it doesn't.
12076 // We will be lenient here and record both ABIs. The primary will be the
12077 // ABI that's higher on the list, i.e, a device that's configured to prefer
12078 // 64 bit apps will see a 64 bit primary ABI,
12080 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12081 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12084 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12085 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12086 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12088 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12089 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12092 pkg.applicationInfo.primaryCpuAbi = null;
12093 pkg.applicationInfo.secondaryCpuAbi = null;
12097 private void killApplication(String pkgName, int appId, String reason) {
12098 killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12101 private void killApplication(String pkgName, int appId, int userId, String reason) {
12102 // Request the ActivityManager to kill the process(only for existing packages)
12103 // so that we do not end up in a confused state while the user is still using the older
12104 // version of the application while the new one gets installed.
12105 final long token = Binder.clearCallingIdentity();
12107 IActivityManager am = ActivityManager.getService();
12110 am.killApplication(pkgName, appId, userId, reason);
12111 } catch (RemoteException e) {
12115 Binder.restoreCallingIdentity(token);
12119 private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12120 // Remove the parent package setting
12121 PackageSetting ps = (PackageSetting) pkg.mExtras;
12123 removePackageLI(ps, chatty);
12125 // Remove the child package setting
12126 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12127 for (int i = 0; i < childCount; i++) {
12128 PackageParser.Package childPkg = pkg.childPackages.get(i);
12129 ps = (PackageSetting) childPkg.mExtras;
12131 removePackageLI(ps, chatty);
12136 void removePackageLI(PackageSetting ps, boolean chatty) {
12137 if (DEBUG_INSTALL) {
12139 Log.d(TAG, "Removing package " + ps.name);
12143 synchronized (mPackages) {
12144 mPackages.remove(ps.name);
12145 final PackageParser.Package pkg = ps.pkg;
12147 cleanPackageDataStructuresLILPw(pkg, chatty);
12152 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12153 if (DEBUG_INSTALL) {
12155 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12159 synchronized (mPackages) {
12160 // Remove the parent package
12161 mPackages.remove(pkg.applicationInfo.packageName);
12162 cleanPackageDataStructuresLILPw(pkg, chatty);
12164 // Remove the child packages
12165 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12166 for (int i = 0; i < childCount; i++) {
12167 PackageParser.Package childPkg = pkg.childPackages.get(i);
12168 mPackages.remove(childPkg.applicationInfo.packageName);
12169 cleanPackageDataStructuresLILPw(childPkg, chatty);
12174 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12175 int N = pkg.providers.size();
12176 StringBuilder r = null;
12178 for (i=0; i<N; i++) {
12179 PackageParser.Provider p = pkg.providers.get(i);
12180 mProviders.removeProvider(p);
12181 if (p.info.authority == null) {
12183 /* There was another ContentProvider with this authority when
12184 * this app was installed so this authority is null,
12185 * Ignore it as we don't have to unregister the provider.
12189 String names[] = p.info.authority.split(";");
12190 for (int j = 0; j < names.length; j++) {
12191 if (mProvidersByAuthority.get(names[j]) == p) {
12192 mProvidersByAuthority.remove(names[j]);
12193 if (DEBUG_REMOVE) {
12195 Log.d(TAG, "Unregistered content provider: " + names[j]
12196 + ", className = " + p.info.name + ", isSyncable = "
12197 + p.info.isSyncable);
12201 if (DEBUG_REMOVE && chatty) {
12203 r = new StringBuilder(256);
12207 r.append(p.info.name);
12211 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
12214 N = pkg.services.size();
12216 for (i=0; i<N; i++) {
12217 PackageParser.Service s = pkg.services.get(i);
12218 mServices.removeService(s);
12221 r = new StringBuilder(256);
12225 r.append(s.info.name);
12229 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
12232 N = pkg.receivers.size();
12234 for (i=0; i<N; i++) {
12235 PackageParser.Activity a = pkg.receivers.get(i);
12236 mReceivers.removeActivity(a, "receiver");
12237 if (DEBUG_REMOVE && chatty) {
12239 r = new StringBuilder(256);
12243 r.append(a.info.name);
12247 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
12250 N = pkg.activities.size();
12252 for (i=0; i<N; i++) {
12253 PackageParser.Activity a = pkg.activities.get(i);
12254 mActivities.removeActivity(a, "activity");
12255 if (DEBUG_REMOVE && chatty) {
12257 r = new StringBuilder(256);
12261 r.append(a.info.name);
12265 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
12268 N = pkg.permissions.size();
12270 for (i=0; i<N; i++) {
12271 PackageParser.Permission p = pkg.permissions.get(i);
12272 BasePermission bp = mSettings.mPermissions.get(p.info.name);
12274 bp = mSettings.mPermissionTrees.get(p.info.name);
12276 if (bp != null && bp.perm == p) {
12278 if (DEBUG_REMOVE && chatty) {
12280 r = new StringBuilder(256);
12284 r.append(p.info.name);
12287 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12288 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12289 if (appOpPkgs != null) {
12290 appOpPkgs.remove(pkg.packageName);
12295 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
12298 N = pkg.requestedPermissions.size();
12300 for (i=0; i<N; i++) {
12301 String perm = pkg.requestedPermissions.get(i);
12302 BasePermission bp = mSettings.mPermissions.get(perm);
12303 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12304 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12305 if (appOpPkgs != null) {
12306 appOpPkgs.remove(pkg.packageName);
12307 if (appOpPkgs.isEmpty()) {
12308 mAppOpPermissionPackages.remove(perm);
12314 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
12317 N = pkg.instrumentation.size();
12319 for (i=0; i<N; i++) {
12320 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12321 mInstrumentation.remove(a.getComponentName());
12322 if (DEBUG_REMOVE && chatty) {
12324 r = new StringBuilder(256);
12328 r.append(a.info.name);
12332 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
12336 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12337 // Only system apps can hold shared libraries.
12338 if (pkg.libraryNames != null) {
12339 for (i = 0; i < pkg.libraryNames.size(); i++) {
12340 String name = pkg.libraryNames.get(i);
12341 if (removeSharedLibraryLPw(name, 0)) {
12342 if (DEBUG_REMOVE && chatty) {
12344 r = new StringBuilder(256);
12357 // Any package can hold static shared libraries.
12358 if (pkg.staticSharedLibName != null) {
12359 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12360 if (DEBUG_REMOVE && chatty) {
12362 r = new StringBuilder(256);
12366 r.append(pkg.staticSharedLibName);
12372 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
12376 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12377 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12378 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12385 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12386 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12387 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12389 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12390 // Update the parent permissions
12391 updatePermissionsLPw(pkg.packageName, pkg, flags);
12392 // Update the child permissions
12393 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12394 for (int i = 0; i < childCount; i++) {
12395 PackageParser.Package childPkg = pkg.childPackages.get(i);
12396 updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12400 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12402 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12403 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12406 private void updatePermissionsLPw(String changingPkg,
12407 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12408 // Make sure there are no dangling permission trees.
12409 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12410 while (it.hasNext()) {
12411 final BasePermission bp = it.next();
12412 if (bp.packageSetting == null) {
12413 // We may not yet have parsed the package, so just see if
12414 // we still know about its settings.
12415 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12417 if (bp.packageSetting == null) {
12418 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12419 + " from package " + bp.sourcePackage);
12421 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12422 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12423 Slog.i(TAG, "Removing old permission tree: " + bp.name
12424 + " from package " + bp.sourcePackage);
12425 flags |= UPDATE_PERMISSIONS_ALL;
12431 // Make sure all dynamic permissions have been assigned to a package,
12432 // and make sure there are no dangling permissions.
12433 it = mSettings.mPermissions.values().iterator();
12434 while (it.hasNext()) {
12435 final BasePermission bp = it.next();
12436 if (bp.type == BasePermission.TYPE_DYNAMIC) {
12437 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12438 + bp.name + " pkg=" + bp.sourcePackage
12439 + " info=" + bp.pendingInfo);
12440 if (bp.packageSetting == null && bp.pendingInfo != null) {
12441 final BasePermission tree = findPermissionTreeLP(bp.name);
12442 if (tree != null && tree.perm != null) {
12443 bp.packageSetting = tree.packageSetting;
12444 bp.perm = new PackageParser.Permission(tree.perm.owner,
12445 new PermissionInfo(bp.pendingInfo));
12446 bp.perm.info.packageName = tree.perm.info.packageName;
12447 bp.perm.info.name = bp.name;
12452 if (bp.packageSetting == null) {
12453 // We may not yet have parsed the package, so just see if
12454 // we still know about its settings.
12455 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12457 if (bp.packageSetting == null) {
12458 Slog.w(TAG, "Removing dangling permission: " + bp.name
12459 + " from package " + bp.sourcePackage);
12461 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12462 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12463 Slog.i(TAG, "Removing old permission: " + bp.name
12464 + " from package " + bp.sourcePackage);
12465 flags |= UPDATE_PERMISSIONS_ALL;
12471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12472 // Now update the permissions for all packages, in particular
12473 // replace the granted permissions of the system packages.
12474 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12475 for (PackageParser.Package pkg : mPackages.values()) {
12476 if (pkg != pkgInfo) {
12477 // Only replace for packages on requested volume
12478 final String volumeUuid = getVolumeUuidForPackage(pkg);
12479 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12480 && Objects.equals(replaceVolumeUuid, volumeUuid);
12481 grantPermissionsLPw(pkg, replace, changingPkg);
12486 if (pkgInfo != null) {
12487 // Only replace for packages on requested volume
12488 final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12489 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12490 && Objects.equals(replaceVolumeUuid, volumeUuid);
12491 grantPermissionsLPw(pkgInfo, replace, changingPkg);
12493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12496 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12497 String packageOfInterest) {
12498 // IMPORTANT: There are two types of permissions: install and runtime.
12499 // Install time permissions are granted when the app is installed to
12500 // all device users and users added in the future. Runtime permissions
12501 // are granted at runtime explicitly to specific users. Normal and signature
12502 // protected permissions are install time permissions. Dangerous permissions
12503 // are install permissions if the app's target SDK is Lollipop MR1 or older,
12504 // otherwise they are runtime permissions. This function does not manage
12505 // runtime permissions except for the case an app targeting Lollipop MR1
12506 // being upgraded to target a newer SDK, in which case dangerous permissions
12507 // are transformed from install time to runtime ones.
12509 final PackageSetting ps = (PackageSetting) pkg.mExtras;
12514 PermissionsState permissionsState = ps.getPermissionsState();
12515 PermissionsState origPermissions = permissionsState;
12517 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12519 boolean runtimePermissionsRevoked = false;
12520 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12522 boolean changedInstallPermission = false;
12525 ps.installPermissionsFixed = false;
12526 if (!ps.isSharedUser()) {
12527 origPermissions = new PermissionsState(permissionsState);
12528 permissionsState.reset();
12530 // We need to know only about runtime permission changes since the
12531 // calling code always writes the install permissions state but
12532 // the runtime ones are written only if changed. The only cases of
12533 // changed runtime permissions here are promotion of an install to
12534 // runtime and revocation of a runtime from a shared user.
12535 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12536 ps.sharedUser, UserManagerService.getInstance().getUserIds());
12537 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12538 runtimePermissionsRevoked = true;
12543 permissionsState.setGlobalGids(mGlobalGids);
12545 final int N = pkg.requestedPermissions.size();
12546 for (int i=0; i<N; i++) {
12547 final String name = pkg.requestedPermissions.get(i);
12548 final BasePermission bp = mSettings.mPermissions.get(name);
12549 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12550 >= Build.VERSION_CODES.M;
12552 if (DEBUG_INSTALL) {
12553 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12556 if (bp == null || bp.packageSetting == null) {
12557 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12558 if (DEBUG_PERMISSIONS) {
12559 Slog.i(TAG, "Unknown permission " + name
12560 + " in package " + pkg.packageName);
12567 // Limit ephemeral apps to ephemeral allowed permissions.
12568 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12569 if (DEBUG_PERMISSIONS) {
12570 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12571 + pkg.packageName);
12576 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12577 if (DEBUG_PERMISSIONS) {
12578 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12579 + pkg.packageName);
12584 final String perm = bp.name;
12585 boolean allowedSig = false;
12586 int grant = GRANT_DENIED;
12588 // Keep track of app op permissions.
12589 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12590 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12591 if (pkgs == null) {
12592 pkgs = new ArraySet<>();
12593 mAppOpPermissionPackages.put(bp.name, pkgs);
12595 pkgs.add(pkg.packageName);
12598 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12600 case PermissionInfo.PROTECTION_NORMAL: {
12601 // For all apps normal permissions are install time ones.
12602 grant = GRANT_INSTALL;
12605 case PermissionInfo.PROTECTION_DANGEROUS: {
12606 // If a permission review is required for legacy apps we represent
12607 // their permissions as always granted runtime ones since we need
12608 // to keep the review required permission flag per user while an
12609 // install permission's state is shared across all users.
12610 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12611 // For legacy apps dangerous permissions are install time ones.
12612 grant = GRANT_INSTALL;
12613 } else if (origPermissions.hasInstallPermission(bp.name)) {
12614 // For legacy apps that became modern, install becomes runtime.
12615 grant = GRANT_UPGRADE;
12616 } else if (mPromoteSystemApps
12618 && mExistingSystemPackages.contains(ps.name)) {
12619 // For legacy system apps, install becomes runtime.
12620 // We cannot check hasInstallPermission() for system apps since those
12621 // permissions were granted implicitly and not persisted pre-M.
12622 grant = GRANT_UPGRADE;
12624 // For modern apps keep runtime permissions unchanged.
12625 grant = GRANT_RUNTIME;
12629 case PermissionInfo.PROTECTION_SIGNATURE: {
12630 // For all apps signature permissions are install time ones.
12631 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12633 grant = GRANT_INSTALL;
12638 if (DEBUG_PERMISSIONS) {
12639 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12642 if (grant != GRANT_DENIED) {
12643 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12644 // If this is an existing, non-system package, then
12645 // we can't add any new permissions to it.
12646 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12647 // Except... if this is a permission that was added
12648 // to the platform (note: need to only do this when
12649 // updating the platform).
12650 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12651 grant = GRANT_DENIED;
12657 case GRANT_INSTALL: {
12658 // Revoke this as runtime permission to handle the case of
12659 // a runtime permission being downgraded to an install one.
12660 // Also in permission review mode we keep dangerous permissions
12662 for (int userId : UserManagerService.getInstance().getUserIds()) {
12663 if (origPermissions.getRuntimePermissionState(
12664 bp.name, userId) != null) {
12665 // Revoke the runtime permission and clear the flags.
12666 origPermissions.revokeRuntimePermission(bp, userId);
12667 origPermissions.updatePermissionFlags(bp, userId,
12668 PackageManager.MASK_PERMISSION_FLAGS, 0);
12669 // If we revoked a permission permission, we have to write.
12670 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12671 changedRuntimePermissionUserIds, userId);
12674 // Grant an install permission.
12675 if (permissionsState.grantInstallPermission(bp) !=
12676 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12677 changedInstallPermission = true;
12681 case GRANT_RUNTIME: {
12682 // Grant previously granted runtime permissions.
12683 for (int userId : UserManagerService.getInstance().getUserIds()) {
12684 PermissionState permissionState = origPermissions
12685 .getRuntimePermissionState(bp.name, userId);
12686 int flags = permissionState != null
12687 ? permissionState.getFlags() : 0;
12688 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12689 // Don't propagate the permission in a permission review mode if
12690 // the former was revoked, i.e. marked to not propagate on upgrade.
12691 // Note that in a permission review mode install permissions are
12692 // represented as constantly granted runtime ones since we need to
12693 // keep a per user state associated with the permission. Also the
12694 // revoke on upgrade flag is no longer applicable and is reset.
12695 final boolean revokeOnUpgrade = (flags & PackageManager
12696 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12697 if (revokeOnUpgrade) {
12698 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12699 // Since we changed the flags, we have to write.
12700 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12701 changedRuntimePermissionUserIds, userId);
12703 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12704 if (permissionsState.grantRuntimePermission(bp, userId) ==
12705 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12706 // If we cannot put the permission as it was,
12707 // we have to write.
12708 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12709 changedRuntimePermissionUserIds, userId);
12713 // If the app supports runtime permissions no need for a review.
12714 if (mPermissionReviewRequired
12715 && appSupportsRuntimePermissions
12716 && (flags & PackageManager
12717 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12718 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12719 // Since we changed the flags, we have to write.
12720 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12721 changedRuntimePermissionUserIds, userId);
12723 } else if (mPermissionReviewRequired
12724 && !appSupportsRuntimePermissions) {
12725 // For legacy apps that need a permission review, every new
12726 // runtime permission is granted but it is pending a review.
12727 // We also need to review only platform defined runtime
12728 // permissions as these are the only ones the platform knows
12729 // how to disable the API to simulate revocation as legacy
12730 // apps don't expect to run with revoked permissions.
12731 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12732 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12733 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12734 // We changed the flags, hence have to write.
12735 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12736 changedRuntimePermissionUserIds, userId);
12739 if (permissionsState.grantRuntimePermission(bp, userId)
12740 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12741 // We changed the permission, hence have to write.
12742 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12743 changedRuntimePermissionUserIds, userId);
12746 // Propagate the permission flags.
12747 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12751 case GRANT_UPGRADE: {
12752 // Grant runtime permissions for a previously held install permission.
12753 PermissionState permissionState = origPermissions
12754 .getInstallPermissionState(bp.name);
12755 final int flags = permissionState != null ? permissionState.getFlags() : 0;
12757 if (origPermissions.revokeInstallPermission(bp)
12758 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12759 // We will be transferring the permission flags, so clear them.
12760 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12761 PackageManager.MASK_PERMISSION_FLAGS, 0);
12762 changedInstallPermission = true;
12765 // If the permission is not to be promoted to runtime we ignore it and
12766 // also its other flags as they are not applicable to install permissions.
12767 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12768 for (int userId : currentUserIds) {
12769 if (permissionsState.grantRuntimePermission(bp, userId) !=
12770 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12771 // Transfer the permission flags.
12772 permissionsState.updatePermissionFlags(bp, userId,
12774 // If we granted the permission, we have to write.
12775 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12776 changedRuntimePermissionUserIds, userId);
12783 if (packageOfInterest == null
12784 || packageOfInterest.equals(pkg.packageName)) {
12785 if (DEBUG_PERMISSIONS) {
12786 Slog.i(TAG, "Not granting permission " + perm
12787 + " to package " + pkg.packageName
12788 + " because it was previously installed without");
12794 if (permissionsState.revokeInstallPermission(bp) !=
12795 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12796 // Also drop the permission flags.
12797 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12798 PackageManager.MASK_PERMISSION_FLAGS, 0);
12799 changedInstallPermission = true;
12800 Slog.i(TAG, "Un-granting permission " + perm
12801 + " from package " + pkg.packageName
12802 + " (protectionLevel=" + bp.protectionLevel
12803 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12805 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12806 // Don't print warning for app op permissions, since it is fine for them
12807 // not to be granted, there is a UI for the user to decide.
12808 if (DEBUG_PERMISSIONS
12809 && (packageOfInterest == null
12810 || packageOfInterest.equals(pkg.packageName))) {
12811 Slog.i(TAG, "Not granting permission " + perm
12812 + " to package " + pkg.packageName
12813 + " (protectionLevel=" + bp.protectionLevel
12814 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12821 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12822 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12823 // This is the first that we have heard about this package, so the
12824 // permissions we have now selected are fixed until explicitly
12826 ps.installPermissionsFixed = true;
12829 // Persist the runtime permissions state for users with changes. If permissions
12830 // were revoked because no app in the shared user declares them we have to
12831 // write synchronously to avoid losing runtime permissions state.
12832 for (int userId : changedRuntimePermissionUserIds) {
12833 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12837 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12838 boolean allowed = false;
12839 final int NP = PackageParser.NEW_PERMISSIONS.length;
12840 for (int ip=0; ip<NP; ip++) {
12841 final PackageParser.NewPermissionInfo npi
12842 = PackageParser.NEW_PERMISSIONS[ip];
12843 if (npi.name.equals(perm)
12844 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12846 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12847 + pkg.packageName);
12854 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12855 BasePermission bp, PermissionsState origPermissions) {
12856 boolean privilegedPermission = (bp.protectionLevel
12857 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12858 boolean privappPermissionsDisable =
12859 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12860 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12861 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12862 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12863 && !platformPackage && platformPermission) {
12864 ArraySet<String> wlPermissions = SystemConfig.getInstance()
12865 .getPrivAppPermissions(pkg.packageName);
12866 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12867 if (!whitelisted) {
12868 Slog.w(TAG, "Privileged permission " + perm + " for package "
12869 + pkg.packageName + " - not in privapp-permissions whitelist");
12870 // Only report violations for apps on system image
12871 if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12872 if (mPrivappPermissionsViolations == null) {
12873 mPrivappPermissionsViolations = new ArraySet<>();
12875 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12877 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12882 boolean allowed = (compareSignatures(
12883 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12884 == PackageManager.SIGNATURE_MATCH)
12885 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12886 == PackageManager.SIGNATURE_MATCH);
12887 if (!allowed && privilegedPermission) {
12888 if (isSystemApp(pkg)) {
12889 // For updated system applications, a system permission
12890 // is granted only if it had been defined by the original application.
12891 if (pkg.isUpdatedSystemApp()) {
12892 final PackageSetting sysPs = mSettings
12893 .getDisabledSystemPkgLPr(pkg.packageName);
12894 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12895 // If the original was granted this permission, we take
12896 // that grant decision as read and propagate it to the
12898 if (sysPs.isPrivileged()) {
12902 // The system apk may have been updated with an older
12903 // version of the one on the data partition, but which
12904 // granted a new system permission that it didn't have
12905 // before. In this case we do want to allow the app to
12906 // now get the new permission if the ancestral apk is
12907 // privileged to get it.
12908 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12909 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12910 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12916 // Also if a privileged parent package on the system image or any of
12917 // its children requested a privileged permission, the updated child
12918 // packages can also get the permission.
12919 if (pkg.parentPackage != null) {
12920 final PackageSetting disabledSysParentPs = mSettings
12921 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12922 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12923 && disabledSysParentPs.isPrivileged()) {
12924 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12926 } else if (disabledSysParentPs.pkg.childPackages != null) {
12927 final int count = disabledSysParentPs.pkg.childPackages.size();
12928 for (int i = 0; i < count; i++) {
12929 PackageParser.Package disabledSysChildPkg =
12930 disabledSysParentPs.pkg.childPackages.get(i);
12931 if (isPackageRequestingPermission(disabledSysChildPkg,
12942 allowed = isPrivilegedApp(pkg);
12947 if (!allowed && (bp.protectionLevel
12948 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12949 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12950 // If this was a previously normal/dangerous permission that got moved
12951 // to a system permission as part of the runtime permission redesign, then
12952 // we still want to blindly grant it to old apps.
12955 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12956 && pkg.packageName.equals(mRequiredInstallerPackage)) {
12957 // If this permission is to be granted to the system installer and
12958 // this app is an installer, then it gets the permission.
12961 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12962 && pkg.packageName.equals(mRequiredVerifierPackage)) {
12963 // If this permission is to be granted to the system verifier and
12964 // this app is a verifier, then it gets the permission.
12967 if (!allowed && (bp.protectionLevel
12968 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12969 && isSystemApp(pkg)) {
12970 // Any pre-installed system app is allowed to get this permission.
12973 if (!allowed && (bp.protectionLevel
12974 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12975 // For development permissions, a development permission
12976 // is granted only if it was already granted.
12977 allowed = origPermissions.hasInstallPermission(perm);
12979 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12980 && pkg.packageName.equals(mSetupWizardPackage)) {
12981 // If this permission is to be granted to the system setup wizard and
12982 // this app is a setup wizard, then it gets the permission.
12989 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12990 final int permCount = pkg.requestedPermissions.size();
12991 for (int j = 0; j < permCount; j++) {
12992 String requestedPermission = pkg.requestedPermissions.get(j);
12993 if (permission.equals(requestedPermission)) {
13000 final class ActivityIntentResolver
13001 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13002 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13003 boolean defaultOnly, int userId) {
13004 if (!sUserManager.exists(userId)) return null;
13005 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13006 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13009 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13011 if (!sUserManager.exists(userId)) return null;
13013 return super.queryIntent(intent, resolvedType,
13014 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13018 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13019 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13020 if (!sUserManager.exists(userId)) return null;
13021 if (packageActivities == null) {
13025 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13026 final int N = packageActivities.size();
13027 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13028 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13030 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13031 for (int i = 0; i < N; ++i) {
13032 intentFilters = packageActivities.get(i).intents;
13033 if (intentFilters != null && intentFilters.size() > 0) {
13034 PackageParser.ActivityIntentInfo[] array =
13035 new PackageParser.ActivityIntentInfo[intentFilters.size()];
13036 intentFilters.toArray(array);
13037 listCut.add(array);
13040 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13044 * Finds a privileged activity that matches the specified activity names.
13046 private PackageParser.Activity findMatchingActivity(
13047 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13048 for (PackageParser.Activity sysActivity : activityList) {
13049 if (sysActivity.info.name.equals(activityInfo.name)) {
13050 return sysActivity;
13052 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13053 return sysActivity;
13055 if (sysActivity.info.targetActivity != null) {
13056 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13057 return sysActivity;
13059 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13060 return sysActivity;
13067 public class IterGenerator<E> {
13068 public Iterator<E> generate(ActivityIntentInfo info) {
13073 public class ActionIterGenerator extends IterGenerator<String> {
13075 public Iterator<String> generate(ActivityIntentInfo info) {
13076 return info.actionsIterator();
13080 public class CategoriesIterGenerator extends IterGenerator<String> {
13082 public Iterator<String> generate(ActivityIntentInfo info) {
13083 return info.categoriesIterator();
13087 public class SchemesIterGenerator extends IterGenerator<String> {
13089 public Iterator<String> generate(ActivityIntentInfo info) {
13090 return info.schemesIterator();
13094 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13096 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13097 return info.authoritiesIterator();
13102 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13103 * MODIFIED. Do not pass in a list that should not be changed.
13105 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13106 IterGenerator<T> generator, Iterator<T> searchIterator) {
13107 // loop through the set of actions; every one must be found in the intent filter
13108 while (searchIterator.hasNext()) {
13109 // we must have at least one filter in the list to consider a match
13110 if (intentList.size() == 0) {
13114 final T searchAction = searchIterator.next();
13116 // loop through the set of intent filters
13117 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13118 while (intentIter.hasNext()) {
13119 final ActivityIntentInfo intentInfo = intentIter.next();
13120 boolean selectionFound = false;
13122 // loop through the intent filter's selection criteria; at least one
13123 // of them must match the searched criteria
13124 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13125 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13126 final T intentSelection = intentSelectionIter.next();
13127 if (intentSelection != null && intentSelection.equals(searchAction)) {
13128 selectionFound = true;
13133 // the selection criteria wasn't found in this filter's set; this filter
13134 // is not a potential match
13135 if (!selectionFound) {
13136 intentIter.remove();
13142 private boolean isProtectedAction(ActivityIntentInfo filter) {
13143 final Iterator<String> actionsIter = filter.actionsIterator();
13144 while (actionsIter != null && actionsIter.hasNext()) {
13145 final String filterAction = actionsIter.next();
13146 if (PROTECTED_ACTIONS.contains(filterAction)) {
13154 * Adjusts the priority of the given intent filter according to policy.
13157 * <li>The priority for non privileged applications is capped to '0'</li>
13158 * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13159 * <li>The priority for unbundled updates to privileged applications is capped to the
13160 * priority defined on the system partition</li>
13163 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13164 * allowed to obtain any priority on any action.
13166 private void adjustPriority(
13167 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13168 // nothing to do; priority is fine as-is
13169 if (intent.getPriority() <= 0) {
13173 final ActivityInfo activityInfo = intent.activity.info;
13174 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13176 final boolean privilegedApp =
13177 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13178 if (!privilegedApp) {
13179 // non-privileged applications can never define a priority >0
13180 if (DEBUG_FILTERS) {
13181 Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13182 + " package: " + applicationInfo.packageName
13183 + " activity: " + intent.activity.className
13184 + " origPrio: " + intent.getPriority());
13186 intent.setPriority(0);
13190 if (systemActivities == null) {
13191 // the system package is not disabled; we're parsing the system partition
13192 if (isProtectedAction(intent)) {
13193 if (mDeferProtectedFilters) {
13194 // We can't deal with these just yet. No component should ever obtain a
13195 // >0 priority for a protected actions, with ONE exception -- the setup
13196 // wizard. The setup wizard, however, cannot be known until we're able to
13197 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13198 // until all intent filters have been processed. Chicken, meet egg.
13199 // Let the filter temporarily have a high priority and rectify the
13200 // priorities after all system packages have been scanned.
13201 mProtectedFilters.add(intent);
13202 if (DEBUG_FILTERS) {
13203 Slog.i(TAG, "Protected action; save for later;"
13204 + " package: " + applicationInfo.packageName
13205 + " activity: " + intent.activity.className
13206 + " origPrio: " + intent.getPriority());
13210 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13211 Slog.i(TAG, "No setup wizard;"
13212 + " All protected intents capped to priority 0");
13214 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13215 if (DEBUG_FILTERS) {
13216 Slog.i(TAG, "Found setup wizard;"
13217 + " allow priority " + intent.getPriority() + ";"
13218 + " package: " + intent.activity.info.packageName
13219 + " activity: " + intent.activity.className
13220 + " priority: " + intent.getPriority());
13222 // setup wizard gets whatever it wants
13225 if (DEBUG_FILTERS) {
13226 Slog.i(TAG, "Protected action; cap priority to 0;"
13227 + " package: " + intent.activity.info.packageName
13228 + " activity: " + intent.activity.className
13229 + " origPrio: " + intent.getPriority());
13231 intent.setPriority(0);
13235 // privileged apps on the system image get whatever priority they request
13239 // privileged app unbundled update ... try to find the same activity
13240 final PackageParser.Activity foundActivity =
13241 findMatchingActivity(systemActivities, activityInfo);
13242 if (foundActivity == null) {
13243 // this is a new activity; it cannot obtain >0 priority
13244 if (DEBUG_FILTERS) {
13245 Slog.i(TAG, "New activity; cap priority to 0;"
13246 + " package: " + applicationInfo.packageName
13247 + " activity: " + intent.activity.className
13248 + " origPrio: " + intent.getPriority());
13250 intent.setPriority(0);
13254 // found activity, now check for filter equivalence
13256 // a shallow copy is enough; we modify the list, not its contents
13257 final List<ActivityIntentInfo> intentListCopy =
13258 new ArrayList<>(foundActivity.intents);
13259 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13261 // find matching action subsets
13262 final Iterator<String> actionsIterator = intent.actionsIterator();
13263 if (actionsIterator != null) {
13264 getIntentListSubset(
13265 intentListCopy, new ActionIterGenerator(), actionsIterator);
13266 if (intentListCopy.size() == 0) {
13267 // no more intents to match; we're not equivalent
13268 if (DEBUG_FILTERS) {
13269 Slog.i(TAG, "Mismatched action; cap priority to 0;"
13270 + " package: " + applicationInfo.packageName
13271 + " activity: " + intent.activity.className
13272 + " origPrio: " + intent.getPriority());
13274 intent.setPriority(0);
13279 // find matching category subsets
13280 final Iterator<String> categoriesIterator = intent.categoriesIterator();
13281 if (categoriesIterator != null) {
13282 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13283 categoriesIterator);
13284 if (intentListCopy.size() == 0) {
13285 // no more intents to match; we're not equivalent
13286 if (DEBUG_FILTERS) {
13287 Slog.i(TAG, "Mismatched category; cap priority to 0;"
13288 + " package: " + applicationInfo.packageName
13289 + " activity: " + intent.activity.className
13290 + " origPrio: " + intent.getPriority());
13292 intent.setPriority(0);
13297 // find matching schemes subsets
13298 final Iterator<String> schemesIterator = intent.schemesIterator();
13299 if (schemesIterator != null) {
13300 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13302 if (intentListCopy.size() == 0) {
13303 // no more intents to match; we're not equivalent
13304 if (DEBUG_FILTERS) {
13305 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13306 + " package: " + applicationInfo.packageName
13307 + " activity: " + intent.activity.className
13308 + " origPrio: " + intent.getPriority());
13310 intent.setPriority(0);
13315 // find matching authorities subsets
13316 final Iterator<IntentFilter.AuthorityEntry>
13317 authoritiesIterator = intent.authoritiesIterator();
13318 if (authoritiesIterator != null) {
13319 getIntentListSubset(intentListCopy,
13320 new AuthoritiesIterGenerator(),
13321 authoritiesIterator);
13322 if (intentListCopy.size() == 0) {
13323 // no more intents to match; we're not equivalent
13324 if (DEBUG_FILTERS) {
13325 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13326 + " package: " + applicationInfo.packageName
13327 + " activity: " + intent.activity.className
13328 + " origPrio: " + intent.getPriority());
13330 intent.setPriority(0);
13335 // we found matching filter(s); app gets the max priority of all intents
13336 int cappedPriority = 0;
13337 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13338 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13340 if (intent.getPriority() > cappedPriority) {
13341 if (DEBUG_FILTERS) {
13342 Slog.i(TAG, "Found matching filter(s);"
13343 + " cap priority to " + cappedPriority + ";"
13344 + " package: " + applicationInfo.packageName
13345 + " activity: " + intent.activity.className
13346 + " origPrio: " + intent.getPriority());
13348 intent.setPriority(cappedPriority);
13351 // all this for nothing; the requested priority was <= what was on the system
13354 public final void addActivity(PackageParser.Activity a, String type) {
13355 mActivities.put(a.getComponentName(), a);
13356 if (DEBUG_SHOW_INFO)
13358 TAG, " " + type + " " +
13359 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13360 if (DEBUG_SHOW_INFO)
13361 Log.v(TAG, " Class=" + a.info.name);
13362 final int NI = a.intents.size();
13363 for (int j=0; j<NI; j++) {
13364 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13365 if ("activity".equals(type)) {
13366 final PackageSetting ps =
13367 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13368 final List<PackageParser.Activity> systemActivities =
13369 ps != null && ps.pkg != null ? ps.pkg.activities : null;
13370 adjustPriority(systemActivities, intent);
13372 if (DEBUG_SHOW_INFO) {
13373 Log.v(TAG, " IntentFilter:");
13374 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13376 if (!intent.debugCheck()) {
13377 Log.w(TAG, "==> For Activity " + a.info.name);
13383 public final void removeActivity(PackageParser.Activity a, String type) {
13384 mActivities.remove(a.getComponentName());
13385 if (DEBUG_SHOW_INFO) {
13386 Log.v(TAG, " " + type + " "
13387 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13388 : a.info.name) + ":");
13389 Log.v(TAG, " Class=" + a.info.name);
13391 final int NI = a.intents.size();
13392 for (int j=0; j<NI; j++) {
13393 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13394 if (DEBUG_SHOW_INFO) {
13395 Log.v(TAG, " IntentFilter:");
13396 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13398 removeFilter(intent);
13403 protected boolean allowFilterResult(
13404 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13405 ActivityInfo filterAi = filter.activity.info;
13406 for (int i=dest.size()-1; i>=0; i--) {
13407 ActivityInfo destAi = dest.get(i).activityInfo;
13408 if (destAi.name == filterAi.name
13409 && destAi.packageName == filterAi.packageName) {
13417 protected ActivityIntentInfo[] newArray(int size) {
13418 return new ActivityIntentInfo[size];
13422 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13423 if (!sUserManager.exists(userId)) return true;
13424 PackageParser.Package p = filter.activity.owner;
13426 PackageSetting ps = (PackageSetting)p.mExtras;
13428 // System apps are never considered stopped for purposes of
13429 // filtering, because there may be no way for the user to
13430 // actually re-launch them.
13431 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13432 && ps.getStopped(userId);
13439 protected boolean isPackageForFilter(String packageName,
13440 PackageParser.ActivityIntentInfo info) {
13441 return packageName.equals(info.activity.owner.packageName);
13445 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13446 int match, int userId) {
13447 if (!sUserManager.exists(userId)) return null;
13448 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13451 final PackageParser.Activity activity = info.activity;
13452 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13456 final PackageUserState userState = ps.readUserState(userId);
13458 PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13462 final boolean matchExplicitlyVisibleOnly =
13463 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13464 final boolean matchVisibleToInstantApp =
13465 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13466 final boolean componentVisible =
13467 matchVisibleToInstantApp
13468 && info.isVisibleToInstantApp()
13469 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13470 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13471 // throw out filters that aren't visible to ephemeral apps
13472 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13475 // throw out instant app filters if we're not explicitly requesting them
13476 if (!matchInstantApp && userState.instantApp) {
13479 // throw out instant app filters if updates are available; will trigger
13480 // instant app resolution
13481 if (userState.instantApp && ps.isUpdateAvailable()) {
13484 final ResolveInfo res = new ResolveInfo();
13485 res.activityInfo = ai;
13486 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13489 if (info != null) {
13490 res.handleAllWebDataURI = info.handleAllWebDataURI();
13492 res.priority = info.getPriority();
13493 res.preferredOrder = activity.owner.mPreferredOrder;
13494 //System.out.println("Result: " + res.activityInfo.className +
13495 // " = " + res.priority);
13497 res.isDefault = info.hasDefault;
13498 res.labelRes = info.labelRes;
13499 res.nonLocalizedLabel = info.nonLocalizedLabel;
13500 if (userNeedsBadging(userId)) {
13501 res.noResourceId = true;
13503 res.icon = info.icon;
13505 res.iconResourceId = info.icon;
13506 res.system = res.activityInfo.applicationInfo.isSystemApp();
13507 res.isInstantAppAvailable = userState.instantApp;
13512 protected void sortResults(List<ResolveInfo> results) {
13513 Collections.sort(results, mResolvePrioritySorter);
13517 protected void dumpFilter(PrintWriter out, String prefix,
13518 PackageParser.ActivityIntentInfo filter) {
13519 out.print(prefix); out.print(
13520 Integer.toHexString(System.identityHashCode(filter.activity)));
13522 filter.activity.printComponentShortName(out);
13523 out.print(" filter ");
13524 out.println(Integer.toHexString(System.identityHashCode(filter)));
13528 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13529 return filter.activity;
13532 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13533 PackageParser.Activity activity = (PackageParser.Activity)label;
13534 out.print(prefix); out.print(
13535 Integer.toHexString(System.identityHashCode(activity)));
13537 activity.printComponentShortName(out);
13539 out.print(" ("); out.print(count); out.print(" filters)");
13544 // Keys are String (activity class name), values are Activity.
13545 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13546 = new ArrayMap<ComponentName, PackageParser.Activity>();
13547 private int mFlags;
13550 private final class ServiceIntentResolver
13551 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13552 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13553 boolean defaultOnly, int userId) {
13554 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13555 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13558 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13560 if (!sUserManager.exists(userId)) return null;
13562 return super.queryIntent(intent, resolvedType,
13563 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13567 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13568 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13569 if (!sUserManager.exists(userId)) return null;
13570 if (packageServices == null) {
13574 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13575 final int N = packageServices.size();
13576 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13577 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13579 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13580 for (int i = 0; i < N; ++i) {
13581 intentFilters = packageServices.get(i).intents;
13582 if (intentFilters != null && intentFilters.size() > 0) {
13583 PackageParser.ServiceIntentInfo[] array =
13584 new PackageParser.ServiceIntentInfo[intentFilters.size()];
13585 intentFilters.toArray(array);
13586 listCut.add(array);
13589 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13592 public final void addService(PackageParser.Service s) {
13593 mServices.put(s.getComponentName(), s);
13594 if (DEBUG_SHOW_INFO) {
13596 + (s.info.nonLocalizedLabel != null
13597 ? s.info.nonLocalizedLabel : s.info.name) + ":");
13598 Log.v(TAG, " Class=" + s.info.name);
13600 final int NI = s.intents.size();
13602 for (j=0; j<NI; j++) {
13603 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13604 if (DEBUG_SHOW_INFO) {
13605 Log.v(TAG, " IntentFilter:");
13606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13608 if (!intent.debugCheck()) {
13609 Log.w(TAG, "==> For Service " + s.info.name);
13615 public final void removeService(PackageParser.Service s) {
13616 mServices.remove(s.getComponentName());
13617 if (DEBUG_SHOW_INFO) {
13618 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
13619 ? s.info.nonLocalizedLabel : s.info.name) + ":");
13620 Log.v(TAG, " Class=" + s.info.name);
13622 final int NI = s.intents.size();
13624 for (j=0; j<NI; j++) {
13625 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13626 if (DEBUG_SHOW_INFO) {
13627 Log.v(TAG, " IntentFilter:");
13628 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13630 removeFilter(intent);
13635 protected boolean allowFilterResult(
13636 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13637 ServiceInfo filterSi = filter.service.info;
13638 for (int i=dest.size()-1; i>=0; i--) {
13639 ServiceInfo destAi = dest.get(i).serviceInfo;
13640 if (destAi.name == filterSi.name
13641 && destAi.packageName == filterSi.packageName) {
13649 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13650 return new PackageParser.ServiceIntentInfo[size];
13654 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13655 if (!sUserManager.exists(userId)) return true;
13656 PackageParser.Package p = filter.service.owner;
13658 PackageSetting ps = (PackageSetting)p.mExtras;
13660 // System apps are never considered stopped for purposes of
13661 // filtering, because there may be no way for the user to
13662 // actually re-launch them.
13663 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13664 && ps.getStopped(userId);
13671 protected boolean isPackageForFilter(String packageName,
13672 PackageParser.ServiceIntentInfo info) {
13673 return packageName.equals(info.service.owner.packageName);
13677 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13678 int match, int userId) {
13679 if (!sUserManager.exists(userId)) return null;
13680 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13681 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13684 final PackageParser.Service service = info.service;
13685 PackageSetting ps = (PackageSetting) service.owner.mExtras;
13689 final PackageUserState userState = ps.readUserState(userId);
13690 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13691 userState, userId);
13695 final boolean matchVisibleToInstantApp =
13696 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13697 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13698 // throw out filters that aren't visible to ephemeral apps
13699 if (matchVisibleToInstantApp
13700 && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13703 // throw out ephemeral filters if we're not explicitly requesting them
13704 if (!isInstantApp && userState.instantApp) {
13707 // throw out instant app filters if updates are available; will trigger
13708 // instant app resolution
13709 if (userState.instantApp && ps.isUpdateAvailable()) {
13712 final ResolveInfo res = new ResolveInfo();
13713 res.serviceInfo = si;
13714 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13715 res.filter = filter;
13717 res.priority = info.getPriority();
13718 res.preferredOrder = service.owner.mPreferredOrder;
13720 res.isDefault = info.hasDefault;
13721 res.labelRes = info.labelRes;
13722 res.nonLocalizedLabel = info.nonLocalizedLabel;
13723 res.icon = info.icon;
13724 res.system = res.serviceInfo.applicationInfo.isSystemApp();
13729 protected void sortResults(List<ResolveInfo> results) {
13730 Collections.sort(results, mResolvePrioritySorter);
13734 protected void dumpFilter(PrintWriter out, String prefix,
13735 PackageParser.ServiceIntentInfo filter) {
13736 out.print(prefix); out.print(
13737 Integer.toHexString(System.identityHashCode(filter.service)));
13739 filter.service.printComponentShortName(out);
13740 out.print(" filter ");
13741 out.println(Integer.toHexString(System.identityHashCode(filter)));
13745 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13746 return filter.service;
13749 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13750 PackageParser.Service service = (PackageParser.Service)label;
13751 out.print(prefix); out.print(
13752 Integer.toHexString(System.identityHashCode(service)));
13754 service.printComponentShortName(out);
13756 out.print(" ("); out.print(count); out.print(" filters)");
13761 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13762 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13763 // final List<ResolveInfo> retList = Lists.newArrayList();
13764 // while (i.hasNext()) {
13765 // final ResolveInfo resolveInfo = (ResolveInfo) i;
13766 // if (isEnabledLP(resolveInfo.serviceInfo)) {
13767 // retList.add(resolveInfo);
13773 // Keys are String (activity class name), values are Activity.
13774 private final ArrayMap<ComponentName, PackageParser.Service> mServices
13775 = new ArrayMap<ComponentName, PackageParser.Service>();
13776 private int mFlags;
13779 private final class ProviderIntentResolver
13780 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13781 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13782 boolean defaultOnly, int userId) {
13783 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13784 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13787 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13789 if (!sUserManager.exists(userId))
13792 return super.queryIntent(intent, resolvedType,
13793 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13797 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13798 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13799 if (!sUserManager.exists(userId))
13801 if (packageProviders == null) {
13805 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13806 final int N = packageProviders.size();
13807 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13808 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13810 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13811 for (int i = 0; i < N; ++i) {
13812 intentFilters = packageProviders.get(i).intents;
13813 if (intentFilters != null && intentFilters.size() > 0) {
13814 PackageParser.ProviderIntentInfo[] array =
13815 new PackageParser.ProviderIntentInfo[intentFilters.size()];
13816 intentFilters.toArray(array);
13817 listCut.add(array);
13820 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13823 public final void addProvider(PackageParser.Provider p) {
13824 if (mProviders.containsKey(p.getComponentName())) {
13825 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13829 mProviders.put(p.getComponentName(), p);
13830 if (DEBUG_SHOW_INFO) {
13832 + (p.info.nonLocalizedLabel != null
13833 ? p.info.nonLocalizedLabel : p.info.name) + ":");
13834 Log.v(TAG, " Class=" + p.info.name);
13836 final int NI = p.intents.size();
13838 for (j = 0; j < NI; j++) {
13839 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13840 if (DEBUG_SHOW_INFO) {
13841 Log.v(TAG, " IntentFilter:");
13842 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13844 if (!intent.debugCheck()) {
13845 Log.w(TAG, "==> For Provider " + p.info.name);
13851 public final void removeProvider(PackageParser.Provider p) {
13852 mProviders.remove(p.getComponentName());
13853 if (DEBUG_SHOW_INFO) {
13854 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
13855 ? p.info.nonLocalizedLabel : p.info.name) + ":");
13856 Log.v(TAG, " Class=" + p.info.name);
13858 final int NI = p.intents.size();
13860 for (j = 0; j < NI; j++) {
13861 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13862 if (DEBUG_SHOW_INFO) {
13863 Log.v(TAG, " IntentFilter:");
13864 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13866 removeFilter(intent);
13871 protected boolean allowFilterResult(
13872 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13873 ProviderInfo filterPi = filter.provider.info;
13874 for (int i = dest.size() - 1; i >= 0; i--) {
13875 ProviderInfo destPi = dest.get(i).providerInfo;
13876 if (destPi.name == filterPi.name
13877 && destPi.packageName == filterPi.packageName) {
13885 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13886 return new PackageParser.ProviderIntentInfo[size];
13890 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13891 if (!sUserManager.exists(userId))
13893 PackageParser.Package p = filter.provider.owner;
13895 PackageSetting ps = (PackageSetting) p.mExtras;
13897 // System apps are never considered stopped for purposes of
13898 // filtering, because there may be no way for the user to
13899 // actually re-launch them.
13900 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13901 && ps.getStopped(userId);
13908 protected boolean isPackageForFilter(String packageName,
13909 PackageParser.ProviderIntentInfo info) {
13910 return packageName.equals(info.provider.owner.packageName);
13914 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13915 int match, int userId) {
13916 if (!sUserManager.exists(userId))
13918 final PackageParser.ProviderIntentInfo info = filter;
13919 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13922 final PackageParser.Provider provider = info.provider;
13923 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13927 final PackageUserState userState = ps.readUserState(userId);
13928 final boolean matchVisibleToInstantApp =
13929 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13930 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13931 // throw out filters that aren't visible to instant applications
13932 if (matchVisibleToInstantApp
13933 && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13936 // throw out instant application filters if we're not explicitly requesting them
13937 if (!isInstantApp && userState.instantApp) {
13940 // throw out instant application filters if updates are available; will trigger
13941 // instant application resolution
13942 if (userState.instantApp && ps.isUpdateAvailable()) {
13945 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13946 userState, userId);
13950 final ResolveInfo res = new ResolveInfo();
13951 res.providerInfo = pi;
13952 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13953 res.filter = filter;
13955 res.priority = info.getPriority();
13956 res.preferredOrder = provider.owner.mPreferredOrder;
13958 res.isDefault = info.hasDefault;
13959 res.labelRes = info.labelRes;
13960 res.nonLocalizedLabel = info.nonLocalizedLabel;
13961 res.icon = info.icon;
13962 res.system = res.providerInfo.applicationInfo.isSystemApp();
13967 protected void sortResults(List<ResolveInfo> results) {
13968 Collections.sort(results, mResolvePrioritySorter);
13972 protected void dumpFilter(PrintWriter out, String prefix,
13973 PackageParser.ProviderIntentInfo filter) {
13976 Integer.toHexString(System.identityHashCode(filter.provider)));
13978 filter.provider.printComponentShortName(out);
13979 out.print(" filter ");
13980 out.println(Integer.toHexString(System.identityHashCode(filter)));
13984 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13985 return filter.provider;
13988 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13989 PackageParser.Provider provider = (PackageParser.Provider)label;
13990 out.print(prefix); out.print(
13991 Integer.toHexString(System.identityHashCode(provider)));
13993 provider.printComponentShortName(out);
13995 out.print(" ("); out.print(count); out.print(" filters)");
14000 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14001 = new ArrayMap<ComponentName, PackageParser.Provider>();
14002 private int mFlags;
14005 static final class EphemeralIntentResolver
14006 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14008 * The result that has the highest defined order. Ordering applies on a
14009 * per-package basis. Mapping is from package name to Pair of order and
14010 * EphemeralResolveInfo.
14012 * NOTE: This is implemented as a field variable for convenience and efficiency.
14013 * By having a field variable, we're able to track filter ordering as soon as
14014 * a non-zero order is defined. Otherwise, multiple loops across the result set
14015 * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14016 * this needs to be contained entirely within {@link #filterResults}.
14018 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14021 protected AuxiliaryResolveInfo[] newArray(int size) {
14022 return new AuxiliaryResolveInfo[size];
14026 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14031 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14033 if (!sUserManager.exists(userId)) {
14036 final String packageName = responseObj.resolveInfo.getPackageName();
14037 final Integer order = responseObj.getOrder();
14038 final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14039 mOrderResult.get(packageName);
14040 // ordering is enabled and this item's order isn't high enough
14041 if (lastOrderResult != null && lastOrderResult.first >= order) {
14044 final InstantAppResolveInfo res = responseObj.resolveInfo;
14046 // non-zero order, enable ordering
14047 mOrderResult.put(packageName, new Pair<>(order, res));
14049 return responseObj;
14053 protected void filterResults(List<AuxiliaryResolveInfo> results) {
14054 // only do work if ordering is enabled [most of the time it won't be]
14055 if (mOrderResult.size() == 0) {
14058 int resultSize = results.size();
14059 for (int i = 0; i < resultSize; i++) {
14060 final InstantAppResolveInfo info = results.get(i).resolveInfo;
14061 final String packageName = info.getPackageName();
14062 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14063 if (savedInfo == null) {
14064 // package doesn't having ordering
14067 if (savedInfo.second == info) {
14068 // circled back to the highest ordered item; remove from order list
14069 mOrderResult.remove(savedInfo);
14070 if (mOrderResult.size() == 0) {
14071 // no more ordered items
14076 // item has a worse order, remove it from the result list
14084 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14085 new Comparator<ResolveInfo>() {
14086 public int compare(ResolveInfo r1, ResolveInfo r2) {
14087 int v1 = r1.priority;
14088 int v2 = r2.priority;
14089 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14091 return (v1 > v2) ? -1 : 1;
14093 v1 = r1.preferredOrder;
14094 v2 = r2.preferredOrder;
14096 return (v1 > v2) ? -1 : 1;
14098 if (r1.isDefault != r2.isDefault) {
14099 return r1.isDefault ? -1 : 1;
14103 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14105 return (v1 > v2) ? -1 : 1;
14107 if (r1.system != r2.system) {
14108 return r1.system ? -1 : 1;
14110 if (r1.activityInfo != null) {
14111 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14113 if (r1.serviceInfo != null) {
14114 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14116 if (r1.providerInfo != null) {
14117 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14123 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14124 new Comparator<ProviderInfo>() {
14125 public int compare(ProviderInfo p1, ProviderInfo p2) {
14126 final int v1 = p1.initOrder;
14127 final int v2 = p2.initOrder;
14128 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14132 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14133 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14134 final int[] userIds) {
14135 mHandler.post(new Runnable() {
14137 public void run() {
14139 final IActivityManager am = ActivityManager.getService();
14140 if (am == null) return;
14141 final int[] resolvedUserIds;
14142 if (userIds == null) {
14143 resolvedUserIds = am.getRunningUserIds();
14145 resolvedUserIds = userIds;
14147 for (int id : resolvedUserIds) {
14148 final Intent intent = new Intent(action,
14149 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14150 if (extras != null) {
14151 intent.putExtras(extras);
14153 if (targetPkg != null) {
14154 intent.setPackage(targetPkg);
14156 // Modify the UID when posting to other users
14157 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14158 if (uid > 0 && UserHandle.getUserId(uid) != id) {
14159 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14160 intent.putExtra(Intent.EXTRA_UID, uid);
14162 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14163 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14164 if (DEBUG_BROADCASTS) {
14165 RuntimeException here = new RuntimeException("here");
14166 here.fillInStackTrace();
14167 Slog.d(TAG, "Sending to user " + id + ": "
14168 + intent.toShortString(false, true, false, false)
14169 + " " + intent.getExtras(), here);
14171 am.broadcastIntent(null, intent, null, finishedReceiver,
14172 0, null, null, null, android.app.AppOpsManager.OP_NONE,
14173 null, finishedReceiver != null, false, id);
14175 } catch (RemoteException ex) {
14182 * Check if the external storage media is available. This is true if there
14183 * is a mounted external storage medium or if the external storage is
14186 private boolean isExternalMediaAvailable() {
14187 return mMediaMounted || Environment.isExternalStorageEmulated();
14191 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14192 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14196 synchronized (mPackages) {
14197 if (!isExternalMediaAvailable()) {
14198 // If the external storage is no longer mounted at this point,
14199 // the caller may not have been able to delete all of this
14200 // packages files and can not delete any more. Bail.
14203 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14204 if (lastPackage != null) {
14205 pkgs.remove(lastPackage);
14207 if (pkgs.size() > 0) {
14208 return pkgs.get(0);
14214 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14215 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14216 userId, andCode ? 1 : 0, packageName);
14217 if (mSystemReady) {
14218 msg.sendToTarget();
14220 if (mPostSystemReadyMessages == null) {
14221 mPostSystemReadyMessages = new ArrayList<>();
14223 mPostSystemReadyMessages.add(msg);
14227 void startCleaningPackages() {
14229 if (!isExternalMediaAvailable()) {
14232 synchronized (mPackages) {
14233 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14237 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14238 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14239 IActivityManager am = ActivityManager.getService();
14242 synchronized (mPackages) {
14243 if (!mDefaultContainerWhitelisted) {
14244 mDefaultContainerWhitelisted = true;
14245 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14246 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14251 am.backgroundWhitelistUid(dcsUid);
14253 am.startService(null, intent, null, false, mContext.getOpPackageName(),
14254 UserHandle.USER_SYSTEM);
14255 } catch (RemoteException e) {
14261 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14262 int installFlags, String installerPackageName, int userId) {
14263 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14265 final int callingUid = Binder.getCallingUid();
14266 enforceCrossUserPermission(callingUid, userId,
14267 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14269 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14271 if (observer != null) {
14272 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14274 } catch (RemoteException re) {
14279 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14280 installFlags |= PackageManager.INSTALL_FROM_ADB;
14283 // Caller holds INSTALL_PACKAGES permission, so we're less strict
14284 // about installerPackageName.
14286 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14287 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14291 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14292 user = UserHandle.ALL;
14294 user = new UserHandle(userId);
14297 // Only system components can circumvent runtime permissions when installing.
14298 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14299 && mContext.checkCallingOrSelfPermission(Manifest.permission
14300 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14301 throw new SecurityException("You need the "
14302 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14303 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14306 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14307 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14308 throw new IllegalArgumentException(
14309 "New installs into ASEC containers no longer supported");
14312 final File originFile = new File(originPath);
14313 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14315 final Message msg = mHandler.obtainMessage(INIT_COPY);
14316 final VerificationInfo verificationInfo = new VerificationInfo(
14317 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14318 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14319 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14320 null /*packageAbiOverride*/, null /*grantedPermissions*/,
14321 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14322 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14325 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14326 System.identityHashCode(msg.obj));
14327 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14328 System.identityHashCode(msg.obj));
14330 mHandler.sendMessage(msg);
14335 * Ensure that the install reason matches what we know about the package installer (e.g. whether
14336 * it is acting on behalf on an enterprise or the user).
14338 * Note that the ordering of the conditionals in this method is important. The checks we perform
14339 * are as follows, in this order:
14341 * 1) If the install is being performed by a system app, we can trust the app to have set the
14342 * install reason correctly. Thus, we pass through the install reason unchanged, no matter
14344 * 2) If the install is being performed by a device or profile owner app, the install reason
14345 * should be enterprise policy. However, we cannot be sure that the device or profile owner
14346 * set the install reason correctly. If the app targets an older SDK version where install
14347 * reasons did not exist yet, or if the app author simply forgot, the install reason may be
14348 * unset or wrong. Thus, we force the install reason to be enterprise policy.
14349 * 3) In all other cases, the install is being performed by a regular app that is neither part
14350 * of the system nor a device or profile owner. We have no reason to believe that this app is
14351 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14352 * set to enterprise policy and if so, change it to unknown instead.
14354 private int fixUpInstallReason(String installerPackageName, int installerUid,
14355 int installReason) {
14356 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14357 == PERMISSION_GRANTED) {
14358 // If the install is being performed by a system app, we trust that app to have set the
14359 // install reason correctly.
14360 return installReason;
14363 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14364 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14366 ComponentName owner = null;
14368 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14369 if (owner == null) {
14370 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14372 } catch (RemoteException e) {
14374 if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14375 // If the install is being performed by a device or profile owner, the install
14376 // reason should be enterprise policy.
14377 return PackageManager.INSTALL_REASON_POLICY;
14381 if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14382 // If the install is being performed by a regular app (i.e. neither system app nor
14383 // device or profile owner), we have no reason to believe that the app is acting on
14384 // behalf of an enterprise. If the app set the install reason to enterprise policy,
14385 // change it to unknown instead.
14386 return PackageManager.INSTALL_REASON_UNKNOWN;
14389 // If the install is being performed by a regular app and the install reason was set to any
14390 // value but enterprise policy, leave the install reason unchanged.
14391 return installReason;
14394 void installStage(String packageName, File stagedDir, String stagedCid,
14395 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14396 String installerPackageName, int installerUid, UserHandle user,
14397 Certificate[][] certificates) {
14398 if (DEBUG_EPHEMERAL) {
14399 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14400 Slog.d(TAG, "Ephemeral install of " + packageName);
14403 final VerificationInfo verificationInfo = new VerificationInfo(
14404 sessionParams.originatingUri, sessionParams.referrerUri,
14405 sessionParams.originatingUid, installerUid);
14407 final OriginInfo origin;
14408 if (stagedDir != null) {
14409 origin = OriginInfo.fromStagedFile(stagedDir);
14411 origin = OriginInfo.fromStagedContainer(stagedCid);
14414 final Message msg = mHandler.obtainMessage(INIT_COPY);
14415 final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14416 sessionParams.installReason);
14417 final InstallParams params = new InstallParams(origin, null, observer,
14418 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14419 verificationInfo, user, sessionParams.abiOverride,
14420 sessionParams.grantedRuntimePermissions, certificates, installReason);
14421 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14424 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14425 System.identityHashCode(msg.obj));
14426 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14427 System.identityHashCode(msg.obj));
14429 mHandler.sendMessage(msg);
14432 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14434 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14435 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14437 // Send a session commit broadcast
14438 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14439 info.installReason = pkgSetting.getInstallReason(userId);
14440 info.appPackageName = packageName;
14441 sendSessionCommitBroadcast(info, userId);
14444 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14445 if (ArrayUtils.isEmpty(userIds)) {
14448 Bundle extras = new Bundle(1);
14449 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14450 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14452 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14453 packageName, extras, 0, null, null, userIds);
14455 mHandler.post(() -> {
14456 for (int userId : userIds) {
14457 sendBootCompletedBroadcastToSystemApp(packageName, userId);
14465 * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14466 * automatically without needing an explicit launch.
14467 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14469 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14470 // If user is not running, the app didn't miss any broadcast
14471 if (!mUserManagerInternal.isUserRunning(userId)) {
14474 final IActivityManager am = ActivityManager.getService();
14476 // Deliver LOCKED_BOOT_COMPLETED first
14477 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14478 .setPackage(packageName);
14479 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14480 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14481 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14483 // Deliver BOOT_COMPLETED only if user is unlocked
14484 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14485 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14486 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14487 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14489 } catch (RemoteException e) {
14490 throw e.rethrowFromSystemServer();
14495 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14497 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14498 PackageSetting pkgSetting;
14499 final int callingUid = Binder.getCallingUid();
14500 enforceCrossUserPermission(callingUid, userId,
14501 true /* requireFullPermission */, true /* checkShell */,
14502 "setApplicationHiddenSetting for user " + userId);
14504 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14505 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14509 long callingId = Binder.clearCallingIdentity();
14511 boolean sendAdded = false;
14512 boolean sendRemoved = false;
14514 synchronized (mPackages) {
14515 pkgSetting = mSettings.mPackages.get(packageName);
14516 if (pkgSetting == null) {
14519 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14522 // Do not allow "android" is being disabled
14523 if ("android".equals(packageName)) {
14524 Slog.w(TAG, "Cannot hide package: android");
14527 // Cannot hide static shared libs as they are considered
14528 // a part of the using app (emulating static linking). Also
14529 // static libs are installed always on internal storage.
14530 PackageParser.Package pkg = mPackages.get(packageName);
14531 if (pkg != null && pkg.staticSharedLibName != null) {
14532 Slog.w(TAG, "Cannot hide package: " + packageName
14533 + " providing static shared library: "
14534 + pkg.staticSharedLibName);
14537 // Only allow protected packages to hide themselves.
14538 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14539 && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14540 Slog.w(TAG, "Not hiding protected package: " + packageName);
14544 if (pkgSetting.getHidden(userId) != hidden) {
14545 pkgSetting.setHidden(hidden, userId);
14546 mSettings.writePackageRestrictionsLPr(userId);
14548 sendRemoved = true;
14555 sendPackageAddedForUser(packageName, pkgSetting, userId);
14559 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14561 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14565 Binder.restoreCallingIdentity(callingId);
14570 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14572 final PackageRemovedInfo info = new PackageRemovedInfo(this);
14573 info.removedPackage = packageName;
14574 info.installerPackageName = pkgSetting.installerPackageName;
14575 info.removedUsers = new int[] {userId};
14576 info.broadcastUsers = new int[] {userId};
14577 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14578 info.sendPackageRemovedBroadcasts(true /*killApp*/);
14581 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14582 if (pkgList.length > 0) {
14583 Bundle extras = new Bundle(1);
14584 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14586 sendPackageBroadcast(
14587 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14588 : Intent.ACTION_PACKAGES_UNSUSPENDED,
14589 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14590 new int[] {userId});
14595 * Returns true if application is not found or there was an error. Otherwise it returns
14596 * the hidden state of the package for the given user.
14599 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14600 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14601 final int callingUid = Binder.getCallingUid();
14602 enforceCrossUserPermission(callingUid, userId,
14603 true /* requireFullPermission */, false /* checkShell */,
14604 "getApplicationHidden for user " + userId);
14606 long callingId = Binder.clearCallingIdentity();
14609 synchronized (mPackages) {
14610 ps = mSettings.mPackages.get(packageName);
14614 if (filterAppAccessLPr(ps, callingUid, userId)) {
14617 return ps.getHidden(userId);
14620 Binder.restoreCallingIdentity(callingId);
14628 public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14629 int installReason) {
14630 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14632 PackageSetting pkgSetting;
14633 final int callingUid = Binder.getCallingUid();
14634 enforceCrossUserPermission(callingUid, userId,
14635 true /* requireFullPermission */, true /* checkShell */,
14636 "installExistingPackage for user " + userId);
14637 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14638 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14641 long callingId = Binder.clearCallingIdentity();
14643 boolean installed = false;
14644 final boolean instantApp =
14645 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14646 final boolean fullApp =
14647 (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14650 synchronized (mPackages) {
14651 pkgSetting = mSettings.mPackages.get(packageName);
14652 if (pkgSetting == null) {
14653 return PackageManager.INSTALL_FAILED_INVALID_URI;
14655 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14656 // only allow the existing package to be used if it's installed as a full
14657 // application for at least one user
14658 boolean installAllowed = false;
14659 for (int checkUserId : sUserManager.getUserIds()) {
14660 installAllowed = !pkgSetting.getInstantApp(checkUserId);
14661 if (installAllowed) {
14665 if (!installAllowed) {
14666 return PackageManager.INSTALL_FAILED_INVALID_URI;
14669 if (!pkgSetting.getInstalled(userId)) {
14670 pkgSetting.setInstalled(true, userId);
14671 pkgSetting.setHidden(false, userId);
14672 pkgSetting.setInstallReason(installReason, userId);
14673 mSettings.writePackageRestrictionsLPr(userId);
14674 mSettings.writeKernelMappingLPr(pkgSetting);
14676 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14677 // upgrade app from instant to full; we don't allow app downgrade
14680 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14684 if (pkgSetting.pkg != null) {
14685 synchronized (mInstallLock) {
14686 // We don't need to freeze for a brand new install
14687 prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14690 sendPackageAddedForUser(packageName, pkgSetting, userId);
14691 synchronized (mPackages) {
14692 updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14696 Binder.restoreCallingIdentity(callingId);
14699 return PackageManager.INSTALL_SUCCEEDED;
14702 void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14703 boolean instantApp, boolean fullApp) {
14704 // no state specified; do nothing
14705 if (!instantApp && !fullApp) {
14708 if (userId != UserHandle.USER_ALL) {
14709 if (instantApp && !pkgSetting.getInstantApp(userId)) {
14710 pkgSetting.setInstantApp(true /*instantApp*/, userId);
14711 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14712 pkgSetting.setInstantApp(false /*instantApp*/, userId);
14715 for (int currentUserId : sUserManager.getUserIds()) {
14716 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14717 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14718 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14719 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14725 boolean isUserRestricted(int userId, String restrictionKey) {
14726 Bundle restrictions = sUserManager.getUserRestrictions(userId);
14727 if (restrictions.getBoolean(restrictionKey, false)) {
14728 Log.w(TAG, "User is restricted: " + restrictionKey);
14735 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14737 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14738 final int callingUid = Binder.getCallingUid();
14739 enforceCrossUserPermission(callingUid, userId,
14740 true /* requireFullPermission */, true /* checkShell */,
14741 "setPackagesSuspended for user " + userId);
14743 if (ArrayUtils.isEmpty(packageNames)) {
14744 return packageNames;
14747 // List of package names for whom the suspended state has changed.
14748 List<String> changedPackages = new ArrayList<>(packageNames.length);
14749 // List of package names for whom the suspended state is not set as requested in this
14751 List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14752 long callingId = Binder.clearCallingIdentity();
14754 for (int i = 0; i < packageNames.length; i++) {
14755 String packageName = packageNames[i];
14756 boolean changed = false;
14758 synchronized (mPackages) {
14759 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14760 if (pkgSetting == null
14761 || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14762 Slog.w(TAG, "Could not find package setting for package \"" + packageName
14763 + "\". Skipping suspending/un-suspending.");
14764 unactionedPackages.add(packageName);
14767 appId = pkgSetting.appId;
14768 if (pkgSetting.getSuspended(userId) != suspended) {
14769 if (!canSuspendPackageForUserLocked(packageName, userId)) {
14770 unactionedPackages.add(packageName);
14773 pkgSetting.setSuspended(suspended, userId);
14774 mSettings.writePackageRestrictionsLPr(userId);
14776 changedPackages.add(packageName);
14780 if (changed && suspended) {
14781 killApplication(packageName, UserHandle.getUid(userId, appId),
14782 "suspending package");
14786 Binder.restoreCallingIdentity(callingId);
14789 if (!changedPackages.isEmpty()) {
14790 sendPackagesSuspendedForUser(changedPackages.toArray(
14791 new String[changedPackages.size()]), userId, suspended);
14794 return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14798 public boolean isPackageSuspendedForUser(String packageName, int userId) {
14799 final int callingUid = Binder.getCallingUid();
14800 enforceCrossUserPermission(callingUid, userId,
14801 true /* requireFullPermission */, false /* checkShell */,
14802 "isPackageSuspendedForUser for user " + userId);
14803 synchronized (mPackages) {
14804 final PackageSetting ps = mSettings.mPackages.get(packageName);
14805 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14806 throw new IllegalArgumentException("Unknown target package: " + packageName);
14808 return ps.getSuspended(userId);
14812 private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14813 if (isPackageDeviceAdmin(packageName, userId)) {
14814 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14815 + "\": has an active device admin");
14819 String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14820 if (packageName.equals(activeLauncherPackageName)) {
14821 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14822 + "\": contains the active launcher");
14826 if (packageName.equals(mRequiredInstallerPackage)) {
14827 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14828 + "\": required for package installation");
14832 if (packageName.equals(mRequiredUninstallerPackage)) {
14833 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14834 + "\": required for package uninstallation");
14838 if (packageName.equals(mRequiredVerifierPackage)) {
14839 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14840 + "\": required for package verification");
14844 if (packageName.equals(getDefaultDialerPackageName(userId))) {
14845 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14846 + "\": is the default dialer");
14850 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14851 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14852 + "\": protected package");
14856 // Cannot suspend static shared libs as they are considered
14857 // a part of the using app (emulating static linking). Also
14858 // static libs are installed always on internal storage.
14859 PackageParser.Package pkg = mPackages.get(packageName);
14860 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14861 Slog.w(TAG, "Cannot suspend package: " + packageName
14862 + " providing static shared library: "
14863 + pkg.staticSharedLibName);
14870 private String getActiveLauncherPackageName(int userId) {
14871 Intent intent = new Intent(Intent.ACTION_MAIN);
14872 intent.addCategory(Intent.CATEGORY_HOME);
14873 ResolveInfo resolveInfo = resolveIntent(
14875 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14876 PackageManager.MATCH_DEFAULT_ONLY,
14879 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14882 private String getDefaultDialerPackageName(int userId) {
14883 synchronized (mPackages) {
14884 return mSettings.getDefaultDialerPackageNameLPw(userId);
14889 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14890 mContext.enforceCallingOrSelfPermission(
14891 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14892 "Only package verification agents can verify applications");
14894 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14895 final PackageVerificationResponse response = new PackageVerificationResponse(
14896 verificationCode, Binder.getCallingUid());
14898 msg.obj = response;
14899 mHandler.sendMessage(msg);
14903 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14904 long millisecondsToDelay) {
14905 mContext.enforceCallingOrSelfPermission(
14906 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14907 "Only package verification agents can extend verification timeouts");
14909 final PackageVerificationState state = mPendingVerification.get(id);
14910 final PackageVerificationResponse response = new PackageVerificationResponse(
14911 verificationCodeAtTimeout, Binder.getCallingUid());
14913 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14914 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14916 if (millisecondsToDelay < 0) {
14917 millisecondsToDelay = 0;
14919 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14920 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14921 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14924 if ((state != null) && !state.timeoutExtended()) {
14925 state.extendTimeout();
14927 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14929 msg.obj = response;
14930 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14934 private void broadcastPackageVerified(int verificationId, Uri packageUri,
14935 int verificationCode, UserHandle user) {
14936 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14937 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14938 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14939 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14940 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14942 mContext.sendBroadcastAsUser(intent, user,
14943 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14946 private ComponentName matchComponentForVerifier(String packageName,
14947 List<ResolveInfo> receivers) {
14948 ActivityInfo targetReceiver = null;
14950 final int NR = receivers.size();
14951 for (int i = 0; i < NR; i++) {
14952 final ResolveInfo info = receivers.get(i);
14953 if (info.activityInfo == null) {
14957 if (packageName.equals(info.activityInfo.packageName)) {
14958 targetReceiver = info.activityInfo;
14963 if (targetReceiver == null) {
14967 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14970 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14971 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14972 if (pkgInfo.verifiers.length == 0) {
14976 final int N = pkgInfo.verifiers.length;
14977 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14978 for (int i = 0; i < N; i++) {
14979 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14981 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14983 if (comp == null) {
14987 final int verifierUid = getUidForVerifier(verifierInfo);
14988 if (verifierUid == -1) {
14992 if (DEBUG_VERIFY) {
14993 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14994 + " with the correct signature");
14996 sufficientVerifiers.add(comp);
14997 verificationState.addSufficientVerifier(verifierUid);
15000 return sufficientVerifiers;
15003 private int getUidForVerifier(VerifierInfo verifierInfo) {
15004 synchronized (mPackages) {
15005 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15008 } else if (pkg.mSignatures.length != 1) {
15009 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15010 + " has more than one signature; ignoring");
15015 * If the public key of the package's signature does not match
15016 * our expected public key, then this is a different package and
15020 final byte[] expectedPublicKey;
15022 final Signature verifierSig = pkg.mSignatures[0];
15023 final PublicKey publicKey = verifierSig.getPublicKey();
15024 expectedPublicKey = publicKey.getEncoded();
15025 } catch (CertificateException e) {
15029 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15031 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15032 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15033 + " does not have the expected public key; ignoring");
15037 return pkg.applicationInfo.uid;
15042 public void finishPackageInstall(int token, boolean didLaunch) {
15043 enforceSystemOrRoot("Only the system is allowed to finish installs");
15045 if (DEBUG_INSTALL) {
15046 Slog.v(TAG, "BM finishing package install for " + token);
15048 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15050 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15051 mHandler.sendMessage(msg);
15055 * Get the verification agent timeout. Used for both the APK verifier and the
15056 * intent filter verifier.
15058 * @return verification timeout in milliseconds
15060 private long getVerificationTimeout() {
15061 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15062 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15063 DEFAULT_VERIFICATION_TIMEOUT);
15067 * Get the default verification agent response code.
15069 * @return default verification response code
15071 private int getDefaultVerificationResponse(UserHandle user) {
15072 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15073 return PackageManager.VERIFICATION_REJECT;
15075 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15076 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15077 DEFAULT_VERIFICATION_RESPONSE);
15081 * Check whether or not package verification has been enabled.
15083 * @return true if verification should be performed
15085 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15086 if (!DEFAULT_VERIFY_ENABLE) {
15090 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15092 // Check if installing from ADB
15093 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15094 // Do not run verification in a test harness environment
15095 if (ActivityManager.isRunningInTestHarness()) {
15098 if (ensureVerifyAppsEnabled) {
15101 // Check if the developer does not want package verification for ADB installs
15102 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15103 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15107 // only when not installed from ADB, skip verification for instant apps when
15108 // the installer and verifier are the same.
15109 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15110 if (mInstantAppInstallerActivity != null
15111 && mInstantAppInstallerActivity.packageName.equals(
15112 mRequiredVerifierPackage)) {
15114 mContext.getSystemService(AppOpsManager.class)
15115 .checkPackage(installerUid, mRequiredVerifierPackage);
15116 if (DEBUG_VERIFY) {
15117 Slog.i(TAG, "disable verification for instant app");
15120 } catch (SecurityException ignore) { }
15125 if (ensureVerifyAppsEnabled) {
15129 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15130 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15134 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15135 throws RemoteException {
15136 mContext.enforceCallingOrSelfPermission(
15137 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15138 "Only intentfilter verification agents can verify applications");
15140 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15141 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15142 Binder.getCallingUid(), verificationCode, failedDomains);
15144 msg.obj = response;
15145 mHandler.sendMessage(msg);
15149 public int getIntentVerificationStatus(String packageName, int userId) {
15150 final int callingUid = Binder.getCallingUid();
15151 if (getInstantAppPackageName(callingUid) != null) {
15152 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15154 synchronized (mPackages) {
15155 final PackageSetting ps = mSettings.mPackages.get(packageName);
15157 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15158 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15160 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15165 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15166 mContext.enforceCallingOrSelfPermission(
15167 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15169 boolean result = false;
15170 synchronized (mPackages) {
15171 final PackageSetting ps = mSettings.mPackages.get(packageName);
15172 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15175 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15178 scheduleWritePackageRestrictionsLocked(userId);
15184 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15185 String packageName) {
15186 final int callingUid = Binder.getCallingUid();
15187 if (getInstantAppPackageName(callingUid) != null) {
15188 return ParceledListSlice.emptyList();
15190 synchronized (mPackages) {
15191 final PackageSetting ps = mSettings.mPackages.get(packageName);
15192 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15193 return ParceledListSlice.emptyList();
15195 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15200 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15201 if (TextUtils.isEmpty(packageName)) {
15202 return ParceledListSlice.emptyList();
15204 final int callingUid = Binder.getCallingUid();
15205 final int callingUserId = UserHandle.getUserId(callingUid);
15206 synchronized (mPackages) {
15207 PackageParser.Package pkg = mPackages.get(packageName);
15208 if (pkg == null || pkg.activities == null) {
15209 return ParceledListSlice.emptyList();
15211 if (pkg.mExtras == null) {
15212 return ParceledListSlice.emptyList();
15214 final PackageSetting ps = (PackageSetting) pkg.mExtras;
15215 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15216 return ParceledListSlice.emptyList();
15218 final int count = pkg.activities.size();
15219 ArrayList<IntentFilter> result = new ArrayList<>();
15220 for (int n=0; n<count; n++) {
15221 PackageParser.Activity activity = pkg.activities.get(n);
15222 if (activity.intents != null && activity.intents.size() > 0) {
15223 result.addAll(activity.intents);
15226 return new ParceledListSlice<>(result);
15231 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15232 mContext.enforceCallingOrSelfPermission(
15233 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15235 synchronized (mPackages) {
15236 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15237 if (packageName != null) {
15238 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15239 packageName, userId);
15246 public String getDefaultBrowserPackageName(int userId) {
15247 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15250 synchronized (mPackages) {
15251 return mSettings.getDefaultBrowserPackageNameLPw(userId);
15256 * Get the "allow unknown sources" setting.
15258 * @return the current "allow unknown sources" setting
15260 private int getUnknownSourcesSettings() {
15261 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15262 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15267 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15268 final int callingUid = Binder.getCallingUid();
15269 if (getInstantAppPackageName(callingUid) != null) {
15273 synchronized (mPackages) {
15274 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15275 if (targetPackageSetting == null
15276 || filterAppAccessLPr(
15277 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15278 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15281 PackageSetting installerPackageSetting;
15282 if (installerPackageName != null) {
15283 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15284 if (installerPackageSetting == null) {
15285 throw new IllegalArgumentException("Unknown installer package: "
15286 + installerPackageName);
15289 installerPackageSetting = null;
15292 Signature[] callerSignature;
15293 Object obj = mSettings.getUserIdLPr(callingUid);
15295 if (obj instanceof SharedUserSetting) {
15296 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15297 } else if (obj instanceof PackageSetting) {
15298 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15300 throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15303 throw new SecurityException("Unknown calling UID: " + callingUid);
15306 // Verify: can't set installerPackageName to a package that is
15307 // not signed with the same cert as the caller.
15308 if (installerPackageSetting != null) {
15309 if (compareSignatures(callerSignature,
15310 installerPackageSetting.signatures.mSignatures)
15311 != PackageManager.SIGNATURE_MATCH) {
15312 throw new SecurityException(
15313 "Caller does not have same cert as new installer package "
15314 + installerPackageName);
15318 // Verify: if target already has an installer package, it must
15319 // be signed with the same cert as the caller.
15320 if (targetPackageSetting.installerPackageName != null) {
15321 PackageSetting setting = mSettings.mPackages.get(
15322 targetPackageSetting.installerPackageName);
15323 // If the currently set package isn't valid, then it's always
15324 // okay to change it.
15325 if (setting != null) {
15326 if (compareSignatures(callerSignature,
15327 setting.signatures.mSignatures)
15328 != PackageManager.SIGNATURE_MATCH) {
15329 throw new SecurityException(
15330 "Caller does not have same cert as old installer package "
15331 + targetPackageSetting.installerPackageName);
15337 targetPackageSetting.installerPackageName = installerPackageName;
15338 if (installerPackageName != null) {
15339 mSettings.mInstallerPackages.add(installerPackageName);
15341 scheduleWriteSettingsLocked();
15346 public void setApplicationCategoryHint(String packageName, int categoryHint,
15347 String callerPackageName) {
15348 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15349 throw new SecurityException("Instant applications don't have access to this method");
15351 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15352 callerPackageName);
15353 synchronized (mPackages) {
15354 PackageSetting ps = mSettings.mPackages.get(packageName);
15356 throw new IllegalArgumentException("Unknown target package " + packageName);
15358 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15359 throw new IllegalArgumentException("Unknown target package " + packageName);
15361 if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15362 throw new IllegalArgumentException("Calling package " + callerPackageName
15363 + " is not installer for " + packageName);
15366 if (ps.categoryHint != categoryHint) {
15367 ps.categoryHint = categoryHint;
15368 scheduleWriteSettingsLocked();
15373 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15374 // Queue up an async operation since the package installation may take a little while.
15375 mHandler.post(new Runnable() {
15376 public void run() {
15377 mHandler.removeCallbacks(this);
15378 // Result object to be returned
15379 PackageInstalledInfo res = new PackageInstalledInfo();
15380 res.setReturnCode(currentStatus);
15383 res.removedInfo = null;
15384 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15385 args.doPreInstall(res.returnCode);
15386 synchronized (mInstallLock) {
15387 installPackageTracedLI(args, res);
15389 args.doPostInstall(res.returnCode, res.uid);
15392 // A restore should be performed at this point if (a) the install
15393 // succeeded, (b) the operation is not an update, and (c) the new
15394 // package has not opted out of backup participation.
15395 final boolean update = res.removedInfo != null
15396 && res.removedInfo.removedPackage != null;
15397 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15398 boolean doRestore = !update
15399 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15401 // Set up the post-install work request bookkeeping. This will be used
15402 // and cleaned up by the post-install event handling regardless of whether
15403 // there's a restore pass performed. Token values are >= 1.
15405 if (mNextInstallToken < 0) mNextInstallToken = 1;
15406 token = mNextInstallToken++;
15408 PostInstallData data = new PostInstallData(args, res);
15409 mRunningInstalls.put(token, data);
15410 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15412 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15413 // Pass responsibility to the Backup Manager. It will perform a
15414 // restore if appropriate, then pass responsibility back to the
15415 // Package Manager to run the post-install observer callbacks
15417 IBackupManager bm = IBackupManager.Stub.asInterface(
15418 ServiceManager.getService(Context.BACKUP_SERVICE));
15420 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15421 + " to BM for possible restore");
15422 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15424 // TODO: http://b/22388012
15425 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15426 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15430 } catch (RemoteException e) {
15431 // can't happen; the backup manager is local
15432 } catch (Exception e) {
15433 Slog.e(TAG, "Exception trying to enqueue restore", e);
15437 Slog.e(TAG, "Backup Manager not found!");
15443 // No restore possible, or the Backup Manager was mysteriously not
15444 // available -- just fire the post-install work request directly.
15445 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15447 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15449 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15450 mHandler.sendMessage(msg);
15457 * Callback from PackageSettings whenever an app is first transitioned out of the
15458 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if
15459 * the app was "launched" for a restoreAtInstall operation. Therefore we check
15460 * here whether the app is the target of an ongoing install, and only send the
15461 * broadcast immediately if it is not in that state. If it *is* undergoing a restore,
15462 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15465 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15466 // Serialize this with the rest of the install-process message chain. In the
15467 // restore-at-install case, this Runnable will necessarily run before the
15468 // POST_INSTALL message is processed, so the contents of mRunningInstalls
15469 // are coherent. In the non-restore case, the app has already completed install
15470 // and been launched through some other means, so it is not in a problematic
15471 // state for observers to see the FIRST_LAUNCH signal.
15472 mHandler.post(new Runnable() {
15474 public void run() {
15475 for (int i = 0; i < mRunningInstalls.size(); i++) {
15476 final PostInstallData data = mRunningInstalls.valueAt(i);
15477 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15480 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15481 // right package; but is it for the right user?
15482 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15483 if (userId == data.res.newUsers[uIndex]) {
15484 if (DEBUG_BACKUP) {
15485 Slog.i(TAG, "Package " + pkgName
15486 + " being restored so deferring FIRST_LAUNCH");
15493 // didn't find it, so not being restored
15494 if (DEBUG_BACKUP) {
15495 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15497 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15502 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15503 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15504 installerPkg, null, userIds);
15507 private abstract class HandlerParams {
15508 private static final int MAX_RETRIES = 4;
15511 * Number of times startCopy() has been attempted and had a non-fatal
15514 private int mRetries = 0;
15516 /** User handle for the user requesting the information or installation. */
15517 private final UserHandle mUser;
15518 String traceMethod;
15521 HandlerParams(UserHandle user) {
15525 UserHandle getUser() {
15529 HandlerParams setTraceMethod(String traceMethod) {
15530 this.traceMethod = traceMethod;
15534 HandlerParams setTraceCookie(int traceCookie) {
15535 this.traceCookie = traceCookie;
15539 final boolean startCopy() {
15542 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15544 if (++mRetries > MAX_RETRIES) {
15545 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15546 mHandler.sendEmptyMessage(MCS_GIVE_UP);
15547 handleServiceError();
15553 } catch (RemoteException e) {
15554 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15555 mHandler.sendEmptyMessage(MCS_RECONNECT);
15558 handleReturnCode();
15562 final void serviceError() {
15563 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15564 handleServiceError();
15565 handleReturnCode();
15568 abstract void handleStartCopy() throws RemoteException;
15569 abstract void handleServiceError();
15570 abstract void handleReturnCode();
15573 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15574 for (File path : paths) {
15576 mcs.clearDirectory(path.getAbsolutePath());
15577 } catch (RemoteException e) {
15582 static class OriginInfo {
15584 * Location where install is coming from, before it has been
15585 * copied/renamed into place. This could be a single monolithic APK
15586 * file, or a cluster directory. This location may be untrusted.
15592 * Flag indicating that {@link #file} or {@link #cid} has already been
15593 * staged, meaning downstream users don't need to defensively copy the
15596 final boolean staged;
15599 * Flag indicating that {@link #file} or {@link #cid} is an already
15600 * installed app that is being moved.
15602 final boolean existing;
15604 final String resolvedPath;
15605 final File resolvedFile;
15607 static OriginInfo fromNothing() {
15608 return new OriginInfo(null, null, false, false);
15611 static OriginInfo fromUntrustedFile(File file) {
15612 return new OriginInfo(file, null, false, false);
15615 static OriginInfo fromExistingFile(File file) {
15616 return new OriginInfo(file, null, false, true);
15619 static OriginInfo fromStagedFile(File file) {
15620 return new OriginInfo(file, null, true, false);
15623 static OriginInfo fromStagedContainer(String cid) {
15624 return new OriginInfo(null, cid, true, false);
15627 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15630 this.staged = staged;
15631 this.existing = existing;
15634 resolvedPath = PackageHelper.getSdDir(cid);
15635 resolvedFile = new File(resolvedPath);
15636 } else if (file != null) {
15637 resolvedPath = file.getAbsolutePath();
15638 resolvedFile = file;
15640 resolvedPath = null;
15641 resolvedFile = null;
15646 static class MoveInfo {
15648 final String fromUuid;
15649 final String toUuid;
15650 final String packageName;
15651 final String dataAppName;
15653 final String seinfo;
15654 final int targetSdkVersion;
15656 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15657 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15658 this.moveId = moveId;
15659 this.fromUuid = fromUuid;
15660 this.toUuid = toUuid;
15661 this.packageName = packageName;
15662 this.dataAppName = dataAppName;
15663 this.appId = appId;
15664 this.seinfo = seinfo;
15665 this.targetSdkVersion = targetSdkVersion;
15669 static class VerificationInfo {
15670 /** A constant used to indicate that a uid value is not present. */
15671 public static final int NO_UID = -1;
15673 /** URI referencing where the package was downloaded from. */
15674 final Uri originatingUri;
15676 /** HTTP referrer URI associated with the originatingURI. */
15677 final Uri referrer;
15679 /** UID of the application that the install request originated from. */
15680 final int originatingUid;
15682 /** UID of application requesting the install */
15683 final int installerUid;
15685 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15686 this.originatingUri = originatingUri;
15687 this.referrer = referrer;
15688 this.originatingUid = originatingUid;
15689 this.installerUid = installerUid;
15693 class InstallParams extends HandlerParams {
15694 final OriginInfo origin;
15695 final MoveInfo move;
15696 final IPackageInstallObserver2 observer;
15698 final String installerPackageName;
15699 final String volumeUuid;
15700 private InstallArgs mArgs;
15702 final String packageAbiOverride;
15703 final String[] grantedRuntimePermissions;
15704 final VerificationInfo verificationInfo;
15705 final Certificate[][] certificates;
15706 final int installReason;
15708 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15709 int installFlags, String installerPackageName, String volumeUuid,
15710 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15711 String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15713 this.origin = origin;
15715 this.observer = observer;
15716 this.installFlags = installFlags;
15717 this.installerPackageName = installerPackageName;
15718 this.volumeUuid = volumeUuid;
15719 this.verificationInfo = verificationInfo;
15720 this.packageAbiOverride = packageAbiOverride;
15721 this.grantedRuntimePermissions = grantedPermissions;
15722 this.certificates = certificates;
15723 this.installReason = installReason;
15727 public String toString() {
15728 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15729 + " file=" + origin.file + " cid=" + origin.cid + "}";
15732 private int installLocationPolicy(PackageInfoLite pkgLite) {
15733 String packageName = pkgLite.packageName;
15734 int installLocation = pkgLite.installLocation;
15735 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15737 synchronized (mPackages) {
15738 // Currently installed package which the new package is attempting to replace or
15739 // null if no such package is installed.
15740 PackageParser.Package installedPkg = mPackages.get(packageName);
15741 // Package which currently owns the data which the new package will own if installed.
15742 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15743 // will be null whereas dataOwnerPkg will contain information about the package
15744 // which was uninstalled while keeping its data.
15745 PackageParser.Package dataOwnerPkg = installedPkg;
15746 if (dataOwnerPkg == null) {
15747 PackageSetting ps = mSettings.mPackages.get(packageName);
15749 dataOwnerPkg = ps.pkg;
15753 if (dataOwnerPkg != null) {
15754 // If installed, the package will get access to data left on the device by its
15755 // predecessor. As a security measure, this is permited only if this is not a
15756 // version downgrade or if the predecessor package is marked as debuggable and
15757 // a downgrade is explicitly requested.
15759 // On debuggable platform builds, downgrades are permitted even for
15760 // non-debuggable packages to make testing easier. Debuggable platform builds do
15761 // not offer security guarantees and thus it's OK to disable some security
15762 // mechanisms to make debugging/testing easier on those builds. However, even on
15763 // debuggable builds downgrades of packages are permitted only if requested via
15764 // installFlags. This is because we aim to keep the behavior of debuggable
15765 // platform builds as close as possible to the behavior of non-debuggable
15766 // platform builds.
15767 final boolean downgradeRequested =
15768 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15769 final boolean packageDebuggable =
15770 (dataOwnerPkg.applicationInfo.flags
15771 & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15772 final boolean downgradePermitted =
15773 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15774 if (!downgradePermitted) {
15776 checkDowngrade(dataOwnerPkg, pkgLite);
15777 } catch (PackageManagerException e) {
15778 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15779 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15784 if (installedPkg != null) {
15785 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15786 // Check for updated system application.
15787 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15789 Slog.w(TAG, "Cannot install update to system app on sdcard");
15790 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15792 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15795 // Install flag overrides everything.
15796 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15798 // If current upgrade specifies particular preference
15799 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15800 // Application explicitly specified internal.
15801 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15802 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15803 // App explictly prefers external. Let policy decide
15805 // Prefer previous location
15806 if (isExternal(installedPkg)) {
15807 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15809 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15813 // Invalid install. Return error code
15814 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15818 // All the special cases have been taken care of.
15819 // Return result based on recommended install location.
15821 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15823 return pkgLite.recommendedInstallLocation;
15827 * Invoke remote method to get package information and install
15828 * location values. Override install location based on default
15829 * policy if needed and then create install arguments based
15830 * on the install location.
15832 public void handleStartCopy() throws RemoteException {
15833 int ret = PackageManager.INSTALL_SUCCEEDED;
15835 // If we're already staged, we've firmly committed to an install location
15836 if (origin.staged) {
15837 if (origin.file != null) {
15838 installFlags |= PackageManager.INSTALL_INTERNAL;
15839 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15840 } else if (origin.cid != null) {
15841 installFlags |= PackageManager.INSTALL_EXTERNAL;
15842 installFlags &= ~PackageManager.INSTALL_INTERNAL;
15844 throw new IllegalStateException("Invalid stage location");
15848 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15849 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15850 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15851 PackageInfoLite pkgLite = null;
15853 if (onInt && onSd) {
15854 // Check if both bits are set.
15855 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15856 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15857 } else if (onSd && ephemeral) {
15858 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external");
15859 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15861 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15862 packageAbiOverride);
15864 if (DEBUG_EPHEMERAL && ephemeral) {
15865 Slog.v(TAG, "pkgLite for install: " + pkgLite);
15869 * If we have too little free space, try to free cache
15870 * before giving up.
15872 if (!origin.staged && pkgLite.recommendedInstallLocation
15873 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15874 // TODO: focus freeing disk space on the target device
15875 final StorageManager storage = StorageManager.from(mContext);
15876 final long lowThreshold = storage.getStorageLowBytes(
15877 Environment.getDataDirectory());
15879 final long sizeBytes = mContainerService.calculateInstalledSize(
15880 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15883 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15884 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15885 installFlags, packageAbiOverride);
15886 } catch (InstallerException e) {
15887 Slog.w(TAG, "Failed to free cache", e);
15891 * The cache free must have deleted the file we
15892 * downloaded to install.
15894 * TODO: fix the "freeCache" call to not delete
15895 * the file we care about.
15897 if (pkgLite.recommendedInstallLocation
15898 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15899 pkgLite.recommendedInstallLocation
15900 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15905 if (ret == PackageManager.INSTALL_SUCCEEDED) {
15906 int loc = pkgLite.recommendedInstallLocation;
15907 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15908 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15909 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15910 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15911 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15912 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15913 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15914 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15915 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15916 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15917 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15918 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15920 // Override with defaults if needed.
15921 loc = installLocationPolicy(pkgLite);
15922 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15923 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15924 } else if (!onSd && !onInt) {
15925 // Override install location with flags
15926 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15927 // Set the flag to install on external media.
15928 installFlags |= PackageManager.INSTALL_EXTERNAL;
15929 installFlags &= ~PackageManager.INSTALL_INTERNAL;
15930 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15931 if (DEBUG_EPHEMERAL) {
15932 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15934 installFlags |= PackageManager.INSTALL_INSTANT_APP;
15935 installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15936 |PackageManager.INSTALL_INTERNAL);
15938 // Make sure the flag for installing on external
15940 installFlags |= PackageManager.INSTALL_INTERNAL;
15941 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15947 final InstallArgs args = createInstallArgs(this);
15950 if (ret == PackageManager.INSTALL_SUCCEEDED) {
15951 // TODO: http://b/22976637
15952 // Apps installed for "all" users use the device owner to verify the app
15953 UserHandle verifierUser = getUser();
15954 if (verifierUser == UserHandle.ALL) {
15955 verifierUser = UserHandle.SYSTEM;
15959 * Determine if we have any installed package verifiers. If we
15960 * do, then we'll defer to them to verify the packages.
15962 final int requiredUid = mRequiredVerifierPackage == null ? -1
15963 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15964 verifierUser.getIdentifier());
15965 final int installerUid =
15966 verificationInfo == null ? -1 : verificationInfo.installerUid;
15967 if (!origin.existing && requiredUid != -1
15968 && isVerificationEnabled(
15969 verifierUser.getIdentifier(), installFlags, installerUid)) {
15970 final Intent verification = new Intent(
15971 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15972 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15973 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15974 PACKAGE_MIME_TYPE);
15975 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15977 // Query all live verifiers based on current user state
15978 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15979 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15981 if (DEBUG_VERIFY) {
15982 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15983 + verification.toString() + " with " + pkgLite.verifiers.length
15984 + " optional verifiers");
15987 final int verificationId = mPendingVerificationToken++;
15989 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15991 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15992 installerPackageName);
15994 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15997 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15998 pkgLite.packageName);
16000 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16001 pkgLite.versionCode);
16003 if (verificationInfo != null) {
16004 if (verificationInfo.originatingUri != null) {
16005 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16006 verificationInfo.originatingUri);
16008 if (verificationInfo.referrer != null) {
16009 verification.putExtra(Intent.EXTRA_REFERRER,
16010 verificationInfo.referrer);
16012 if (verificationInfo.originatingUid >= 0) {
16013 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16014 verificationInfo.originatingUid);
16016 if (verificationInfo.installerUid >= 0) {
16017 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16018 verificationInfo.installerUid);
16022 final PackageVerificationState verificationState = new PackageVerificationState(
16023 requiredUid, args);
16025 mPendingVerification.append(verificationId, verificationState);
16027 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16028 receivers, verificationState);
16030 DeviceIdleController.LocalService idleController = getDeviceIdleController();
16031 final long idleDuration = getVerificationTimeout();
16034 * If any sufficient verifiers were listed in the package
16035 * manifest, attempt to ask them.
16037 if (sufficientVerifiers != null) {
16038 final int N = sufficientVerifiers.size();
16040 Slog.i(TAG, "Additional verifiers required, but none installed.");
16041 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16043 for (int i = 0; i < N; i++) {
16044 final ComponentName verifierComponent = sufficientVerifiers.get(i);
16045 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16046 verifierComponent.getPackageName(), idleDuration,
16047 verifierUser.getIdentifier(), false, "package verifier");
16049 final Intent sufficientIntent = new Intent(verification);
16050 sufficientIntent.setComponent(verifierComponent);
16051 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16056 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16057 mRequiredVerifierPackage, receivers);
16058 if (ret == PackageManager.INSTALL_SUCCEEDED
16059 && mRequiredVerifierPackage != null) {
16060 Trace.asyncTraceBegin(
16061 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16063 * Send the intent to the required verification agent,
16064 * but only start the verification timeout after the
16065 * target BroadcastReceivers have run.
16067 verification.setComponent(requiredVerifierComponent);
16068 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16069 mRequiredVerifierPackage, idleDuration,
16070 verifierUser.getIdentifier(), false, "package verifier");
16071 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16072 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16073 new BroadcastReceiver() {
16075 public void onReceive(Context context, Intent intent) {
16076 final Message msg = mHandler
16077 .obtainMessage(CHECK_PENDING_VERIFICATION);
16078 msg.arg1 = verificationId;
16079 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16081 }, null, 0, null, null);
16084 * We don't want the copy to proceed until verification
16085 * succeeds, so null out this field.
16091 * No package verification is enabled, so immediately start
16092 * the remote call to initiate copy using temporary file.
16094 ret = args.copyApk(mContainerService, true);
16102 void handleReturnCode() {
16103 // If mArgs is null, then MCS couldn't be reached. When it
16104 // reconnects, it will try again to install. At that point, this
16106 if (mArgs != null) {
16107 processPendingInstall(mArgs, mRet);
16112 void handleServiceError() {
16113 mArgs = createInstallArgs(this);
16114 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16117 public boolean isForwardLocked() {
16118 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16123 * Used during creation of InstallArgs
16125 * @param installFlags package installation flags
16126 * @return true if should be installed on external storage
16128 private static boolean installOnExternalAsec(int installFlags) {
16129 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16132 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16139 * Used during creation of InstallArgs
16141 * @param installFlags package installation flags
16142 * @return true if should be installed as forward locked
16144 private static boolean installForwardLocked(int installFlags) {
16145 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16148 private InstallArgs createInstallArgs(InstallParams params) {
16149 if (params.move != null) {
16150 return new MoveInstallArgs(params);
16151 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16152 return new AsecInstallArgs(params);
16154 return new FileInstallArgs(params);
16159 * Create args that describe an existing installed package. Typically used
16160 * when cleaning up old installs, or used as a move source.
16162 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16163 String resourcePath, String[] instructionSets) {
16164 final boolean isInAsec;
16165 if (installOnExternalAsec(installFlags)) {
16166 /* Apps on SD card are always in ASEC containers. */
16168 } else if (installForwardLocked(installFlags)
16169 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16171 * Forward-locked apps are only in ASEC containers if they're the
16180 return new AsecInstallArgs(codePath, instructionSets,
16181 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16183 return new FileInstallArgs(codePath, resourcePath, instructionSets);
16187 static abstract class InstallArgs {
16188 /** @see InstallParams#origin */
16189 final OriginInfo origin;
16190 /** @see InstallParams#move */
16191 final MoveInfo move;
16193 final IPackageInstallObserver2 observer;
16194 // Always refers to PackageManager flags only
16195 final int installFlags;
16196 final String installerPackageName;
16197 final String volumeUuid;
16198 final UserHandle user;
16199 final String abiOverride;
16200 final String[] installGrantPermissions;
16201 /** If non-null, drop an async trace when the install completes */
16202 final String traceMethod;
16203 final int traceCookie;
16204 final Certificate[][] certificates;
16205 final int installReason;
16207 // The list of instruction sets supported by this app. This is currently
16208 // only used during the rmdex() phase to clean up resources. We can get rid of this
16209 // if we move dex files under the common app path.
16210 /* nullable */ String[] instructionSets;
16212 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16213 int installFlags, String installerPackageName, String volumeUuid,
16214 UserHandle user, String[] instructionSets,
16215 String abiOverride, String[] installGrantPermissions,
16216 String traceMethod, int traceCookie, Certificate[][] certificates,
16217 int installReason) {
16218 this.origin = origin;
16220 this.installFlags = installFlags;
16221 this.observer = observer;
16222 this.installerPackageName = installerPackageName;
16223 this.volumeUuid = volumeUuid;
16225 this.instructionSets = instructionSets;
16226 this.abiOverride = abiOverride;
16227 this.installGrantPermissions = installGrantPermissions;
16228 this.traceMethod = traceMethod;
16229 this.traceCookie = traceCookie;
16230 this.certificates = certificates;
16231 this.installReason = installReason;
16234 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16235 abstract int doPreInstall(int status);
16238 * Rename package into final resting place. All paths on the given
16239 * scanned package should be updated to reflect the rename.
16241 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16242 abstract int doPostInstall(int status, int uid);
16244 /** @see PackageSettingBase#codePathString */
16245 abstract String getCodePath();
16246 /** @see PackageSettingBase#resourcePathString */
16247 abstract String getResourcePath();
16249 // Need installer lock especially for dex file removal.
16250 abstract void cleanUpResourcesLI();
16251 abstract boolean doPostDeleteLI(boolean delete);
16254 * Called before the source arguments are copied. This is used mostly
16255 * for MoveParams when it needs to read the source file to put it in the
16259 return PackageManager.INSTALL_SUCCEEDED;
16263 * Called after the source arguments are copied. This is used mostly for
16264 * MoveParams when it needs to read the source file to put it in the
16267 int doPostCopy(int uid) {
16268 return PackageManager.INSTALL_SUCCEEDED;
16271 protected boolean isFwdLocked() {
16272 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16275 protected boolean isExternalAsec() {
16276 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16279 protected boolean isEphemeral() {
16280 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16283 UserHandle getUser() {
16288 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16289 if (!allCodePaths.isEmpty()) {
16290 if (instructionSets == null) {
16291 throw new IllegalStateException("instructionSet == null");
16293 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16294 for (String codePath : allCodePaths) {
16295 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16297 mInstaller.rmdex(codePath, dexCodeInstructionSet);
16298 } catch (InstallerException ignored) {
16306 * Logic to handle installation of non-ASEC applications, including copying
16307 * and renaming logic.
16309 class FileInstallArgs extends InstallArgs {
16310 private File codeFile;
16311 private File resourceFile;
16313 // Example topology:
16314 // /data/app/com.example/base.apk
16315 // /data/app/com.example/split_foo.apk
16316 // /data/app/com.example/lib/arm/libfoo.so
16317 // /data/app/com.example/lib/arm64/libfoo.so
16318 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16321 FileInstallArgs(InstallParams params) {
16322 super(params.origin, params.move, params.observer, params.installFlags,
16323 params.installerPackageName, params.volumeUuid,
16324 params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16325 params.grantedRuntimePermissions,
16326 params.traceMethod, params.traceCookie, params.certificates,
16327 params.installReason);
16328 if (isFwdLocked()) {
16329 throw new IllegalArgumentException("Forward locking only supported in ASEC");
16333 /** Existing install */
16334 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16335 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16336 null, null, null, 0, null /*certificates*/,
16337 PackageManager.INSTALL_REASON_UNKNOWN);
16338 this.codeFile = (codePath != null) ? new File(codePath) : null;
16339 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16342 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16343 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16345 return doCopyApk(imcs, temp);
16347 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16351 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16352 if (origin.staged) {
16353 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16354 codeFile = origin.file;
16355 resourceFile = origin.file;
16356 return PackageManager.INSTALL_SUCCEEDED;
16360 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16361 final File tempDir =
16362 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16363 codeFile = tempDir;
16364 resourceFile = tempDir;
16365 } catch (IOException e) {
16366 Slog.w(TAG, "Failed to create copy file: " + e);
16367 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16370 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16372 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16373 if (!FileUtils.isValidExtFilename(name)) {
16374 throw new IllegalArgumentException("Invalid filename: " + name);
16377 final File file = new File(codeFile, name);
16378 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16379 O_RDWR | O_CREAT, 0644);
16380 Os.chmod(file.getAbsolutePath(), 0644);
16381 return new ParcelFileDescriptor(fd);
16382 } catch (ErrnoException e) {
16383 throw new RemoteException("Failed to open: " + e.getMessage());
16388 int ret = PackageManager.INSTALL_SUCCEEDED;
16389 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16390 if (ret != PackageManager.INSTALL_SUCCEEDED) {
16391 Slog.e(TAG, "Failed to copy package");
16395 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16396 NativeLibraryHelper.Handle handle = null;
16398 handle = NativeLibraryHelper.Handle.create(codeFile);
16399 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16401 } catch (IOException e) {
16402 Slog.e(TAG, "Copying native libraries failed", e);
16403 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16405 IoUtils.closeQuietly(handle);
16411 int doPreInstall(int status) {
16412 if (status != PackageManager.INSTALL_SUCCEEDED) {
16418 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16419 if (status != PackageManager.INSTALL_SUCCEEDED) {
16424 final File targetDir = codeFile.getParentFile();
16425 final File beforeCodeFile = codeFile;
16426 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16428 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16430 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16431 } catch (ErrnoException e) {
16432 Slog.w(TAG, "Failed to rename", e);
16436 if (!SELinux.restoreconRecursive(afterCodeFile)) {
16437 Slog.w(TAG, "Failed to restorecon");
16441 // Reflect the rename internally
16442 codeFile = afterCodeFile;
16443 resourceFile = afterCodeFile;
16445 // Reflect the rename in scanned details
16446 pkg.setCodePath(afterCodeFile.getAbsolutePath());
16447 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16448 afterCodeFile, pkg.baseCodePath));
16449 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16450 afterCodeFile, pkg.splitCodePaths));
16452 // Reflect the rename in app info
16453 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16454 pkg.setApplicationInfoCodePath(pkg.codePath);
16455 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16456 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16457 pkg.setApplicationInfoResourcePath(pkg.codePath);
16458 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16459 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16464 int doPostInstall(int status, int uid) {
16465 if (status != PackageManager.INSTALL_SUCCEEDED) {
16472 String getCodePath() {
16473 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16477 String getResourcePath() {
16478 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16481 private boolean cleanUp() {
16482 if (codeFile == null || !codeFile.exists()) {
16486 removeCodePathLI(codeFile);
16488 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16489 resourceFile.delete();
16495 void cleanUpResourcesLI() {
16496 // Try enumerating all code paths before deleting
16497 List<String> allCodePaths = Collections.EMPTY_LIST;
16498 if (codeFile != null && codeFile.exists()) {
16500 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16501 allCodePaths = pkg.getAllCodePaths();
16502 } catch (PackageParserException e) {
16503 // Ignored; we tried our best
16508 removeDexFiles(allCodePaths, instructionSets);
16511 boolean doPostDeleteLI(boolean delete) {
16512 // XXX err, shouldn't we respect the delete flag?
16513 cleanUpResourcesLI();
16518 private boolean isAsecExternal(String cid) {
16519 final String asecPath = PackageHelper.getSdFilesystem(cid);
16520 return !asecPath.startsWith(mAsecInternalPath);
16523 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16524 PackageManagerException {
16526 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16527 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16528 throw new PackageManagerException(copyRet, message);
16534 * Extract the StorageManagerService "container ID" from the full code path of an
16537 static String cidFromCodePath(String fullCodePath) {
16538 int eidx = fullCodePath.lastIndexOf("/");
16539 String subStr1 = fullCodePath.substring(0, eidx);
16540 int sidx = subStr1.lastIndexOf("/");
16541 return subStr1.substring(sidx+1, eidx);
16545 * Logic to handle installation of ASEC applications, including copying and
16548 class AsecInstallArgs extends InstallArgs {
16549 static final String RES_FILE_NAME = "pkg.apk";
16550 static final String PUBLIC_RES_FILE_NAME = "res.zip";
16553 String packagePath;
16554 String resourcePath;
16557 AsecInstallArgs(InstallParams params) {
16558 super(params.origin, params.move, params.observer, params.installFlags,
16559 params.installerPackageName, params.volumeUuid,
16560 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16561 params.grantedRuntimePermissions,
16562 params.traceMethod, params.traceCookie, params.certificates,
16563 params.installReason);
16566 /** Existing install */
16567 AsecInstallArgs(String fullCodePath, String[] instructionSets,
16568 boolean isExternal, boolean isForwardLocked) {
16569 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16570 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16571 instructionSets, null, null, null, 0, null /*certificates*/,
16572 PackageManager.INSTALL_REASON_UNKNOWN);
16573 // Hackily pretend we're still looking at a full code path
16574 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16575 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16578 // Extract cid from fullCodePath
16579 int eidx = fullCodePath.lastIndexOf("/");
16580 String subStr1 = fullCodePath.substring(0, eidx);
16581 int sidx = subStr1.lastIndexOf("/");
16582 cid = subStr1.substring(sidx+1, eidx);
16583 setMountPath(subStr1);
16586 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16587 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16588 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16589 instructionSets, null, null, null, 0, null /*certificates*/,
16590 PackageManager.INSTALL_REASON_UNKNOWN);
16592 setMountPath(PackageHelper.getSdDir(cid));
16595 void createCopyFile() {
16596 cid = mInstallerService.allocateExternalStageCidLegacy();
16599 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16600 if (origin.staged && origin.cid != null) {
16601 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16603 setMountPath(PackageHelper.getSdDir(cid));
16604 return PackageManager.INSTALL_SUCCEEDED;
16611 * Pre-emptively destroy the container since it's destroyed if
16612 * copying fails due to it existing anyway.
16614 PackageHelper.destroySdDir(cid);
16617 final String newMountPath = imcs.copyPackageToContainer(
16618 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16619 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16621 if (newMountPath != null) {
16622 setMountPath(newMountPath);
16623 return PackageManager.INSTALL_SUCCEEDED;
16625 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16630 String getCodePath() {
16631 return packagePath;
16635 String getResourcePath() {
16636 return resourcePath;
16639 int doPreInstall(int status) {
16640 if (status != PackageManager.INSTALL_SUCCEEDED) {
16641 // Destroy container
16642 PackageHelper.destroySdDir(cid);
16644 boolean mounted = PackageHelper.isContainerMounted(cid);
16646 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16647 Process.SYSTEM_UID);
16648 if (newMountPath != null) {
16649 setMountPath(newMountPath);
16651 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16658 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16659 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16660 String newMountPath = null;
16661 if (PackageHelper.isContainerMounted(cid)) {
16662 // Unmount the container
16663 if (!PackageHelper.unMountSdDir(cid)) {
16664 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16668 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16669 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16670 " which might be stale. Will try to clean up.");
16671 // Clean up the stale container and proceed to recreate.
16672 if (!PackageHelper.destroySdDir(newCacheId)) {
16673 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16676 // Successfully cleaned up stale container. Try to rename again.
16677 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16678 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16679 + " inspite of cleaning it up.");
16683 if (!PackageHelper.isContainerMounted(newCacheId)) {
16684 Slog.w(TAG, "Mounting container " + newCacheId);
16685 newMountPath = PackageHelper.mountSdDir(newCacheId,
16686 getEncryptKey(), Process.SYSTEM_UID);
16688 newMountPath = PackageHelper.getSdDir(newCacheId);
16690 if (newMountPath == null) {
16691 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
16694 Log.i(TAG, "Succesfully renamed " + cid +
16695 " to " + newCacheId +
16696 " at new path: " + newMountPath);
16699 final File beforeCodeFile = new File(packagePath);
16700 setMountPath(newMountPath);
16701 final File afterCodeFile = new File(packagePath);
16703 // Reflect the rename in scanned details
16704 pkg.setCodePath(afterCodeFile.getAbsolutePath());
16705 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16706 afterCodeFile, pkg.baseCodePath));
16707 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16708 afterCodeFile, pkg.splitCodePaths));
16710 // Reflect the rename in app info
16711 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16712 pkg.setApplicationInfoCodePath(pkg.codePath);
16713 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16714 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16715 pkg.setApplicationInfoResourcePath(pkg.codePath);
16716 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16717 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16722 private void setMountPath(String mountPath) {
16723 final File mountFile = new File(mountPath);
16725 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16726 if (monolithicFile.exists()) {
16727 packagePath = monolithicFile.getAbsolutePath();
16728 if (isFwdLocked()) {
16729 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16731 resourcePath = packagePath;
16734 packagePath = mountFile.getAbsolutePath();
16735 resourcePath = packagePath;
16739 int doPostInstall(int status, int uid) {
16740 if (status != PackageManager.INSTALL_SUCCEEDED) {
16743 final int groupOwner;
16744 final String protectedFile;
16745 if (isFwdLocked()) {
16746 groupOwner = UserHandle.getSharedAppGid(uid);
16747 protectedFile = RES_FILE_NAME;
16750 protectedFile = null;
16753 if (uid < Process.FIRST_APPLICATION_UID
16754 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16755 Slog.e(TAG, "Failed to finalize " + cid);
16756 PackageHelper.destroySdDir(cid);
16757 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16760 boolean mounted = PackageHelper.isContainerMounted(cid);
16762 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16768 private void cleanUp() {
16769 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16771 // Destroy secure container
16772 PackageHelper.destroySdDir(cid);
16775 private List<String> getAllCodePaths() {
16776 final File codeFile = new File(getCodePath());
16777 if (codeFile != null && codeFile.exists()) {
16779 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16780 return pkg.getAllCodePaths();
16781 } catch (PackageParserException e) {
16782 // Ignored; we tried our best
16785 return Collections.EMPTY_LIST;
16788 void cleanUpResourcesLI() {
16789 // Enumerate all code paths before deleting
16790 cleanUpResourcesLI(getAllCodePaths());
16793 private void cleanUpResourcesLI(List<String> allCodePaths) {
16795 removeDexFiles(allCodePaths, instructionSets);
16798 String getPackageName() {
16799 return getAsecPackageName(cid);
16802 boolean doPostDeleteLI(boolean delete) {
16803 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16804 final List<String> allCodePaths = getAllCodePaths();
16805 boolean mounted = PackageHelper.isContainerMounted(cid);
16808 if (PackageHelper.unMountSdDir(cid)) {
16812 if (!mounted && delete) {
16813 cleanUpResourcesLI(allCodePaths);
16820 if (isFwdLocked()) {
16821 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16822 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16823 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16827 return PackageManager.INSTALL_SUCCEEDED;
16831 int doPostCopy(int uid) {
16832 if (isFwdLocked()) {
16833 if (uid < Process.FIRST_APPLICATION_UID
16834 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16836 Slog.e(TAG, "Failed to finalize " + cid);
16837 PackageHelper.destroySdDir(cid);
16838 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16842 return PackageManager.INSTALL_SUCCEEDED;
16847 * Logic to handle movement of existing installed applications.
16849 class MoveInstallArgs extends InstallArgs {
16850 private File codeFile;
16851 private File resourceFile;
16854 MoveInstallArgs(InstallParams params) {
16855 super(params.origin, params.move, params.observer, params.installFlags,
16856 params.installerPackageName, params.volumeUuid,
16857 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16858 params.grantedRuntimePermissions,
16859 params.traceMethod, params.traceCookie, params.certificates,
16860 params.installReason);
16863 int copyApk(IMediaContainerService imcs, boolean temp) {
16864 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16865 + move.fromUuid + " to " + move.toUuid);
16866 synchronized (mInstaller) {
16868 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16869 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16870 } catch (InstallerException e) {
16871 Slog.w(TAG, "Failed to move app", e);
16872 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16876 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16877 resourceFile = codeFile;
16878 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16880 return PackageManager.INSTALL_SUCCEEDED;
16883 int doPreInstall(int status) {
16884 if (status != PackageManager.INSTALL_SUCCEEDED) {
16885 cleanUp(move.toUuid);
16890 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16891 if (status != PackageManager.INSTALL_SUCCEEDED) {
16892 cleanUp(move.toUuid);
16896 // Reflect the move in app info
16897 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16898 pkg.setApplicationInfoCodePath(pkg.codePath);
16899 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16900 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16901 pkg.setApplicationInfoResourcePath(pkg.codePath);
16902 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16903 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16908 int doPostInstall(int status, int uid) {
16909 if (status == PackageManager.INSTALL_SUCCEEDED) {
16910 cleanUp(move.fromUuid);
16912 cleanUp(move.toUuid);
16918 String getCodePath() {
16919 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16923 String getResourcePath() {
16924 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16927 private boolean cleanUp(String volumeUuid) {
16928 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16930 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16931 final int[] userIds = sUserManager.getUserIds();
16932 synchronized (mInstallLock) {
16933 // Clean up both app data and code
16934 // All package moves are frozen until finished
16935 for (int userId : userIds) {
16937 mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16938 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16939 } catch (InstallerException e) {
16940 Slog.w(TAG, String.valueOf(e));
16943 removeCodePathLI(codeFile);
16948 void cleanUpResourcesLI() {
16949 throw new UnsupportedOperationException();
16952 boolean doPostDeleteLI(boolean delete) {
16953 throw new UnsupportedOperationException();
16957 static String getAsecPackageName(String packageCid) {
16958 int idx = packageCid.lastIndexOf("-");
16962 return packageCid.substring(0, idx);
16965 // Utility method used to create code paths based on package name and available index.
16966 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16967 String idxStr = "";
16969 // Fall back to default value of idx=1 if prefix is not
16970 // part of oldCodePath
16971 if (oldCodePath != null) {
16972 String subStr = oldCodePath;
16973 // Drop the suffix right away
16974 if (suffix != null && subStr.endsWith(suffix)) {
16975 subStr = subStr.substring(0, subStr.length() - suffix.length());
16977 // If oldCodePath already contains prefix find out the
16978 // ending index to either increment or decrement.
16979 int sidx = subStr.lastIndexOf(prefix);
16981 subStr = subStr.substring(sidx + prefix.length());
16982 if (subStr != null) {
16983 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16984 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16987 idx = Integer.parseInt(subStr);
16993 } catch(NumberFormatException e) {
16998 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16999 return prefix + idxStr;
17002 private File getNextCodePath(File targetDir, String packageName) {
17004 SecureRandom random = new SecureRandom();
17005 byte[] bytes = new byte[16];
17007 random.nextBytes(bytes);
17008 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17009 result = new File(targetDir, packageName + "-" + suffix);
17010 } while (result.exists());
17014 // Utility method that returns the relative package path with respect
17015 // to the installation directory. Like say for /data/data/com.test-1.apk
17016 // string com.test-1 is returned.
17017 static String deriveCodePathName(String codePath) {
17018 if (codePath == null) {
17021 final File codeFile = new File(codePath);
17022 final String name = codeFile.getName();
17023 if (codeFile.isDirectory()) {
17025 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17026 final int lastDot = name.lastIndexOf('.');
17027 return name.substring(0, lastDot);
17029 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17034 static class PackageInstalledInfo {
17037 // The set of users that originally had this package installed.
17039 // The set of users that now have this package installed.
17041 PackageParser.Package pkg;
17044 PackageRemovedInfo removedInfo;
17045 ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17047 public void setError(int code, String msg) {
17048 setReturnCode(code);
17049 setReturnMessage(msg);
17053 public void setError(String msg, PackageParserException e) {
17054 setReturnCode(e.error);
17055 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17056 Slog.w(TAG, msg, e);
17059 public void setError(String msg, PackageManagerException e) {
17060 returnCode = e.error;
17061 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17062 Slog.w(TAG, msg, e);
17065 public void setReturnCode(int returnCode) {
17066 this.returnCode = returnCode;
17067 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17068 for (int i = 0; i < childCount; i++) {
17069 addedChildPackages.valueAt(i).returnCode = returnCode;
17073 private void setReturnMessage(String returnMsg) {
17074 this.returnMsg = returnMsg;
17075 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17076 for (int i = 0; i < childCount; i++) {
17077 addedChildPackages.valueAt(i).returnMsg = returnMsg;
17081 // In some error cases we want to convey more info back to the observer
17082 String origPackage;
17083 String origPermission;
17087 * Install a non-existing package.
17089 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17090 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17091 PackageInstalledInfo res, int installReason) {
17092 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17094 // Remember this for later, in case we need to rollback this install
17095 String pkgName = pkg.packageName;
17097 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17099 synchronized(mPackages) {
17100 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17101 if (renamedPackage != null) {
17102 // A package with the same name is already installed, though
17103 // it has been renamed to an older name. The package we
17104 // are trying to install should be installed as an update to
17105 // the existing one, but that has not been requested, so bail.
17106 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17107 + " without first uninstalling package running as "
17111 if (mPackages.containsKey(pkgName)) {
17112 // Don't allow installation over an existing package with the same name.
17113 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17114 + " without first uninstalling.");
17120 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17121 System.currentTimeMillis(), user);
17123 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17125 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17126 prepareAppDataAfterInstallLIF(newPackage);
17129 // Remove package from internal structures, but keep around any
17130 // data that might have already existed
17131 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17132 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17134 } catch (PackageManagerException e) {
17135 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17138 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17141 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17142 // Can't rotate keys during boot or if sharedUser.
17143 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17144 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17147 // app is using upgradeKeySets; make sure all are valid
17148 KeySetManagerService ksms = mSettings.mKeySetManagerService;
17149 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17150 for (int i = 0; i < upgradeKeySets.length; i++) {
17151 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17152 Slog.wtf(TAG, "Package "
17153 + (oldPs.name != null ? oldPs.name : "<null>")
17154 + " contains upgrade-key-set reference to unknown key-set: "
17155 + upgradeKeySets[i]
17156 + " reverting to signatures check.");
17163 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17164 // Upgrade keysets are being used. Determine if new package has a superset of the
17166 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17167 KeySetManagerService ksms = mSettings.mKeySetManagerService;
17168 for (int i = 0; i < upgradeKeySets.length; i++) {
17169 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17170 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17177 private static void updateDigest(MessageDigest digest, File file) throws IOException {
17178 try (DigestInputStream digestStream =
17179 new DigestInputStream(new FileInputStream(file), digest)) {
17180 while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17184 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17185 UserHandle user, String installerPackageName, PackageInstalledInfo res,
17186 int installReason) {
17187 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17189 final PackageParser.Package oldPackage;
17190 final PackageSetting ps;
17191 final String pkgName = pkg.packageName;
17192 final int[] allUsers;
17193 final int[] installedUsers;
17195 synchronized(mPackages) {
17196 oldPackage = mPackages.get(pkgName);
17197 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17199 // don't allow upgrade to target a release SDK from a pre-release SDK
17200 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17201 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17202 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17203 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17204 if (oldTargetsPreRelease
17205 && !newTargetsPreRelease
17206 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17207 Slog.w(TAG, "Can't install package targeting released sdk");
17208 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17212 ps = mSettings.mPackages.get(pkgName);
17214 // verify signatures are valid
17215 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17216 if (!checkUpgradeKeySetLP(ps, pkg)) {
17217 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17218 "New package not signed by keys specified by upgrade-keysets: "
17223 // default to original signature matching
17224 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17225 != PackageManager.SIGNATURE_MATCH) {
17226 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17227 "New package has a different signature: " + pkgName);
17232 // don't allow a system upgrade unless the upgrade hash matches
17233 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17234 byte[] digestBytes = null;
17236 final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17237 updateDigest(digest, new File(pkg.baseCodePath));
17238 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17239 for (String path : pkg.splitCodePaths) {
17240 updateDigest(digest, new File(path));
17243 digestBytes = digest.digest();
17244 } catch (NoSuchAlgorithmException | IOException e) {
17245 res.setError(INSTALL_FAILED_INVALID_APK,
17246 "Could not compute hash: " + pkgName);
17249 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17250 res.setError(INSTALL_FAILED_INVALID_APK,
17251 "New package fails restrict-update check: " + pkgName);
17254 // retain upgrade restriction
17255 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17258 // Check for shared user id changes
17259 String invalidPackageName =
17260 getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17261 if (invalidPackageName != null) {
17262 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17263 "Package " + invalidPackageName + " tried to change user "
17264 + oldPackage.mSharedUserId);
17268 // In case of rollback, remember per-user/profile install state
17269 allUsers = sUserManager.getUserIds();
17270 installedUsers = ps.queryInstalledUsers(allUsers, true);
17272 // don't allow an upgrade from full to ephemeral
17273 if (isInstantApp) {
17274 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17275 for (int currentUser : allUsers) {
17276 if (!ps.getInstantApp(currentUser)) {
17277 // can't downgrade from full to instant
17278 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17279 + " for user: " + currentUser);
17280 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17284 } else if (!ps.getInstantApp(user.getIdentifier())) {
17285 // can't downgrade from full to instant
17286 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17287 + " for user: " + user.getIdentifier());
17288 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17294 // Update what is removed
17295 res.removedInfo = new PackageRemovedInfo(this);
17296 res.removedInfo.uid = oldPackage.applicationInfo.uid;
17297 res.removedInfo.removedPackage = oldPackage.packageName;
17298 res.removedInfo.installerPackageName = ps.installerPackageName;
17299 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17300 res.removedInfo.isUpdate = true;
17301 res.removedInfo.origUsers = installedUsers;
17302 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17303 for (int i = 0; i < installedUsers.length; i++) {
17304 final int userId = installedUsers[i];
17305 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17308 final int childCount = (oldPackage.childPackages != null)
17309 ? oldPackage.childPackages.size() : 0;
17310 for (int i = 0; i < childCount; i++) {
17311 boolean childPackageUpdated = false;
17312 PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17313 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17314 if (res.addedChildPackages != null) {
17315 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17316 if (childRes != null) {
17317 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17318 childRes.removedInfo.removedPackage = childPkg.packageName;
17319 if (childPs != null) {
17320 childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17322 childRes.removedInfo.isUpdate = true;
17323 childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17324 childPackageUpdated = true;
17327 if (!childPackageUpdated) {
17328 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17329 childRemovedRes.removedPackage = childPkg.packageName;
17330 if (childPs != null) {
17331 childRemovedRes.installerPackageName = childPs.installerPackageName;
17333 childRemovedRes.isUpdate = false;
17334 childRemovedRes.dataRemoved = true;
17335 synchronized (mPackages) {
17336 if (childPs != null) {
17337 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17340 if (res.removedInfo.removedChildPackages == null) {
17341 res.removedInfo.removedChildPackages = new ArrayMap<>();
17343 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17347 boolean sysPkg = (isSystemApp(oldPackage));
17349 // Set the system/privileged flags as needed
17350 final boolean privileged =
17351 (oldPackage.applicationInfo.privateFlags
17352 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17353 final int systemPolicyFlags = policyFlags
17354 | PackageParser.PARSE_IS_SYSTEM
17355 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17357 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17358 user, allUsers, installerPackageName, res, installReason);
17360 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17361 user, allUsers, installerPackageName, res, installReason);
17366 public List<String> getPreviousCodePaths(String packageName) {
17367 final int callingUid = Binder.getCallingUid();
17368 final List<String> result = new ArrayList<>();
17369 if (getInstantAppPackageName(callingUid) != null) {
17372 final PackageSetting ps = mSettings.mPackages.get(packageName);
17374 && ps.oldCodePaths != null
17375 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17376 result.addAll(ps.oldCodePaths);
17381 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17382 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17383 int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17384 int installReason) {
17385 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17388 String pkgName = deletedPackage.packageName;
17389 boolean deletedPkg = true;
17390 boolean addedPkg = false;
17391 boolean updatedSettings = false;
17392 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17393 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17394 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17396 final long origUpdateTime = (pkg.mExtras != null)
17397 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17399 // First delete the existing package while retaining the data directory
17400 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17401 res.removedInfo, true, pkg)) {
17402 // If the existing package wasn't successfully deleted
17403 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17404 deletedPkg = false;
17406 // Successfully deleted the old package; proceed with replace.
17408 // If deleted package lived in a container, give users a chance to
17409 // relinquish resources before killing.
17410 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17411 if (DEBUG_INSTALL) {
17412 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17414 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17415 final ArrayList<String> pkgList = new ArrayList<String>(1);
17416 pkgList.add(deletedPackage.applicationInfo.packageName);
17417 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17420 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17421 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17422 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17425 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17426 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17427 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17430 // Update the in-memory copy of the previous code paths.
17431 PackageSetting ps = mSettings.mPackages.get(pkgName);
17433 if (ps.oldCodePaths == null) {
17434 ps.oldCodePaths = new ArraySet<>();
17436 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17437 if (deletedPackage.splitCodePaths != null) {
17438 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17441 ps.oldCodePaths = null;
17443 if (ps.childPackageNames != null) {
17444 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17445 final String childPkgName = ps.childPackageNames.get(i);
17446 final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17447 childPs.oldCodePaths = ps.oldCodePaths;
17450 // set instant app status, but, only if it's explicitly specified
17451 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17452 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17453 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17454 prepareAppDataAfterInstallLIF(newPackage);
17456 mDexManager.notifyPackageUpdated(newPackage.packageName,
17457 newPackage.baseCodePath, newPackage.splitCodePaths);
17458 } catch (PackageManagerException e) {
17459 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17463 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17464 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17466 // Revert all internal state mutations and added folders for the failed install
17468 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17469 res.removedInfo, true, null);
17472 // Restore the old package
17474 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17475 File restoreFile = new File(deletedPackage.codePath);
17476 // Parse old package
17477 boolean oldExternal = isExternal(deletedPackage);
17478 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
17479 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17480 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17481 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17483 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17485 } catch (PackageManagerException e) {
17486 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17491 synchronized (mPackages) {
17492 // Ensure the installer package name up to date
17493 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17495 // Update permissions for restored package
17496 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17498 mSettings.writeLPr();
17501 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17504 synchronized (mPackages) {
17505 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17507 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17508 if (res.removedInfo.removedChildPackages != null) {
17509 final int childCount = res.removedInfo.removedChildPackages.size();
17510 // Iterate in reverse as we may modify the collection
17511 for (int i = childCount - 1; i >= 0; i--) {
17512 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17513 if (res.addedChildPackages.containsKey(childPackageName)) {
17514 res.removedInfo.removedChildPackages.removeAt(i);
17516 PackageRemovedInfo childInfo = res.removedInfo
17517 .removedChildPackages.valueAt(i);
17518 childInfo.removedForAllUsers = mPackages.get(
17519 childInfo.removedPackage) == null;
17528 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17529 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17530 int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17531 int installReason) {
17532 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17533 + ", old=" + deletedPackage);
17535 final boolean disabledSystem;
17537 // Remove existing system package
17538 removePackageLI(deletedPackage, true);
17540 synchronized (mPackages) {
17541 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17543 if (!disabledSystem) {
17544 // We didn't need to disable the .apk as a current system package,
17545 // which means we are replacing another update that is already
17546 // installed. We need to make sure to delete the older one's .apk.
17547 res.removedInfo.args = createInstallArgsForExisting(0,
17548 deletedPackage.applicationInfo.getCodePath(),
17549 deletedPackage.applicationInfo.getResourcePath(),
17550 getAppDexInstructionSets(deletedPackage.applicationInfo));
17552 res.removedInfo.args = null;
17555 // Successfully disabled the old package. Now proceed with re-installation
17556 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17557 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17558 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17560 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17561 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17562 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17564 PackageParser.Package newPackage = null;
17566 // Add the package to the internal data structures
17567 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17569 // Set the update and install times
17570 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17571 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17572 System.currentTimeMillis());
17574 // Update the package dynamic state if succeeded
17575 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17576 // Now that the install succeeded make sure we remove data
17577 // directories for any child package the update removed.
17578 final int deletedChildCount = (deletedPackage.childPackages != null)
17579 ? deletedPackage.childPackages.size() : 0;
17580 final int newChildCount = (newPackage.childPackages != null)
17581 ? newPackage.childPackages.size() : 0;
17582 for (int i = 0; i < deletedChildCount; i++) {
17583 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17584 boolean childPackageDeleted = true;
17585 for (int j = 0; j < newChildCount; j++) {
17586 PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17587 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17588 childPackageDeleted = false;
17592 if (childPackageDeleted) {
17593 PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17594 deletedChildPkg.packageName);
17595 if (ps != null && res.removedInfo.removedChildPackages != null) {
17596 PackageRemovedInfo removedChildRes = res.removedInfo
17597 .removedChildPackages.get(deletedChildPkg.packageName);
17598 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17599 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17604 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17606 prepareAppDataAfterInstallLIF(newPackage);
17608 mDexManager.notifyPackageUpdated(newPackage.packageName,
17609 newPackage.baseCodePath, newPackage.splitCodePaths);
17611 } catch (PackageManagerException e) {
17612 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17613 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17616 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17617 // Re installation failed. Restore old information
17618 // Remove new pkg information
17619 if (newPackage != null) {
17620 removeInstalledPackageLI(newPackage, true);
17622 // Add back the old system package
17624 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17625 } catch (PackageManagerException e) {
17626 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17629 synchronized (mPackages) {
17630 if (disabledSystem) {
17631 enableSystemPackageLPw(deletedPackage);
17634 // Ensure the installer package name up to date
17635 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17637 // Update permissions for restored package
17638 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17640 mSettings.writeLPr();
17643 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17644 + " after failed upgrade");
17649 * Checks whether the parent or any of the child packages have a change shared
17650 * user. For a package to be a valid update the shred users of the parent and
17651 * the children should match. We may later support changing child shared users.
17652 * @param oldPkg The updated package.
17653 * @param newPkg The update package.
17654 * @return The shared user that change between the versions.
17656 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17657 PackageParser.Package newPkg) {
17658 // Check parent shared user
17659 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17660 return newPkg.packageName;
17662 // Check child shared users
17663 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17664 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17665 for (int i = 0; i < newChildCount; i++) {
17666 PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17667 // If this child was present, did it have the same shared user?
17668 for (int j = 0; j < oldChildCount; j++) {
17669 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17670 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17671 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17672 return newChildPkg.packageName;
17679 private void removeNativeBinariesLI(PackageSetting ps) {
17680 // Remove the lib path for the parent package
17682 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17683 // Remove the lib path for the child packages
17684 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17685 for (int i = 0; i < childCount; i++) {
17686 PackageSetting childPs = null;
17687 synchronized (mPackages) {
17688 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17690 if (childPs != null) {
17691 NativeLibraryHelper.removeNativeBinariesLI(childPs
17692 .legacyNativeLibraryPathString);
17698 private void enableSystemPackageLPw(PackageParser.Package pkg) {
17699 // Enable the parent package
17700 mSettings.enableSystemPackageLPw(pkg.packageName);
17701 // Enable the child packages
17702 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17703 for (int i = 0; i < childCount; i++) {
17704 PackageParser.Package childPkg = pkg.childPackages.get(i);
17705 mSettings.enableSystemPackageLPw(childPkg.packageName);
17709 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17710 PackageParser.Package newPkg) {
17711 // Disable the parent package (parent always replaced)
17712 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17713 // Disable the child packages
17714 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17715 for (int i = 0; i < childCount; i++) {
17716 PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17717 final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17718 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17723 private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17724 String installerPackageName) {
17725 // Enable the parent package
17726 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17727 // Enable the child packages
17728 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17729 for (int i = 0; i < childCount; i++) {
17730 PackageParser.Package childPkg = pkg.childPackages.get(i);
17731 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17735 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17736 // Collect all used permissions in the UID
17737 ArraySet<String> usedPermissions = new ArraySet<>();
17738 final int packageCount = su.packages.size();
17739 for (int i = 0; i < packageCount; i++) {
17740 PackageSetting ps = su.packages.valueAt(i);
17741 if (ps.pkg == null) {
17744 final int requestedPermCount = ps.pkg.requestedPermissions.size();
17745 for (int j = 0; j < requestedPermCount; j++) {
17746 String permission = ps.pkg.requestedPermissions.get(j);
17747 BasePermission bp = mSettings.mPermissions.get(permission);
17749 usedPermissions.add(permission);
17754 PermissionsState permissionsState = su.getPermissionsState();
17755 // Prune install permissions
17756 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17757 final int installPermCount = installPermStates.size();
17758 for (int i = installPermCount - 1; i >= 0; i--) {
17759 PermissionState permissionState = installPermStates.get(i);
17760 if (!usedPermissions.contains(permissionState.getName())) {
17761 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17763 permissionsState.revokeInstallPermission(bp);
17764 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17765 PackageManager.MASK_PERMISSION_FLAGS, 0);
17770 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17772 // Prune runtime permissions
17773 for (int userId : allUserIds) {
17774 List<PermissionState> runtimePermStates = permissionsState
17775 .getRuntimePermissionStates(userId);
17776 final int runtimePermCount = runtimePermStates.size();
17777 for (int i = runtimePermCount - 1; i >= 0; i--) {
17778 PermissionState permissionState = runtimePermStates.get(i);
17779 if (!usedPermissions.contains(permissionState.getName())) {
17780 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17782 permissionsState.revokeRuntimePermission(bp, userId);
17783 permissionsState.updatePermissionFlags(bp, userId,
17784 PackageManager.MASK_PERMISSION_FLAGS, 0);
17785 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17786 runtimePermissionChangedUserIds, userId);
17792 return runtimePermissionChangedUserIds;
17795 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17796 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17797 // Update the parent package setting
17798 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17799 res, user, installReason);
17800 // Update the child packages setting
17801 final int childCount = (newPackage.childPackages != null)
17802 ? newPackage.childPackages.size() : 0;
17803 for (int i = 0; i < childCount; i++) {
17804 PackageParser.Package childPackage = newPackage.childPackages.get(i);
17805 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17806 updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17807 childRes.origUsers, childRes, user, installReason);
17811 private void updateSettingsInternalLI(PackageParser.Package newPackage,
17812 String installerPackageName, int[] allUsers, int[] installedForUsers,
17813 PackageInstalledInfo res, UserHandle user, int installReason) {
17814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17816 String pkgName = newPackage.packageName;
17817 synchronized (mPackages) {
17818 //write settings. the installStatus will be incomplete at this stage.
17819 //note that the new package setting would have already been
17820 //added to mPackages. It hasn't been persisted yet.
17821 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17822 // TODO: Remove this write? It's also written at the end of this method
17823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17824 mSettings.writeLPr();
17825 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17828 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17829 synchronized (mPackages) {
17830 updatePermissionsLPw(newPackage.packageName, newPackage,
17831 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17832 ? UPDATE_PERMISSIONS_ALL : 0));
17833 // For system-bundled packages, we assume that installing an upgraded version
17834 // of the package implies that the user actually wants to run that new code,
17835 // so we enable the package.
17836 PackageSetting ps = mSettings.mPackages.get(pkgName);
17837 final int userId = user.getIdentifier();
17839 if (isSystemApp(newPackage)) {
17840 if (DEBUG_INSTALL) {
17841 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17843 // Enable system package for requested users
17844 if (res.origUsers != null) {
17845 for (int origUserId : res.origUsers) {
17846 if (userId == UserHandle.USER_ALL || userId == origUserId) {
17847 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17848 origUserId, installerPackageName);
17852 // Also convey the prior install/uninstall state
17853 if (allUsers != null && installedForUsers != null) {
17854 for (int currentUserId : allUsers) {
17855 final boolean installed = ArrayUtils.contains(
17856 installedForUsers, currentUserId);
17857 if (DEBUG_INSTALL) {
17858 Slog.d(TAG, " user " + currentUserId + " => " + installed);
17860 ps.setInstalled(installed, currentUserId);
17862 // these install state changes will be persisted in the
17863 // upcoming call to mSettings.writeLPr().
17866 // It's implied that when a user requests installation, they want the app to be
17867 // installed and enabled.
17868 if (userId != UserHandle.USER_ALL) {
17869 ps.setInstalled(true, userId);
17870 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17873 // When replacing an existing package, preserve the original install reason for all
17874 // users that had the package installed before.
17875 final Set<Integer> previousUserIds = new ArraySet<>();
17876 if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17877 final int installReasonCount = res.removedInfo.installReasons.size();
17878 for (int i = 0; i < installReasonCount; i++) {
17879 final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17880 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17881 ps.setInstallReason(previousInstallReason, previousUserId);
17882 previousUserIds.add(previousUserId);
17886 // Set install reason for users that are having the package newly installed.
17887 if (userId == UserHandle.USER_ALL) {
17888 for (int currentUserId : sUserManager.getUserIds()) {
17889 if (!previousUserIds.contains(currentUserId)) {
17890 ps.setInstallReason(installReason, currentUserId);
17893 } else if (!previousUserIds.contains(userId)) {
17894 ps.setInstallReason(installReason, userId);
17896 mSettings.writeKernelMappingLPr(ps);
17898 res.name = pkgName;
17899 res.uid = newPackage.applicationInfo.uid;
17900 res.pkg = newPackage;
17901 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17902 mSettings.setInstallerPackageName(pkgName, installerPackageName);
17903 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17904 //to update install status
17905 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17906 mSettings.writeLPr();
17907 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17910 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17913 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17915 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17916 installPackageLI(args, res);
17918 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17922 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17923 final int installFlags = args.installFlags;
17924 final String installerPackageName = args.installerPackageName;
17925 final String volumeUuid = args.volumeUuid;
17926 final File tmpPackageFile = new File(args.getCodePath());
17927 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17928 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17929 || (args.volumeUuid != null));
17930 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17931 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17932 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17933 boolean replace = false;
17934 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17935 if (args.move != null) {
17936 // moving a complete application; perform an initial scan on the new install location
17937 scanFlags |= SCAN_INITIAL;
17939 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17940 scanFlags |= SCAN_DONT_KILL_APP;
17943 scanFlags |= SCAN_AS_INSTANT_APP;
17946 scanFlags |= SCAN_AS_FULL_APP;
17949 // Result object to be returned
17950 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17952 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17955 if (instantApp && (forwardLocked || onExternal)) {
17956 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17957 + " external=" + onExternal);
17958 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17962 // Retrieve PackageSettings and parse package
17963 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17964 | PackageParser.PARSE_ENFORCE_CODE
17965 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17966 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17967 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17968 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17969 PackageParser pp = new PackageParser();
17970 pp.setSeparateProcesses(mSeparateProcesses);
17971 pp.setDisplayMetrics(mMetrics);
17972 pp.setCallback(mPackageParserCallback);
17974 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17975 final PackageParser.Package pkg;
17977 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17978 } catch (PackageParserException e) {
17979 res.setError("Failed parse during installPackageLI", e);
17982 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17985 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17986 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17987 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17988 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17989 "Instant app package must target O");
17992 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17993 Slog.w(TAG, "Instant app package " + pkg.packageName
17994 + " does not target targetSandboxVersion 2");
17995 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17996 "Instant app package must use targetSanboxVersion 2");
18000 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18001 // Static shared libraries have synthetic package names
18002 renameStaticSharedLibraryPackage(pkg);
18004 // No static shared libs on external storage
18006 Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18007 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18008 "Packages declaring static-shared libs cannot be updated");
18013 // If we are installing a clustered package add results for the children
18014 if (pkg.childPackages != null) {
18015 synchronized (mPackages) {
18016 final int childCount = pkg.childPackages.size();
18017 for (int i = 0; i < childCount; i++) {
18018 PackageParser.Package childPkg = pkg.childPackages.get(i);
18019 PackageInstalledInfo childRes = new PackageInstalledInfo();
18020 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18021 childRes.pkg = childPkg;
18022 childRes.name = childPkg.packageName;
18023 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18024 if (childPs != null) {
18025 childRes.origUsers = childPs.queryInstalledUsers(
18026 sUserManager.getUserIds(), true);
18028 if ((mPackages.containsKey(childPkg.packageName))) {
18029 childRes.removedInfo = new PackageRemovedInfo(this);
18030 childRes.removedInfo.removedPackage = childPkg.packageName;
18031 childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18033 if (res.addedChildPackages == null) {
18034 res.addedChildPackages = new ArrayMap<>();
18036 res.addedChildPackages.put(childPkg.packageName, childRes);
18041 // If package doesn't declare API override, mark that we have an install
18042 // time CPU ABI override.
18043 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18044 pkg.cpuAbiOverride = args.abiOverride;
18047 String pkgName = res.name = pkg.packageName;
18048 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18049 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18050 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18056 // either use what we've been given or parse directly from the APK
18057 if (args.certificates != null) {
18059 PackageParser.populateCertificates(pkg, args.certificates);
18060 } catch (PackageParserException e) {
18061 // there was something wrong with the certificates we were given;
18062 // try to pull them from the APK
18063 PackageParser.collectCertificates(pkg, parseFlags);
18066 PackageParser.collectCertificates(pkg, parseFlags);
18068 } catch (PackageParserException e) {
18069 res.setError("Failed collect during installPackageLI", e);
18073 // Get rid of all references to package scan path via parser.
18075 String oldCodePath = null;
18076 boolean systemApp = false;
18077 synchronized (mPackages) {
18078 // Check if installing already existing package
18079 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18080 String oldName = mSettings.getRenamedPackageLPr(pkgName);
18081 if (pkg.mOriginalPackages != null
18082 && pkg.mOriginalPackages.contains(oldName)
18083 && mPackages.containsKey(oldName)) {
18084 // This package is derived from an original package,
18085 // and this device has been updating from that original
18086 // name. We must continue using the original name, so
18087 // rename the new package here.
18088 pkg.setPackageName(oldName);
18089 pkgName = pkg.packageName;
18091 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18092 + oldName + " pkgName=" + pkgName);
18093 } else if (mPackages.containsKey(pkgName)) {
18094 // This package, under its official name, already exists
18095 // on the device; we should replace it.
18097 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18100 // Child packages are installed through the parent package
18101 if (pkg.parentPackage != null) {
18102 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18103 "Package " + pkg.packageName + " is child of package "
18104 + pkg.parentPackage.parentPackage + ". Child packages "
18105 + "can be updated only through the parent package.");
18110 // Prevent apps opting out from runtime permissions
18111 PackageParser.Package oldPackage = mPackages.get(pkgName);
18112 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18113 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18114 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18115 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18116 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18117 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18118 + " doesn't support runtime permissions but the old"
18119 + " target SDK " + oldTargetSdk + " does.");
18122 // Prevent apps from downgrading their targetSandbox.
18123 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18124 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18125 if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18126 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18127 "Package " + pkg.packageName + " new target sandbox "
18128 + newTargetSandbox + " is incompatible with the previous value of"
18129 + oldTargetSandbox + ".");
18133 // Prevent installing of child packages
18134 if (oldPackage.parentPackage != null) {
18135 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18136 "Package " + pkg.packageName + " is child of package "
18137 + oldPackage.parentPackage + ". Child packages "
18138 + "can be updated only through the parent package.");
18144 PackageSetting ps = mSettings.mPackages.get(pkgName);
18146 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18148 // Static shared libs have same package with different versions where
18149 // we internally use a synthetic package name to allow multiple versions
18150 // of the same package, therefore we need to compare signatures against
18151 // the package setting for the latest library version.
18152 PackageSetting signatureCheckPs = ps;
18153 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18154 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18155 if (libraryEntry != null) {
18156 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18160 // Quick sanity check that we're signed correctly if updating;
18161 // we'll check this again later when scanning, but we want to
18162 // bail early here before tripping over redefined permissions.
18163 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18164 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18165 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18166 + pkg.packageName + " upgrade keys do not match the "
18167 + "previously installed version");
18172 verifySignaturesLP(signatureCheckPs, pkg);
18173 } catch (PackageManagerException e) {
18174 res.setError(e.error, e.getMessage());
18179 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18180 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18181 systemApp = (ps.pkg.applicationInfo.flags &
18182 ApplicationInfo.FLAG_SYSTEM) != 0;
18184 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18187 int N = pkg.permissions.size();
18188 for (int i = N-1; i >= 0; i--) {
18189 PackageParser.Permission perm = pkg.permissions.get(i);
18190 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18192 // Don't allow anyone but the system to define ephemeral permissions.
18193 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18195 Slog.w(TAG, "Non-System package " + pkg.packageName
18196 + " attempting to delcare ephemeral permission "
18197 + perm.info.name + "; Removing ephemeral.");
18198 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18200 // Check whether the newly-scanned package wants to define an already-defined perm
18202 // If the defining package is signed with our cert, it's okay. This
18203 // also includes the "updating the same package" case, of course.
18204 // "updating same package" could also involve key-rotation.
18205 final boolean sigsOk;
18206 if (bp.sourcePackage.equals(pkg.packageName)
18207 && (bp.packageSetting instanceof PackageSetting)
18208 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18210 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18212 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18213 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18216 // If the owning package is the system itself, we log but allow
18217 // install to proceed; we fail the install on all other permission
18219 if (!bp.sourcePackage.equals("android")) {
18220 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18221 + pkg.packageName + " attempting to redeclare permission "
18222 + perm.info.name + " already owned by " + bp.sourcePackage);
18223 res.origPermission = perm.info.name;
18224 res.origPackage = bp.sourcePackage;
18227 Slog.w(TAG, "Package " + pkg.packageName
18228 + " attempting to redeclare system permission "
18229 + perm.info.name + "; ignoring new declaration");
18230 pkg.permissions.remove(i);
18232 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18233 // Prevent apps to change protection level to dangerous from any other
18234 // type as this would allow a privilege escalation where an app adds a
18235 // normal/signature permission in other app's group and later redefines
18236 // it as dangerous leading to the group auto-grant.
18237 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18238 == PermissionInfo.PROTECTION_DANGEROUS) {
18239 if (bp != null && !bp.isRuntime()) {
18240 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18241 + "non-runtime permission " + perm.info.name
18242 + " to runtime; keeping old protection level");
18243 perm.info.protectionLevel = bp.protectionLevel;
18253 // Abort update; system app can't be replaced with app on sdcard
18254 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18255 "Cannot install updates to system apps on sdcard");
18257 } else if (instantApp) {
18258 // Abort update; system app can't be replaced with an instant app
18259 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18260 "Cannot update a system app with an instant app");
18265 if (args.move != null) {
18266 // We did an in-place move, so dex is ready to roll
18267 scanFlags |= SCAN_NO_DEX;
18268 scanFlags |= SCAN_MOVE;
18270 synchronized (mPackages) {
18271 final PackageSetting ps = mSettings.mPackages.get(pkgName);
18273 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18274 "Missing settings for moved package " + pkgName);
18277 // We moved the entire application as-is, so bring over the
18278 // previously derived ABI information.
18279 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18280 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18283 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18284 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18285 scanFlags |= SCAN_NO_DEX;
18288 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18289 args.abiOverride : pkg.cpuAbiOverride);
18290 final boolean extractNativeLibs = !pkg.isLibrary();
18291 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18292 extractNativeLibs, mAppLib32InstallDir);
18293 } catch (PackageManagerException pme) {
18294 Slog.e(TAG, "Error deriving application ABI", pme);
18295 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18299 // Shared libraries for the package need to be updated.
18300 synchronized (mPackages) {
18302 updateSharedLibrariesLPr(pkg, null);
18303 } catch (PackageManagerException e) {
18304 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18308 // dexopt can take some time to complete, so, for instant apps, we skip this
18309 // step during installation. Instead, we'll take extra time the first time the
18310 // instant app starts. It's preferred to do it this way to provide continuous
18311 // progress to the user instead of mysteriously blocking somewhere in the
18312 // middle of running an instant app. The default behaviour can be overridden
18314 if (!instantApp || Global.getInt(
18315 mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18316 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18317 // Do not run PackageDexOptimizer through the local performDexOpt
18318 // method because `pkg` may not be in `mPackages` yet.
18320 // Also, don't fail application installs if the dexopt step fails.
18321 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18322 null /* instructionSets */, false /* checkProfiles */,
18323 getCompilerFilterForReason(REASON_INSTALL),
18324 getOrCreateCompilerPackageStats(pkg),
18325 mDexManager.isUsedByOtherApps(pkg.packageName));
18326 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18329 // Notify BackgroundDexOptService that the package has been changed.
18330 // If this is an update of a package which used to fail to compile,
18331 // BDOS will remove it from its blacklist.
18332 // TODO: Layering violation
18333 BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18336 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18337 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18341 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18343 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18344 "installPackageLI")) {
18346 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18347 // Static libs have a synthetic package name containing the version
18348 // and cannot be updated as an update would get a new package name,
18349 // unless this is the exact same version code which is useful for
18351 PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18352 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18353 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18354 + "static-shared libs cannot be updated");
18358 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18359 installerPackageName, res, args.installReason);
18361 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18362 args.user, installerPackageName, volumeUuid, res, args.installReason);
18366 synchronized (mPackages) {
18367 final PackageSetting ps = mSettings.mPackages.get(pkgName);
18369 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18370 ps.setUpdateAvailable(false /*updateAvailable*/);
18373 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18374 for (int i = 0; i < childCount; i++) {
18375 PackageParser.Package childPkg = pkg.childPackages.get(i);
18376 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18377 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18378 if (childPs != null) {
18379 childRes.newUsers = childPs.queryInstalledUsers(
18380 sUserManager.getUserIds(), true);
18384 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18385 updateSequenceNumberLP(ps, res.newUsers);
18386 updateInstantAppInstallerLocked(pkgName);
18391 private void startIntentFilterVerifications(int userId, boolean replacing,
18392 PackageParser.Package pkg) {
18393 if (mIntentFilterVerifierComponent == null) {
18394 Slog.w(TAG, "No IntentFilter verification will not be done as "
18395 + "there is no IntentFilterVerifier available!");
18399 final int verifierUid = getPackageUid(
18400 mIntentFilterVerifierComponent.getPackageName(),
18401 MATCH_DEBUG_TRIAGED_MISSING,
18402 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18404 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18405 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18406 mHandler.sendMessage(msg);
18408 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18409 for (int i = 0; i < childCount; i++) {
18410 PackageParser.Package childPkg = pkg.childPackages.get(i);
18411 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18412 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18413 mHandler.sendMessage(msg);
18417 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18418 PackageParser.Package pkg) {
18419 int size = pkg.activities.size();
18421 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18422 "No activity, so no need to verify any IntentFilter!");
18426 final boolean hasDomainURLs = hasDomainURLs(pkg);
18427 if (!hasDomainURLs) {
18428 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18429 "No domain URLs, so no need to verify any IntentFilter!");
18433 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18434 + " if any IntentFilter from the " + size
18435 + " Activities needs verification ...");
18438 final String packageName = pkg.packageName;
18440 synchronized (mPackages) {
18441 // If this is a new install and we see that we've already run verification for this
18442 // package, we have nothing to do: it means the state was restored from backup.
18444 IntentFilterVerificationInfo ivi =
18445 mSettings.getIntentFilterVerificationLPr(packageName);
18447 if (DEBUG_DOMAIN_VERIFICATION) {
18448 Slog.i(TAG, "Package " + packageName+ " already verified: status="
18449 + ivi.getStatusString());
18455 // If any filters need to be verified, then all need to be.
18456 boolean needToVerify = false;
18457 for (PackageParser.Activity a : pkg.activities) {
18458 for (ActivityIntentInfo filter : a.intents) {
18459 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18460 if (DEBUG_DOMAIN_VERIFICATION) {
18461 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18463 needToVerify = true;
18469 if (needToVerify) {
18470 final int verificationId = mIntentFilterVerificationToken++;
18471 for (PackageParser.Activity a : pkg.activities) {
18472 for (ActivityIntentInfo filter : a.intents) {
18473 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18474 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18475 "Verification needed for IntentFilter:" + filter.toString());
18476 mIntentFilterVerifier.addOneIntentFilterVerification(
18477 verifierUid, userId, verificationId, filter, packageName);
18486 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18487 + " IntentFilter verification" + (count > 1 ? "s" : "")
18488 + " for userId:" + userId);
18489 mIntentFilterVerifier.startVerifications(userId);
18491 if (DEBUG_DOMAIN_VERIFICATION) {
18492 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18497 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18498 final ComponentName cn = filter.activity.getComponentName();
18499 final String packageName = cn.getPackageName();
18501 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18506 int status = ivi.getStatus();
18508 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18509 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18518 private static boolean isMultiArch(ApplicationInfo info) {
18519 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18522 private static boolean isExternal(PackageParser.Package pkg) {
18523 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18526 private static boolean isExternal(PackageSetting ps) {
18527 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18530 private static boolean isSystemApp(PackageParser.Package pkg) {
18531 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18534 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18535 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18538 private static boolean hasDomainURLs(PackageParser.Package pkg) {
18539 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18542 private static boolean isSystemApp(PackageSetting ps) {
18543 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18546 private static boolean isUpdatedSystemApp(PackageSetting ps) {
18547 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18550 private int packageFlagsToInstallFlags(PackageSetting ps) {
18551 int installFlags = 0;
18552 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18553 // This existing package was an external ASEC install when we have
18554 // the external flag without a UUID
18555 installFlags |= PackageManager.INSTALL_EXTERNAL;
18557 if (ps.isForwardLocked()) {
18558 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18560 return installFlags;
18563 private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18564 if (isExternal(pkg)) {
18565 if (TextUtils.isEmpty(pkg.volumeUuid)) {
18566 return StorageManager.UUID_PRIMARY_PHYSICAL;
18568 return pkg.volumeUuid;
18571 return StorageManager.UUID_PRIVATE_INTERNAL;
18575 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18576 if (isExternal(pkg)) {
18577 if (TextUtils.isEmpty(pkg.volumeUuid)) {
18578 return mSettings.getExternalVersion();
18580 return mSettings.findOrCreateVersion(pkg.volumeUuid);
18583 return mSettings.getInternalVersion();
18587 private void deleteTempPackageFiles() {
18588 final FilenameFilter filter = new FilenameFilter() {
18589 public boolean accept(File dir, String name) {
18590 return name.startsWith("vmdl") && name.endsWith(".tmp");
18593 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18599 public void deletePackageAsUser(String packageName, int versionCode,
18600 IPackageDeleteObserver observer, int userId, int flags) {
18601 deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18602 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18606 public void deletePackageVersioned(VersionedPackage versionedPackage,
18607 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18608 final int callingUid = Binder.getCallingUid();
18609 mContext.enforceCallingOrSelfPermission(
18610 android.Manifest.permission.DELETE_PACKAGES, null);
18611 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18612 Preconditions.checkNotNull(versionedPackage);
18613 Preconditions.checkNotNull(observer);
18614 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18615 PackageManager.VERSION_CODE_HIGHEST,
18616 Integer.MAX_VALUE, "versionCode must be >= -1");
18618 final String packageName = versionedPackage.getPackageName();
18619 final int versionCode = versionedPackage.getVersionCode();
18620 final String internalPackageName;
18621 synchronized (mPackages) {
18622 // Normalize package name to handle renamed packages and static libs
18623 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18624 versionedPackage.getVersionCode());
18627 final int uid = Binder.getCallingUid();
18628 if (!isOrphaned(internalPackageName)
18629 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18631 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18632 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18633 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18634 observer.onUserActionRequired(intent);
18635 } catch (RemoteException re) {
18639 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18640 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18641 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18642 mContext.enforceCallingOrSelfPermission(
18643 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18644 "deletePackage for user " + userId);
18647 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18649 observer.onPackageDeleted(packageName,
18650 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18651 } catch (RemoteException re) {
18656 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18658 observer.onPackageDeleted(packageName,
18659 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18660 } catch (RemoteException re) {
18665 if (DEBUG_REMOVE) {
18666 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18667 + " deleteAllUsers: " + deleteAllUsers + " version="
18668 + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18669 ? "VERSION_CODE_HIGHEST" : versionCode));
18671 // Queue up an async operation since the package deletion may take a little while.
18672 mHandler.post(new Runnable() {
18673 public void run() {
18674 mHandler.removeCallbacks(this);
18676 final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18677 boolean doDeletePackage = true;
18679 final boolean targetIsInstantApp =
18680 ps.getInstantApp(UserHandle.getUserId(callingUid));
18681 doDeletePackage = !targetIsInstantApp
18682 || canViewInstantApps;
18684 if (doDeletePackage) {
18685 if (!deleteAllUsers) {
18686 returnCode = deletePackageX(internalPackageName, versionCode,
18687 userId, deleteFlags);
18689 int[] blockUninstallUserIds = getBlockUninstallForUsers(
18690 internalPackageName, users);
18691 // If nobody is blocking uninstall, proceed with delete for all users
18692 if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18693 returnCode = deletePackageX(internalPackageName, versionCode,
18694 userId, deleteFlags);
18696 // Otherwise uninstall individually for users with blockUninstalls=false
18697 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18698 for (int userId : users) {
18699 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18700 returnCode = deletePackageX(internalPackageName, versionCode,
18701 userId, userFlags);
18702 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18703 Slog.w(TAG, "Package delete failed for user " + userId
18704 + ", returnCode " + returnCode);
18708 // The app has only been marked uninstalled for certain users.
18709 // We still need to report that delete was blocked
18710 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18714 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18717 observer.onPackageDeleted(packageName, returnCode, null);
18718 } catch (RemoteException e) {
18719 Log.i(TAG, "Observer no longer exists.");
18725 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18726 if (pkg.staticSharedLibName != null) {
18727 return pkg.manifestPackageName;
18729 return pkg.packageName;
18732 private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18733 // Handle renamed packages
18734 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18735 packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18737 // Is this a static library?
18738 SparseArray<SharedLibraryEntry> versionedLib =
18739 mStaticLibsByDeclaringPackage.get(packageName);
18740 if (versionedLib == null || versionedLib.size() <= 0) {
18741 return packageName;
18744 // Figure out which lib versions the caller can see
18745 SparseIntArray versionsCallerCanSee = null;
18746 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18747 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18748 && callingAppId != Process.ROOT_UID) {
18749 versionsCallerCanSee = new SparseIntArray();
18750 String libName = versionedLib.valueAt(0).info.getName();
18751 String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18752 if (uidPackages != null) {
18753 for (String uidPackage : uidPackages) {
18754 PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18755 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18757 final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18758 versionsCallerCanSee.append(libVersion, libVersion);
18764 // Caller can see nothing - done
18765 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18766 return packageName;
18769 // Find the version the caller can see and the app version code
18770 SharedLibraryEntry highestVersion = null;
18771 final int versionCount = versionedLib.size();
18772 for (int i = 0; i < versionCount; i++) {
18773 SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18774 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18775 libEntry.info.getVersion()) < 0) {
18778 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18779 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18780 if (libVersionCode == versionCode) {
18781 return libEntry.apk;
18783 } else if (highestVersion == null) {
18784 highestVersion = libEntry;
18785 } else if (libVersionCode > highestVersion.info
18786 .getDeclaringPackage().getVersionCode()) {
18787 highestVersion = libEntry;
18791 if (highestVersion != null) {
18792 return highestVersion.apk;
18795 return packageName;
18798 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18799 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18800 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18803 final int callingUserId = UserHandle.getUserId(callingUid);
18804 // If the caller installed the pkgName, then allow it to silently uninstall.
18805 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18809 // Allow package verifier to silently uninstall.
18810 if (mRequiredVerifierPackage != null &&
18811 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18815 // Allow package uninstaller to silently uninstall.
18816 if (mRequiredUninstallerPackage != null &&
18817 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18821 // Allow storage manager to silently uninstall.
18822 if (mStorageManagerPackage != null &&
18823 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18829 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18830 int[] result = EMPTY_INT_ARRAY;
18831 for (int userId : userIds) {
18832 if (getBlockUninstallForUser(packageName, userId)) {
18833 result = ArrayUtils.appendInt(result, userId);
18840 public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18841 final int callingUid = Binder.getCallingUid();
18842 if (checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid)
18843 != PERMISSION_GRANTED) {
18844 EventLog.writeEvent(0x534e4554, "128599183", -1, "");
18845 throw new SecurityException(android.Manifest.permission.MANAGE_USERS
18846 + " permission is required to call this API");
18848 if (getInstantAppPackageName(callingUid) != null
18849 && !isCallerSameApp(packageName, callingUid)) {
18852 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18855 private boolean isPackageDeviceAdmin(String packageName, int userId) {
18856 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18857 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18860 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18861 /* callingUserOnly =*/ false);
18862 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18863 : deviceOwnerComponentName.getPackageName();
18864 // Does the package contains the device owner?
18865 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise,
18866 // this check is probably not needed, since DO should be registered as a device
18867 // admin on some user too. (Original bug for this: b/17657954)
18868 if (packageName.equals(deviceOwnerPackageName)) {
18871 // Does it contain a device admin for any user?
18873 if (userId == UserHandle.USER_ALL) {
18874 users = sUserManager.getUserIds();
18876 users = new int[]{userId};
18878 for (int i = 0; i < users.length; ++i) {
18879 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18884 } catch (RemoteException e) {
18889 private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18890 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18894 * This method is an internal method that could be get invoked either
18895 * to delete an installed package or to clean up a failed installation.
18896 * After deleting an installed package, a broadcast is sent to notify any
18897 * listeners that the package has been removed. For cleaning up a failed
18898 * installation, the broadcast is not necessary since the package's
18899 * installation wouldn't have sent the initial broadcast either
18900 * The key steps in deleting a package are
18901 * deleting the package information in internal structures like mPackages,
18902 * deleting the packages base directories through installd
18903 * updating mSettings to reflect current status
18904 * persisting settings for later use
18905 * sending a broadcast if necessary
18907 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18908 final PackageRemovedInfo info = new PackageRemovedInfo(this);
18911 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18912 ? UserHandle.USER_ALL : userId;
18914 if (isPackageDeviceAdmin(packageName, removeUser)) {
18915 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18916 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18919 PackageSetting uninstalledPs = null;
18920 PackageParser.Package pkg = null;
18922 // for the uninstall-updates case and restricted profiles, remember the per-
18923 // user handle installed state
18925 synchronized (mPackages) {
18926 uninstalledPs = mSettings.mPackages.get(packageName);
18927 if (uninstalledPs == null) {
18928 Slog.w(TAG, "Not removing non-existent package " + packageName);
18929 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18932 if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18933 && uninstalledPs.versionCode != versionCode) {
18934 Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18935 + uninstalledPs.versionCode + " != " + versionCode);
18936 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18939 // Static shared libs can be declared by any package, so let us not
18940 // allow removing a package if it provides a lib others depend on.
18941 pkg = mPackages.get(packageName);
18943 allUsers = sUserManager.getUserIds();
18945 if (pkg != null && pkg.staticSharedLibName != null) {
18946 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18947 pkg.staticSharedLibVersion);
18948 if (libEntry != null) {
18949 for (int currUserId : allUsers) {
18950 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18953 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18954 libEntry.info, 0, currUserId);
18955 if (!ArrayUtils.isEmpty(libClientPackages)) {
18956 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18957 + " hosting lib " + libEntry.info.getName() + " version "
18958 + libEntry.info.getVersion() + " used by " + libClientPackages
18959 + " for user " + currUserId);
18960 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18966 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18969 final int freezeUser;
18970 if (isUpdatedSystemApp(uninstalledPs)
18971 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18972 // We're downgrading a system app, which will apply to all users, so
18973 // freeze them all during the downgrade
18974 freezeUser = UserHandle.USER_ALL;
18976 freezeUser = removeUser;
18979 synchronized (mInstallLock) {
18980 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18981 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18982 deleteFlags, "deletePackageX")) {
18983 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18984 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18986 synchronized (mPackages) {
18989 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18991 updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18992 updateInstantAppInstallerLocked(packageName);
18998 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18999 info.sendPackageRemovedBroadcasts(killApp);
19000 info.sendSystemPackageUpdatedBroadcasts();
19001 info.sendSystemPackageAppearedBroadcasts();
19003 // Force a gc here.
19004 Runtime.getRuntime().gc();
19005 // Delete the resources here after sending the broadcast to let
19006 // other processes clean up before deleting resources.
19007 if (info.args != null) {
19008 synchronized (mInstallLock) {
19009 info.args.doPostDeleteLI(true);
19013 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19016 static class PackageRemovedInfo {
19017 final PackageSender packageSender;
19018 String removedPackage;
19019 String installerPackageName;
19021 int removedAppId = -1;
19023 int[] removedUsers = null;
19024 int[] broadcastUsers = null;
19025 SparseArray<Integer> installReasons;
19026 boolean isRemovedPackageSystemUpdate = false;
19028 boolean dataRemoved;
19029 boolean removedForAllUsers;
19030 boolean isStaticSharedLib;
19031 // Clean up resources deleted packages.
19032 InstallArgs args = null;
19033 ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19034 ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19036 PackageRemovedInfo(PackageSender packageSender) {
19037 this.packageSender = packageSender;
19040 void sendPackageRemovedBroadcasts(boolean killApp) {
19041 sendPackageRemovedBroadcastInternal(killApp);
19042 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19043 for (int i = 0; i < childCount; i++) {
19044 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19045 childInfo.sendPackageRemovedBroadcastInternal(killApp);
19049 void sendSystemPackageUpdatedBroadcasts() {
19050 if (isRemovedPackageSystemUpdate) {
19051 sendSystemPackageUpdatedBroadcastsInternal();
19052 final int childCount = (removedChildPackages != null)
19053 ? removedChildPackages.size() : 0;
19054 for (int i = 0; i < childCount; i++) {
19055 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19056 if (childInfo.isRemovedPackageSystemUpdate) {
19057 childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19063 void sendSystemPackageAppearedBroadcasts() {
19064 final int packageCount = (appearedChildPackages != null)
19065 ? appearedChildPackages.size() : 0;
19066 for (int i = 0; i < packageCount; i++) {
19067 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19068 packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19069 true, UserHandle.getAppId(installedInfo.uid),
19070 installedInfo.newUsers);
19074 private void sendSystemPackageUpdatedBroadcastsInternal() {
19075 Bundle extras = new Bundle(2);
19076 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19077 extras.putBoolean(Intent.EXTRA_REPLACING, true);
19078 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19079 removedPackage, extras, 0, null /*targetPackage*/, null, null);
19080 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19081 removedPackage, extras, 0, null /*targetPackage*/, null, null);
19082 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19083 null, null, 0, removedPackage, null, null);
19084 if (installerPackageName != null) {
19085 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19086 removedPackage, extras, 0 /*flags*/,
19087 installerPackageName, null, null);
19088 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19089 removedPackage, extras, 0 /*flags*/,
19090 installerPackageName, null, null);
19094 private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19095 // Don't send static shared library removal broadcasts as these
19096 // libs are visible only the the apps that depend on them an one
19097 // cannot remove the library if it has a dependency.
19098 if (isStaticSharedLib) {
19101 Bundle extras = new Bundle(2);
19102 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19103 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19104 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19105 if (isUpdate || isRemovedPackageSystemUpdate) {
19106 extras.putBoolean(Intent.EXTRA_REPLACING, true);
19108 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19109 if (removedPackage != null) {
19110 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19111 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19112 if (installerPackageName != null) {
19113 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19114 removedPackage, extras, 0 /*flags*/,
19115 installerPackageName, null, broadcastUsers);
19117 if (dataRemoved && !isRemovedPackageSystemUpdate) {
19118 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19119 removedPackage, extras,
19120 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19121 null, null, broadcastUsers);
19124 if (removedAppId >= 0) {
19125 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
19126 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
19130 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19131 removedUsers = userIds;
19132 if (removedUsers == null) {
19133 broadcastUsers = null;
19137 broadcastUsers = EMPTY_INT_ARRAY;
19138 for (int i = userIds.length - 1; i >= 0; --i) {
19139 final int userId = userIds[i];
19140 if (deletedPackageSetting.getInstantApp(userId)) {
19143 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19149 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19150 * flag is not set, the data directory is removed as well.
19151 * make sure this flag is set for partially installed apps. If not its meaningless to
19152 * delete a partially installed application.
19154 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19155 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19156 String packageName = ps.name;
19157 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19158 // Retrieve object to delete permissions for shared user later on
19159 final PackageParser.Package deletedPkg;
19160 final PackageSetting deletedPs;
19162 synchronized (mPackages) {
19163 deletedPkg = mPackages.get(packageName);
19164 deletedPs = mSettings.mPackages.get(packageName);
19165 if (outInfo != null) {
19166 outInfo.removedPackage = packageName;
19167 outInfo.installerPackageName = ps.installerPackageName;
19168 outInfo.isStaticSharedLib = deletedPkg != null
19169 && deletedPkg.staticSharedLibName != null;
19170 outInfo.populateUsers(deletedPs == null ? null
19171 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19175 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19177 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19178 final PackageParser.Package resolvedPkg;
19179 if (deletedPkg != null) {
19180 resolvedPkg = deletedPkg;
19182 // We don't have a parsed package when it lives on an ejected
19183 // adopted storage device, so fake something together
19184 resolvedPkg = new PackageParser.Package(ps.name);
19185 resolvedPkg.setVolumeUuid(ps.volumeUuid);
19187 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19188 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19189 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19190 if (outInfo != null) {
19191 outInfo.dataRemoved = true;
19193 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19196 int removedAppId = -1;
19199 synchronized (mPackages) {
19200 boolean installedStateChanged = false;
19201 if (deletedPs != null) {
19202 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19203 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19204 clearDefaultBrowserIfNeeded(packageName);
19205 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19206 removedAppId = mSettings.removePackageLPw(packageName);
19207 if (outInfo != null) {
19208 outInfo.removedAppId = removedAppId;
19210 updatePermissionsLPw(deletedPs.name, null, 0);
19211 if (deletedPs.sharedUser != null) {
19212 // Remove permissions associated with package. Since runtime
19213 // permissions are per user we have to kill the removed package
19214 // or packages running under the shared user of the removed
19215 // package if revoking the permissions requested only by the removed
19216 // package is successful and this causes a change in gids.
19217 for (int userId : UserManagerService.getInstance().getUserIds()) {
19218 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19220 if (userIdToKill == UserHandle.USER_ALL
19221 || userIdToKill >= UserHandle.USER_SYSTEM) {
19222 // If gids changed for this user, kill all affected packages.
19223 mHandler.post(new Runnable() {
19225 public void run() {
19226 // This has to happen with no lock held.
19227 killApplication(deletedPs.name, deletedPs.appId,
19228 KILL_APP_REASON_GIDS_CHANGED);
19235 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19237 // make sure to preserve per-user disabled state if this removal was just
19238 // a downgrade of a system app to the factory package
19239 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19240 if (DEBUG_REMOVE) {
19241 Slog.d(TAG, "Propagating install state across downgrade");
19243 for (int userId : allUserHandles) {
19244 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19245 if (DEBUG_REMOVE) {
19246 Slog.d(TAG, " user " + userId + " => " + installed);
19248 if (installed != ps.getInstalled(userId)) {
19249 installedStateChanged = true;
19251 ps.setInstalled(installed, userId);
19255 // can downgrade to reader
19256 if (writeSettings) {
19257 // Save settings now
19258 mSettings.writeLPr();
19260 if (installedStateChanged) {
19261 mSettings.writeKernelMappingLPr(ps);
19264 if (removedAppId != -1) {
19265 // A user ID was deleted here. Go through all users and remove it
19267 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19271 static boolean locationIsPrivileged(File path) {
19273 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19274 .getCanonicalPath();
19275 return path.getCanonicalPath().startsWith(privilegedAppDir);
19276 } catch (IOException e) {
19277 Slog.e(TAG, "Unable to access code path " + path);
19283 * Tries to delete system package.
19285 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19286 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19287 boolean writeSettings) {
19288 if (deletedPs.parentPackageName != null) {
19289 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19293 final boolean applyUserRestrictions
19294 = (allUserHandles != null) && (outInfo.origUsers != null);
19295 final PackageSetting disabledPs;
19296 // Confirm if the system package has been updated
19297 // An updated system app can be deleted. This will also have to restore
19298 // the system pkg from system partition
19300 synchronized (mPackages) {
19301 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19304 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19305 + " disabledPs=" + disabledPs);
19307 if (disabledPs == null) {
19308 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19310 } else if (DEBUG_REMOVE) {
19311 Slog.d(TAG, "Deleting system pkg from data partition");
19314 if (DEBUG_REMOVE) {
19315 if (applyUserRestrictions) {
19316 Slog.d(TAG, "Remembering install states:");
19317 for (int userId : allUserHandles) {
19318 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19319 Slog.d(TAG, " u=" + userId + " inst=" + finstalled);
19324 // Delete the updated package
19325 outInfo.isRemovedPackageSystemUpdate = true;
19326 if (outInfo.removedChildPackages != null) {
19327 final int childCount = (deletedPs.childPackageNames != null)
19328 ? deletedPs.childPackageNames.size() : 0;
19329 for (int i = 0; i < childCount; i++) {
19330 String childPackageName = deletedPs.childPackageNames.get(i);
19331 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19332 .contains(childPackageName)) {
19333 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19335 if (childInfo != null) {
19336 childInfo.isRemovedPackageSystemUpdate = true;
19342 if (disabledPs.versionCode < deletedPs.versionCode) {
19343 // Delete data for downgrades
19344 flags &= ~PackageManager.DELETE_KEEP_DATA;
19346 // Preserve data by setting flag
19347 flags |= PackageManager.DELETE_KEEP_DATA;
19350 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19351 outInfo, writeSettings, disabledPs.pkg);
19357 synchronized (mPackages) {
19358 // Reinstate the old system package
19359 enableSystemPackageLPw(disabledPs.pkg);
19360 // Remove any native libraries from the upgraded package.
19361 removeNativeBinariesLI(deletedPs);
19364 // Install the system package
19365 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19366 int parseFlags = mDefParseFlags
19367 | PackageParser.PARSE_MUST_BE_APK
19368 | PackageParser.PARSE_IS_SYSTEM
19369 | PackageParser.PARSE_IS_SYSTEM_DIR;
19370 if (locationIsPrivileged(disabledPs.codePath)) {
19371 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19374 final PackageParser.Package newPkg;
19376 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19377 0 /* currentTime */, null);
19378 } catch (PackageManagerException e) {
19379 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19385 // update shared libraries for the newly re-installed system package
19386 updateSharedLibrariesLPr(newPkg, null);
19387 } catch (PackageManagerException e) {
19388 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19391 prepareAppDataAfterInstallLIF(newPkg);
19394 synchronized (mPackages) {
19395 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19397 // Propagate the permissions state as we do not want to drop on the floor
19398 // runtime permissions. The update permissions method below will take
19399 // care of removing obsolete permissions and grant install permissions.
19400 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19401 updatePermissionsLPw(newPkg.packageName, newPkg,
19402 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19404 if (applyUserRestrictions) {
19405 boolean installedStateChanged = false;
19406 if (DEBUG_REMOVE) {
19407 Slog.d(TAG, "Propagating install state across reinstall");
19409 for (int userId : allUserHandles) {
19410 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19411 if (DEBUG_REMOVE) {
19412 Slog.d(TAG, " user " + userId + " => " + installed);
19414 if (installed != ps.getInstalled(userId)) {
19415 installedStateChanged = true;
19417 ps.setInstalled(installed, userId);
19419 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19421 // Regardless of writeSettings we need to ensure that this restriction
19422 // state propagation is persisted
19423 mSettings.writeAllUsersPackageRestrictionsLPr();
19424 if (installedStateChanged) {
19425 mSettings.writeKernelMappingLPr(ps);
19428 // can downgrade to reader here
19429 if (writeSettings) {
19430 mSettings.writeLPr();
19436 private boolean deleteInstalledPackageLIF(PackageSetting ps,
19437 boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19438 PackageRemovedInfo outInfo, boolean writeSettings,
19439 PackageParser.Package replacingPackage) {
19440 synchronized (mPackages) {
19441 if (outInfo != null) {
19442 outInfo.uid = ps.appId;
19445 if (outInfo != null && outInfo.removedChildPackages != null) {
19446 final int childCount = (ps.childPackageNames != null)
19447 ? ps.childPackageNames.size() : 0;
19448 for (int i = 0; i < childCount; i++) {
19449 String childPackageName = ps.childPackageNames.get(i);
19450 PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19451 if (childPs == null) {
19454 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19456 if (childInfo != null) {
19457 childInfo.uid = childPs.appId;
19463 // Delete package data from internal structures and also remove data if flag is set
19464 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19466 // Delete the child packages data
19467 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19468 for (int i = 0; i < childCount; i++) {
19469 PackageSetting childPs;
19470 synchronized (mPackages) {
19471 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19473 if (childPs != null) {
19474 PackageRemovedInfo childOutInfo = (outInfo != null
19475 && outInfo.removedChildPackages != null)
19476 ? outInfo.removedChildPackages.get(childPs.name) : null;
19477 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19478 && (replacingPackage != null
19479 && !replacingPackage.hasChildPackage(childPs.name))
19480 ? flags & ~DELETE_KEEP_DATA : flags;
19481 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19482 deleteFlags, writeSettings);
19486 // Delete application code and resources only for parent packages
19487 if (ps.parentPackageName == null) {
19488 if (deleteCodeAndResources && (outInfo != null)) {
19489 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19490 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19491 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19499 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19501 mContext.enforceCallingOrSelfPermission(
19502 android.Manifest.permission.DELETE_PACKAGES, null);
19503 synchronized (mPackages) {
19504 // Cannot block uninstall of static shared libs as they are
19505 // considered a part of the using app (emulating static linking).
19506 // Also static libs are installed always on internal storage.
19507 PackageParser.Package pkg = mPackages.get(packageName);
19508 if (pkg != null && pkg.staticSharedLibName != null) {
19509 Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19510 + " providing static shared library: " + pkg.staticSharedLibName);
19513 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19514 mSettings.writePackageRestrictionsLPr(userId);
19520 public boolean getBlockUninstallForUser(String packageName, int userId) {
19521 synchronized (mPackages) {
19522 final PackageSetting ps = mSettings.mPackages.get(packageName);
19523 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19526 return mSettings.getBlockUninstallLPr(userId, packageName);
19531 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19532 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19533 synchronized (mPackages) {
19534 PackageSetting ps = mSettings.mPackages.get(packageName);
19536 Log.w(TAG, "Package doesn't exist: " + packageName);
19539 if (systemUserApp) {
19540 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19542 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19544 mSettings.writeLPr();
19550 * This method handles package deletion in general
19552 private boolean deletePackageLIF(String packageName, UserHandle user,
19553 boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19554 PackageRemovedInfo outInfo, boolean writeSettings,
19555 PackageParser.Package replacingPackage) {
19556 if (packageName == null) {
19557 Slog.w(TAG, "Attempt to delete null packageName.");
19561 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19564 synchronized (mPackages) {
19565 ps = mSettings.mPackages.get(packageName);
19567 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19571 if (ps.parentPackageName != null && (!isSystemApp(ps)
19572 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19573 if (DEBUG_REMOVE) {
19574 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19575 + ((user == null) ? UserHandle.USER_ALL : user));
19577 final int removedUserId = (user != null) ? user.getIdentifier()
19578 : UserHandle.USER_ALL;
19579 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19582 markPackageUninstalledForUserLPw(ps, user);
19583 scheduleWritePackageRestrictionsLocked(user);
19588 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19589 && user.getIdentifier() != UserHandle.USER_ALL)) {
19590 // The caller is asking that the package only be deleted for a single
19591 // user. To do this, we just mark its uninstalled state and delete
19592 // its data. If this is a system app, we only allow this to happen if
19593 // they have set the special DELETE_SYSTEM_APP which requests different
19594 // semantics than normal for uninstalling system apps.
19595 markPackageUninstalledForUserLPw(ps, user);
19597 if (!isSystemApp(ps)) {
19598 // Do not uninstall the APK if an app should be cached
19599 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19600 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19601 // Other user still have this package installed, so all
19602 // we need to do is clear this user's data and save that
19603 // it is uninstalled.
19604 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19605 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19608 scheduleWritePackageRestrictionsLocked(user);
19611 // We need to set it back to 'installed' so the uninstall
19612 // broadcasts will be sent correctly.
19613 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19614 ps.setInstalled(true, user.getIdentifier());
19615 mSettings.writeKernelMappingLPr(ps);
19618 // This is a system app, so we assume that the
19619 // other users still have this package installed, so all
19620 // we need to do is clear this user's data and save that
19621 // it is uninstalled.
19622 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19623 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19626 scheduleWritePackageRestrictionsLocked(user);
19631 // If we are deleting a composite package for all users, keep track
19632 // of result for each child.
19633 if (ps.childPackageNames != null && outInfo != null) {
19634 synchronized (mPackages) {
19635 final int childCount = ps.childPackageNames.size();
19636 outInfo.removedChildPackages = new ArrayMap<>(childCount);
19637 for (int i = 0; i < childCount; i++) {
19638 String childPackageName = ps.childPackageNames.get(i);
19639 PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19640 childInfo.removedPackage = childPackageName;
19641 childInfo.installerPackageName = ps.installerPackageName;
19642 outInfo.removedChildPackages.put(childPackageName, childInfo);
19643 PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19644 if (childPs != null) {
19645 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19651 boolean ret = false;
19652 if (isSystemApp(ps)) {
19653 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19654 // When an updated system application is deleted we delete the existing resources
19655 // as well and fall back to existing code in system partition
19656 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19658 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19659 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19660 outInfo, writeSettings, replacingPackage);
19663 // Take a note whether we deleted the package for all users
19664 if (outInfo != null) {
19665 outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19666 if (outInfo.removedChildPackages != null) {
19667 synchronized (mPackages) {
19668 final int childCount = outInfo.removedChildPackages.size();
19669 for (int i = 0; i < childCount; i++) {
19670 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19671 if (childInfo != null) {
19672 childInfo.removedForAllUsers = mPackages.get(
19673 childInfo.removedPackage) == null;
19678 // If we uninstalled an update to a system app there may be some
19679 // child packages that appeared as they are declared in the system
19680 // app but were not declared in the update.
19681 if (isSystemApp(ps)) {
19682 synchronized (mPackages) {
19683 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19684 final int childCount = (updatedPs.childPackageNames != null)
19685 ? updatedPs.childPackageNames.size() : 0;
19686 for (int i = 0; i < childCount; i++) {
19687 String childPackageName = updatedPs.childPackageNames.get(i);
19688 if (outInfo.removedChildPackages == null
19689 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19690 PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19691 if (childPs == null) {
19694 PackageInstalledInfo installRes = new PackageInstalledInfo();
19695 installRes.name = childPackageName;
19696 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19697 installRes.pkg = mPackages.get(childPackageName);
19698 installRes.uid = childPs.pkg.applicationInfo.uid;
19699 if (outInfo.appearedChildPackages == null) {
19700 outInfo.appearedChildPackages = new ArrayMap<>();
19702 outInfo.appearedChildPackages.put(childPackageName, installRes);
19712 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19713 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19714 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19715 for (int nextUserId : userIds) {
19716 if (DEBUG_REMOVE) {
19717 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19719 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19720 false /*installed*/,
19722 true /*notLaunched*/,
19724 false /*suspended*/,
19725 false /*instantApp*/,
19726 null /*lastDisableAppCaller*/,
19727 null /*enabledComponents*/,
19728 null /*disabledComponents*/,
19729 ps.readUserState(nextUserId).domainVerificationStatus,
19730 0, PackageManager.INSTALL_REASON_UNKNOWN);
19732 mSettings.writeKernelMappingLPr(ps);
19735 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19736 PackageRemovedInfo outInfo) {
19737 final PackageParser.Package pkg;
19738 synchronized (mPackages) {
19739 pkg = mPackages.get(ps.name);
19742 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19743 : new int[] {userId};
19744 for (int nextUserId : userIds) {
19745 if (DEBUG_REMOVE) {
19746 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19750 destroyAppDataLIF(pkg, userId,
19751 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19752 destroyAppProfilesLIF(pkg, userId);
19753 clearDefaultBrowserIfNeededForUser(ps.name, userId);
19754 removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19755 schedulePackageCleaning(ps.name, nextUserId, false);
19756 synchronized (mPackages) {
19757 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19758 scheduleWritePackageRestrictionsLocked(nextUserId);
19760 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19764 if (outInfo != null) {
19765 outInfo.removedPackage = ps.name;
19766 outInfo.installerPackageName = ps.installerPackageName;
19767 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19768 outInfo.removedAppId = ps.appId;
19769 outInfo.removedUsers = userIds;
19770 outInfo.broadcastUsers = userIds;
19776 private final class ClearStorageConnection implements ServiceConnection {
19777 IMediaContainerService mContainerService;
19780 public void onServiceConnected(ComponentName name, IBinder service) {
19781 synchronized (this) {
19782 mContainerService = IMediaContainerService.Stub
19783 .asInterface(Binder.allowBlocking(service));
19789 public void onServiceDisconnected(ComponentName name) {
19793 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19794 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19796 final boolean mounted;
19797 if (Environment.isExternalStorageEmulated()) {
19800 final String status = Environment.getExternalStorageState();
19802 mounted = status.equals(Environment.MEDIA_MOUNTED)
19803 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19810 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19812 if (userId == UserHandle.USER_ALL) {
19813 users = sUserManager.getUserIds();
19815 users = new int[] { userId };
19817 final ClearStorageConnection conn = new ClearStorageConnection();
19818 if (mContext.bindServiceAsUser(
19819 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19821 for (int curUser : users) {
19822 long timeout = SystemClock.uptimeMillis() + 5000;
19823 synchronized (conn) {
19825 while (conn.mContainerService == null &&
19826 (now = SystemClock.uptimeMillis()) < timeout) {
19828 conn.wait(timeout - now);
19829 } catch (InterruptedException e) {
19833 if (conn.mContainerService == null) {
19837 final UserEnvironment userEnv = new UserEnvironment(curUser);
19838 clearDirectory(conn.mContainerService,
19839 userEnv.buildExternalStorageAppCacheDirs(packageName));
19841 clearDirectory(conn.mContainerService,
19842 userEnv.buildExternalStorageAppDataDirs(packageName));
19843 clearDirectory(conn.mContainerService,
19844 userEnv.buildExternalStorageAppMediaDirs(packageName));
19848 mContext.unbindService(conn);
19854 public void clearApplicationProfileData(String packageName) {
19855 enforceSystemOrRoot("Only the system can clear all profile data");
19857 final PackageParser.Package pkg;
19858 synchronized (mPackages) {
19859 pkg = mPackages.get(packageName);
19862 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19863 synchronized (mInstallLock) {
19864 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19870 public void clearApplicationUserData(final String packageName,
19871 final IPackageDataObserver observer, final int userId) {
19872 mContext.enforceCallingOrSelfPermission(
19873 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19875 final int callingUid = Binder.getCallingUid();
19876 enforceCrossUserPermission(callingUid, userId,
19877 true /* requireFullPermission */, false /* checkShell */, "clear application data");
19879 final PackageSetting ps = mSettings.getPackageLPr(packageName);
19880 if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19883 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19884 throw new SecurityException("Cannot clear data for a protected package: "
19887 // Queue up an async operation since the package deletion may take a little while.
19888 mHandler.post(new Runnable() {
19889 public void run() {
19890 mHandler.removeCallbacks(this);
19891 final boolean succeeded;
19892 try (PackageFreezer freezer = freezePackage(packageName,
19893 "clearApplicationUserData")) {
19894 synchronized (mInstallLock) {
19895 succeeded = clearApplicationUserDataLIF(packageName, userId);
19897 clearExternalStorageDataSync(packageName, userId, true);
19898 synchronized (mPackages) {
19899 mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19900 packageName, userId);
19904 // invoke DeviceStorageMonitor's update method to clear any notifications
19905 DeviceStorageMonitorInternal dsm = LocalServices
19906 .getService(DeviceStorageMonitorInternal.class);
19911 if(observer != null) {
19913 observer.onRemoveCompleted(packageName, succeeded);
19914 } catch (RemoteException e) {
19915 Log.i(TAG, "Observer no longer exists.");
19917 } //end if observer
19922 private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19923 if (packageName == null) {
19924 Slog.w(TAG, "Attempt to delete null packageName.");
19928 // Try finding details about the requested package
19929 PackageParser.Package pkg;
19930 synchronized (mPackages) {
19931 pkg = mPackages.get(packageName);
19933 final PackageSetting ps = mSettings.mPackages.get(packageName);
19940 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19944 PackageSetting ps = (PackageSetting) pkg.mExtras;
19945 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19948 clearAppDataLIF(pkg, userId,
19949 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19951 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19952 removeKeystoreDataIfNeeded(userId, appId);
19954 UserManagerInternal umInternal = getUserManagerInternal();
19956 if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19957 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19958 } else if (umInternal.isUserRunning(userId)) {
19959 flags = StorageManager.FLAG_STORAGE_DE;
19963 prepareAppDataContentsLIF(pkg, userId, flags);
19969 * Reverts user permission state changes (permissions and flags) in
19970 * all packages for a given user.
19972 * @param userId The device user for which to do a reset.
19974 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19975 final int packageCount = mPackages.size();
19976 for (int i = 0; i < packageCount; i++) {
19977 PackageParser.Package pkg = mPackages.valueAt(i);
19978 PackageSetting ps = (PackageSetting) pkg.mExtras;
19979 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19983 private void resetNetworkPolicies(int userId) {
19984 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19988 * Reverts user permission state changes (permissions and flags).
19990 * @param ps The package for which to reset.
19991 * @param userId The device user for which to do a reset.
19993 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19994 final PackageSetting ps, final int userId) {
19995 if (ps.pkg == null) {
19999 // These are flags that can change base on user actions.
20000 final int userSettableMask = FLAG_PERMISSION_USER_SET
20001 | FLAG_PERMISSION_USER_FIXED
20002 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20003 | FLAG_PERMISSION_REVIEW_REQUIRED;
20005 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20006 | FLAG_PERMISSION_POLICY_FIXED;
20008 boolean writeInstallPermissions = false;
20009 boolean writeRuntimePermissions = false;
20011 final int permissionCount = ps.pkg.requestedPermissions.size();
20012 for (int i = 0; i < permissionCount; i++) {
20013 String permission = ps.pkg.requestedPermissions.get(i);
20015 BasePermission bp = mSettings.mPermissions.get(permission);
20020 // If shared user we just reset the state to which only this app contributed.
20021 if (ps.sharedUser != null) {
20022 boolean used = false;
20023 final int packageCount = ps.sharedUser.packages.size();
20024 for (int j = 0; j < packageCount; j++) {
20025 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20026 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20027 && pkg.pkg.requestedPermissions.contains(permission)) {
20037 PermissionsState permissionsState = ps.getPermissionsState();
20039 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20041 // Always clear the user settable flags.
20042 final boolean hasInstallState = permissionsState.getInstallPermissionState(
20044 // If permission review is enabled and this is a legacy app, mark the
20045 // permission as requiring a review as this is the initial state.
20047 if (mPermissionReviewRequired
20048 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20049 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20051 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20052 if (hasInstallState) {
20053 writeInstallPermissions = true;
20055 writeRuntimePermissions = true;
20059 // Below is only runtime permission handling.
20060 if (!bp.isRuntime()) {
20064 // Never clobber system or policy.
20065 if ((oldFlags & policyOrSystemFlags) != 0) {
20069 // If this permission was granted by default, make sure it is.
20070 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20071 if (permissionsState.grantRuntimePermission(bp, userId)
20072 != PERMISSION_OPERATION_FAILURE) {
20073 writeRuntimePermissions = true;
20075 // If permission review is enabled the permissions for a legacy apps
20076 // are represented as constantly granted runtime ones, so don't revoke.
20077 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20078 // Otherwise, reset the permission.
20079 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20080 switch (revokeResult) {
20081 case PERMISSION_OPERATION_SUCCESS:
20082 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20083 writeRuntimePermissions = true;
20084 final int appId = ps.appId;
20085 mHandler.post(new Runnable() {
20087 public void run() {
20088 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20096 // Synchronously write as we are taking permissions away.
20097 if (writeRuntimePermissions) {
20098 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20101 // Synchronously write as we are taking permissions away.
20102 if (writeInstallPermissions) {
20103 mSettings.writeLPr();
20108 * Remove entries from the keystore daemon. Will only remove it if the
20109 * {@code appId} is valid.
20111 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20116 final KeyStore keyStore = KeyStore.getInstance();
20117 if (keyStore != null) {
20118 if (userId == UserHandle.USER_ALL) {
20119 for (final int individual : sUserManager.getUserIds()) {
20120 keyStore.clearUid(UserHandle.getUid(individual, appId));
20123 keyStore.clearUid(UserHandle.getUid(userId, appId));
20126 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20131 public void deleteApplicationCacheFiles(final String packageName,
20132 final IPackageDataObserver observer) {
20133 final int userId = UserHandle.getCallingUserId();
20134 deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20138 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20139 final IPackageDataObserver observer) {
20140 final int callingUid = Binder.getCallingUid();
20141 mContext.enforceCallingOrSelfPermission(
20142 android.Manifest.permission.DELETE_CACHE_FILES, null);
20143 enforceCrossUserPermission(callingUid, userId,
20144 /* requireFullPermission= */ true, /* checkShell= */ false,
20145 "delete application cache files");
20146 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20147 android.Manifest.permission.ACCESS_INSTANT_APPS);
20149 final PackageParser.Package pkg;
20150 synchronized (mPackages) {
20151 pkg = mPackages.get(packageName);
20154 // Queue up an async operation since the package deletion may take a little while.
20155 mHandler.post(new Runnable() {
20156 public void run() {
20157 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20158 boolean doClearData = true;
20160 final boolean targetIsInstantApp =
20161 ps.getInstantApp(UserHandle.getUserId(callingUid));
20162 doClearData = !targetIsInstantApp
20163 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20166 synchronized (mInstallLock) {
20167 final int flags = StorageManager.FLAG_STORAGE_DE
20168 | StorageManager.FLAG_STORAGE_CE;
20169 // We're only clearing cache files, so we don't care if the
20170 // app is unfrozen and still able to run
20171 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20172 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20174 clearExternalStorageDataSync(packageName, userId, false);
20176 if (observer != null) {
20178 observer.onRemoveCompleted(packageName, true);
20179 } catch (RemoteException e) {
20180 Log.i(TAG, "Observer no longer exists.");
20188 public void getPackageSizeInfo(final String packageName, int userHandle,
20189 final IPackageStatsObserver observer) {
20190 throw new UnsupportedOperationException(
20191 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20194 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20195 final PackageSetting ps;
20196 synchronized (mPackages) {
20197 ps = mSettings.mPackages.get(packageName);
20199 Slog.w(TAG, "Failed to find settings for " + packageName);
20204 final String[] packageNames = { packageName };
20205 final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20206 final String[] codePaths = { ps.codePathString };
20209 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20210 ps.appId, ceDataInodes, codePaths, stats);
20212 // For now, ignore code size of packages on system partition
20213 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20214 stats.codeSize = 0;
20217 // External clients expect these to be tracked separately
20218 stats.dataSize -= stats.cacheSize;
20220 } catch (InstallerException e) {
20221 Slog.w(TAG, String.valueOf(e));
20228 private int getUidTargetSdkVersionLockedLPr(int uid) {
20229 Object obj = mSettings.getUserIdLPr(uid);
20230 if (obj instanceof SharedUserSetting) {
20231 final SharedUserSetting sus = (SharedUserSetting) obj;
20232 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20233 final Iterator<PackageSetting> it = sus.packages.iterator();
20234 while (it.hasNext()) {
20235 final PackageSetting ps = it.next();
20236 if (ps.pkg != null) {
20237 int v = ps.pkg.applicationInfo.targetSdkVersion;
20238 if (v < vers) vers = v;
20242 } else if (obj instanceof PackageSetting) {
20243 final PackageSetting ps = (PackageSetting) obj;
20244 if (ps.pkg != null) {
20245 return ps.pkg.applicationInfo.targetSdkVersion;
20248 return Build.VERSION_CODES.CUR_DEVELOPMENT;
20252 public void addPreferredActivity(IntentFilter filter, int match,
20253 ComponentName[] set, ComponentName activity, int userId) {
20254 addPreferredActivityInternal(filter, match, set, activity, true, userId,
20255 "Adding preferred");
20258 private void addPreferredActivityInternal(IntentFilter filter, int match,
20259 ComponentName[] set, ComponentName activity, boolean always, int userId,
20262 int callingUid = Binder.getCallingUid();
20263 enforceCrossUserPermission(callingUid, userId,
20264 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20265 if (filter.countActions() == 0) {
20266 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20269 synchronized (mPackages) {
20270 if (mContext.checkCallingOrSelfPermission(
20271 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20272 != PackageManager.PERMISSION_GRANTED) {
20273 if (getUidTargetSdkVersionLockedLPr(callingUid)
20274 < Build.VERSION_CODES.FROYO) {
20275 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20279 mContext.enforceCallingOrSelfPermission(
20280 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20283 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20284 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20286 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20287 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20288 scheduleWritePackageRestrictionsLocked(userId);
20289 postPreferredActivityChangedBroadcast(userId);
20293 private void postPreferredActivityChangedBroadcast(int userId) {
20294 mHandler.post(() -> {
20295 final IActivityManager am = ActivityManager.getService();
20300 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20301 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20303 am.broadcastIntent(null, intent, null, null,
20304 0, null, null, null, android.app.AppOpsManager.OP_NONE,
20305 null, false, false, userId);
20306 } catch (RemoteException e) {
20312 public void replacePreferredActivity(IntentFilter filter, int match,
20313 ComponentName[] set, ComponentName activity, int userId) {
20314 if (filter.countActions() != 1) {
20315 throw new IllegalArgumentException(
20316 "replacePreferredActivity expects filter to have only 1 action.");
20318 if (filter.countDataAuthorities() != 0
20319 || filter.countDataPaths() != 0
20320 || filter.countDataSchemes() > 1
20321 || filter.countDataTypes() != 0) {
20322 throw new IllegalArgumentException(
20323 "replacePreferredActivity expects filter to have no data authorities, " +
20324 "paths, or types; and at most one scheme.");
20327 final int callingUid = Binder.getCallingUid();
20328 enforceCrossUserPermission(callingUid, userId,
20329 true /* requireFullPermission */, false /* checkShell */,
20330 "replace preferred activity");
20331 synchronized (mPackages) {
20332 if (mContext.checkCallingOrSelfPermission(
20333 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20334 != PackageManager.PERMISSION_GRANTED) {
20335 if (getUidTargetSdkVersionLockedLPr(callingUid)
20336 < Build.VERSION_CODES.FROYO) {
20337 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20338 + Binder.getCallingUid());
20341 mContext.enforceCallingOrSelfPermission(
20342 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20345 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20347 // Get all of the existing entries that exactly match this filter.
20348 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20349 if (existing != null && existing.size() == 1) {
20350 PreferredActivity cur = existing.get(0);
20351 if (DEBUG_PREFERRED) {
20352 Slog.i(TAG, "Checking replace of preferred:");
20353 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20354 if (!cur.mPref.mAlways) {
20355 Slog.i(TAG, " -- CUR; not mAlways!");
20357 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
20358 Slog.i(TAG, " -- CUR: mSet="
20359 + Arrays.toString(cur.mPref.mSetComponents));
20360 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
20361 Slog.i(TAG, " -- NEW: mMatch="
20362 + (match&IntentFilter.MATCH_CATEGORY_MASK));
20363 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
20364 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
20367 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20368 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20369 && cur.mPref.sameSet(set)) {
20370 // Setting the preferred activity to what it happens to be already
20371 if (DEBUG_PREFERRED) {
20372 Slog.i(TAG, "Replacing with same preferred activity "
20373 + cur.mPref.mShortComponent + " for user "
20375 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20381 if (existing != null) {
20382 if (DEBUG_PREFERRED) {
20383 Slog.i(TAG, existing.size() + " existing preferred matches for:");
20384 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20386 for (int i = 0; i < existing.size(); i++) {
20387 PreferredActivity pa = existing.get(i);
20388 if (DEBUG_PREFERRED) {
20389 Slog.i(TAG, "Removing existing preferred activity "
20390 + pa.mPref.mComponent + ":");
20391 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
20393 pir.removeFilter(pa);
20397 addPreferredActivityInternal(filter, match, set, activity, true, userId,
20398 "Replacing preferred");
20403 public void clearPackagePreferredActivities(String packageName) {
20404 final int callingUid = Binder.getCallingUid();
20405 if (getInstantAppPackageName(callingUid) != null) {
20409 synchronized (mPackages) {
20410 PackageParser.Package pkg = mPackages.get(packageName);
20411 if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20412 if (mContext.checkCallingOrSelfPermission(
20413 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20414 != PackageManager.PERMISSION_GRANTED) {
20415 if (getUidTargetSdkVersionLockedLPr(callingUid)
20416 < Build.VERSION_CODES.FROYO) {
20417 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20421 mContext.enforceCallingOrSelfPermission(
20422 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20425 final PackageSetting ps = mSettings.getPackageLPr(packageName);
20427 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20430 int user = UserHandle.getCallingUserId();
20431 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20432 scheduleWritePackageRestrictionsLocked(user);
20437 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20438 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20439 ArrayList<PreferredActivity> removed = null;
20440 boolean changed = false;
20441 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20442 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20443 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20444 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20447 Iterator<PreferredActivity> it = pir.filterIterator();
20448 while (it.hasNext()) {
20449 PreferredActivity pa = it.next();
20450 // Mark entry for removal only if it matches the package name
20451 // and the entry is of type "always".
20452 if (packageName == null ||
20453 (pa.mPref.mComponent.getPackageName().equals(packageName)
20454 && pa.mPref.mAlways)) {
20455 if (removed == null) {
20456 removed = new ArrayList<PreferredActivity>();
20461 if (removed != null) {
20462 for (int j=0; j<removed.size(); j++) {
20463 PreferredActivity pa = removed.get(j);
20464 pir.removeFilter(pa);
20470 postPreferredActivityChangedBroadcast(userId);
20475 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20476 private void clearIntentFilterVerificationsLPw(int userId) {
20477 final int packageCount = mPackages.size();
20478 for (int i = 0; i < packageCount; i++) {
20479 PackageParser.Package pkg = mPackages.valueAt(i);
20480 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20484 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20485 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20486 if (userId == UserHandle.USER_ALL) {
20487 if (mSettings.removeIntentFilterVerificationLPw(packageName,
20488 sUserManager.getUserIds())) {
20489 for (int oneUserId : sUserManager.getUserIds()) {
20490 scheduleWritePackageRestrictionsLocked(oneUserId);
20494 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20495 scheduleWritePackageRestrictionsLocked(userId);
20500 /** Clears state for all users, and touches intent filter verification policy */
20501 void clearDefaultBrowserIfNeeded(String packageName) {
20502 for (int oneUserId : sUserManager.getUserIds()) {
20503 clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20507 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20508 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20509 if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20510 if (packageName.equals(defaultBrowserPackageName)) {
20511 setDefaultBrowserPackageName(null, userId);
20517 public void resetApplicationPreferences(int userId) {
20518 mContext.enforceCallingOrSelfPermission(
20519 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20520 final long identity = Binder.clearCallingIdentity();
20523 synchronized (mPackages) {
20524 clearPackagePreferredActivitiesLPw(null, userId);
20525 mSettings.applyDefaultPreferredAppsLPw(this, userId);
20526 // TODO: We have to reset the default SMS and Phone. This requires
20527 // significant refactoring to keep all default apps in the package
20528 // manager (cleaner but more work) or have the services provide
20529 // callbacks to the package manager to request a default app reset.
20530 applyFactoryDefaultBrowserLPw(userId);
20531 clearIntentFilterVerificationsLPw(userId);
20532 primeDomainVerificationsLPw(userId);
20533 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20534 scheduleWritePackageRestrictionsLocked(userId);
20536 resetNetworkPolicies(userId);
20538 Binder.restoreCallingIdentity(identity);
20543 public int getPreferredActivities(List<IntentFilter> outFilters,
20544 List<ComponentName> outActivities, String packageName) {
20545 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20549 final int userId = UserHandle.getCallingUserId();
20551 synchronized (mPackages) {
20552 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20554 final Iterator<PreferredActivity> it = pir.filterIterator();
20555 while (it.hasNext()) {
20556 final PreferredActivity pa = it.next();
20557 if (packageName == null
20558 || (pa.mPref.mComponent.getPackageName().equals(packageName)
20559 && pa.mPref.mAlways)) {
20560 if (outFilters != null) {
20561 outFilters.add(new IntentFilter(pa));
20563 if (outActivities != null) {
20564 outActivities.add(pa.mPref.mComponent);
20575 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20577 int callingUid = Binder.getCallingUid();
20578 if (callingUid != Process.SYSTEM_UID) {
20579 throw new SecurityException(
20580 "addPersistentPreferredActivity can only be run by the system");
20582 if (filter.countActions() == 0) {
20583 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20586 synchronized (mPackages) {
20587 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20589 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20590 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20591 new PersistentPreferredActivity(filter, activity));
20592 scheduleWritePackageRestrictionsLocked(userId);
20593 postPreferredActivityChangedBroadcast(userId);
20598 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20599 int callingUid = Binder.getCallingUid();
20600 if (callingUid != Process.SYSTEM_UID) {
20601 throw new SecurityException(
20602 "clearPackagePersistentPreferredActivities can only be run by the system");
20604 ArrayList<PersistentPreferredActivity> removed = null;
20605 boolean changed = false;
20606 synchronized (mPackages) {
20607 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20608 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20609 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20611 if (userId != thisUserId) {
20614 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20615 while (it.hasNext()) {
20616 PersistentPreferredActivity ppa = it.next();
20617 // Mark entry for removal only if it matches the package name.
20618 if (ppa.mComponent.getPackageName().equals(packageName)) {
20619 if (removed == null) {
20620 removed = new ArrayList<PersistentPreferredActivity>();
20625 if (removed != null) {
20626 for (int j=0; j<removed.size(); j++) {
20627 PersistentPreferredActivity ppa = removed.get(j);
20628 ppir.removeFilter(ppa);
20635 scheduleWritePackageRestrictionsLocked(userId);
20636 postPreferredActivityChangedBroadcast(userId);
20642 * Common machinery for picking apart a restored XML blob and passing
20643 * it to a caller-supplied functor to be applied to the running system.
20645 private void restoreFromXml(XmlPullParser parser, int userId,
20646 String expectedStartTag, BlobXmlRestorer functor)
20647 throws IOException, XmlPullParserException {
20649 while ((type = parser.next()) != XmlPullParser.START_TAG
20650 && type != XmlPullParser.END_DOCUMENT) {
20652 if (type != XmlPullParser.START_TAG) {
20653 // oops didn't find a start tag?!
20654 if (DEBUG_BACKUP) {
20655 Slog.e(TAG, "Didn't find start tag during restore");
20659 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20660 // this is supposed to be TAG_PREFERRED_BACKUP
20661 if (!expectedStartTag.equals(parser.getName())) {
20662 if (DEBUG_BACKUP) {
20663 Slog.e(TAG, "Found unexpected tag " + parser.getName());
20668 // skip interfering stuff, then we're aligned with the backing implementation
20669 while ((type = parser.next()) == XmlPullParser.TEXT) { }
20670 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20671 functor.apply(parser, userId);
20674 private interface BlobXmlRestorer {
20675 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20679 * Non-Binder method, support for the backup/restore mechanism: write the
20680 * full set of preferred activities in its canonical XML format. Returns the
20681 * XML output as a byte array, or null if there is none.
20684 public byte[] getPreferredActivityBackup(int userId) {
20685 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20686 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20689 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20691 final XmlSerializer serializer = new FastXmlSerializer();
20692 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20693 serializer.startDocument(null, true);
20694 serializer.startTag(null, TAG_PREFERRED_BACKUP);
20696 synchronized (mPackages) {
20697 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20700 serializer.endTag(null, TAG_PREFERRED_BACKUP);
20701 serializer.endDocument();
20702 serializer.flush();
20703 } catch (Exception e) {
20704 if (DEBUG_BACKUP) {
20705 Slog.e(TAG, "Unable to write preferred activities for backup", e);
20710 return dataStream.toByteArray();
20714 public void restorePreferredActivities(byte[] backup, int userId) {
20715 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20716 throw new SecurityException("Only the system may call restorePreferredActivities()");
20720 final XmlPullParser parser = Xml.newPullParser();
20721 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20722 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20723 new BlobXmlRestorer() {
20725 public void apply(XmlPullParser parser, int userId)
20726 throws XmlPullParserException, IOException {
20727 synchronized (mPackages) {
20728 mSettings.readPreferredActivitiesLPw(parser, userId);
20732 } catch (Exception e) {
20733 if (DEBUG_BACKUP) {
20734 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20740 * Non-Binder method, support for the backup/restore mechanism: write the
20741 * default browser (etc) settings in its canonical XML format. Returns the default
20742 * browser XML representation as a byte array, or null if there is none.
20745 public byte[] getDefaultAppsBackup(int userId) {
20746 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20747 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20750 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20752 final XmlSerializer serializer = new FastXmlSerializer();
20753 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20754 serializer.startDocument(null, true);
20755 serializer.startTag(null, TAG_DEFAULT_APPS);
20757 synchronized (mPackages) {
20758 mSettings.writeDefaultAppsLPr(serializer, userId);
20761 serializer.endTag(null, TAG_DEFAULT_APPS);
20762 serializer.endDocument();
20763 serializer.flush();
20764 } catch (Exception e) {
20765 if (DEBUG_BACKUP) {
20766 Slog.e(TAG, "Unable to write default apps for backup", e);
20771 return dataStream.toByteArray();
20775 public void restoreDefaultApps(byte[] backup, int userId) {
20776 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20777 throw new SecurityException("Only the system may call restoreDefaultApps()");
20781 final XmlPullParser parser = Xml.newPullParser();
20782 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20783 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20784 new BlobXmlRestorer() {
20786 public void apply(XmlPullParser parser, int userId)
20787 throws XmlPullParserException, IOException {
20788 synchronized (mPackages) {
20789 mSettings.readDefaultAppsLPw(parser, userId);
20793 } catch (Exception e) {
20794 if (DEBUG_BACKUP) {
20795 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20801 public byte[] getIntentFilterVerificationBackup(int userId) {
20802 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20803 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20806 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20808 final XmlSerializer serializer = new FastXmlSerializer();
20809 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20810 serializer.startDocument(null, true);
20811 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20813 synchronized (mPackages) {
20814 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20817 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20818 serializer.endDocument();
20819 serializer.flush();
20820 } catch (Exception e) {
20821 if (DEBUG_BACKUP) {
20822 Slog.e(TAG, "Unable to write default apps for backup", e);
20827 return dataStream.toByteArray();
20831 public void restoreIntentFilterVerification(byte[] backup, int userId) {
20832 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20833 throw new SecurityException("Only the system may call restorePreferredActivities()");
20837 final XmlPullParser parser = Xml.newPullParser();
20838 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20839 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20840 new BlobXmlRestorer() {
20842 public void apply(XmlPullParser parser, int userId)
20843 throws XmlPullParserException, IOException {
20844 synchronized (mPackages) {
20845 mSettings.readAllDomainVerificationsLPr(parser, userId);
20846 mSettings.writeLPr();
20850 } catch (Exception e) {
20851 if (DEBUG_BACKUP) {
20852 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20858 public byte[] getPermissionGrantBackup(int userId) {
20859 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20860 throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20863 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20865 final XmlSerializer serializer = new FastXmlSerializer();
20866 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20867 serializer.startDocument(null, true);
20868 serializer.startTag(null, TAG_PERMISSION_BACKUP);
20870 synchronized (mPackages) {
20871 serializeRuntimePermissionGrantsLPr(serializer, userId);
20874 serializer.endTag(null, TAG_PERMISSION_BACKUP);
20875 serializer.endDocument();
20876 serializer.flush();
20877 } catch (Exception e) {
20878 if (DEBUG_BACKUP) {
20879 Slog.e(TAG, "Unable to write default apps for backup", e);
20884 return dataStream.toByteArray();
20888 public void restorePermissionGrants(byte[] backup, int userId) {
20889 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20890 throw new SecurityException("Only the system may call restorePermissionGrants()");
20894 final XmlPullParser parser = Xml.newPullParser();
20895 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20896 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20897 new BlobXmlRestorer() {
20899 public void apply(XmlPullParser parser, int userId)
20900 throws XmlPullParserException, IOException {
20901 synchronized (mPackages) {
20902 processRestoredPermissionGrantsLPr(parser, userId);
20906 } catch (Exception e) {
20907 if (DEBUG_BACKUP) {
20908 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20913 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20914 throws IOException {
20915 serializer.startTag(null, TAG_ALL_GRANTS);
20917 final int N = mSettings.mPackages.size();
20918 for (int i = 0; i < N; i++) {
20919 final PackageSetting ps = mSettings.mPackages.valueAt(i);
20920 boolean pkgGrantsKnown = false;
20922 PermissionsState packagePerms = ps.getPermissionsState();
20924 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20925 final int grantFlags = state.getFlags();
20926 // only look at grants that are not system/policy fixed
20927 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20928 final boolean isGranted = state.isGranted();
20929 // And only back up the user-twiddled state bits
20930 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20931 final String packageName = mSettings.mPackages.keyAt(i);
20932 if (!pkgGrantsKnown) {
20933 serializer.startTag(null, TAG_GRANT);
20934 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20935 pkgGrantsKnown = true;
20938 final boolean userSet =
20939 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20940 final boolean userFixed =
20941 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20942 final boolean revoke =
20943 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20945 serializer.startTag(null, TAG_PERMISSION);
20946 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20948 serializer.attribute(null, ATTR_IS_GRANTED, "true");
20951 serializer.attribute(null, ATTR_USER_SET, "true");
20954 serializer.attribute(null, ATTR_USER_FIXED, "true");
20957 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20959 serializer.endTag(null, TAG_PERMISSION);
20964 if (pkgGrantsKnown) {
20965 serializer.endTag(null, TAG_GRANT);
20969 serializer.endTag(null, TAG_ALL_GRANTS);
20972 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20973 throws XmlPullParserException, IOException {
20974 String pkgName = null;
20975 int outerDepth = parser.getDepth();
20977 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20978 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20979 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20983 final String tagName = parser.getName();
20984 if (tagName.equals(TAG_GRANT)) {
20985 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20986 if (DEBUG_BACKUP) {
20987 Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20989 } else if (tagName.equals(TAG_PERMISSION)) {
20991 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20992 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20994 int newFlagSet = 0;
20995 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20996 newFlagSet |= FLAG_PERMISSION_USER_SET;
20998 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20999 newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21001 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21002 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21004 if (DEBUG_BACKUP) {
21005 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName
21006 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21008 final PackageSetting ps = mSettings.mPackages.get(pkgName);
21010 // Already installed so we apply the grant immediately
21011 if (DEBUG_BACKUP) {
21012 Slog.v(TAG, " + already installed; applying");
21014 PermissionsState perms = ps.getPermissionsState();
21015 BasePermission bp = mSettings.mPermissions.get(permName);
21018 perms.grantRuntimePermission(bp, userId);
21020 if (newFlagSet != 0) {
21021 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21025 // Need to wait for post-restore install to apply the grant
21026 if (DEBUG_BACKUP) {
21027 Slog.v(TAG, " - not yet installed; saving for later");
21029 mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21030 isGranted, newFlagSet, userId);
21033 PackageManagerService.reportSettingsProblem(Log.WARN,
21034 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21035 XmlUtils.skipCurrentTag(parser);
21039 scheduleWriteSettingsLocked();
21040 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21044 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21045 int sourceUserId, int targetUserId, int flags) {
21046 mContext.enforceCallingOrSelfPermission(
21047 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21048 int callingUid = Binder.getCallingUid();
21049 enforceOwnerRights(ownerPackage, callingUid);
21050 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21051 if (intentFilter.countActions() == 0) {
21052 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21055 synchronized (mPackages) {
21056 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21057 ownerPackage, targetUserId, flags);
21058 CrossProfileIntentResolver resolver =
21059 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21060 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21061 // We have all those whose filter is equal. Now checking if the rest is equal as well.
21062 if (existing != null) {
21063 int size = existing.size();
21064 for (int i = 0; i < size; i++) {
21065 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21070 resolver.addFilter(newFilter);
21071 scheduleWritePackageRestrictionsLocked(sourceUserId);
21076 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21077 mContext.enforceCallingOrSelfPermission(
21078 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21079 final int callingUid = Binder.getCallingUid();
21080 enforceOwnerRights(ownerPackage, callingUid);
21081 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21082 synchronized (mPackages) {
21083 CrossProfileIntentResolver resolver =
21084 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21085 ArraySet<CrossProfileIntentFilter> set =
21086 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21087 for (CrossProfileIntentFilter filter : set) {
21088 if (filter.getOwnerPackage().equals(ownerPackage)) {
21089 resolver.removeFilter(filter);
21092 scheduleWritePackageRestrictionsLocked(sourceUserId);
21096 // Enforcing that callingUid is owning pkg on userId
21097 private void enforceOwnerRights(String pkg, int callingUid) {
21098 // The system owns everything.
21099 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21102 final int callingUserId = UserHandle.getUserId(callingUid);
21103 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21105 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21108 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21109 throw new SecurityException("Calling uid " + callingUid
21110 + " does not own package " + pkg);
21115 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21116 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21119 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21122 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21123 UserManagerService ums = UserManagerService.getInstance();
21125 final UserInfo parent = ums.getProfileParent(userId);
21126 final int launcherUid = (parent != null) ? parent.id : userId;
21127 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21128 if (launcherComponent != null) {
21129 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21130 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21131 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21132 .setPackage(launcherComponent.getPackageName());
21133 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21139 * Report the 'Home' activity which is currently set as "always use this one". If non is set
21140 * then reports the most likely home activity or null if there are more than one.
21142 private ComponentName getDefaultHomeActivity(int userId) {
21143 List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21144 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21149 // Find the launcher with the highest priority and return that component if there are no
21150 // other home activity with the same priority.
21151 int lastPriority = Integer.MIN_VALUE;
21152 ComponentName lastComponent = null;
21153 final int size = allHomeCandidates.size();
21154 for (int i = 0; i < size; i++) {
21155 final ResolveInfo ri = allHomeCandidates.get(i);
21156 if (ri.priority > lastPriority) {
21157 lastComponent = ri.activityInfo.getComponentName();
21158 lastPriority = ri.priority;
21159 } else if (ri.priority == lastPriority) {
21160 // Two components found with same priority.
21161 lastComponent = null;
21164 return lastComponent;
21167 private Intent getHomeIntent() {
21168 Intent intent = new Intent(Intent.ACTION_MAIN);
21169 intent.addCategory(Intent.CATEGORY_HOME);
21170 intent.addCategory(Intent.CATEGORY_DEFAULT);
21174 private IntentFilter getHomeFilter() {
21175 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21176 filter.addCategory(Intent.CATEGORY_HOME);
21177 filter.addCategory(Intent.CATEGORY_DEFAULT);
21181 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21183 Intent intent = getHomeIntent();
21184 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21185 PackageManager.GET_META_DATA, userId);
21186 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21187 true, false, false, userId);
21189 allHomeCandidates.clear();
21190 if (list != null) {
21191 for (ResolveInfo ri : list) {
21192 allHomeCandidates.add(ri);
21195 return (preferred == null || preferred.activityInfo == null)
21197 : new ComponentName(preferred.activityInfo.packageName,
21198 preferred.activityInfo.name);
21202 public void setHomeActivity(ComponentName comp, int userId) {
21203 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21206 ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21207 getHomeActivitiesAsUser(homeActivities, userId);
21209 boolean found = false;
21211 final int size = homeActivities.size();
21212 final ComponentName[] set = new ComponentName[size];
21213 for (int i = 0; i < size; i++) {
21214 final ResolveInfo candidate = homeActivities.get(i);
21215 final ActivityInfo info = candidate.activityInfo;
21216 final ComponentName activityName = new ComponentName(info.packageName, info.name);
21217 set[i] = activityName;
21218 if (!found && activityName.equals(comp)) {
21223 throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21226 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21227 set, comp, userId);
21230 private @Nullable String getSetupWizardPackageName() {
21231 final Intent intent = new Intent(Intent.ACTION_MAIN);
21232 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21234 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21235 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21236 | MATCH_DISABLED_COMPONENTS,
21237 UserHandle.myUserId());
21238 if (matches.size() == 1) {
21239 return matches.get(0).getComponentInfo().packageName;
21241 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21242 + ": matches=" + matches);
21247 private @Nullable String getStorageManagerPackageName() {
21248 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21250 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21251 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21252 | MATCH_DISABLED_COMPONENTS,
21253 UserHandle.myUserId());
21254 if (matches.size() == 1) {
21255 return matches.get(0).getComponentInfo().packageName;
21257 Slog.e(TAG, "There should probably be exactly one storage manager; found "
21258 + matches.size() + ": matches=" + matches);
21264 public void setApplicationEnabledSetting(String appPackageName,
21265 int newState, int flags, int userId, String callingPackage) {
21266 if (!sUserManager.exists(userId)) return;
21267 if (callingPackage == null) {
21268 callingPackage = Integer.toString(Binder.getCallingUid());
21270 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21274 public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21275 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21276 synchronized (mPackages) {
21277 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21278 if (pkgSetting != null) {
21279 pkgSetting.setUpdateAvailable(updateAvailable);
21285 public void setComponentEnabledSetting(ComponentName componentName,
21286 int newState, int flags, int userId) {
21287 if (!sUserManager.exists(userId)) return;
21288 setEnabledSetting(componentName.getPackageName(),
21289 componentName.getClassName(), newState, flags, userId, null);
21292 private void setEnabledSetting(final String packageName, String className, int newState,
21293 final int flags, int userId, String callingPackage) {
21294 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21295 || newState == COMPONENT_ENABLED_STATE_ENABLED
21296 || newState == COMPONENT_ENABLED_STATE_DISABLED
21297 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21298 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21299 throw new IllegalArgumentException("Invalid new component state: "
21302 PackageSetting pkgSetting;
21303 final int callingUid = Binder.getCallingUid();
21304 final int permission;
21305 if (callingUid == Process.SYSTEM_UID) {
21306 permission = PackageManager.PERMISSION_GRANTED;
21308 permission = mContext.checkCallingOrSelfPermission(
21309 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21311 enforceCrossUserPermission(callingUid, userId,
21312 false /* requireFullPermission */, true /* checkShell */, "set enabled");
21313 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21314 boolean sendNow = false;
21315 boolean isApp = (className == null);
21316 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21317 String componentName = isApp ? packageName : className;
21318 int packageUid = -1;
21319 ArrayList<String> components;
21322 synchronized (mPackages) {
21323 pkgSetting = mSettings.mPackages.get(packageName);
21324 if (pkgSetting == null) {
21325 if (!isCallerInstantApp) {
21326 if (className == null) {
21327 throw new IllegalArgumentException("Unknown package: " + packageName);
21329 throw new IllegalArgumentException(
21330 "Unknown component: " + packageName + "/" + className);
21332 // throw SecurityException to prevent leaking package information
21333 throw new SecurityException(
21334 "Attempt to change component state; "
21335 + "pid=" + Binder.getCallingPid()
21336 + ", uid=" + callingUid
21337 + (className == null
21338 ? ", package=" + packageName
21339 : ", component=" + packageName + "/" + className));
21344 // Limit who can change which apps
21345 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21346 // Don't allow apps that don't have permission to modify other apps
21347 if (!allowedByPermission
21348 || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21349 throw new SecurityException(
21350 "Attempt to change component state; "
21351 + "pid=" + Binder.getCallingPid()
21352 + ", uid=" + callingUid
21353 + (className == null
21354 ? ", package=" + packageName
21355 : ", component=" + packageName + "/" + className));
21357 // Don't allow changing protected packages.
21358 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21359 throw new SecurityException("Cannot disable a protected package: " + packageName);
21363 synchronized (mPackages) {
21364 if (callingUid == Process.SHELL_UID
21365 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21366 // Shell can only change whole packages between ENABLED and DISABLED_USER states
21367 // unless it is a test package.
21368 int oldState = pkgSetting.getEnabled(userId);
21369 if (className == null
21371 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21372 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21373 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21375 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21376 || newState == COMPONENT_ENABLED_STATE_DEFAULT
21377 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21380 throw new SecurityException(
21381 "Shell cannot change component state for " + packageName + "/"
21382 + className + " to " + newState);
21385 if (className == null) {
21386 // We're dealing with an application/package level state change
21387 if (pkgSetting.getEnabled(userId) == newState) {
21391 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21392 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21393 // Don't care about who enables an app.
21394 callingPackage = null;
21396 pkgSetting.setEnabled(newState, userId, callingPackage);
21397 // pkgSetting.pkg.mSetEnabled = newState;
21399 // We're dealing with a component level state change
21400 // First, verify that this is a valid class name.
21401 PackageParser.Package pkg = pkgSetting.pkg;
21402 if (pkg == null || !pkg.hasComponentClassName(className)) {
21404 pkg.applicationInfo.targetSdkVersion >=
21405 Build.VERSION_CODES.JELLY_BEAN) {
21406 throw new IllegalArgumentException("Component class " + className
21407 + " does not exist in " + packageName);
21409 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21410 + className + " does not exist in " + packageName);
21413 switch (newState) {
21414 case COMPONENT_ENABLED_STATE_ENABLED:
21415 if (!pkgSetting.enableComponentLPw(className, userId)) {
21419 case COMPONENT_ENABLED_STATE_DISABLED:
21420 if (!pkgSetting.disableComponentLPw(className, userId)) {
21424 case COMPONENT_ENABLED_STATE_DEFAULT:
21425 if (!pkgSetting.restoreComponentLPw(className, userId)) {
21430 Slog.e(TAG, "Invalid new component state: " + newState);
21434 scheduleWritePackageRestrictionsLocked(userId);
21435 updateSequenceNumberLP(pkgSetting, new int[] { userId });
21436 final long callingId = Binder.clearCallingIdentity();
21438 updateInstantAppInstallerLocked(packageName);
21440 Binder.restoreCallingIdentity(callingId);
21442 components = mPendingBroadcasts.get(userId, packageName);
21443 final boolean newPackage = components == null;
21445 components = new ArrayList<String>();
21447 if (!components.contains(componentName)) {
21448 components.add(componentName);
21450 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21452 // Purge entry from pending broadcast list if another one exists already
21453 // since we are sending one right away.
21454 mPendingBroadcasts.remove(userId, packageName);
21457 mPendingBroadcasts.put(userId, packageName, components);
21459 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21460 // Schedule a message
21461 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21466 long callingId = Binder.clearCallingIdentity();
21469 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21470 sendPackageChangedBroadcast(packageName,
21471 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21474 Binder.restoreCallingIdentity(callingId);
21479 public void flushPackageRestrictionsAsUser(int userId) {
21480 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21483 if (!sUserManager.exists(userId)) {
21486 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21487 false /* checkShell */, "flushPackageRestrictions");
21488 synchronized (mPackages) {
21489 mSettings.writePackageRestrictionsLPr(userId);
21490 mDirtyUsers.remove(userId);
21491 if (mDirtyUsers.isEmpty()) {
21492 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21497 private void sendPackageChangedBroadcast(String packageName,
21498 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21500 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21502 Bundle extras = new Bundle(4);
21503 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21504 String nameList[] = new String[componentNames.size()];
21505 componentNames.toArray(nameList);
21506 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21507 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21508 extras.putInt(Intent.EXTRA_UID, packageUid);
21509 // If this is not reporting a change of the overall package, then only send it
21510 // to registered receivers. We don't want to launch a swath of apps for every
21511 // little component state change.
21512 final int flags = !componentNames.contains(packageName)
21513 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21514 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null,
21515 new int[] {UserHandle.getUserId(packageUid)});
21519 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21520 if (!sUserManager.exists(userId)) return;
21521 final int callingUid = Binder.getCallingUid();
21522 if (getInstantAppPackageName(callingUid) != null) {
21525 final int permission = mContext.checkCallingOrSelfPermission(
21526 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21527 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21528 enforceCrossUserPermission(callingUid, userId,
21529 true /* requireFullPermission */, true /* checkShell */, "stop package");
21531 synchronized (mPackages) {
21532 final PackageSetting ps = mSettings.mPackages.get(packageName);
21533 if (!filterAppAccessLPr(ps, callingUid, userId)
21534 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21535 allowedByPermission, callingUid, userId)) {
21536 scheduleWritePackageRestrictionsLocked(userId);
21542 public String getInstallerPackageName(String packageName) {
21543 final int callingUid = Binder.getCallingUid();
21544 if (getInstantAppPackageName(callingUid) != null) {
21548 synchronized (mPackages) {
21549 final PackageSetting ps = mSettings.mPackages.get(packageName);
21550 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21553 return mSettings.getInstallerPackageNameLPr(packageName);
21557 public boolean isOrphaned(String packageName) {
21559 synchronized (mPackages) {
21560 return mSettings.isOrphaned(packageName);
21565 public int getApplicationEnabledSetting(String packageName, int userId) {
21566 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21567 int callingUid = Binder.getCallingUid();
21568 enforceCrossUserPermission(callingUid, userId,
21569 false /* requireFullPermission */, false /* checkShell */, "get enabled");
21571 synchronized (mPackages) {
21572 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21573 return COMPONENT_ENABLED_STATE_DISABLED;
21575 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21580 public int getComponentEnabledSetting(ComponentName component, int userId) {
21581 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21582 int callingUid = Binder.getCallingUid();
21583 enforceCrossUserPermission(callingUid, userId,
21584 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21585 synchronized (mPackages) {
21586 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21587 component, TYPE_UNKNOWN, userId)) {
21588 return COMPONENT_ENABLED_STATE_DISABLED;
21590 return mSettings.getComponentEnabledSettingLPr(component, userId);
21595 public void enterSafeMode() {
21596 enforceSystemOrRoot("Only the system can request entering safe mode");
21598 if (!mSystemReady) {
21604 public void systemReady() {
21605 enforceSystemOrRoot("Only the system can claim the system is ready");
21607 mSystemReady = true;
21608 final ContentResolver resolver = mContext.getContentResolver();
21609 ContentObserver co = new ContentObserver(mHandler) {
21611 public void onChange(boolean selfChange) {
21612 mEphemeralAppsDisabled =
21613 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21614 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21617 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21618 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21619 false, co, UserHandle.USER_SYSTEM);
21620 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21621 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21624 // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21625 // disabled after already being started.
21626 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21627 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21629 // Read the compatibilty setting when the system is ready.
21630 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21631 mContext.getContentResolver(),
21632 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21633 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21634 if (DEBUG_SETTINGS) {
21635 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21638 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21640 synchronized (mPackages) {
21641 // Verify that all of the preferred activity components actually
21642 // exist. It is possible for applications to be updated and at
21643 // that point remove a previously declared activity component that
21644 // had been set as a preferred activity. We try to clean this up
21645 // the next time we encounter that preferred activity, but it is
21646 // possible for the user flow to never be able to return to that
21647 // situation so here we do a sanity check to make sure we haven't
21648 // left any junk around.
21649 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21650 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21651 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21653 for (PreferredActivity pa : pir.filterSet()) {
21654 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21658 if (removed.size() > 0) {
21659 for (int r=0; r<removed.size(); r++) {
21660 PreferredActivity pa = removed.get(r);
21661 Slog.w(TAG, "Removing dangling preferred activity: "
21662 + pa.mPref.mComponent);
21663 pir.removeFilter(pa);
21665 mSettings.writePackageRestrictionsLPr(
21666 mSettings.mPreferredActivities.keyAt(i));
21670 for (int userId : UserManagerService.getInstance().getUserIds()) {
21671 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21672 grantPermissionsUserIds = ArrayUtils.appendInt(
21673 grantPermissionsUserIds, userId);
21677 sUserManager.systemReady();
21679 // If we upgraded grant all default permissions before kicking off.
21680 for (int userId : grantPermissionsUserIds) {
21681 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21684 // If we did not grant default permissions, we preload from this the
21685 // default permission exceptions lazily to ensure we don't hit the
21686 // disk on a new user creation.
21687 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21688 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21691 // Kick off any messages waiting for system ready
21692 if (mPostSystemReadyMessages != null) {
21693 for (Message msg : mPostSystemReadyMessages) {
21694 msg.sendToTarget();
21696 mPostSystemReadyMessages = null;
21699 // Watch for external volumes that come and go over time
21700 final StorageManager storage = mContext.getSystemService(StorageManager.class);
21701 storage.registerListener(mStorageListener);
21703 mInstallerService.systemReady();
21704 mPackageDexOptimizer.systemReady();
21706 StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21707 StorageManagerInternal.class);
21708 StorageManagerInternal.addExternalStoragePolicy(
21709 new StorageManagerInternal.ExternalStorageMountPolicy() {
21711 public int getMountMode(int uid, String packageName) {
21712 if (Process.isIsolated(uid)) {
21713 return Zygote.MOUNT_EXTERNAL_NONE;
21715 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21716 return Zygote.MOUNT_EXTERNAL_DEFAULT;
21718 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21719 return Zygote.MOUNT_EXTERNAL_DEFAULT;
21721 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21722 return Zygote.MOUNT_EXTERNAL_READ;
21724 return Zygote.MOUNT_EXTERNAL_WRITE;
21728 public boolean hasExternalStorage(int uid, String packageName) {
21733 // Now that we're mostly running, clean up stale users and apps
21734 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21735 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21737 if (mPrivappPermissionsViolations != null) {
21738 Slog.wtf(TAG,"Signature|privileged permissions not in "
21739 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21740 mPrivappPermissionsViolations = null;
21744 public void waitForAppDataPrepared() {
21745 if (mPrepareAppDataFuture == null) {
21748 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21749 mPrepareAppDataFuture = null;
21753 public boolean isSafeMode() {
21754 // allow instant applications
21759 public boolean hasSystemUidErrors() {
21760 // allow instant applications
21761 return mHasSystemUidErrors;
21764 static String arrayToString(int[] array) {
21765 StringBuffer buf = new StringBuffer(128);
21767 if (array != null) {
21768 for (int i=0; i<array.length; i++) {
21769 if (i > 0) buf.append(", ");
21770 buf.append(array[i]);
21774 return buf.toString();
21777 static class DumpState {
21778 public static final int DUMP_LIBS = 1 << 0;
21779 public static final int DUMP_FEATURES = 1 << 1;
21780 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21781 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21782 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21783 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21784 public static final int DUMP_PERMISSIONS = 1 << 6;
21785 public static final int DUMP_PACKAGES = 1 << 7;
21786 public static final int DUMP_SHARED_USERS = 1 << 8;
21787 public static final int DUMP_MESSAGES = 1 << 9;
21788 public static final int DUMP_PROVIDERS = 1 << 10;
21789 public static final int DUMP_VERIFIERS = 1 << 11;
21790 public static final int DUMP_PREFERRED = 1 << 12;
21791 public static final int DUMP_PREFERRED_XML = 1 << 13;
21792 public static final int DUMP_KEYSETS = 1 << 14;
21793 public static final int DUMP_VERSION = 1 << 15;
21794 public static final int DUMP_INSTALLS = 1 << 16;
21795 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21796 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21797 public static final int DUMP_FROZEN = 1 << 19;
21798 public static final int DUMP_DEXOPT = 1 << 20;
21799 public static final int DUMP_COMPILER_STATS = 1 << 21;
21800 public static final int DUMP_CHANGES = 1 << 22;
21802 public static final int OPTION_SHOW_FILTERS = 1 << 0;
21804 private int mTypes;
21806 private int mOptions;
21808 private boolean mTitlePrinted;
21810 private SharedUserSetting mSharedUser;
21812 public boolean isDumping(int type) {
21813 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21817 return (mTypes & type) != 0;
21820 public void setDump(int type) {
21824 public boolean isOptionEnabled(int option) {
21825 return (mOptions & option) != 0;
21828 public void setOptionEnabled(int option) {
21829 mOptions |= option;
21832 public boolean onTitlePrinted() {
21833 final boolean printed = mTitlePrinted;
21834 mTitlePrinted = true;
21838 public boolean getTitlePrinted() {
21839 return mTitlePrinted;
21842 public void setTitlePrinted(boolean enabled) {
21843 mTitlePrinted = enabled;
21846 public SharedUserSetting getSharedUser() {
21847 return mSharedUser;
21850 public void setSharedUser(SharedUserSetting user) {
21851 mSharedUser = user;
21856 public void onShellCommand(FileDescriptor in, FileDescriptor out,
21857 FileDescriptor err, String[] args, ShellCallback callback,
21858 ResultReceiver resultReceiver) {
21859 (new PackageManagerShellCommand(this)).exec(
21860 this, in, out, err, args, callback, resultReceiver);
21864 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21865 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21867 DumpState dumpState = new DumpState();
21868 boolean fullPreferred = false;
21869 boolean checkin = false;
21871 String packageName = null;
21872 ArraySet<String> permissionNames = null;
21875 while (opti < args.length) {
21876 String opt = args[opti];
21877 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21882 if ("-a".equals(opt)) {
21883 // Right now we only know how to print all.
21884 } else if ("-h".equals(opt)) {
21885 pw.println("Package manager dump options:");
21886 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
21887 pw.println(" --checkin: dump for a checkin");
21888 pw.println(" -f: print details of intent filters");
21889 pw.println(" -h: print this help");
21890 pw.println(" cmd may be one of:");
21891 pw.println(" l[ibraries]: list known shared libraries");
21892 pw.println(" f[eatures]: list device features");
21893 pw.println(" k[eysets]: print known keysets");
21894 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21895 pw.println(" perm[issions]: dump permissions");
21896 pw.println(" permission [name ...]: dump declaration and use of given permission");
21897 pw.println(" pref[erred]: print preferred package settings");
21898 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
21899 pw.println(" prov[iders]: dump content providers");
21900 pw.println(" p[ackages]: dump installed packages");
21901 pw.println(" s[hared-users]: dump shared user IDs");
21902 pw.println(" m[essages]: print collected runtime messages");
21903 pw.println(" v[erifiers]: print package verifier info");
21904 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
21905 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21906 pw.println(" version: print database version info");
21907 pw.println(" write: write current settings now");
21908 pw.println(" installs: details about install sessions");
21909 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
21910 pw.println(" dexopt: dump dexopt state");
21911 pw.println(" compiler-stats: dump compiler statistics");
21912 pw.println(" enabled-overlays: dump list of enabled overlay packages");
21913 pw.println(" <package.name>: info about given package");
21915 } else if ("--checkin".equals(opt)) {
21917 } else if ("-f".equals(opt)) {
21918 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21919 } else if ("--proto".equals(opt)) {
21923 pw.println("Unknown argument: " + opt + "; use -h for help");
21927 // Is the caller requesting to dump a particular piece of data?
21928 if (opti < args.length) {
21929 String cmd = args[opti];
21931 // Is this a package name?
21932 if ("android".equals(cmd) || cmd.contains(".")) {
21934 // When dumping a single package, we always dump all of its
21935 // filter information since the amount of data will be reasonable.
21936 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21937 } else if ("check-permission".equals(cmd)) {
21938 if (opti >= args.length) {
21939 pw.println("Error: check-permission missing permission argument");
21942 String perm = args[opti];
21944 if (opti >= args.length) {
21945 pw.println("Error: check-permission missing package argument");
21949 String pkg = args[opti];
21951 int user = UserHandle.getUserId(Binder.getCallingUid());
21952 if (opti < args.length) {
21954 user = Integer.parseInt(args[opti]);
21955 } catch (NumberFormatException e) {
21956 pw.println("Error: check-permission user argument is not a number: "
21962 // Normalize package name to handle renamed packages and static libs
21963 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21965 pw.println(checkPermission(perm, pkg, user));
21967 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21968 dumpState.setDump(DumpState.DUMP_LIBS);
21969 } else if ("f".equals(cmd) || "features".equals(cmd)) {
21970 dumpState.setDump(DumpState.DUMP_FEATURES);
21971 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21972 if (opti >= args.length) {
21973 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21974 | DumpState.DUMP_SERVICE_RESOLVERS
21975 | DumpState.DUMP_RECEIVER_RESOLVERS
21976 | DumpState.DUMP_CONTENT_RESOLVERS);
21978 while (opti < args.length) {
21979 String name = args[opti];
21980 if ("a".equals(name) || "activity".equals(name)) {
21981 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21982 } else if ("s".equals(name) || "service".equals(name)) {
21983 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21984 } else if ("r".equals(name) || "receiver".equals(name)) {
21985 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21986 } else if ("c".equals(name) || "content".equals(name)) {
21987 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21989 pw.println("Error: unknown resolver table type: " + name);
21995 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21996 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21997 } else if ("permission".equals(cmd)) {
21998 if (opti >= args.length) {
21999 pw.println("Error: permission requires permission name");
22002 permissionNames = new ArraySet<>();
22003 while (opti < args.length) {
22004 permissionNames.add(args[opti]);
22007 dumpState.setDump(DumpState.DUMP_PERMISSIONS
22008 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22009 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22010 dumpState.setDump(DumpState.DUMP_PREFERRED);
22011 } else if ("preferred-xml".equals(cmd)) {
22012 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22013 if (opti < args.length && "--full".equals(args[opti])) {
22014 fullPreferred = true;
22017 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22018 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22019 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22020 dumpState.setDump(DumpState.DUMP_PACKAGES);
22021 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22022 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22023 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22024 dumpState.setDump(DumpState.DUMP_PROVIDERS);
22025 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22026 dumpState.setDump(DumpState.DUMP_MESSAGES);
22027 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22028 dumpState.setDump(DumpState.DUMP_VERIFIERS);
22029 } else if ("i".equals(cmd) || "ifv".equals(cmd)
22030 || "intent-filter-verifiers".equals(cmd)) {
22031 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22032 } else if ("version".equals(cmd)) {
22033 dumpState.setDump(DumpState.DUMP_VERSION);
22034 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22035 dumpState.setDump(DumpState.DUMP_KEYSETS);
22036 } else if ("installs".equals(cmd)) {
22037 dumpState.setDump(DumpState.DUMP_INSTALLS);
22038 } else if ("frozen".equals(cmd)) {
22039 dumpState.setDump(DumpState.DUMP_FROZEN);
22040 } else if ("dexopt".equals(cmd)) {
22041 dumpState.setDump(DumpState.DUMP_DEXOPT);
22042 } else if ("compiler-stats".equals(cmd)) {
22043 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22044 } else if ("changes".equals(cmd)) {
22045 dumpState.setDump(DumpState.DUMP_CHANGES);
22046 } else if ("write".equals(cmd)) {
22047 synchronized (mPackages) {
22048 mSettings.writeLPr();
22049 pw.println("Settings written.");
22056 pw.println("vers,1");
22060 synchronized (mPackages) {
22061 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22063 if (dumpState.onTitlePrinted())
22065 pw.println("Database versions:");
22066 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
22070 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22072 if (dumpState.onTitlePrinted())
22074 pw.println("Verifiers:");
22075 pw.print(" Required: ");
22076 pw.print(mRequiredVerifierPackage);
22077 pw.print(" (uid=");
22078 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22079 UserHandle.USER_SYSTEM));
22081 } else if (mRequiredVerifierPackage != null) {
22082 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22084 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22085 UserHandle.USER_SYSTEM));
22089 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22090 packageName == null) {
22091 if (mIntentFilterVerifierComponent != null) {
22092 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22094 if (dumpState.onTitlePrinted())
22096 pw.println("Intent Filter Verifier:");
22097 pw.print(" Using: ");
22098 pw.print(verifierPackageName);
22099 pw.print(" (uid=");
22100 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22101 UserHandle.USER_SYSTEM));
22103 } else if (verifierPackageName != null) {
22104 pw.print("ifv,"); pw.print(verifierPackageName);
22106 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22107 UserHandle.USER_SYSTEM));
22111 pw.println("No Intent Filter Verifier available!");
22115 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22116 boolean printedHeader = false;
22117 final Iterator<String> it = mSharedLibraries.keySet().iterator();
22118 while (it.hasNext()) {
22119 String libName = it.next();
22120 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22121 if (versionedLib == null) {
22124 final int versionCount = versionedLib.size();
22125 for (int i = 0; i < versionCount; i++) {
22126 SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22128 if (!printedHeader) {
22129 if (dumpState.onTitlePrinted())
22131 pw.println("Libraries:");
22132 printedHeader = true;
22138 pw.print(libEntry.info.getName());
22139 if (libEntry.info.isStatic()) {
22140 pw.print(" version=" + libEntry.info.getVersion());
22145 if (libEntry.path != null) {
22146 pw.print(" (jar) ");
22147 pw.print(libEntry.path);
22149 pw.print(" (apk) ");
22150 pw.print(libEntry.apk);
22157 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22158 if (dumpState.onTitlePrinted())
22161 pw.println("Features:");
22164 synchronized (mAvailableFeatures) {
22165 for (FeatureInfo feat : mAvailableFeatures.values()) {
22168 pw.print(feat.name);
22170 pw.println(feat.version);
22173 pw.print(feat.name);
22174 if (feat.version > 0) {
22175 pw.print(" version=");
22176 pw.print(feat.version);
22184 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22185 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22186 : "Activity Resolver Table:", " ", packageName,
22187 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22188 dumpState.setTitlePrinted(true);
22191 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22192 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22193 : "Receiver Resolver Table:", " ", packageName,
22194 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22195 dumpState.setTitlePrinted(true);
22198 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22199 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22200 : "Service Resolver Table:", " ", packageName,
22201 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22202 dumpState.setTitlePrinted(true);
22205 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22206 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22207 : "Provider Resolver Table:", " ", packageName,
22208 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22209 dumpState.setTitlePrinted(true);
22213 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22214 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22215 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22216 int user = mSettings.mPreferredActivities.keyAt(i);
22218 dumpState.getTitlePrinted()
22219 ? "\nPreferred Activities User " + user + ":"
22220 : "Preferred Activities User " + user + ":", " ",
22221 packageName, true, false)) {
22222 dumpState.setTitlePrinted(true);
22227 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22229 FileOutputStream fout = new FileOutputStream(fd);
22230 BufferedOutputStream str = new BufferedOutputStream(fout);
22231 XmlSerializer serializer = new FastXmlSerializer();
22233 serializer.setOutput(str, StandardCharsets.UTF_8.name());
22234 serializer.startDocument(null, true);
22235 serializer.setFeature(
22236 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22237 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22238 serializer.endDocument();
22239 serializer.flush();
22240 } catch (IllegalArgumentException e) {
22241 pw.println("Failed writing: " + e);
22242 } catch (IllegalStateException e) {
22243 pw.println("Failed writing: " + e);
22244 } catch (IOException e) {
22245 pw.println("Failed writing: " + e);
22250 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22251 && packageName == null) {
22253 int count = mSettings.mPackages.size();
22255 pw.println("No applications!");
22258 final String prefix = " ";
22259 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22260 if (allPackageSettings.size() == 0) {
22261 pw.println("No domain preferred apps!");
22264 pw.println("App verification status:");
22267 for (PackageSetting ps : allPackageSettings) {
22268 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22269 if (ivi == null || ivi.getPackageName() == null) continue;
22270 pw.println(prefix + "Package: " + ivi.getPackageName());
22271 pw.println(prefix + "Domains: " + ivi.getDomainsString());
22272 pw.println(prefix + "Status: " + ivi.getStatusString());
22277 pw.println(prefix + "No app verification established.");
22280 for (int userId : sUserManager.getUserIds()) {
22281 pw.println("App linkages for user " + userId + ":");
22284 for (PackageSetting ps : allPackageSettings) {
22285 final long status = ps.getDomainVerificationStatusForUser(userId);
22286 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22287 && !DEBUG_DOMAIN_VERIFICATION) {
22290 pw.println(prefix + "Package: " + ps.name);
22291 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22292 String statusStr = IntentFilterVerificationInfo.
22293 getStatusStringFromValue(status);
22294 pw.println(prefix + "Status: " + statusStr);
22299 pw.println(prefix + "No configured app linkages.");
22307 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22308 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22309 if (packageName == null && permissionNames == null) {
22310 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22312 if (dumpState.onTitlePrinted())
22314 pw.println("AppOp Permissions:");
22316 pw.print(" AppOp Permission ");
22317 pw.print(mAppOpPermissionPackages.keyAt(iperm));
22319 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22320 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22321 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
22327 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22328 boolean printedSomething = false;
22329 for (PackageParser.Provider p : mProviders.mProviders.values()) {
22330 if (packageName != null && !packageName.equals(p.info.packageName)) {
22333 if (!printedSomething) {
22334 if (dumpState.onTitlePrinted())
22336 pw.println("Registered ContentProviders:");
22337 printedSomething = true;
22339 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
22340 pw.print(" "); pw.println(p.toString());
22342 printedSomething = false;
22343 for (Map.Entry<String, PackageParser.Provider> entry :
22344 mProvidersByAuthority.entrySet()) {
22345 PackageParser.Provider p = entry.getValue();
22346 if (packageName != null && !packageName.equals(p.info.packageName)) {
22349 if (!printedSomething) {
22350 if (dumpState.onTitlePrinted())
22352 pw.println("ContentProvider Authorities:");
22353 printedSomething = true;
22355 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
22356 pw.print(" "); pw.println(p.toString());
22357 if (p.info != null && p.info.applicationInfo != null) {
22358 final String appInfo = p.info.applicationInfo.toString();
22359 pw.print(" applicationInfo="); pw.println(appInfo);
22364 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22365 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22368 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22369 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22372 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22373 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22376 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22377 if (dumpState.onTitlePrinted()) pw.println();
22378 pw.println("Package Changes:");
22379 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22380 final int K = mChangedPackages.size();
22381 for (int i = 0; i < K; i++) {
22382 final SparseArray<String> changes = mChangedPackages.valueAt(i);
22383 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22384 final int N = changes.size();
22386 pw.print(" "); pw.println("No packages changed");
22388 for (int j = 0; j < N; j++) {
22389 final String pkgName = changes.valueAt(j);
22390 final int sequenceNumber = changes.keyAt(j);
22393 pw.print(sequenceNumber);
22394 pw.print(", package=");
22395 pw.println(pkgName);
22401 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22402 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22405 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22406 // XXX should handle packageName != null by dumping only install data that
22407 // the given package is involved with.
22408 if (dumpState.onTitlePrinted()) pw.println();
22410 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
22412 ipw.println("Frozen packages:");
22413 ipw.increaseIndent();
22414 if (mFrozenPackages.size() == 0) {
22415 ipw.println("(none)");
22417 for (int i = 0; i < mFrozenPackages.size(); i++) {
22418 ipw.println(mFrozenPackages.valueAt(i));
22421 ipw.decreaseIndent();
22424 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22425 if (dumpState.onTitlePrinted()) pw.println();
22426 dumpDexoptStateLPr(pw, packageName);
22429 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22430 if (dumpState.onTitlePrinted()) pw.println();
22431 dumpCompilerStatsLPr(pw, packageName);
22434 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22435 if (dumpState.onTitlePrinted()) pw.println();
22436 mSettings.dumpReadMessagesLPr(pw, dumpState);
22439 pw.println("Package warning messages:");
22440 BufferedReader in = null;
22441 String line = null;
22443 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22444 while ((line = in.readLine()) != null) {
22445 if (line.contains("ignored: updated version")) continue;
22448 } catch (IOException ignored) {
22450 IoUtils.closeQuietly(in);
22454 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22455 BufferedReader in = null;
22456 String line = null;
22458 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22459 while ((line = in.readLine()) != null) {
22460 if (line.contains("ignored: updated version")) continue;
22464 } catch (IOException ignored) {
22466 IoUtils.closeQuietly(in);
22471 // PackageInstaller should be called outside of mPackages lock
22472 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22473 // XXX should handle packageName != null by dumping only install data that
22474 // the given package is involved with.
22475 if (dumpState.onTitlePrinted()) pw.println();
22476 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
22480 private void dumpProto(FileDescriptor fd) {
22481 final ProtoOutputStream proto = new ProtoOutputStream(fd);
22483 synchronized (mPackages) {
22484 final long requiredVerifierPackageToken =
22485 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22486 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22488 PackageServiceDumpProto.PackageShortProto.UID,
22490 mRequiredVerifierPackage,
22491 MATCH_DEBUG_TRIAGED_MISSING,
22492 UserHandle.USER_SYSTEM));
22493 proto.end(requiredVerifierPackageToken);
22495 if (mIntentFilterVerifierComponent != null) {
22496 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22497 final long verifierPackageToken =
22498 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22499 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22501 PackageServiceDumpProto.PackageShortProto.UID,
22503 verifierPackageName,
22504 MATCH_DEBUG_TRIAGED_MISSING,
22505 UserHandle.USER_SYSTEM));
22506 proto.end(verifierPackageToken);
22509 dumpSharedLibrariesProto(proto);
22510 dumpFeaturesProto(proto);
22511 mSettings.dumpPackagesProto(proto);
22512 mSettings.dumpSharedUsersProto(proto);
22513 dumpMessagesProto(proto);
22518 private void dumpMessagesProto(ProtoOutputStream proto) {
22519 BufferedReader in = null;
22520 String line = null;
22522 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22523 while ((line = in.readLine()) != null) {
22524 if (line.contains("ignored: updated version")) continue;
22525 proto.write(PackageServiceDumpProto.MESSAGES, line);
22527 } catch (IOException ignored) {
22529 IoUtils.closeQuietly(in);
22533 private void dumpFeaturesProto(ProtoOutputStream proto) {
22534 synchronized (mAvailableFeatures) {
22535 final int count = mAvailableFeatures.size();
22536 for (int i = 0; i < count; i++) {
22537 final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22538 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22539 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22540 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22541 proto.end(featureToken);
22546 private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22547 final int count = mSharedLibraries.size();
22548 for (int i = 0; i < count; i++) {
22549 final String libName = mSharedLibraries.keyAt(i);
22550 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22551 if (versionedLib == null) {
22554 final int versionCount = versionedLib.size();
22555 for (int j = 0; j < versionCount; j++) {
22556 final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22557 final long sharedLibraryToken =
22558 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22559 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22560 final boolean isJar = (libEntry.path != null);
22561 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22563 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22565 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22567 proto.end(sharedLibraryToken);
22572 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22573 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
22575 ipw.println("Dexopt state:");
22576 ipw.increaseIndent();
22577 Collection<PackageParser.Package> packages = null;
22578 if (packageName != null) {
22579 PackageParser.Package targetPackage = mPackages.get(packageName);
22580 if (targetPackage != null) {
22581 packages = Collections.singletonList(targetPackage);
22583 ipw.println("Unable to find package: " + packageName);
22587 packages = mPackages.values();
22590 for (PackageParser.Package pkg : packages) {
22591 ipw.println("[" + pkg.packageName + "]");
22592 ipw.increaseIndent();
22593 mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22594 ipw.decreaseIndent();
22598 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22599 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
22601 ipw.println("Compiler stats:");
22602 ipw.increaseIndent();
22603 Collection<PackageParser.Package> packages = null;
22604 if (packageName != null) {
22605 PackageParser.Package targetPackage = mPackages.get(packageName);
22606 if (targetPackage != null) {
22607 packages = Collections.singletonList(targetPackage);
22609 ipw.println("Unable to find package: " + packageName);
22613 packages = mPackages.values();
22616 for (PackageParser.Package pkg : packages) {
22617 ipw.println("[" + pkg.packageName + "]");
22618 ipw.increaseIndent();
22620 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22621 if (stats == null) {
22622 ipw.println("(No recorded stats)");
22626 ipw.decreaseIndent();
22630 private String dumpDomainString(String packageName) {
22631 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22633 List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22635 ArraySet<String> result = new ArraySet<>();
22636 if (iviList.size() > 0) {
22637 for (IntentFilterVerificationInfo ivi : iviList) {
22638 for (String host : ivi.getDomains()) {
22643 if (filters != null && filters.size() > 0) {
22644 for (IntentFilter filter : filters) {
22645 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22646 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22647 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22648 result.addAll(filter.getHostsList());
22653 StringBuilder sb = new StringBuilder(result.size() * 16);
22654 for (String domain : result) {
22655 if (sb.length() > 0) sb.append(" ");
22658 return sb.toString();
22661 // ------- apps on sdcard specific code -------
22662 static final boolean DEBUG_SD_INSTALL = false;
22664 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22666 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22668 private boolean mMediaMounted = false;
22670 static String getEncryptKey() {
22672 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22673 SD_ENCRYPTION_KEYSTORE_NAME);
22674 if (sdEncKey == null) {
22675 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22676 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22677 if (sdEncKey == null) {
22678 Slog.e(TAG, "Failed to create encryption keys");
22683 } catch (NoSuchAlgorithmException nsae) {
22684 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22686 } catch (IOException ioe) {
22687 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22693 * Update media status on PackageManager.
22696 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22697 enforceSystemOrRoot("Media status can only be updated by the system");
22698 // reader; this apparently protects mMediaMounted, but should probably
22699 // be a different lock in that case.
22700 synchronized (mPackages) {
22701 Log.i(TAG, "Updating external media status from "
22702 + (mMediaMounted ? "mounted" : "unmounted") + " to "
22703 + (mediaStatus ? "mounted" : "unmounted"));
22704 if (DEBUG_SD_INSTALL)
22705 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22706 + ", mMediaMounted=" + mMediaMounted);
22707 if (mediaStatus == mMediaMounted) {
22708 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22710 mHandler.sendMessage(msg);
22713 mMediaMounted = mediaStatus;
22715 // Queue up an async operation since the package installation may take a
22717 mHandler.post(new Runnable() {
22718 public void run() {
22719 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22725 * Called by StorageManagerService when the initial ASECs to scan are available.
22726 * Should block until all the ASEC containers are finished being scanned.
22728 public void scanAvailableAsecs() {
22729 updateExternalMediaStatusInner(true, false, false);
22733 * Collect information of applications on external media, map them against
22734 * existing containers and update information based on current mount status.
22735 * Please note that we always have to report status if reportStatus has been
22736 * set to true especially when unloading packages.
22738 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22739 boolean externalStorage) {
22740 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22741 int[] uidArr = EmptyArray.INT;
22743 final String[] list = PackageHelper.getSecureContainerList();
22744 if (ArrayUtils.isEmpty(list)) {
22745 Log.i(TAG, "No secure containers found");
22747 // Process list of secure containers and categorize them
22748 // as active or stale based on their package internal state.
22751 synchronized (mPackages) {
22752 for (String cid : list) {
22753 // Leave stages untouched for now; installer service owns them
22754 if (PackageInstallerService.isStageName(cid)) continue;
22756 if (DEBUG_SD_INSTALL)
22757 Log.i(TAG, "Processing container " + cid);
22758 String pkgName = getAsecPackageName(cid);
22759 if (pkgName == null) {
22760 Slog.i(TAG, "Found stale container " + cid + " with no package name");
22763 if (DEBUG_SD_INSTALL)
22764 Log.i(TAG, "Looking for pkg : " + pkgName);
22766 final PackageSetting ps = mSettings.mPackages.get(pkgName);
22768 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22773 * Skip packages that are not external if we're unmounting
22774 * external storage.
22776 if (externalStorage && !isMounted && !isExternal(ps)) {
22780 final AsecInstallArgs args = new AsecInstallArgs(cid,
22781 getAppDexInstructionSets(ps), ps.isForwardLocked());
22782 // The package status is changed only if the code path
22783 // matches between settings and the container id.
22784 if (ps.codePathString != null
22785 && ps.codePathString.startsWith(args.getCodePath())) {
22786 if (DEBUG_SD_INSTALL) {
22787 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22788 + " at code path: " + ps.codePathString);
22791 // We do have a valid package installed on sdcard
22792 processCids.put(args, ps.codePathString);
22793 final int uid = ps.appId;
22795 uidArr = ArrayUtils.appendInt(uidArr, uid);
22798 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22799 + ps.codePathString);
22804 Arrays.sort(uidArr);
22807 // Process packages with valid entries.
22809 if (DEBUG_SD_INSTALL)
22810 Log.i(TAG, "Loading packages");
22811 loadMediaPackages(processCids, uidArr, externalStorage);
22812 startCleaningPackages();
22813 mInstallerService.onSecureContainersAvailable();
22815 if (DEBUG_SD_INSTALL)
22816 Log.i(TAG, "Unloading packages");
22817 unloadMediaPackages(processCids, uidArr, reportStatus);
22821 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22822 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22823 final int size = infos.size();
22824 final String[] packageNames = new String[size];
22825 final int[] packageUids = new int[size];
22826 for (int i = 0; i < size; i++) {
22827 final ApplicationInfo info = infos.get(i);
22828 packageNames[i] = info.packageName;
22829 packageUids[i] = info.uid;
22831 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22835 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22836 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22837 sendResourcesChangedBroadcast(mediaStatus, replacing,
22838 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22841 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22842 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22843 int size = pkgList.length;
22845 // Send broadcasts here
22846 Bundle extras = new Bundle();
22847 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22848 if (uidArr != null) {
22849 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22852 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22854 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22855 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22856 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22861 * Look at potentially valid container ids from processCids If package
22862 * information doesn't match the one on record or package scanning fails,
22863 * the cid is added to list of removeCids. We currently don't delete stale
22866 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22867 boolean externalStorage) {
22868 ArrayList<String> pkgList = new ArrayList<String>();
22869 Set<AsecInstallArgs> keys = processCids.keySet();
22871 for (AsecInstallArgs args : keys) {
22872 String codePath = processCids.get(args);
22873 if (DEBUG_SD_INSTALL)
22874 Log.i(TAG, "Loading container : " + args.cid);
22875 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22877 // Make sure there are no container errors first.
22878 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22879 Slog.e(TAG, "Failed to mount cid : " + args.cid
22880 + " when installing from sdcard");
22883 // Check code path here.
22884 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22885 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22886 + " does not match one in settings " + codePath);
22890 int parseFlags = mDefParseFlags;
22891 if (args.isExternalAsec()) {
22892 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22894 if (args.isFwdLocked()) {
22895 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22898 synchronized (mInstallLock) {
22899 PackageParser.Package pkg = null;
22901 // Sadly we don't know the package name yet to freeze it
22902 pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22903 SCAN_IGNORE_FROZEN, 0, null);
22904 } catch (PackageManagerException e) {
22905 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22907 // Scan the package
22910 * TODO why is the lock being held? doPostInstall is
22911 * called in other places without the lock. This needs
22912 * to be straightened out.
22915 synchronized (mPackages) {
22916 retCode = PackageManager.INSTALL_SUCCEEDED;
22917 pkgList.add(pkg.packageName);
22918 // Post process args
22919 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22920 pkg.applicationInfo.uid);
22923 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
22928 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22929 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22934 synchronized (mPackages) {
22935 // If the platform SDK has changed since the last time we booted,
22936 // we need to re-grant app permission to catch any new ones that
22937 // appear. This is really a hack, and means that apps can in some
22938 // cases get permissions that the user didn't initially explicitly
22939 // allow... it would be nice to have some better way to handle
22941 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22942 : mSettings.getInternalVersion();
22943 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22944 : StorageManager.UUID_PRIVATE_INTERNAL;
22946 int updateFlags = UPDATE_PERMISSIONS_ALL;
22947 if (ver.sdkVersion != mSdkVersion) {
22948 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22949 + mSdkVersion + "; regranting permissions for external");
22950 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22952 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22954 // Yay, everything is now upgraded
22955 ver.forceCurrent();
22957 // can downgrade to reader
22958 // Persist settings
22959 mSettings.writeLPr();
22961 // Send a broadcast to let everyone know we are done processing
22962 if (pkgList.size() > 0) {
22963 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22968 * Utility method to unload a list of specified containers
22970 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22971 // Just unmount all valid containers.
22972 for (AsecInstallArgs arg : cidArgs) {
22973 synchronized (mInstallLock) {
22974 arg.doPostDeleteLI(false);
22980 * Unload packages mounted on external media. This involves deleting package
22981 * data from internal structures, sending broadcasts about disabled packages,
22982 * gc'ing to free up references, unmounting all secure containers
22983 * corresponding to packages on external media, and posting a
22984 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22985 * that we always have to post this message if status has been requested no
22988 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22989 final boolean reportStatus) {
22990 if (DEBUG_SD_INSTALL)
22991 Log.i(TAG, "unloading media packages");
22992 ArrayList<String> pkgList = new ArrayList<String>();
22993 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22994 final Set<AsecInstallArgs> keys = processCids.keySet();
22995 for (AsecInstallArgs args : keys) {
22996 String pkgName = args.getPackageName();
22997 if (DEBUG_SD_INSTALL)
22998 Log.i(TAG, "Trying to unload pkg : " + pkgName);
22999 // Delete package internally
23000 PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23001 synchronized (mInstallLock) {
23002 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23004 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23005 "unloadMediaPackages")) {
23006 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23010 pkgList.add(pkgName);
23012 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23013 failedList.add(args);
23019 synchronized (mPackages) {
23020 // We didn't update the settings after removing each package;
23021 // write them now for all packages.
23022 mSettings.writeLPr();
23025 // We have to absolutely send UPDATED_MEDIA_STATUS only
23026 // after confirming that all the receivers processed the ordered
23027 // broadcast when packages get disabled, force a gc to clean things up.
23028 // and unload all the containers.
23029 if (pkgList.size() > 0) {
23030 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23031 new IIntentReceiver.Stub() {
23032 public void performReceive(Intent intent, int resultCode, String data,
23033 Bundle extras, boolean ordered, boolean sticky,
23034 int sendingUser) throws RemoteException {
23035 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23036 reportStatus ? 1 : 0, 1, keys);
23037 mHandler.sendMessage(msg);
23041 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23043 mHandler.sendMessage(msg);
23047 private void loadPrivatePackages(final VolumeInfo vol) {
23048 mHandler.post(new Runnable() {
23050 public void run() {
23051 loadPrivatePackagesInner(vol);
23056 private void loadPrivatePackagesInner(VolumeInfo vol) {
23057 final String volumeUuid = vol.fsUuid;
23058 if (TextUtils.isEmpty(volumeUuid)) {
23059 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23063 final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23064 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23065 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23067 final VersionInfo ver;
23068 final List<PackageSetting> packages;
23069 synchronized (mPackages) {
23070 ver = mSettings.findOrCreateVersion(volumeUuid);
23071 packages = mSettings.getVolumePackagesLPr(volumeUuid);
23074 for (PackageSetting ps : packages) {
23075 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23076 synchronized (mInstallLock) {
23077 final PackageParser.Package pkg;
23079 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23080 loaded.add(pkg.applicationInfo);
23082 } catch (PackageManagerException e) {
23083 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23086 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23087 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23088 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23089 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23094 // Reconcile app data for all started/unlocked users
23095 final StorageManager sm = mContext.getSystemService(StorageManager.class);
23096 final UserManager um = mContext.getSystemService(UserManager.class);
23097 UserManagerInternal umInternal = getUserManagerInternal();
23098 for (UserInfo user : um.getUsers()) {
23100 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23101 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23102 } else if (umInternal.isUserRunning(user.id)) {
23103 flags = StorageManager.FLAG_STORAGE_DE;
23109 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23110 synchronized (mInstallLock) {
23111 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23113 } catch (IllegalStateException e) {
23114 // Device was probably ejected, and we'll process that event momentarily
23115 Slog.w(TAG, "Failed to prepare storage: " + e);
23119 synchronized (mPackages) {
23120 int updateFlags = UPDATE_PERMISSIONS_ALL;
23121 if (ver.sdkVersion != mSdkVersion) {
23122 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23123 + mSdkVersion + "; regranting permissions for " + volumeUuid);
23124 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23126 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23128 // Yay, everything is now upgraded
23129 ver.forceCurrent();
23131 mSettings.writeLPr();
23134 for (PackageFreezer freezer : freezers) {
23138 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23139 sendResourcesChangedBroadcast(true, false, loaded, null);
23142 private void unloadPrivatePackages(final VolumeInfo vol) {
23143 mHandler.post(new Runnable() {
23145 public void run() {
23146 unloadPrivatePackagesInner(vol);
23151 private void unloadPrivatePackagesInner(VolumeInfo vol) {
23152 final String volumeUuid = vol.fsUuid;
23153 if (TextUtils.isEmpty(volumeUuid)) {
23154 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23158 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23159 synchronized (mInstallLock) {
23160 synchronized (mPackages) {
23161 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23162 for (PackageSetting ps : packages) {
23163 if (ps.pkg == null) continue;
23165 final ApplicationInfo info = ps.pkg.applicationInfo;
23166 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23167 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23169 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23170 "unloadPrivatePackagesInner")) {
23171 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23173 unloaded.add(info);
23175 Slog.w(TAG, "Failed to unload " + ps.codePath);
23179 // Try very hard to release any references to this package
23180 // so we don't risk the system server being killed due to
23182 AttributeCache.instance().removePackage(ps.name);
23185 mSettings.writeLPr();
23189 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23190 sendResourcesChangedBroadcast(false, false, unloaded, null);
23192 // Try very hard to release any references to this path so we don't risk
23193 // the system server being killed due to open FDs
23194 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23196 for (int i = 0; i < 3; i++) {
23198 System.runFinalization();
23202 private void assertPackageKnown(String volumeUuid, String packageName)
23203 throws PackageManagerException {
23204 synchronized (mPackages) {
23205 // Normalize package name to handle renamed packages
23206 packageName = normalizePackageNameLPr(packageName);
23208 final PackageSetting ps = mSettings.mPackages.get(packageName);
23210 throw new PackageManagerException("Package " + packageName + " is unknown");
23211 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23212 throw new PackageManagerException(
23213 "Package " + packageName + " found on unknown volume " + volumeUuid
23214 + "; expected volume " + ps.volumeUuid);
23219 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23220 throws PackageManagerException {
23221 synchronized (mPackages) {
23222 // Normalize package name to handle renamed packages
23223 packageName = normalizePackageNameLPr(packageName);
23225 final PackageSetting ps = mSettings.mPackages.get(packageName);
23227 throw new PackageManagerException("Package " + packageName + " is unknown");
23228 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23229 throw new PackageManagerException(
23230 "Package " + packageName + " found on unknown volume " + volumeUuid
23231 + "; expected volume " + ps.volumeUuid);
23232 } else if (!ps.getInstalled(userId)) {
23233 throw new PackageManagerException(
23234 "Package " + packageName + " not installed for user " + userId);
23239 private List<String> collectAbsoluteCodePaths() {
23240 synchronized (mPackages) {
23241 List<String> codePaths = new ArrayList<>();
23242 final int packageCount = mSettings.mPackages.size();
23243 for (int i = 0; i < packageCount; i++) {
23244 final PackageSetting ps = mSettings.mPackages.valueAt(i);
23245 codePaths.add(ps.codePath.getAbsolutePath());
23252 * Examine all apps present on given mounted volume, and destroy apps that
23253 * aren't expected, either due to uninstallation or reinstallation on
23256 private void reconcileApps(String volumeUuid) {
23257 List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23258 List<File> filesToDelete = null;
23260 final File[] files = FileUtils.listFilesOrEmpty(
23261 Environment.getDataAppDirectory(volumeUuid));
23262 for (File file : files) {
23263 final boolean isPackage = (isApkFile(file) || file.isDirectory())
23264 && !PackageInstallerService.isStageName(file.getName());
23266 // Ignore entries which are not packages
23270 String absolutePath = file.getAbsolutePath();
23272 boolean pathValid = false;
23273 final int absoluteCodePathCount = absoluteCodePaths.size();
23274 for (int i = 0; i < absoluteCodePathCount; i++) {
23275 String absoluteCodePath = absoluteCodePaths.get(i);
23276 if (absolutePath.startsWith(absoluteCodePath)) {
23283 if (filesToDelete == null) {
23284 filesToDelete = new ArrayList<>();
23286 filesToDelete.add(file);
23290 if (filesToDelete != null) {
23291 final int fileToDeleteCount = filesToDelete.size();
23292 for (int i = 0; i < fileToDeleteCount; i++) {
23293 File fileToDelete = filesToDelete.get(i);
23294 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23295 synchronized (mInstallLock) {
23296 removeCodePathLI(fileToDelete);
23303 * Reconcile all app data for the given user.
23305 * Verifies that directories exist and that ownership and labeling is
23306 * correct for all installed apps on all mounted volumes.
23308 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23309 final StorageManager storage = mContext.getSystemService(StorageManager.class);
23310 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23311 final String volumeUuid = vol.getFsUuid();
23312 synchronized (mInstallLock) {
23313 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23318 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23319 boolean migrateAppData) {
23320 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23324 * Reconcile all app data on given mounted volume.
23326 * Destroys app data that isn't expected, either due to uninstallation or
23327 * reinstallation on another volume.
23329 * Verifies that directories exist and that ownership and labeling is
23330 * correct for all installed apps.
23331 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23333 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23334 boolean migrateAppData, boolean onlyCoreApps) {
23335 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23336 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23337 List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23339 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23340 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23342 // First look for stale data that doesn't belong, and check if things
23343 // have changed since we did our last restorecon
23344 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23345 if (StorageManager.isFileEncryptedNativeOrEmulated()
23346 && !StorageManager.isUserKeyUnlocked(userId)) {
23347 throw new RuntimeException(
23348 "Yikes, someone asked us to reconcile CE storage while " + userId
23349 + " was still locked; this would have caused massive data loss!");
23352 final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23353 for (File file : files) {
23354 final String packageName = file.getName();
23356 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23357 } catch (PackageManagerException e) {
23358 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23360 mInstaller.destroyAppData(volumeUuid, packageName, userId,
23361 StorageManager.FLAG_STORAGE_CE, 0);
23362 } catch (InstallerException e2) {
23363 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23368 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23369 final File[] files = FileUtils.listFilesOrEmpty(deDir);
23370 for (File file : files) {
23371 final String packageName = file.getName();
23373 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23374 } catch (PackageManagerException e) {
23375 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23377 mInstaller.destroyAppData(volumeUuid, packageName, userId,
23378 StorageManager.FLAG_STORAGE_DE, 0);
23379 } catch (InstallerException e2) {
23380 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23386 // Ensure that data directories are ready to roll for all packages
23387 // installed for this volume and user
23388 final List<PackageSetting> packages;
23389 synchronized (mPackages) {
23390 packages = mSettings.getVolumePackagesLPr(volumeUuid);
23392 int preparedCount = 0;
23393 for (PackageSetting ps : packages) {
23394 final String packageName = ps.name;
23395 if (ps.pkg == null) {
23396 Slog.w(TAG, "Odd, missing scanned package " + packageName);
23397 // TODO: might be due to legacy ASEC apps; we should circle back
23398 // and reconcile again once they're scanned
23401 // Skip non-core apps if requested
23402 if (onlyCoreApps && !ps.pkg.coreApp) {
23403 result.add(packageName);
23407 if (ps.getInstalled(userId)) {
23408 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23413 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23418 * Prepare app data for the given app just after it was installed or
23419 * upgraded. This method carefully only touches users that it's installed
23420 * for, and it forces a restorecon to handle any seinfo changes.
23422 * Verifies that directories exist and that ownership and labeling is
23423 * correct for all installed apps. If there is an ownership mismatch, it
23424 * will try recovering system apps by wiping data; third-party app data is
23427 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23429 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23430 final PackageSetting ps;
23431 synchronized (mPackages) {
23432 ps = mSettings.mPackages.get(pkg.packageName);
23433 mSettings.writeKernelMappingLPr(ps);
23436 final UserManager um = mContext.getSystemService(UserManager.class);
23437 UserManagerInternal umInternal = getUserManagerInternal();
23438 for (UserInfo user : um.getUsers()) {
23440 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23441 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23442 } else if (umInternal.isUserRunning(user.id)) {
23443 flags = StorageManager.FLAG_STORAGE_DE;
23448 if (ps.getInstalled(user.id)) {
23449 // TODO: when user data is locked, mark that we're still dirty
23450 prepareAppDataLIF(pkg, user.id, flags);
23456 * Prepare app data for the given app.
23458 * Verifies that directories exist and that ownership and labeling is
23459 * correct for all installed apps. If there is an ownership mismatch, this
23460 * will try recovering system apps by wiping data; third-party app data is
23463 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23465 Slog.wtf(TAG, "Package was null!", new Throwable());
23468 prepareAppDataLeafLIF(pkg, userId, flags);
23469 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23470 for (int i = 0; i < childCount; i++) {
23471 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23475 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23476 boolean maybeMigrateAppData) {
23477 prepareAppDataLIF(pkg, userId, flags);
23479 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23480 // We may have just shuffled around app data directories, so
23481 // prepare them one more time
23482 prepareAppDataLIF(pkg, userId, flags);
23486 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23487 if (DEBUG_APP_DATA) {
23488 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23489 + Integer.toHexString(flags));
23492 final String volumeUuid = pkg.volumeUuid;
23493 final String packageName = pkg.packageName;
23494 final ApplicationInfo app = pkg.applicationInfo;
23495 final int appId = UserHandle.getAppId(app.uid);
23497 Preconditions.checkNotNull(app.seInfo);
23499 long ceDataInode = -1;
23501 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23502 appId, app.seInfo, app.targetSdkVersion);
23503 } catch (InstallerException e) {
23504 if (app.isSystemApp()) {
23505 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23506 + ", but trying to recover: " + e);
23507 destroyAppDataLeafLIF(pkg, userId, flags);
23509 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23510 appId, app.seInfo, app.targetSdkVersion);
23511 logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23512 } catch (InstallerException e2) {
23513 logCriticalInfo(Log.DEBUG, "Recovery failed!");
23516 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23520 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23521 // TODO: mark this structure as dirty so we persist it!
23522 synchronized (mPackages) {
23523 final PackageSetting ps = mSettings.mPackages.get(packageName);
23525 ps.setCeDataInode(ceDataInode, userId);
23530 prepareAppDataContentsLeafLIF(pkg, userId, flags);
23533 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23535 Slog.wtf(TAG, "Package was null!", new Throwable());
23538 prepareAppDataContentsLeafLIF(pkg, userId, flags);
23539 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23540 for (int i = 0; i < childCount; i++) {
23541 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23545 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23546 final String volumeUuid = pkg.volumeUuid;
23547 final String packageName = pkg.packageName;
23548 final ApplicationInfo app = pkg.applicationInfo;
23550 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23551 // Create a native library symlink only if we have native libraries
23552 // and if the native libraries are 32 bit libraries. We do not provide
23553 // this symlink for 64 bit libraries.
23554 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23555 final String nativeLibPath = app.nativeLibraryDir;
23557 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23558 nativeLibPath, userId);
23559 } catch (InstallerException e) {
23560 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23567 * For system apps on non-FBE devices, this method migrates any existing
23568 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23569 * requested by the app.
23571 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23572 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23573 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23574 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23575 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23577 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23579 } catch (InstallerException e) {
23580 logCriticalInfo(Log.WARN,
23581 "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23589 public PackageFreezer freezePackage(String packageName, String killReason) {
23590 return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23593 public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23594 return new PackageFreezer(packageName, userId, killReason);
23597 public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23598 String killReason) {
23599 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23602 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23603 String killReason) {
23604 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23605 return new PackageFreezer();
23607 return freezePackage(packageName, userId, killReason);
23611 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23612 String killReason) {
23613 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23616 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23617 String killReason) {
23618 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23619 return new PackageFreezer();
23621 return freezePackage(packageName, userId, killReason);
23626 * Class that freezes and kills the given package upon creation, and
23627 * unfreezes it upon closing. This is typically used when doing surgery on
23628 * app code/data to prevent the app from running while you're working.
23630 private class PackageFreezer implements AutoCloseable {
23631 private final String mPackageName;
23632 private final PackageFreezer[] mChildren;
23634 private final boolean mWeFroze;
23636 private final AtomicBoolean mClosed = new AtomicBoolean();
23637 private final CloseGuard mCloseGuard = CloseGuard.get();
23640 * Create and return a stub freezer that doesn't actually do anything,
23641 * typically used when someone requested
23642 * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23643 * {@link PackageManager#DELETE_DONT_KILL_APP}.
23645 public PackageFreezer() {
23646 mPackageName = null;
23649 mCloseGuard.open("close");
23652 public PackageFreezer(String packageName, int userId, String killReason) {
23653 synchronized (mPackages) {
23654 mPackageName = packageName;
23655 mWeFroze = mFrozenPackages.add(mPackageName);
23657 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23659 killApplication(ps.name, ps.appId, userId, killReason);
23662 final PackageParser.Package p = mPackages.get(packageName);
23663 if (p != null && p.childPackages != null) {
23664 final int N = p.childPackages.size();
23665 mChildren = new PackageFreezer[N];
23666 for (int i = 0; i < N; i++) {
23667 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23668 userId, killReason);
23674 mCloseGuard.open("close");
23678 protected void finalize() throws Throwable {
23680 mCloseGuard.warnIfOpen();
23688 public void close() {
23689 mCloseGuard.close();
23690 if (mClosed.compareAndSet(false, true)) {
23691 synchronized (mPackages) {
23693 mFrozenPackages.remove(mPackageName);
23696 if (mChildren != null) {
23697 for (PackageFreezer freezer : mChildren) {
23707 * Verify that given package is currently frozen.
23709 private void checkPackageFrozen(String packageName) {
23710 synchronized (mPackages) {
23711 if (!mFrozenPackages.contains(packageName)) {
23712 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23718 public int movePackage(final String packageName, final String volumeUuid) {
23719 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23721 final int callingUid = Binder.getCallingUid();
23722 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23723 final int moveId = mNextMoveId.getAndIncrement();
23724 mHandler.post(new Runnable() {
23726 public void run() {
23728 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23729 } catch (PackageManagerException e) {
23730 Slog.w(TAG, "Failed to move " + packageName, e);
23731 mMoveCallbacks.notifyStatusChanged(moveId,
23732 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23739 private void movePackageInternal(final String packageName, final String volumeUuid,
23740 final int moveId, final int callingUid, UserHandle user)
23741 throws PackageManagerException {
23742 final StorageManager storage = mContext.getSystemService(StorageManager.class);
23743 final PackageManager pm = mContext.getPackageManager();
23745 final boolean currentAsec;
23746 final String currentVolumeUuid;
23747 final File codeFile;
23748 final String installerPackageName;
23749 final String packageAbiOverride;
23751 final String seinfo;
23752 final String label;
23753 final int targetSdkVersion;
23754 final PackageFreezer freezer;
23755 final int[] installedUserIds;
23758 synchronized (mPackages) {
23759 final PackageParser.Package pkg = mPackages.get(packageName);
23760 final PackageSetting ps = mSettings.mPackages.get(packageName);
23763 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23764 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23766 if (pkg.applicationInfo.isSystemApp()) {
23767 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23768 "Cannot move system application");
23771 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23772 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23773 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23774 if (isInternalStorage && !allow3rdPartyOnInternal) {
23775 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23776 "3rd party apps are not allowed on internal storage");
23779 if (pkg.applicationInfo.isExternalAsec()) {
23780 currentAsec = true;
23781 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23782 } else if (pkg.applicationInfo.isForwardLocked()) {
23783 currentAsec = true;
23784 currentVolumeUuid = "forward_locked";
23786 currentAsec = false;
23787 currentVolumeUuid = ps.volumeUuid;
23789 final File probe = new File(pkg.codePath);
23790 final File probeOat = new File(probe, "oat");
23791 if (!probe.isDirectory() || !probeOat.isDirectory()) {
23792 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23793 "Move only supported for modern cluster style installs");
23797 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23798 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23799 "Package already moved to " + volumeUuid);
23801 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23802 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23803 "Device admin cannot be moved");
23806 if (mFrozenPackages.contains(packageName)) {
23807 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23808 "Failed to move already frozen package");
23811 codeFile = new File(pkg.codePath);
23812 installerPackageName = ps.installerPackageName;
23813 packageAbiOverride = ps.cpuAbiOverrideString;
23814 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23815 seinfo = pkg.applicationInfo.seInfo;
23816 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23817 targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23818 freezer = freezePackage(packageName, "movePackageInternal");
23819 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23822 final Bundle extras = new Bundle();
23823 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23824 extras.putString(Intent.EXTRA_TITLE, label);
23825 mMoveCallbacks.notifyCreated(moveId, extras);
23828 final boolean moveCompleteApp;
23829 final File measurePath;
23831 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23832 installFlags = INSTALL_INTERNAL;
23833 moveCompleteApp = !currentAsec;
23834 measurePath = Environment.getDataAppDirectory(volumeUuid);
23835 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23836 installFlags = INSTALL_EXTERNAL;
23837 moveCompleteApp = false;
23838 measurePath = storage.getPrimaryPhysicalVolume().getPath();
23840 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23841 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23842 || !volume.isMountedWritable()) {
23844 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23845 "Move location not mounted private volume");
23848 Preconditions.checkState(!currentAsec);
23850 installFlags = INSTALL_INTERNAL;
23851 moveCompleteApp = true;
23852 measurePath = Environment.getDataAppDirectory(volumeUuid);
23855 final PackageStats stats = new PackageStats(null, -1);
23856 synchronized (mInstaller) {
23857 for (int userId : installedUserIds) {
23858 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23860 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23861 "Failed to measure package size");
23866 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23869 final long startFreeBytes = measurePath.getUsableSpace();
23870 final long sizeBytes;
23871 if (moveCompleteApp) {
23872 sizeBytes = stats.codeSize + stats.dataSize;
23874 sizeBytes = stats.codeSize;
23877 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23879 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23880 "Not enough free space to move");
23883 mMoveCallbacks.notifyStatusChanged(moveId, 10);
23885 final CountDownLatch installedLatch = new CountDownLatch(1);
23886 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23888 public void onUserActionRequired(Intent intent) throws RemoteException {
23889 throw new IllegalStateException();
23893 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23894 Bundle extras) throws RemoteException {
23895 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23896 + PackageManager.installStatusToString(returnCode, msg));
23898 installedLatch.countDown();
23901 final int status = PackageManager.installStatusToPublicStatus(returnCode);
23903 case PackageInstaller.STATUS_SUCCESS:
23904 mMoveCallbacks.notifyStatusChanged(moveId,
23905 PackageManager.MOVE_SUCCEEDED);
23907 case PackageInstaller.STATUS_FAILURE_STORAGE:
23908 mMoveCallbacks.notifyStatusChanged(moveId,
23909 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23912 mMoveCallbacks.notifyStatusChanged(moveId,
23913 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23919 final MoveInfo move;
23920 if (moveCompleteApp) {
23921 // Kick off a thread to report progress estimates
23924 public void run() {
23927 if (installedLatch.await(1, TimeUnit.SECONDS)) {
23930 } catch (InterruptedException ignored) {
23933 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23934 final int progress = 10 + (int) MathUtils.constrain(
23935 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23936 mMoveCallbacks.notifyStatusChanged(moveId, progress);
23941 final String dataAppName = codeFile.getName();
23942 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23943 dataAppName, appId, seinfo, targetSdkVersion);
23948 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23950 final Message msg = mHandler.obtainMessage(INIT_COPY);
23951 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23952 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23953 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23954 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23955 PackageManager.INSTALL_REASON_UNKNOWN);
23956 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23959 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23960 System.identityHashCode(msg.obj));
23961 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23962 System.identityHashCode(msg.obj));
23964 mHandler.sendMessage(msg);
23968 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23969 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23971 final int realMoveId = mNextMoveId.getAndIncrement();
23972 final Bundle extras = new Bundle();
23973 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23974 mMoveCallbacks.notifyCreated(realMoveId, extras);
23976 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23978 public void onCreated(int moveId, Bundle extras) {
23983 public void onStatusChanged(int moveId, int status, long estMillis) {
23984 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23988 final StorageManager storage = mContext.getSystemService(StorageManager.class);
23989 storage.setPrimaryStorageUuid(volumeUuid, callback);
23994 public int getMoveStatus(int moveId) {
23995 mContext.enforceCallingOrSelfPermission(
23996 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23997 return mMoveCallbacks.mLastStatus.get(moveId);
24001 public void registerMoveCallback(IPackageMoveObserver callback) {
24002 mContext.enforceCallingOrSelfPermission(
24003 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24004 mMoveCallbacks.register(callback);
24008 public void unregisterMoveCallback(IPackageMoveObserver callback) {
24009 mContext.enforceCallingOrSelfPermission(
24010 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24011 mMoveCallbacks.unregister(callback);
24015 public boolean setInstallLocation(int loc) {
24016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24018 if (getInstallLocation() == loc) {
24021 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24022 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24023 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24024 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24031 public int getInstallLocation() {
24032 // allow instant app access
24033 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24034 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24035 PackageHelper.APP_INSTALL_AUTO);
24038 /** Called by UserManagerService */
24039 void cleanUpUser(UserManagerService userManager, int userHandle) {
24040 synchronized (mPackages) {
24041 mDirtyUsers.remove(userHandle);
24042 mUserNeedsBadging.delete(userHandle);
24043 mSettings.removeUserLPw(userHandle);
24044 mPendingBroadcasts.remove(userHandle);
24045 mInstantAppRegistry.onUserRemovedLPw(userHandle);
24046 removeUnusedPackagesLPw(userManager, userHandle);
24051 * We're removing userHandle and would like to remove any downloaded packages
24052 * that are no longer in use by any other user.
24053 * @param userHandle the user being removed
24055 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24056 final boolean DEBUG_CLEAN_APKS = false;
24057 int [] users = userManager.getUserIds();
24058 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24059 while (psit.hasNext()) {
24060 PackageSetting ps = psit.next();
24061 if (ps.pkg == null) {
24064 final String packageName = ps.pkg.packageName;
24065 // Skip over if system app
24066 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24069 if (DEBUG_CLEAN_APKS) {
24070 Slog.i(TAG, "Checking package " + packageName);
24072 boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24074 if (DEBUG_CLEAN_APKS) {
24075 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO");
24078 for (int i = 0; i < users.length; i++) {
24079 if (users[i] != userHandle && ps.getInstalled(users[i])) {
24081 if (DEBUG_CLEAN_APKS) {
24082 Slog.i(TAG, " Keeping package " + packageName + " for user "
24090 if (DEBUG_CLEAN_APKS) {
24091 Slog.i(TAG, " Removing package " + packageName);
24093 mHandler.post(new Runnable() {
24094 public void run() {
24095 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24103 /** Called by UserManagerService */
24104 void createNewUser(int userId, String[] disallowedPackages) {
24105 synchronized (mInstallLock) {
24106 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24108 synchronized (mPackages) {
24109 scheduleWritePackageRestrictionsLocked(userId);
24110 scheduleWritePackageListLocked(userId);
24111 applyFactoryDefaultBrowserLPw(userId);
24112 primeDomainVerificationsLPw(userId);
24116 void onNewUserCreated(final int userId) {
24117 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24118 // If permission review for legacy apps is required, we represent
24119 // dagerous permissions for such apps as always granted runtime
24120 // permissions to keep per user flag state whether review is needed.
24121 // Hence, if a new user is added we have to propagate dangerous
24122 // permission grants for these legacy apps.
24123 if (mPermissionReviewRequired) {
24124 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24125 | UPDATE_PERMISSIONS_REPLACE_ALL);
24130 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24131 mContext.enforceCallingOrSelfPermission(
24132 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24133 "Only package verification agents can read the verifier device identity");
24135 synchronized (mPackages) {
24136 return mSettings.getVerifierDeviceIdentityLPw();
24141 public void setPermissionEnforced(String permission, boolean enforced) {
24142 // TODO: Now that we no longer change GID for storage, this should to away.
24143 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24144 "setPermissionEnforced");
24145 if (READ_EXTERNAL_STORAGE.equals(permission)) {
24146 synchronized (mPackages) {
24147 if (mSettings.mReadExternalStorageEnforced == null
24148 || mSettings.mReadExternalStorageEnforced != enforced) {
24149 mSettings.mReadExternalStorageEnforced = enforced;
24150 mSettings.writeLPr();
24153 // kill any non-foreground processes so we restart them and
24154 // grant/revoke the GID.
24155 final IActivityManager am = ActivityManager.getService();
24157 final long token = Binder.clearCallingIdentity();
24159 am.killProcessesBelowForeground("setPermissionEnforcement");
24160 } catch (RemoteException e) {
24162 Binder.restoreCallingIdentity(token);
24166 throw new IllegalArgumentException("No selective enforcement for " + permission);
24172 public boolean isPermissionEnforced(String permission) {
24173 // allow instant applications
24178 public boolean isStorageLow() {
24179 // allow instant applications
24180 final long token = Binder.clearCallingIdentity();
24182 final DeviceStorageMonitorInternal
24183 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24185 return dsm.isMemoryLow();
24190 Binder.restoreCallingIdentity(token);
24195 public IPackageInstaller getPackageInstaller() {
24196 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24199 return mInstallerService;
24202 private boolean userNeedsBadging(int userId) {
24203 int index = mUserNeedsBadging.indexOfKey(userId);
24205 final UserInfo userInfo;
24206 final long token = Binder.clearCallingIdentity();
24208 userInfo = sUserManager.getUserInfo(userId);
24210 Binder.restoreCallingIdentity(token);
24213 if (userInfo != null && userInfo.isManagedProfile()) {
24218 mUserNeedsBadging.put(userId, b);
24221 return mUserNeedsBadging.valueAt(index);
24225 public KeySet getKeySetByAlias(String packageName, String alias) {
24226 if (packageName == null || alias == null) {
24229 synchronized(mPackages) {
24230 final PackageParser.Package pkg = mPackages.get(packageName);
24232 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24233 throw new IllegalArgumentException("Unknown package: " + packageName);
24235 final PackageSetting ps = (PackageSetting) pkg.mExtras;
24236 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24237 Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24238 throw new IllegalArgumentException("Unknown package: " + packageName);
24240 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24241 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24246 public KeySet getSigningKeySet(String packageName) {
24247 if (packageName == null) {
24250 synchronized(mPackages) {
24251 final int callingUid = Binder.getCallingUid();
24252 final int callingUserId = UserHandle.getUserId(callingUid);
24253 final PackageParser.Package pkg = mPackages.get(packageName);
24255 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24256 throw new IllegalArgumentException("Unknown package: " + packageName);
24258 final PackageSetting ps = (PackageSetting) pkg.mExtras;
24259 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24260 // filter and pretend the package doesn't exist
24261 Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24262 + ", uid:" + callingUid);
24263 throw new IllegalArgumentException("Unknown package: " + packageName);
24265 if (pkg.applicationInfo.uid != callingUid
24266 && Process.SYSTEM_UID != callingUid) {
24267 throw new SecurityException("May not access signing KeySet of other apps.");
24269 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24270 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24275 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24276 final int callingUid = Binder.getCallingUid();
24277 if (getInstantAppPackageName(callingUid) != null) {
24280 if (packageName == null || ks == null) {
24283 synchronized(mPackages) {
24284 final PackageParser.Package pkg = mPackages.get(packageName);
24286 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24287 UserHandle.getUserId(callingUid))) {
24288 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24289 throw new IllegalArgumentException("Unknown package: " + packageName);
24291 IBinder ksh = ks.getToken();
24292 if (ksh instanceof KeySetHandle) {
24293 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24294 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24301 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24302 final int callingUid = Binder.getCallingUid();
24303 if (getInstantAppPackageName(callingUid) != null) {
24306 if (packageName == null || ks == null) {
24309 synchronized(mPackages) {
24310 final PackageParser.Package pkg = mPackages.get(packageName);
24312 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24313 UserHandle.getUserId(callingUid))) {
24314 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24315 throw new IllegalArgumentException("Unknown package: " + packageName);
24317 IBinder ksh = ks.getToken();
24318 if (ksh instanceof KeySetHandle) {
24319 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24320 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24326 private void deletePackageIfUnusedLPr(final String packageName) {
24327 PackageSetting ps = mSettings.mPackages.get(packageName);
24331 if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24332 // TODO Implement atomic delete if package is unused
24333 // It is currently possible that the package will be deleted even if it is installed
24334 // after this method returns.
24335 mHandler.post(new Runnable() {
24336 public void run() {
24337 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24338 0, PackageManager.DELETE_ALL_USERS);
24345 * Check and throw if the given before/after packages would be considered a
24348 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24349 throws PackageManagerException {
24350 if (after.versionCode < before.mVersionCode) {
24351 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24352 "Update version code " + after.versionCode + " is older than current "
24353 + before.mVersionCode);
24354 } else if (after.versionCode == before.mVersionCode) {
24355 if (after.baseRevisionCode < before.baseRevisionCode) {
24356 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24357 "Update base revision code " + after.baseRevisionCode
24358 + " is older than current " + before.baseRevisionCode);
24361 if (!ArrayUtils.isEmpty(after.splitNames)) {
24362 for (int i = 0; i < after.splitNames.length; i++) {
24363 final String splitName = after.splitNames[i];
24364 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24366 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24367 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24368 "Update split " + splitName + " revision code "
24369 + after.splitRevisionCodes[i] + " is older than current "
24370 + before.splitRevisionCodes[j]);
24378 private static class MoveCallbacks extends Handler {
24379 private static final int MSG_CREATED = 1;
24380 private static final int MSG_STATUS_CHANGED = 2;
24382 private final RemoteCallbackList<IPackageMoveObserver>
24383 mCallbacks = new RemoteCallbackList<>();
24385 private final SparseIntArray mLastStatus = new SparseIntArray();
24387 public MoveCallbacks(Looper looper) {
24391 public void register(IPackageMoveObserver callback) {
24392 mCallbacks.register(callback);
24395 public void unregister(IPackageMoveObserver callback) {
24396 mCallbacks.unregister(callback);
24400 public void handleMessage(Message msg) {
24401 final SomeArgs args = (SomeArgs) msg.obj;
24402 final int n = mCallbacks.beginBroadcast();
24403 for (int i = 0; i < n; i++) {
24404 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24406 invokeCallback(callback, msg.what, args);
24407 } catch (RemoteException ignored) {
24410 mCallbacks.finishBroadcast();
24414 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24415 throws RemoteException {
24417 case MSG_CREATED: {
24418 callback.onCreated(args.argi1, (Bundle) args.arg2);
24421 case MSG_STATUS_CHANGED: {
24422 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24428 private void notifyCreated(int moveId, Bundle extras) {
24429 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24431 final SomeArgs args = SomeArgs.obtain();
24432 args.argi1 = moveId;
24433 args.arg2 = extras;
24434 obtainMessage(MSG_CREATED, args).sendToTarget();
24437 private void notifyStatusChanged(int moveId, int status) {
24438 notifyStatusChanged(moveId, status, -1);
24441 private void notifyStatusChanged(int moveId, int status, long estMillis) {
24442 Slog.v(TAG, "Move " + moveId + " status " + status);
24444 final SomeArgs args = SomeArgs.obtain();
24445 args.argi1 = moveId;
24446 args.argi2 = status;
24447 args.arg3 = estMillis;
24448 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24450 synchronized (mLastStatus) {
24451 mLastStatus.put(moveId, status);
24456 private final static class OnPermissionChangeListeners extends Handler {
24457 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24459 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24460 new RemoteCallbackList<>();
24462 public OnPermissionChangeListeners(Looper looper) {
24467 public void handleMessage(Message msg) {
24468 switch (msg.what) {
24469 case MSG_ON_PERMISSIONS_CHANGED: {
24470 final int uid = msg.arg1;
24471 handleOnPermissionsChanged(uid);
24476 public void addListenerLocked(IOnPermissionsChangeListener listener) {
24477 mPermissionListeners.register(listener);
24481 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24482 mPermissionListeners.unregister(listener);
24485 public void onPermissionsChanged(int uid) {
24486 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24487 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24491 private void handleOnPermissionsChanged(int uid) {
24492 final int count = mPermissionListeners.beginBroadcast();
24494 for (int i = 0; i < count; i++) {
24495 IOnPermissionsChangeListener callback = mPermissionListeners
24496 .getBroadcastItem(i);
24498 callback.onPermissionsChanged(uid);
24499 } catch (RemoteException e) {
24500 Log.e(TAG, "Permission listener is dead", e);
24504 mPermissionListeners.finishBroadcast();
24509 private class PackageManagerInternalImpl extends PackageManagerInternal {
24511 public void setLocationPackagesProvider(PackagesProvider provider) {
24512 synchronized (mPackages) {
24513 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24518 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24519 synchronized (mPackages) {
24520 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24525 public void setSmsAppPackagesProvider(PackagesProvider provider) {
24526 synchronized (mPackages) {
24527 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24532 public void setDialerAppPackagesProvider(PackagesProvider provider) {
24533 synchronized (mPackages) {
24534 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24539 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24540 synchronized (mPackages) {
24541 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24546 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24547 synchronized (mPackages) {
24548 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24553 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24554 synchronized (mPackages) {
24555 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24556 packageName, userId);
24561 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24562 synchronized (mPackages) {
24563 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24564 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24565 packageName, userId);
24570 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24571 synchronized (mPackages) {
24572 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24573 packageName, userId);
24578 public void setKeepUninstalledPackages(final List<String> packageList) {
24579 Preconditions.checkNotNull(packageList);
24580 List<String> removedFromList = null;
24581 synchronized (mPackages) {
24582 if (mKeepUninstalledPackages != null) {
24583 final int packagesCount = mKeepUninstalledPackages.size();
24584 for (int i = 0; i < packagesCount; i++) {
24585 String oldPackage = mKeepUninstalledPackages.get(i);
24586 if (packageList != null && packageList.contains(oldPackage)) {
24589 if (removedFromList == null) {
24590 removedFromList = new ArrayList<>();
24592 removedFromList.add(oldPackage);
24595 mKeepUninstalledPackages = new ArrayList<>(packageList);
24596 if (removedFromList != null) {
24597 final int removedCount = removedFromList.size();
24598 for (int i = 0; i < removedCount; i++) {
24599 deletePackageIfUnusedLPr(removedFromList.get(i));
24606 public boolean isPermissionsReviewRequired(String packageName, int userId) {
24607 synchronized (mPackages) {
24608 // If we do not support permission review, done.
24609 if (!mPermissionReviewRequired) {
24613 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24614 if (packageSetting == null) {
24618 // Permission review applies only to apps not supporting the new permission model.
24619 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24623 // Legacy apps have the permission and get user consent on launch.
24624 PermissionsState permissionsState = packageSetting.getPermissionsState();
24625 return permissionsState.isPermissionReviewRequired(userId);
24630 public PackageInfo getPackageInfo(
24631 String packageName, int flags, int filterCallingUid, int userId) {
24632 return PackageManagerService.this
24633 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24634 flags, filterCallingUid, userId);
24638 public ApplicationInfo getApplicationInfo(
24639 String packageName, int flags, int filterCallingUid, int userId) {
24640 return PackageManagerService.this
24641 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24645 public ActivityInfo getActivityInfo(
24646 ComponentName component, int flags, int filterCallingUid, int userId) {
24647 return PackageManagerService.this
24648 .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24652 public List<ResolveInfo> queryIntentActivities(
24653 Intent intent, int flags, int filterCallingUid, int userId) {
24654 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24655 return PackageManagerService.this
24656 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24657 userId, false /*resolveForStart*/);
24661 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24663 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24667 public void setDeviceAndProfileOwnerPackages(
24668 int deviceOwnerUserId, String deviceOwnerPackage,
24669 SparseArray<String> profileOwnerPackages) {
24670 mProtectedPackages.setDeviceAndProfileOwnerPackages(
24671 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24675 public boolean isPackageDataProtected(int userId, String packageName) {
24676 return mProtectedPackages.isPackageDataProtected(userId, packageName);
24680 public boolean isPackageEphemeral(int userId, String packageName) {
24681 synchronized (mPackages) {
24682 final PackageSetting ps = mSettings.mPackages.get(packageName);
24683 return ps != null ? ps.getInstantApp(userId) : false;
24688 public boolean wasPackageEverLaunched(String packageName, int userId) {
24689 synchronized (mPackages) {
24690 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24695 public void grantRuntimePermission(String packageName, String name, int userId,
24696 boolean overridePolicy) {
24697 PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24702 public void revokeRuntimePermission(String packageName, String name, int userId,
24703 boolean overridePolicy) {
24704 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24709 public String getNameForUid(int uid) {
24710 return PackageManagerService.this.getNameForUid(uid);
24714 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24715 Intent origIntent, String resolvedType, String callingPackage,
24716 Bundle verificationBundle, int userId) {
24717 PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24718 responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24723 public void grantEphemeralAccess(int userId, Intent intent,
24724 int targetAppId, int ephemeralAppId) {
24725 synchronized (mPackages) {
24726 mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24727 targetAppId, ephemeralAppId);
24732 public boolean isInstantAppInstallerComponent(ComponentName component) {
24733 synchronized (mPackages) {
24734 return mInstantAppInstallerActivity != null
24735 && mInstantAppInstallerActivity.getComponentName().equals(component);
24740 public void pruneInstantApps() {
24741 mInstantAppRegistry.pruneInstantApps();
24745 public String getSetupWizardPackageName() {
24746 return mSetupWizardPackage;
24749 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24750 if (policy != null) {
24751 mExternalSourcesPolicy = policy;
24756 public boolean isPackagePersistent(String packageName) {
24757 synchronized (mPackages) {
24758 PackageParser.Package pkg = mPackages.get(packageName);
24760 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24761 | ApplicationInfo.FLAG_PERSISTENT)) ==
24762 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24768 public List<PackageInfo> getOverlayPackages(int userId) {
24769 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24770 synchronized (mPackages) {
24771 for (PackageParser.Package p : mPackages.values()) {
24772 if (p.mOverlayTarget != null) {
24773 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24775 overlayPackages.add(pkg);
24780 return overlayPackages;
24784 public List<String> getTargetPackageNames(int userId) {
24785 List<String> targetPackages = new ArrayList<>();
24786 synchronized (mPackages) {
24787 for (PackageParser.Package p : mPackages.values()) {
24788 if (p.mOverlayTarget == null) {
24789 targetPackages.add(p.packageName);
24793 return targetPackages;
24797 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24798 @Nullable List<String> overlayPackageNames) {
24799 synchronized (mPackages) {
24800 if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24801 Slog.e(TAG, "failed to find package " + targetPackageName);
24804 ArrayList<String> overlayPaths = null;
24805 if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24806 final int N = overlayPackageNames.size();
24807 overlayPaths = new ArrayList<>(N);
24808 for (int i = 0; i < N; i++) {
24809 final String packageName = overlayPackageNames.get(i);
24810 final PackageParser.Package pkg = mPackages.get(packageName);
24812 Slog.e(TAG, "failed to find package " + packageName);
24815 overlayPaths.add(pkg.baseCodePath);
24819 final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24820 ps.setOverlayPaths(overlayPaths, userId);
24826 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24827 int flags, int userId) {
24828 return resolveIntentInternal(
24829 intent, resolvedType, flags, userId, true /*resolveForStart*/);
24833 public ResolveInfo resolveService(Intent intent, String resolvedType,
24834 int flags, int userId, int callingUid) {
24835 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24839 public void addIsolatedUid(int isolatedUid, int ownerUid) {
24840 synchronized (mPackages) {
24841 mIsolatedOwners.put(isolatedUid, ownerUid);
24846 public void removeIsolatedUid(int isolatedUid) {
24847 synchronized (mPackages) {
24848 mIsolatedOwners.delete(isolatedUid);
24853 public int getUidTargetSdkVersion(int uid) {
24854 synchronized (mPackages) {
24855 return getUidTargetSdkVersionLockedLPr(uid);
24860 public boolean canAccessInstantApps(int callingUid, int userId) {
24861 return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24866 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24867 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24868 synchronized (mPackages) {
24869 final long identity = Binder.clearCallingIdentity();
24871 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24872 packageNames, userId);
24874 Binder.restoreCallingIdentity(identity);
24880 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24881 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24882 synchronized (mPackages) {
24883 final long identity = Binder.clearCallingIdentity();
24885 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24886 packageNames, userId);
24888 Binder.restoreCallingIdentity(identity);
24893 private static void enforceSystemOrPhoneCaller(String tag) {
24894 int callingUid = Binder.getCallingUid();
24895 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24896 throw new SecurityException(
24897 "Cannot call " + tag + " from UID " + callingUid);
24901 boolean isHistoricalPackageUsageAvailable() {
24902 return mPackageUsage.isHistoricalPackageUsageAvailable();
24906 * Return a <b>copy</b> of the collection of packages known to the package manager.
24907 * @return A copy of the values of mPackages.
24909 Collection<PackageParser.Package> getPackages() {
24910 synchronized (mPackages) {
24911 return new ArrayList<>(mPackages.values());
24916 * Logs process start information (including base APK hash) to the security log.
24920 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24921 String apkFile, int pid) {
24922 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24925 if (!SecurityLog.isLoggingEnabled()) {
24928 Bundle data = new Bundle();
24929 data.putLong("startTimestamp", System.currentTimeMillis());
24930 data.putString("processName", processName);
24931 data.putInt("uid", uid);
24932 data.putString("seinfo", seinfo);
24933 data.putString("apkFile", apkFile);
24934 data.putInt("pid", pid);
24935 Message msg = mProcessLoggingHandler.obtainMessage(
24936 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24938 mProcessLoggingHandler.sendMessage(msg);
24941 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24942 return mCompilerStats.getPackageStats(pkgName);
24945 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24946 return getOrCreateCompilerPackageStats(pkg.packageName);
24949 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24950 return mCompilerStats.getOrCreatePackageStats(pkgName);
24953 public void deleteCompilerPackageStats(String pkgName) {
24954 mCompilerStats.deletePackageStats(pkgName);
24958 public int getInstallReason(String packageName, int userId) {
24959 final int callingUid = Binder.getCallingUid();
24960 enforceCrossUserPermission(callingUid, userId,
24961 true /* requireFullPermission */, false /* checkShell */,
24962 "get install reason");
24963 synchronized (mPackages) {
24964 final PackageSetting ps = mSettings.mPackages.get(packageName);
24965 if (filterAppAccessLPr(ps, callingUid, userId)) {
24966 return PackageManager.INSTALL_REASON_UNKNOWN;
24969 return ps.getInstallReason(userId);
24972 return PackageManager.INSTALL_REASON_UNKNOWN;
24976 public boolean canRequestPackageInstalls(String packageName, int userId) {
24977 return canRequestPackageInstallsInternal(packageName, 0, userId,
24978 true /* throwIfPermNotDeclared*/);
24981 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24982 boolean throwIfPermNotDeclared) {
24983 int callingUid = Binder.getCallingUid();
24984 int uid = getPackageUid(packageName, 0, userId);
24985 if (callingUid != uid && callingUid != Process.ROOT_UID
24986 && callingUid != Process.SYSTEM_UID) {
24987 throw new SecurityException(
24988 "Caller uid " + callingUid + " does not own package " + packageName);
24990 ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24991 if (info == null) {
24994 if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24997 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24998 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24999 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25000 if (throwIfPermNotDeclared) {
25001 throw new SecurityException("Need to declare " + appOpPermission
25002 + " to call this api");
25004 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25008 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25011 if (mExternalSourcesPolicy != null) {
25012 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25013 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25019 public ComponentName getInstantAppResolverSettingsComponent() {
25020 return mInstantAppResolverSettingsComponent;
25024 public ComponentName getInstantAppInstallerComponent() {
25025 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25028 return mInstantAppInstallerActivity == null
25029 ? null : mInstantAppInstallerActivity.getComponentName();
25033 public String getInstantAppAndroidId(String packageName, int userId) {
25034 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25035 "getInstantAppAndroidId");
25036 enforceCrossUserPermission(Binder.getCallingUid(), userId,
25037 true /* requireFullPermission */, false /* checkShell */,
25038 "getInstantAppAndroidId");
25039 // Make sure the target is an Instant App.
25040 if (!isInstantApp(packageName, userId)) {
25043 synchronized (mPackages) {
25044 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25049 interface PackageSender {
25050 void sendPackageBroadcast(final String action, final String pkg,
25051 final Bundle extras, final int flags, final String targetPkg,
25052 final IIntentReceiver finishedReceiver, final int[] userIds);
25053 void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25054 int appId, int... userIds);