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.READ_EXTERNAL_STORAGE;
20 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61 import static android.content.pm.PackageManager.MATCH_ALL;
62 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74 import static android.content.pm.PackageManager.PERMISSION_DENIED;
75 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77 import static android.content.pm.PackageParser.isApkFile;
78 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79 import static android.system.OsConstants.O_CREAT;
80 import static android.system.OsConstants.O_RDWR;
82 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86 import static com.android.internal.util.ArrayUtils.appendInt;
87 import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100 import android.Manifest;
101 import android.annotation.NonNull;
102 import android.annotation.Nullable;
103 import android.app.ActivityManager;
104 import android.app.ActivityManagerNative;
105 import android.app.IActivityManager;
106 import android.app.ResourcesManager;
107 import android.app.admin.IDevicePolicyManager;
108 import android.app.admin.SecurityLog;
109 import android.app.backup.IBackupManager;
110 import android.content.BroadcastReceiver;
111 import android.content.ComponentName;
112 import android.content.ContentResolver;
113 import android.content.Context;
114 import android.content.IIntentReceiver;
115 import android.content.Intent;
116 import android.content.IntentFilter;
117 import android.content.IntentSender;
118 import android.content.IntentSender.SendIntentException;
119 import android.content.ServiceConnection;
120 import android.content.pm.ActivityInfo;
121 import android.content.pm.ApplicationInfo;
122 import android.content.pm.AppsQueryHelper;
123 import android.content.pm.ComponentInfo;
124 import android.content.pm.EphemeralApplicationInfo;
125 import android.content.pm.EphemeralResolveInfo;
126 import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127 import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128 import android.content.pm.FeatureInfo;
129 import android.content.pm.IOnPermissionsChangeListener;
130 import android.content.pm.IPackageDataObserver;
131 import android.content.pm.IPackageDeleteObserver;
132 import android.content.pm.IPackageDeleteObserver2;
133 import android.content.pm.IPackageInstallObserver2;
134 import android.content.pm.IPackageInstaller;
135 import android.content.pm.IPackageManager;
136 import android.content.pm.IPackageMoveObserver;
137 import android.content.pm.IPackageStatsObserver;
138 import android.content.pm.InstrumentationInfo;
139 import android.content.pm.IntentFilterVerificationInfo;
140 import android.content.pm.KeySet;
141 import android.content.pm.PackageCleanItem;
142 import android.content.pm.PackageInfo;
143 import android.content.pm.PackageInfoLite;
144 import android.content.pm.PackageInstaller;
145 import android.content.pm.PackageManager;
146 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147 import android.content.pm.PackageManagerInternal;
148 import android.content.pm.PackageParser;
149 import android.content.pm.PackageParser.ActivityIntentInfo;
150 import android.content.pm.PackageParser.PackageLite;
151 import android.content.pm.PackageParser.PackageParserException;
152 import android.content.pm.PackageStats;
153 import android.content.pm.PackageUserState;
154 import android.content.pm.ParceledListSlice;
155 import android.content.pm.PermissionGroupInfo;
156 import android.content.pm.PermissionInfo;
157 import android.content.pm.ProviderInfo;
158 import android.content.pm.ResolveInfo;
159 import android.content.pm.ServiceInfo;
160 import android.content.pm.Signature;
161 import android.content.pm.UserInfo;
162 import android.content.pm.VerifierDeviceIdentity;
163 import android.content.pm.VerifierInfo;
164 import android.content.res.Resources;
165 import android.graphics.Bitmap;
166 import android.hardware.display.DisplayManager;
167 import android.net.Uri;
168 import android.os.AsyncTask;
169 import android.os.Binder;
170 import android.os.Build;
171 import android.os.Bundle;
172 import android.os.Debug;
173 import android.os.Environment;
174 import android.os.Environment.UserEnvironment;
175 import android.os.FileUtils;
176 import android.os.Handler;
177 import android.os.IBinder;
178 import android.os.Looper;
179 import android.os.Message;
180 import android.os.Parcel;
181 import android.os.ParcelFileDescriptor;
182 import android.os.PatternMatcher;
183 import android.os.Process;
184 import android.os.RemoteCallbackList;
185 import android.os.RemoteException;
186 import android.os.ResultReceiver;
187 import android.os.SELinux;
188 import android.os.ServiceManager;
189 import android.os.SystemClock;
190 import android.os.SystemProperties;
191 import android.os.Trace;
192 import android.os.UserHandle;
193 import android.os.UserManager;
194 import android.os.UserManagerInternal;
195 import android.os.storage.IMountService;
196 import android.os.storage.MountServiceInternal;
197 import android.os.storage.StorageEventListener;
198 import android.os.storage.StorageManager;
199 import android.os.storage.VolumeInfo;
200 import android.os.storage.VolumeRecord;
201 import android.provider.Settings.Global;
202 import android.provider.Settings.Secure;
203 import android.security.KeyStore;
204 import android.security.SystemKeyStore;
205 import android.system.ErrnoException;
206 import android.system.Os;
207 import android.text.TextUtils;
208 import android.text.format.DateUtils;
209 import android.util.ArrayMap;
210 import android.util.ArraySet;
211 import android.util.DisplayMetrics;
212 import android.util.EventLog;
213 import android.util.ExceptionUtils;
214 import android.util.Log;
215 import android.util.LogPrinter;
216 import android.util.MathUtils;
217 import android.util.Pair;
218 import android.util.PrintStreamPrinter;
219 import android.util.Slog;
220 import android.util.SparseArray;
221 import android.util.SparseBooleanArray;
222 import android.util.SparseIntArray;
223 import android.util.Xml;
224 import android.util.jar.StrictJarFile;
225 import android.view.Display;
227 import com.android.internal.R;
228 import com.android.internal.annotations.GuardedBy;
229 import com.android.internal.app.IMediaContainerService;
230 import com.android.internal.app.ResolverActivity;
231 import com.android.internal.content.NativeLibraryHelper;
232 import com.android.internal.content.PackageHelper;
233 import com.android.internal.logging.MetricsLogger;
234 import com.android.internal.os.IParcelFileDescriptorFactory;
235 import com.android.internal.os.InstallerConnection.InstallerException;
236 import com.android.internal.os.SomeArgs;
237 import com.android.internal.os.Zygote;
238 import com.android.internal.telephony.CarrierAppUtils;
239 import com.android.internal.util.ArrayUtils;
240 import com.android.internal.util.FastPrintWriter;
241 import com.android.internal.util.FastXmlSerializer;
242 import com.android.internal.util.IndentingPrintWriter;
243 import com.android.internal.util.Preconditions;
244 import com.android.internal.util.XmlUtils;
245 import com.android.server.AttributeCache;
246 import com.android.server.EventLogTags;
247 import com.android.server.FgThread;
248 import com.android.server.IntentResolver;
249 import com.android.server.LocalServices;
250 import com.android.server.ServiceThread;
251 import com.android.server.SystemConfig;
252 import com.android.server.Watchdog;
253 import com.android.server.net.NetworkPolicyManagerInternal;
254 import com.android.server.pm.PermissionsState.PermissionState;
255 import com.android.server.pm.Settings.DatabaseVersion;
256 import com.android.server.pm.Settings.VersionInfo;
257 import com.android.server.storage.DeviceStorageMonitorInternal;
259 import dalvik.system.CloseGuard;
260 import dalvik.system.DexFile;
261 import dalvik.system.VMRuntime;
263 import libcore.io.IoUtils;
264 import libcore.util.EmptyArray;
266 import org.xmlpull.v1.XmlPullParser;
267 import org.xmlpull.v1.XmlPullParserException;
268 import org.xmlpull.v1.XmlSerializer;
270 import java.io.BufferedOutputStream;
271 import java.io.BufferedReader;
272 import java.io.ByteArrayInputStream;
273 import java.io.ByteArrayOutputStream;
275 import java.io.FileDescriptor;
276 import java.io.FileInputStream;
277 import java.io.FileNotFoundException;
278 import java.io.FileOutputStream;
279 import java.io.FileReader;
280 import java.io.FilenameFilter;
281 import java.io.IOException;
282 import java.io.PrintWriter;
283 import java.nio.charset.StandardCharsets;
284 import java.security.DigestInputStream;
285 import java.security.MessageDigest;
286 import java.security.NoSuchAlgorithmException;
287 import java.security.PublicKey;
288 import java.security.cert.Certificate;
289 import java.security.cert.CertificateEncodingException;
290 import java.security.cert.CertificateException;
291 import java.text.SimpleDateFormat;
292 import java.util.ArrayList;
293 import java.util.Arrays;
294 import java.util.Collection;
295 import java.util.Collections;
296 import java.util.Comparator;
297 import java.util.Date;
298 import java.util.HashSet;
299 import java.util.Iterator;
300 import java.util.List;
301 import java.util.Map;
302 import java.util.Objects;
303 import java.util.Set;
304 import java.util.concurrent.CountDownLatch;
305 import java.util.concurrent.TimeUnit;
306 import java.util.concurrent.atomic.AtomicBoolean;
307 import java.util.concurrent.atomic.AtomicInteger;
310 * Keep track of all those APKs everywhere.
312 * Internally there are two important locks:
314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315 * and other related state. It is a fine-grained lock that should only be held
316 * momentarily, as it's one of the most contended locks in the system.
317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318 * operations typically involve heavy lifting of application data on disk. Since
319 * {@code installd} is single-threaded, and it's operations can often be slow,
320 * this lock should never be acquired while already holding {@link #mPackages}.
321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322 * holding {@link #mInstallLock}.
324 * Many internal methods rely on the caller to hold the appropriate locks, and
325 * this contract is expressed through method name suffixes:
327 * <li>fooLI(): the caller must hold {@link #mInstallLock}
328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329 * being modified must be frozen
330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
334 * Because this class is very central to the platform's security; please run all
335 * CTS and unit tests whenever making modifications:
338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
342 public class PackageManagerService extends IPackageManager.Stub {
343 static final String TAG = "PackageManager";
344 static final boolean DEBUG_SETTINGS = false;
345 static final boolean DEBUG_PREFERRED = false;
346 static final boolean DEBUG_UPGRADE = false;
347 static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348 private static final boolean DEBUG_BACKUP = false;
349 private static final boolean DEBUG_INSTALL = false;
350 private static final boolean DEBUG_REMOVE = false;
351 private static final boolean DEBUG_BROADCASTS = false;
352 private static final boolean DEBUG_SHOW_INFO = false;
353 private static final boolean DEBUG_PACKAGE_INFO = false;
354 private static final boolean DEBUG_INTENT_MATCHING = false;
355 private static final boolean DEBUG_PACKAGE_SCANNING = false;
356 private static final boolean DEBUG_VERIFY = false;
357 private static final boolean DEBUG_FILTERS = false;
359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361 // user, but by default initialize to this.
362 static final boolean DEBUG_DEXOPT = false;
364 private static final boolean DEBUG_ABI_SELECTION = false;
365 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
366 private static final boolean DEBUG_TRIAGED_MISSING = false;
367 private static final boolean DEBUG_APP_DATA = false;
369 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
371 private static final boolean DISABLE_EPHEMERAL_APPS = false;
372 private static final boolean HIDE_EPHEMERAL_APIS = true;
374 private static final int RADIO_UID = Process.PHONE_UID;
375 private static final int LOG_UID = Process.LOG_UID;
376 private static final int NFC_UID = Process.NFC_UID;
377 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
378 private static final int SHELL_UID = Process.SHELL_UID;
380 // Cap the size of permission trees that 3rd party apps can define
381 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text
383 // Suffix used during package installation when copying/moving
384 // package apks to install directory.
385 private static final String INSTALL_PACKAGE_SUFFIX = "-";
387 static final int SCAN_NO_DEX = 1<<1;
388 static final int SCAN_FORCE_DEX = 1<<2;
389 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
390 static final int SCAN_NEW_INSTALL = 1<<4;
391 static final int SCAN_NO_PATHS = 1<<5;
392 static final int SCAN_UPDATE_TIME = 1<<6;
393 static final int SCAN_DEFER_DEX = 1<<7;
394 static final int SCAN_BOOTING = 1<<8;
395 static final int SCAN_TRUSTED_OVERLAY = 1<<9;
396 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
397 static final int SCAN_REPLACING = 1<<11;
398 static final int SCAN_REQUIRE_KNOWN = 1<<12;
399 static final int SCAN_MOVE = 1<<13;
400 static final int SCAN_INITIAL = 1<<14;
401 static final int SCAN_CHECK_ONLY = 1<<15;
402 static final int SCAN_DONT_KILL_APP = 1<<17;
403 static final int SCAN_IGNORE_FROZEN = 1<<18;
405 static final int REMOVE_CHATTY = 1<<16;
407 private static final int[] EMPTY_INT_ARRAY = new int[0];
410 * Timeout (in milliseconds) after which the watchdog should declare that
411 * our handler thread is wedged. The usual default for such things is one
412 * minute but we sometimes do very lengthy I/O operations on this thread,
413 * such as installing multi-gigabyte applications, so ours needs to be longer.
415 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes
418 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
419 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
420 * settings entry if available, otherwise we use the hardcoded default. If it's been
421 * more than this long since the last fstrim, we force one during the boot sequence.
423 * This backstops other fstrim scheduling: if the device is alive at midnight+idle,
424 * one gets run at the next available charging+idle time. This final mandatory
425 * no-fstrim check kicks in only of the other scheduling criteria is never met.
427 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
430 * Whether verification is enabled by default.
432 private static final boolean DEFAULT_VERIFY_ENABLE = true;
435 * The default maximum time to wait for the verification agent to return in
438 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
441 * The default response for package verification timeout.
443 * This can be either PackageManager.VERIFICATION_ALLOW or
444 * PackageManager.VERIFICATION_REJECT.
446 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448 static final String PLATFORM_PACKAGE_NAME = "android";
450 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
453 DEFAULT_CONTAINER_PACKAGE,
454 "com.android.defcontainer.DefaultContainerService");
456 private static final String KILL_APP_REASON_GIDS_CHANGED =
457 "permission grant or revoke changed gids";
459 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
460 "permissions revoked";
462 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464 private static final String PACKAGE_SCHEME = "package";
466 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
468 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
469 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
470 * VENDOR_OVERLAY_DIR.
472 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
474 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
475 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
477 /** Permission grant: not grant the permission. */
478 private static final int GRANT_DENIED = 1;
480 /** Permission grant: grant the permission as an install permission. */
481 private static final int GRANT_INSTALL = 2;
483 /** Permission grant: grant the permission as a runtime one. */
484 private static final int GRANT_RUNTIME = 3;
486 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
487 private static final int GRANT_UPGRADE = 4;
489 /** Canonical intent used to identify what counts as a "web browser" app */
490 private static final Intent sBrowserIntent;
492 sBrowserIntent = new Intent();
493 sBrowserIntent.setAction(Intent.ACTION_VIEW);
494 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
495 sBrowserIntent.setData(Uri.parse("http:"));
499 * The set of all protected actions [i.e. those actions for which a high priority
500 * intent filter is disallowed].
502 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
504 PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
505 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
506 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
507 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
510 // Compilation reasons.
511 public static final int REASON_FIRST_BOOT = 0;
512 public static final int REASON_BOOT = 1;
513 public static final int REASON_INSTALL = 2;
514 public static final int REASON_BACKGROUND_DEXOPT = 3;
515 public static final int REASON_AB_OTA = 4;
516 public static final int REASON_NON_SYSTEM_LIBRARY = 5;
517 public static final int REASON_SHARED_APK = 6;
518 public static final int REASON_FORCED_DEXOPT = 7;
519 public static final int REASON_CORE_APP = 8;
521 public static final int REASON_LAST = REASON_CORE_APP;
523 /** Special library name that skips shared libraries check during compilation. */
524 private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
526 final ServiceThread mHandlerThread;
528 final PackageHandler mHandler;
530 private final ProcessLoggingHandler mProcessLoggingHandler;
533 * Messages for {@link #mHandler} that need to wait for system ready before
536 private ArrayList<Message> mPostSystemReadyMessages;
538 final int mSdkVersion = Build.VERSION.SDK_INT;
540 final Context mContext;
541 final boolean mFactoryTest;
542 final boolean mOnlyCore;
543 final DisplayMetrics mMetrics;
544 final int mDefParseFlags;
545 final String[] mSeparateProcesses;
546 final boolean mIsUpgrade;
547 final boolean mIsPreNUpgrade;
548 final boolean mIsPreNMR1Upgrade;
550 @GuardedBy("mPackages")
551 private boolean mDexOptDialogShown;
553 /** The location for ASEC container files on internal storage. */
554 final String mAsecInternalPath;
556 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
557 // LOCK HELD. Can be called with mInstallLock held.
558 @GuardedBy("mInstallLock")
559 final Installer mInstaller;
561 /** Directory where installed third-party apps stored */
562 final File mAppInstallDir;
563 final File mEphemeralInstallDir;
566 * Directory to which applications installed internally have their
567 * 32 bit native libraries copied.
569 private File mAppLib32InstallDir;
571 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
573 final File mDrmAppPrivateInstallDir;
575 // ----------------------------------------------------------------
577 // Lock for state used when installing and doing other long running
578 // operations. Methods that must be called with this lock held have
580 final Object mInstallLock = new Object();
582 // ----------------------------------------------------------------
584 // Keys are String (package name), values are Package. This also serves
585 // as the lock for the global state. Methods that must be called with
586 // this lock held have the prefix "LP".
587 @GuardedBy("mPackages")
588 final ArrayMap<String, PackageParser.Package> mPackages =
589 new ArrayMap<String, PackageParser.Package>();
591 final ArrayMap<String, Set<String>> mKnownCodebase =
592 new ArrayMap<String, Set<String>>();
594 // Tracks available target package names -> overlay package paths.
595 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
596 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
599 * Tracks new system packages [received in an OTA] that we expect to
600 * find updated user-installed versions. Keys are package name, values
601 * are package location.
603 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
605 * Tracks high priority intent filters for protected actions. During boot, certain
606 * filter actions are protected and should never be allowed to have a high priority
607 * intent filter for them. However, there is one, and only one exception -- the
608 * setup wizard. It must be able to define a high priority intent filter for these
609 * actions to ensure there are no escapes from the wizard. We need to delay processing
610 * of these during boot as we need to look at all of the system packages in order
611 * to know which component is the setup wizard.
613 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
615 * Whether or not processing protected filters should be deferred.
617 private boolean mDeferProtectedFilters = true;
620 * Tracks existing system packages prior to receiving an OTA. Keys are package name.
622 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
624 * Whether or not system app permissions should be promoted from install to runtime.
626 boolean mPromoteSystemApps;
628 @GuardedBy("mPackages")
629 final Settings mSettings;
632 * Set of package names that are currently "frozen", which means active
633 * surgery is being done on the code/data for that package. The platform
634 * will refuse to launch frozen packages to avoid race conditions.
636 * @see PackageFreezer
638 @GuardedBy("mPackages")
639 final ArraySet<String> mFrozenPackages = new ArraySet<>();
641 final ProtectedPackages mProtectedPackages;
645 // System configuration read by SystemConfig.
646 final int[] mGlobalGids;
647 final SparseArray<ArraySet<String>> mSystemPermissions;
648 final ArrayMap<String, FeatureInfo> mAvailableFeatures;
650 // If mac_permissions.xml was found for seinfo labeling.
651 boolean mFoundPolicyFile;
653 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
655 public static final class SharedLibraryEntry {
656 public final String path;
657 public final String apk;
659 SharedLibraryEntry(String _path, String _apk) {
665 // Currently known shared libraries.
666 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
667 new ArrayMap<String, SharedLibraryEntry>();
669 // All available activities, for your resolving pleasure.
670 final ActivityIntentResolver mActivities =
671 new ActivityIntentResolver();
673 // All available receivers, for your resolving pleasure.
674 final ActivityIntentResolver mReceivers =
675 new ActivityIntentResolver();
677 // All available services, for your resolving pleasure.
678 final ServiceIntentResolver mServices = new ServiceIntentResolver();
680 // All available providers, for your resolving pleasure.
681 final ProviderIntentResolver mProviders = new ProviderIntentResolver();
683 // Mapping from provider base names (first directory in content URI codePath)
684 // to the provider information.
685 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
686 new ArrayMap<String, PackageParser.Provider>();
688 // Mapping from instrumentation class names to info about them.
689 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
690 new ArrayMap<ComponentName, PackageParser.Instrumentation>();
692 // Mapping from permission names to info about them.
693 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
694 new ArrayMap<String, PackageParser.PermissionGroup>();
696 // Packages whose data we have transfered into another package, thus
697 // should no longer exist.
698 final ArraySet<String> mTransferedPackages = new ArraySet<String>();
700 // Broadcast actions that are only available to the system.
701 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
703 /** List of packages waiting for verification. */
704 final SparseArray<PackageVerificationState> mPendingVerification
705 = new SparseArray<PackageVerificationState>();
707 /** Set of packages associated with each app op permission. */
708 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
710 final PackageInstallerService mInstallerService;
712 private final PackageDexOptimizer mPackageDexOptimizer;
714 private AtomicInteger mNextMoveId = new AtomicInteger();
715 private final MoveCallbacks mMoveCallbacks;
717 private final OnPermissionChangeListeners mOnPermissionChangeListeners;
719 // Cache of users who need badging.
720 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
722 /** Token for keys in mPendingVerification. */
723 private int mPendingVerificationToken = 0;
725 volatile boolean mSystemReady;
726 volatile boolean mSafeMode;
727 volatile boolean mHasSystemUidErrors;
729 ApplicationInfo mAndroidApplication;
730 final ActivityInfo mResolveActivity = new ActivityInfo();
731 final ResolveInfo mResolveInfo = new ResolveInfo();
732 ComponentName mResolveComponentName;
733 PackageParser.Package mPlatformPackage;
734 ComponentName mCustomResolverComponentName;
736 boolean mResolverReplaced = false;
738 private final @Nullable ComponentName mIntentFilterVerifierComponent;
739 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
741 private int mIntentFilterVerificationToken = 0;
743 /** Component that knows whether or not an ephemeral application exists */
744 final ComponentName mEphemeralResolverComponent;
745 /** The service connection to the ephemeral resolver */
746 final EphemeralResolverConnection mEphemeralResolverConnection;
748 /** Component used to install ephemeral applications */
749 final ComponentName mEphemeralInstallerComponent;
750 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
751 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
753 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
754 = new SparseArray<IntentFilterVerificationState>();
756 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
758 // List of packages names to keep cached, even if they are uninstalled for all users
759 private List<String> mKeepUninstalledPackages;
761 private UserManagerInternal mUserManagerInternal;
763 private static class IFVerificationParams {
764 PackageParser.Package pkg;
769 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
770 int _userId, int _verifierUid) {
772 replacing = _replacing;
774 replacing = _replacing;
775 verifierUid = _verifierUid;
779 private interface IntentFilterVerifier<T extends IntentFilter> {
780 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
781 T filter, String packageName);
782 void startVerifications(int userId);
783 void receiveVerificationResponse(int verificationId);
786 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
787 private Context mContext;
788 private ComponentName mIntentFilterVerifierComponent;
789 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
791 public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
793 mIntentFilterVerifierComponent = verifierComponent;
796 private String getDefaultScheme() {
797 return IntentFilter.SCHEME_HTTPS;
801 public void startVerifications(int userId) {
802 // Launch verifications requests
803 int count = mCurrentIntentFilterVerifications.size();
804 for (int n=0; n<count; n++) {
805 int verificationId = mCurrentIntentFilterVerifications.get(n);
806 final IntentFilterVerificationState ivs =
807 mIntentFilterVerificationStates.get(verificationId);
809 String packageName = ivs.getPackageName();
811 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
812 final int filterCount = filters.size();
813 ArraySet<String> domainsSet = new ArraySet<>();
814 for (int m=0; m<filterCount; m++) {
815 PackageParser.ActivityIntentInfo filter = filters.get(m);
816 domainsSet.addAll(filter.getHostsList());
818 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
819 synchronized (mPackages) {
820 if (mSettings.createIntentFilterVerificationIfNeededLPw(
821 packageName, domainsList) != null) {
822 scheduleWriteSettingsLocked();
825 sendVerificationRequest(userId, verificationId, ivs);
827 mCurrentIntentFilterVerifications.clear();
830 private void sendVerificationRequest(int userId, int verificationId,
831 IntentFilterVerificationState ivs) {
833 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
834 verificationIntent.putExtra(
835 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
837 verificationIntent.putExtra(
838 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
840 verificationIntent.putExtra(
841 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
842 ivs.getHostsString());
843 verificationIntent.putExtra(
844 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
845 ivs.getPackageName());
846 verificationIntent.setComponent(mIntentFilterVerifierComponent);
847 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
849 UserHandle user = new UserHandle(userId);
850 mContext.sendBroadcastAsUser(verificationIntent, user);
851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
852 "Sending IntentFilter verification broadcast");
855 public void receiveVerificationResponse(int verificationId) {
856 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
858 final boolean verified = ivs.isVerified();
860 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
861 final int count = filters.size();
862 if (DEBUG_DOMAIN_VERIFICATION) {
863 Slog.i(TAG, "Received verification response " + verificationId
864 + " for " + count + " filters, verified=" + verified);
866 for (int n=0; n<count; n++) {
867 PackageParser.ActivityIntentInfo filter = filters.get(n);
868 filter.setVerified(verified);
870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
871 + " verified with result:" + verified + " and hosts:"
872 + ivs.getHostsString());
875 mIntentFilterVerificationStates.remove(verificationId);
877 final String packageName = ivs.getPackageName();
878 IntentFilterVerificationInfo ivi = null;
880 synchronized (mPackages) {
881 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
884 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
885 + verificationId + " packageName:" + packageName);
888 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
889 "Updating IntentFilterVerificationInfo for package " + packageName
890 +" verificationId:" + verificationId);
892 synchronized (mPackages) {
894 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
896 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
898 scheduleWriteSettingsLocked();
900 final int userId = ivs.getUserId();
901 if (userId != UserHandle.USER_ALL) {
902 final int userStatus =
903 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
905 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
906 boolean needUpdate = false;
908 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
909 // already been set by the User thru the Disambiguation dialog
910 switch (userStatus) {
911 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
913 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
915 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
920 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
922 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
932 mSettings.updateIntentFilterVerificationStatusLPw(
933 packageName, updatedStatus, userId);
934 scheduleWritePackageRestrictionsLocked(userId);
941 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
942 ActivityIntentInfo filter, String packageName) {
943 if (!hasValidDomains(filter)) {
946 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
948 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
951 if (DEBUG_DOMAIN_VERIFICATION) {
952 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
954 ivs.addFilter(filter);
958 private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
959 int userId, int verificationId, String packageName) {
960 IntentFilterVerificationState ivs = new IntentFilterVerificationState(
961 verifierUid, userId, packageName);
962 ivs.setPendingState();
963 synchronized (mPackages) {
964 mIntentFilterVerificationStates.append(verificationId, ivs);
965 mCurrentIntentFilterVerifications.add(verificationId);
971 private static boolean hasValidDomains(ActivityIntentInfo filter) {
972 return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
973 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
974 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
977 // Set of pending broadcasts for aggregating enable/disable of components.
978 static class PendingPackageBroadcasts {
979 // for each user id, a map of <package name -> components within that package>
980 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
982 public PendingPackageBroadcasts() {
983 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
986 public ArrayList<String> get(int userId, String packageName) {
987 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
988 return packages.get(packageName);
991 public void put(int userId, String packageName, ArrayList<String> components) {
992 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
993 packages.put(packageName, components);
996 public void remove(int userId, String packageName) {
997 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
998 if (packages != null) {
999 packages.remove(packageName);
1003 public void remove(int userId) {
1004 mUidMap.remove(userId);
1007 public int userIdCount() {
1008 return mUidMap.size();
1011 public int userIdAt(int n) {
1012 return mUidMap.keyAt(n);
1015 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1016 return mUidMap.get(userId);
1020 // total number of pending broadcast entries across all userIds
1022 for (int i = 0; i< mUidMap.size(); i++) {
1023 num += mUidMap.valueAt(i).size();
1028 public void clear() {
1032 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1033 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1035 map = new ArrayMap<String, ArrayList<String>>();
1036 mUidMap.put(userId, map);
1041 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1043 // Service Connection to remote media container service to copy
1044 // package uri's from external media onto secure containers
1045 // or internal storage.
1046 private IMediaContainerService mContainerService = null;
1048 static final int SEND_PENDING_BROADCAST = 1;
1049 static final int MCS_BOUND = 3;
1050 static final int END_COPY = 4;
1051 static final int INIT_COPY = 5;
1052 static final int MCS_UNBIND = 6;
1053 static final int START_CLEANING_PACKAGE = 7;
1054 static final int FIND_INSTALL_LOC = 8;
1055 static final int POST_INSTALL = 9;
1056 static final int MCS_RECONNECT = 10;
1057 static final int MCS_GIVE_UP = 11;
1058 static final int UPDATED_MEDIA_STATUS = 12;
1059 static final int WRITE_SETTINGS = 13;
1060 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1061 static final int PACKAGE_VERIFIED = 15;
1062 static final int CHECK_PENDING_VERIFICATION = 16;
1063 static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1064 static final int INTENT_FILTER_VERIFIED = 18;
1065 static final int WRITE_PACKAGE_LIST = 19;
1067 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
1069 // Delay time in millisecs
1070 static final int BROADCAST_DELAY = 10 * 1000;
1072 static UserManagerService sUserManager;
1074 // Stores a list of users whose package restrictions file needs to be updated
1075 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1077 final private DefaultContainerConnection mDefContainerConn =
1078 new DefaultContainerConnection();
1079 class DefaultContainerConnection implements ServiceConnection {
1080 public void onServiceConnected(ComponentName name, IBinder service) {
1081 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1082 IMediaContainerService imcs =
1083 IMediaContainerService.Stub.asInterface(service);
1084 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1087 public void onServiceDisconnected(ComponentName name) {
1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1092 // Recordkeeping of restore-after-install operations that are currently in flight
1093 // between the Package Manager and the Backup Manager
1094 static class PostInstallData {
1095 public InstallArgs args;
1096 public PackageInstalledInfo res;
1098 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1104 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1105 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
1107 // XML tags for backup/restore of various bits of state
1108 private static final String TAG_PREFERRED_BACKUP = "pa";
1109 private static final String TAG_DEFAULT_APPS = "da";
1110 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1112 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1113 private static final String TAG_ALL_GRANTS = "rt-grants";
1114 private static final String TAG_GRANT = "grant";
1115 private static final String ATTR_PACKAGE_NAME = "pkg";
1117 private static final String TAG_PERMISSION = "perm";
1118 private static final String ATTR_PERMISSION_NAME = "name";
1119 private static final String ATTR_IS_GRANTED = "g";
1120 private static final String ATTR_USER_SET = "set";
1121 private static final String ATTR_USER_FIXED = "fixed";
1122 private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1124 // System/policy permission grants are not backed up
1125 private static final int SYSTEM_RUNTIME_GRANT_MASK =
1126 FLAG_PERMISSION_POLICY_FIXED
1127 | FLAG_PERMISSION_SYSTEM_FIXED
1128 | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1130 // And we back up these user-adjusted states
1131 private static final int USER_RUNTIME_GRANT_MASK =
1132 FLAG_PERMISSION_USER_SET
1133 | FLAG_PERMISSION_USER_FIXED
1134 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1136 final @Nullable String mRequiredVerifierPackage;
1137 final @NonNull String mRequiredInstallerPackage;
1138 final @NonNull String mRequiredUninstallerPackage;
1139 final @Nullable String mSetupWizardPackage;
1140 final @Nullable String mStorageManagerPackage;
1141 final @NonNull String mServicesSystemSharedLibraryPackageName;
1142 final @NonNull String mSharedSystemSharedLibraryPackageName;
1144 final boolean mPermissionReviewRequired;
1146 private final PackageUsage mPackageUsage = new PackageUsage();
1147 private final CompilerStats mCompilerStats = new CompilerStats();
1149 class PackageHandler extends Handler {
1150 private boolean mBound = false;
1151 final ArrayList<HandlerParams> mPendingInstalls =
1152 new ArrayList<HandlerParams>();
1154 private boolean connectToService() {
1155 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1156 " DefaultContainerService");
1157 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1158 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1159 if (mContext.bindServiceAsUser(service, mDefContainerConn,
1160 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1161 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1169 private void disconnectService() {
1170 mContainerService = null;
1172 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1173 mContext.unbindService(mDefContainerConn);
1174 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1177 PackageHandler(Looper looper) {
1181 public void handleMessage(Message msg) {
1183 doHandleMessage(msg);
1185 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1189 void doHandleMessage(Message msg) {
1192 HandlerParams params = (HandlerParams) msg.obj;
1193 int idx = mPendingInstalls.size();
1194 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1195 // If a bind was already initiated we dont really
1196 // need to do anything. The pending install
1197 // will be processed later on.
1199 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1200 System.identityHashCode(mHandler));
1201 // If this is the only one pending we might
1202 // have to bind to the service again.
1203 if (!connectToService()) {
1204 Slog.e(TAG, "Failed to bind to media container service");
1205 params.serviceError();
1206 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1207 System.identityHashCode(mHandler));
1208 if (params.traceMethod != null) {
1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1210 params.traceCookie);
1214 // Once we bind to the service, the first
1215 // pending request will be processed.
1216 mPendingInstalls.add(idx, params);
1219 mPendingInstalls.add(idx, params);
1220 // Already bound to the service. Just make
1221 // sure we trigger off processing the first request.
1223 mHandler.sendEmptyMessage(MCS_BOUND);
1229 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1230 if (msg.obj != null) {
1231 mContainerService = (IMediaContainerService) msg.obj;
1232 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1233 System.identityHashCode(mHandler));
1235 if (mContainerService == null) {
1237 // Something seriously wrong since we are not bound and we are not
1238 // waiting for connection. Bail out.
1239 Slog.e(TAG, "Cannot bind to media container service");
1240 for (HandlerParams params : mPendingInstalls) {
1241 // Indicate service bind error
1242 params.serviceError();
1243 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1244 System.identityHashCode(params));
1245 if (params.traceMethod != null) {
1246 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1247 params.traceMethod, params.traceCookie);
1251 mPendingInstalls.clear();
1253 Slog.w(TAG, "Waiting to connect to media container service");
1255 } else if (mPendingInstalls.size() > 0) {
1256 HandlerParams params = mPendingInstalls.get(0);
1257 if (params != null) {
1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259 System.identityHashCode(params));
1260 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1261 if (params.startCopy()) {
1262 // We are done... look for more work or to
1264 if (DEBUG_SD_INSTALL) Log.i(TAG,
1265 "Checking for more work or unbind...");
1266 // Delete pending install
1267 if (mPendingInstalls.size() > 0) {
1268 mPendingInstalls.remove(0);
1270 if (mPendingInstalls.size() == 0) {
1272 if (DEBUG_SD_INSTALL) Log.i(TAG,
1273 "Posting delayed MCS_UNBIND");
1274 removeMessages(MCS_UNBIND);
1275 Message ubmsg = obtainMessage(MCS_UNBIND);
1276 // Unbind after a little delay, to avoid
1277 // continual thrashing.
1278 sendMessageDelayed(ubmsg, 10000);
1281 // There are more pending requests in queue.
1282 // Just post MCS_BOUND message to trigger processing
1283 // of next pending install.
1284 if (DEBUG_SD_INSTALL) Log.i(TAG,
1285 "Posting MCS_BOUND for next work");
1286 mHandler.sendEmptyMessage(MCS_BOUND);
1289 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1292 // Should never happen ideally.
1293 Slog.w(TAG, "Empty queue");
1297 case MCS_RECONNECT: {
1298 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1299 if (mPendingInstalls.size() > 0) {
1301 disconnectService();
1303 if (!connectToService()) {
1304 Slog.e(TAG, "Failed to bind to media container service");
1305 for (HandlerParams params : mPendingInstalls) {
1306 // Indicate service bind error
1307 params.serviceError();
1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1309 System.identityHashCode(params));
1311 mPendingInstalls.clear();
1317 // If there is no actual work left, then time to unbind.
1318 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1320 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1322 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1324 disconnectService();
1326 } else if (mPendingInstalls.size() > 0) {
1327 // There are more pending requests in queue.
1328 // Just post MCS_BOUND message to trigger processing
1329 // of next pending install.
1330 mHandler.sendEmptyMessage(MCS_BOUND);
1336 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1337 HandlerParams params = mPendingInstalls.remove(0);
1338 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1339 System.identityHashCode(params));
1342 case SEND_PENDING_BROADCAST: {
1344 ArrayList<String> components[];
1347 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1348 synchronized (mPackages) {
1349 if (mPendingBroadcasts == null) {
1352 size = mPendingBroadcasts.size();
1354 // Nothing to be done. Just return
1357 packages = new String[size];
1358 components = new ArrayList[size];
1359 uids = new int[size];
1360 int i = 0; // filling out the above arrays
1362 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1363 int packageUserId = mPendingBroadcasts.userIdAt(n);
1364 Iterator<Map.Entry<String, ArrayList<String>>> it
1365 = mPendingBroadcasts.packagesForUserId(packageUserId)
1366 .entrySet().iterator();
1367 while (it.hasNext() && i < size) {
1368 Map.Entry<String, ArrayList<String>> ent = it.next();
1369 packages[i] = ent.getKey();
1370 components[i] = ent.getValue();
1371 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1372 uids[i] = (ps != null)
1373 ? UserHandle.getUid(packageUserId, ps.appId)
1379 mPendingBroadcasts.clear();
1382 for (int i = 0; i < size; i++) {
1383 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1385 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1388 case START_CLEANING_PACKAGE: {
1389 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1390 final String packageName = (String)msg.obj;
1391 final int userId = msg.arg1;
1392 final boolean andCode = msg.arg2 != 0;
1393 synchronized (mPackages) {
1394 if (userId == UserHandle.USER_ALL) {
1395 int[] users = sUserManager.getUserIds();
1396 for (int user : users) {
1397 mSettings.addPackageToCleanLPw(
1398 new PackageCleanItem(user, packageName, andCode));
1401 mSettings.addPackageToCleanLPw(
1402 new PackageCleanItem(userId, packageName, andCode));
1405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1406 startCleaningPackages();
1408 case POST_INSTALL: {
1409 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1411 PostInstallData data = mRunningInstalls.get(msg.arg1);
1412 final boolean didRestore = (msg.arg2 != 0);
1413 mRunningInstalls.delete(msg.arg1);
1416 InstallArgs args = data.args;
1417 PackageInstalledInfo parentRes = data.res;
1419 final boolean grantPermissions = (args.installFlags
1420 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1421 final boolean killApp = (args.installFlags
1422 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1423 final String[] grantedPermissions = args.installGrantPermissions;
1425 // Handle the parent package
1426 handlePackagePostInstall(parentRes, grantPermissions, killApp,
1427 grantedPermissions, didRestore, args.installerPackageName,
1430 // Handle the child packages
1431 final int childCount = (parentRes.addedChildPackages != null)
1432 ? parentRes.addedChildPackages.size() : 0;
1433 for (int i = 0; i < childCount; i++) {
1434 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1435 handlePackagePostInstall(childRes, grantPermissions, killApp,
1436 grantedPermissions, false, args.installerPackageName,
1440 // Log tracing if needed
1441 if (args.traceMethod != null) {
1442 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1446 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1449 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1451 case UPDATED_MEDIA_STATUS: {
1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1453 boolean reportStatus = msg.arg1 == 1;
1454 boolean doGc = msg.arg2 == 1;
1455 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1457 // Force a gc to clear up stale containers.
1458 Runtime.getRuntime().gc();
1460 if (msg.obj != null) {
1461 @SuppressWarnings("unchecked")
1462 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1463 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1464 // Unload containers
1465 unloadAllContainers(args);
1469 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1470 PackageHelper.getMountService().finishMediaUpdate();
1471 } catch (RemoteException e) {
1472 Log.e(TAG, "MountService not running?");
1476 case WRITE_SETTINGS: {
1477 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1478 synchronized (mPackages) {
1479 removeMessages(WRITE_SETTINGS);
1480 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481 mSettings.writeLPr();
1482 mDirtyUsers.clear();
1484 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1486 case WRITE_PACKAGE_RESTRICTIONS: {
1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488 synchronized (mPackages) {
1489 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490 for (int userId : mDirtyUsers) {
1491 mSettings.writePackageRestrictionsLPr(userId);
1493 mDirtyUsers.clear();
1495 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1497 case WRITE_PACKAGE_LIST: {
1498 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499 synchronized (mPackages) {
1500 removeMessages(WRITE_PACKAGE_LIST);
1501 mSettings.writePackageListLPr(msg.arg1);
1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1505 case CHECK_PENDING_VERIFICATION: {
1506 final int verificationId = msg.arg1;
1507 final PackageVerificationState state = mPendingVerification.get(verificationId);
1509 if ((state != null) && !state.timeoutExtended()) {
1510 final InstallArgs args = state.getInstallArgs();
1511 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1513 Slog.i(TAG, "Verification timed out for " + originUri);
1514 mPendingVerification.remove(verificationId);
1516 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1518 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1519 Slog.i(TAG, "Continuing with installation of " + originUri);
1520 state.setVerifierResponse(Binder.getCallingUid(),
1521 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1522 broadcastPackageVerified(verificationId, originUri,
1523 PackageManager.VERIFICATION_ALLOW,
1524 state.getInstallArgs().getUser());
1526 ret = args.copyApk(mContainerService, true);
1527 } catch (RemoteException e) {
1528 Slog.e(TAG, "Could not contact the ContainerService");
1531 broadcastPackageVerified(verificationId, originUri,
1532 PackageManager.VERIFICATION_REJECT,
1533 state.getInstallArgs().getUser());
1536 Trace.asyncTraceEnd(
1537 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1539 processPendingInstall(args, ret);
1540 mHandler.sendEmptyMessage(MCS_UNBIND);
1544 case PACKAGE_VERIFIED: {
1545 final int verificationId = msg.arg1;
1547 final PackageVerificationState state = mPendingVerification.get(verificationId);
1548 if (state == null) {
1549 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1553 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1555 state.setVerifierResponse(response.callerUid, response.code);
1557 if (state.isVerificationComplete()) {
1558 mPendingVerification.remove(verificationId);
1560 final InstallArgs args = state.getInstallArgs();
1561 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1564 if (state.isInstallAllowed()) {
1565 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1566 broadcastPackageVerified(verificationId, originUri,
1567 response.code, state.getInstallArgs().getUser());
1569 ret = args.copyApk(mContainerService, true);
1570 } catch (RemoteException e) {
1571 Slog.e(TAG, "Could not contact the ContainerService");
1574 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1577 Trace.asyncTraceEnd(
1578 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1580 processPendingInstall(args, ret);
1581 mHandler.sendEmptyMessage(MCS_UNBIND);
1586 case START_INTENT_FILTER_VERIFICATIONS: {
1587 IFVerificationParams params = (IFVerificationParams) msg.obj;
1588 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1589 params.replacing, params.pkg);
1592 case INTENT_FILTER_VERIFIED: {
1593 final int verificationId = msg.arg1;
1595 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1597 if (state == null) {
1598 Slog.w(TAG, "Invalid IntentFilter verification token "
1599 + verificationId + " received");
1603 final int userId = state.getUserId();
1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1606 "Processing IntentFilter verification with token:"
1607 + verificationId + " and userId:" + userId);
1609 final IntentFilterVerificationResponse response =
1610 (IntentFilterVerificationResponse) msg.obj;
1612 state.setVerifierResponse(response.callerUid, response.code);
1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615 "IntentFilter verification with token:" + verificationId
1616 + " and userId:" + userId
1617 + " is settings verifier response with response code:"
1620 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1621 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1622 + response.getFailedDomainsString());
1625 if (state.isVerificationComplete()) {
1626 mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1629 "IntentFilter verification with token:" + verificationId
1630 + " was not said to be complete");
1639 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1640 boolean killApp, String[] grantedPermissions,
1641 boolean launchedForRestore, String installerPackage,
1642 IPackageInstallObserver2 installObserver) {
1643 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1644 // Send the removed broadcasts
1645 if (res.removedInfo != null) {
1646 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1649 // Now that we successfully installed the package, grant runtime
1650 // permissions if requested before broadcasting the install.
1651 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1652 >= Build.VERSION_CODES.M) {
1653 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1656 final boolean update = res.removedInfo != null
1657 && res.removedInfo.removedPackage != null;
1659 // If this is the first time we have child packages for a disabled privileged
1660 // app that had no children, we grant requested runtime permissions to the new
1661 // children if the parent on the system image had them already granted.
1662 if (res.pkg.parentPackage != null) {
1663 synchronized (mPackages) {
1664 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1668 synchronized (mPackages) {
1669 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1672 final String packageName = res.pkg.applicationInfo.packageName;
1673 Bundle extras = new Bundle(1);
1674 extras.putInt(Intent.EXTRA_UID, res.uid);
1676 // Determine the set of users who are adding this package for
1677 // the first time vs. those who are seeing an update.
1678 int[] firstUsers = EMPTY_INT_ARRAY;
1679 int[] updateUsers = EMPTY_INT_ARRAY;
1680 if (res.origUsers == null || res.origUsers.length == 0) {
1681 firstUsers = res.newUsers;
1683 for (int newUser : res.newUsers) {
1684 boolean isNew = true;
1685 for (int origUser : res.origUsers) {
1686 if (origUser == newUser) {
1692 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1694 updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1699 // Send installed broadcasts if the install/update is not ephemeral
1700 if (!isEphemeral(res.pkg)) {
1701 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1703 // Send added for users that see the package for the first time
1704 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705 extras, 0 /*flags*/, null /*targetPackage*/,
1706 null /*finishedReceiver*/, firstUsers);
1708 // Send added for users that don't see the package for the first time
1710 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1712 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1713 extras, 0 /*flags*/, null /*targetPackage*/,
1714 null /*finishedReceiver*/, updateUsers);
1716 // Send replaced for users that don't see the package for the first time
1718 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1719 packageName, extras, 0 /*flags*/,
1720 null /*targetPackage*/, null /*finishedReceiver*/,
1722 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1723 null /*package*/, null /*extras*/, 0 /*flags*/,
1724 packageName /*targetPackage*/,
1725 null /*finishedReceiver*/, updateUsers);
1726 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1727 // First-install and we did a restore, so we're responsible for the
1728 // first-launch broadcast.
1730 Slog.i(TAG, "Post-restore of " + packageName
1731 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1733 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1736 // Send broadcast package appeared if forward locked/external for all users
1737 // treat asec-hosted packages like removable media on upgrade
1738 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1739 if (DEBUG_INSTALL) {
1740 Slog.i(TAG, "upgrading pkg " + res.pkg
1741 + " is ASEC-hosted -> AVAILABLE");
1743 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1744 ArrayList<String> pkgList = new ArrayList<>(1);
1745 pkgList.add(packageName);
1746 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1750 // Work that needs to happen on first install within each user
1751 if (firstUsers != null && firstUsers.length > 0) {
1752 synchronized (mPackages) {
1753 for (int userId : firstUsers) {
1754 // If this app is a browser and it's newly-installed for some
1755 // users, clear any default-browser state in those users. The
1756 // app's nature doesn't depend on the user, so we can just check
1757 // its browser nature in any user and generalize.
1758 if (packageIsBrowser(packageName, userId)) {
1759 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1762 // We may also need to apply pending (restored) runtime
1763 // permission grants within these users.
1764 mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1769 // Log current value of "unknown sources" setting
1770 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1771 getUnknownSourcesSettings());
1773 // Force a gc to clear up things
1774 Runtime.getRuntime().gc();
1776 // Remove the replaced package's older resources safely now
1777 // We delete after a gc for applications on sdcard.
1778 if (res.removedInfo != null && res.removedInfo.args != null) {
1779 synchronized (mInstallLock) {
1780 res.removedInfo.args.doPostDeleteLI(true);
1785 // If someone is watching installs - notify them
1786 if (installObserver != null) {
1788 Bundle extras = extrasForInstallResult(res);
1789 installObserver.onPackageInstalled(res.name, res.returnCode,
1790 res.returnMsg, extras);
1791 } catch (RemoteException e) {
1792 Slog.i(TAG, "Observer no longer exists.");
1797 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1798 PackageParser.Package pkg) {
1799 if (pkg.parentPackage == null) {
1802 if (pkg.requestedPermissions == null) {
1805 final PackageSetting disabledSysParentPs = mSettings
1806 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1807 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1808 || !disabledSysParentPs.isPrivileged()
1809 || (disabledSysParentPs.childPackageNames != null
1810 && !disabledSysParentPs.childPackageNames.isEmpty())) {
1813 final int[] allUserIds = sUserManager.getUserIds();
1814 final int permCount = pkg.requestedPermissions.size();
1815 for (int i = 0; i < permCount; i++) {
1816 String permission = pkg.requestedPermissions.get(i);
1817 BasePermission bp = mSettings.mPermissions.get(permission);
1818 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1821 for (int userId : allUserIds) {
1822 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1823 permission, userId)) {
1824 grantRuntimePermission(pkg.packageName, permission, userId);
1830 private StorageEventListener mStorageListener = new StorageEventListener() {
1832 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1833 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1834 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1835 final String volumeUuid = vol.getFsUuid();
1837 // Clean up any users or apps that were removed or recreated
1838 // while this volume was missing
1839 reconcileUsers(volumeUuid);
1840 reconcileApps(volumeUuid);
1842 // Clean up any install sessions that expired or were
1843 // cancelled while this volume was missing
1844 mInstallerService.onPrivateVolumeMounted(volumeUuid);
1846 loadPrivatePackages(vol);
1848 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1849 unloadPrivatePackages(vol);
1853 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1854 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1855 updateExternalMediaStatus(true, false);
1856 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1857 updateExternalMediaStatus(false, false);
1863 public void onVolumeForgotten(String fsUuid) {
1864 if (TextUtils.isEmpty(fsUuid)) {
1865 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1869 // Remove any apps installed on the forgotten volume
1870 synchronized (mPackages) {
1871 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1872 for (PackageSetting ps : packages) {
1873 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1874 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1875 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1878 mSettings.onVolumeForgotten(fsUuid);
1879 mSettings.writeLPr();
1884 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1885 String[] grantedPermissions) {
1886 for (int userId : userIds) {
1887 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1890 // We could have touched GID membership, so flush out packages.list
1891 synchronized (mPackages) {
1892 mSettings.writePackageListLPr();
1896 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1897 String[] grantedPermissions) {
1898 SettingBase sb = (SettingBase) pkg.mExtras;
1903 PermissionsState permissionsState = sb.getPermissionsState();
1905 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1906 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1908 for (String permission : pkg.requestedPermissions) {
1909 final BasePermission bp;
1910 synchronized (mPackages) {
1911 bp = mSettings.mPermissions.get(permission);
1913 if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1914 && (grantedPermissions == null
1915 || ArrayUtils.contains(grantedPermissions, permission))) {
1916 final int flags = permissionsState.getPermissionFlags(permission, userId);
1917 // Installer cannot change immutable permissions.
1918 if ((flags & immutableFlags) == 0) {
1919 grantRuntimePermission(pkg.packageName, permission, userId);
1925 Bundle extrasForInstallResult(PackageInstalledInfo res) {
1926 Bundle extras = null;
1927 switch (res.returnCode) {
1928 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1929 extras = new Bundle();
1930 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1931 res.origPermission);
1932 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1936 case PackageManager.INSTALL_SUCCEEDED: {
1937 extras = new Bundle();
1938 extras.putBoolean(Intent.EXTRA_REPLACING,
1939 res.removedInfo != null && res.removedInfo.removedPackage != null);
1946 void scheduleWriteSettingsLocked() {
1947 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1948 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1952 void scheduleWritePackageListLocked(int userId) {
1953 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1954 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1956 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1960 void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1961 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1962 scheduleWritePackageRestrictionsLocked(userId);
1965 void scheduleWritePackageRestrictionsLocked(int userId) {
1966 final int[] userIds = (userId == UserHandle.USER_ALL)
1967 ? sUserManager.getUserIds() : new int[]{userId};
1968 for (int nextUserId : userIds) {
1969 if (!sUserManager.exists(nextUserId)) return;
1970 mDirtyUsers.add(nextUserId);
1971 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1972 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1977 public static PackageManagerService main(Context context, Installer installer,
1978 boolean factoryTest, boolean onlyCore) {
1979 // Self-check for initial settings.
1980 PackageManagerServiceCompilerMapping.checkProperties();
1982 PackageManagerService m = new PackageManagerService(context, installer,
1983 factoryTest, onlyCore);
1984 m.enableSystemUserPackages();
1985 ServiceManager.addService("package", m);
1989 private void enableSystemUserPackages() {
1990 if (!UserManager.isSplitSystemUser()) {
1993 // For system user, enable apps based on the following conditions:
1994 // - app is whitelisted or belong to one of these groups:
1995 // -- system app which has no launcher icons
1996 // -- system app which has INTERACT_ACROSS_USERS permission
1997 // -- system IME app
1998 // - app is not in the blacklist
1999 AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2000 Set<String> enableApps = new ArraySet<>();
2001 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2002 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2003 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2004 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2005 enableApps.addAll(wlApps);
2006 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2007 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2008 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2009 enableApps.removeAll(blApps);
2010 Log.i(TAG, "Applications installed for system user: " + enableApps);
2011 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2013 final int allAppsSize = allAps.size();
2014 synchronized (mPackages) {
2015 for (int i = 0; i < allAppsSize; i++) {
2016 String pName = allAps.get(i);
2017 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2018 // Should not happen, but we shouldn't be failing if it does
2019 if (pkgSetting == null) {
2022 boolean install = enableApps.contains(pName);
2023 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2024 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2025 + " for system user");
2026 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2032 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2033 DisplayManager displayManager = (DisplayManager) context.getSystemService(
2034 Context.DISPLAY_SERVICE);
2035 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2039 * Requests that files preopted on a secondary system partition be copied to the data partition
2040 * if possible. Note that the actual copying of the files is accomplished by init for security
2041 * reasons. This simply requests that the copy takes place and awaits confirmation of its
2042 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2044 private static void requestCopyPreoptedFiles() {
2045 final int WAIT_TIME_MS = 100;
2046 final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2047 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2048 SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2049 // We will wait for up to 100 seconds.
2050 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2051 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2053 Thread.sleep(WAIT_TIME_MS);
2054 } catch (InterruptedException e) {
2057 if (SystemClock.uptimeMillis() > timeEnd) {
2058 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2059 Slog.wtf(TAG, "cppreopt did not finish!");
2066 public PackageManagerService(Context context, Installer installer,
2067 boolean factoryTest, boolean onlyCore) {
2068 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2069 SystemClock.uptimeMillis());
2071 if (mSdkVersion <= 0) {
2072 Slog.w(TAG, "**** ro.build.version.sdk not set!");
2077 mPermissionReviewRequired = context.getResources().getBoolean(
2078 R.bool.config_permissionReviewRequired);
2080 mFactoryTest = factoryTest;
2081 mOnlyCore = onlyCore;
2082 mMetrics = new DisplayMetrics();
2083 mSettings = new Settings(mPackages);
2084 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2085 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2086 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2087 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2088 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2089 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2090 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2091 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2092 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2093 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2095 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2097 String separateProcesses = SystemProperties.get("debug.separate_processes");
2098 if (separateProcesses != null && separateProcesses.length() > 0) {
2099 if ("*".equals(separateProcesses)) {
2100 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2101 mSeparateProcesses = null;
2102 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2105 mSeparateProcesses = separateProcesses.split(",");
2106 Slog.w(TAG, "Running with debug.separate_processes: "
2107 + separateProcesses);
2111 mSeparateProcesses = null;
2114 mInstaller = installer;
2115 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2117 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2119 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2120 FgThread.get().getLooper());
2122 getDefaultDisplayMetrics(context, mMetrics);
2124 SystemConfig systemConfig = SystemConfig.getInstance();
2125 mGlobalGids = systemConfig.getGlobalGids();
2126 mSystemPermissions = systemConfig.getSystemPermissions();
2127 mAvailableFeatures = systemConfig.getAvailableFeatures();
2129 mProtectedPackages = new ProtectedPackages(mContext);
2131 synchronized (mInstallLock) {
2133 synchronized (mPackages) {
2134 mHandlerThread = new ServiceThread(TAG,
2135 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2136 mHandlerThread.start();
2137 mHandler = new PackageHandler(mHandlerThread.getLooper());
2138 mProcessLoggingHandler = new ProcessLoggingHandler();
2139 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2141 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2143 File dataDir = Environment.getDataDirectory();
2144 mAppInstallDir = new File(dataDir, "app");
2145 mAppLib32InstallDir = new File(dataDir, "app-lib");
2146 mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2147 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2148 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2150 sUserManager = new UserManagerService(context, this, mPackages);
2152 // Propagate permission configuration in to package manager.
2153 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2154 = systemConfig.getPermissions();
2155 for (int i=0; i<permConfig.size(); i++) {
2156 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2157 BasePermission bp = mSettings.mPermissions.get(perm.name);
2159 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2160 mSettings.mPermissions.put(perm.name, bp);
2162 if (perm.gids != null) {
2163 bp.setGids(perm.gids, perm.perUser);
2167 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2168 for (int i=0; i<libConfig.size(); i++) {
2169 mSharedLibraries.put(libConfig.keyAt(i),
2170 new SharedLibraryEntry(libConfig.valueAt(i), null));
2173 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2175 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2177 // Clean up orphaned packages for which the code path doesn't exist
2178 // and they are an update to a system app - caused by bug/32321269
2179 final int packageSettingCount = mSettings.mPackages.size();
2180 for (int i = packageSettingCount - 1; i >= 0; i--) {
2181 PackageSetting ps = mSettings.mPackages.valueAt(i);
2182 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2183 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2184 mSettings.mPackages.removeAt(i);
2185 mSettings.enableSystemPackageLPw(ps.name);
2190 requestCopyPreoptedFiles();
2193 String customResolverActivity = Resources.getSystem().getString(
2194 R.string.config_customResolverActivity);
2195 if (TextUtils.isEmpty(customResolverActivity)) {
2196 customResolverActivity = null;
2198 mCustomResolverComponentName = ComponentName.unflattenFromString(
2199 customResolverActivity);
2202 long startTime = SystemClock.uptimeMillis();
2204 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2207 // Set flag to monitor and not change apk file paths when
2208 // scanning install directories.
2209 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2211 final String bootClassPath = System.getenv("BOOTCLASSPATH");
2212 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2214 if (bootClassPath == null) {
2215 Slog.w(TAG, "No BOOTCLASSPATH found!");
2218 if (systemServerClassPath == null) {
2219 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2222 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2223 final String[] dexCodeInstructionSets =
2224 getDexCodeInstructionSets(
2225 allInstructionSets.toArray(new String[allInstructionSets.size()]));
2228 * Ensure all external libraries have had dexopt run on them.
2230 if (mSharedLibraries.size() > 0) {
2231 // NOTE: For now, we're compiling these system "shared libraries"
2232 // (and framework jars) into all available architectures. It's possible
2233 // to compile them only when we come across an app that uses them (there's
2234 // already logic for that in scanPackageLI) but that adds some complexity.
2235 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2236 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2237 final String lib = libEntry.path;
2243 // Shared libraries do not have profiles so we perform a full
2244 // AOT compilation (if needed).
2245 int dexoptNeeded = DexFile.getDexOptNeeded(
2246 lib, dexCodeInstructionSet,
2247 getCompilerFilterForReason(REASON_SHARED_APK),
2248 false /* newProfile */);
2249 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2250 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2251 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2252 getCompilerFilterForReason(REASON_SHARED_APK),
2253 StorageManager.UUID_PRIVATE_INTERNAL,
2254 SKIP_SHARED_LIBRARY_CHECK);
2256 } catch (FileNotFoundException e) {
2257 Slog.w(TAG, "Library not found: " + lib);
2258 } catch (IOException | InstallerException e) {
2259 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2266 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2268 final VersionInfo ver = mSettings.getInternalVersion();
2269 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2271 // when upgrading from pre-M, promote system app permissions from install to runtime
2272 mPromoteSystemApps =
2273 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2275 // When upgrading from pre-N, we need to handle package extraction like first boot,
2276 // as there is no profiling data available.
2277 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2279 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2281 // save off the names of pre-existing system packages prior to scanning; we don't
2282 // want to automatically grant runtime permissions for new system apps
2283 if (mPromoteSystemApps) {
2284 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2285 while (pkgSettingIter.hasNext()) {
2286 PackageSetting ps = pkgSettingIter.next();
2287 if (isSystemApp(ps)) {
2288 mExistingSystemPackages.add(ps.name);
2293 // Collect vendor overlay packages. (Do this before scanning any apps.)
2294 // For security and version matching reason, only consider
2295 // overlay packages if they reside in the right directory.
2296 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2297 if (!overlayThemeDir.isEmpty()) {
2298 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2299 | PackageParser.PARSE_IS_SYSTEM
2300 | PackageParser.PARSE_IS_SYSTEM_DIR
2301 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2303 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2304 | PackageParser.PARSE_IS_SYSTEM
2305 | PackageParser.PARSE_IS_SYSTEM_DIR
2306 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2308 // Find base frameworks (resource packages without code).
2309 scanDirTracedLI(frameworkDir, mDefParseFlags
2310 | PackageParser.PARSE_IS_SYSTEM
2311 | PackageParser.PARSE_IS_SYSTEM_DIR
2312 | PackageParser.PARSE_IS_PRIVILEGED,
2313 scanFlags | SCAN_NO_DEX, 0);
2315 // Collected privileged system packages.
2316 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2317 scanDirTracedLI(privilegedAppDir, mDefParseFlags
2318 | PackageParser.PARSE_IS_SYSTEM
2319 | PackageParser.PARSE_IS_SYSTEM_DIR
2320 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2322 // Collect ordinary system packages.
2323 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2324 scanDirTracedLI(systemAppDir, mDefParseFlags
2325 | PackageParser.PARSE_IS_SYSTEM
2326 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2328 // Collect all vendor packages.
2329 File vendorAppDir = new File("/vendor/app");
2331 vendorAppDir = vendorAppDir.getCanonicalFile();
2332 } catch (IOException e) {
2333 // failed to look up canonical path, continue with original one
2335 scanDirTracedLI(vendorAppDir, mDefParseFlags
2336 | PackageParser.PARSE_IS_SYSTEM
2337 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2339 // Collect all OEM packages.
2340 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2341 scanDirTracedLI(oemAppDir, mDefParseFlags
2342 | PackageParser.PARSE_IS_SYSTEM
2343 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2345 // Prune any system packages that no longer exist.
2346 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2348 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2349 while (psit.hasNext()) {
2350 PackageSetting ps = psit.next();
2353 * If this is not a system app, it can't be a
2354 * disable system app.
2356 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2361 * If the package is scanned, it's not erased.
2363 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2364 if (scannedPkg != null) {
2366 * If the system app is both scanned and in the
2367 * disabled packages list, then it must have been
2368 * added via OTA. Remove it from the currently
2369 * scanned package so the previously user-installed
2370 * application can be scanned.
2372 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2373 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2374 + ps.name + "; removing system app. Last known codePath="
2375 + ps.codePathString + ", installStatus=" + ps.installStatus
2376 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2377 + scannedPkg.mVersionCode);
2378 removePackageLI(scannedPkg, true);
2379 mExpectingBetter.put(ps.name, ps.codePath);
2385 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2387 logCriticalInfo(Log.WARN, "System package " + ps.name
2388 + " no longer exists; it's data will be wiped");
2389 // Actual deletion of code and data will be handled by later
2390 // reconciliation step
2392 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2393 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2394 possiblyDeletedUpdatedSystemApps.add(ps.name);
2400 //look for any incomplete package installations
2401 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2402 for (int i = 0; i < deletePkgsList.size(); i++) {
2403 // Actual deletion of code and data will be handled by later
2404 // reconciliation step
2405 final String packageName = deletePkgsList.get(i).name;
2406 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2407 synchronized (mPackages) {
2408 mSettings.removePackageLPw(packageName);
2413 deleteTempPackageFiles();
2415 // Remove any shared userIDs that have no associated packages
2416 mSettings.pruneSharedUsersLPw();
2419 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2420 SystemClock.uptimeMillis());
2421 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2423 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2424 | PackageParser.PARSE_FORWARD_LOCK,
2425 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2427 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2428 | PackageParser.PARSE_IS_EPHEMERAL,
2429 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2432 * Remove disable package settings for any updated system
2433 * apps that were removed via an OTA. If they're not a
2434 * previously-updated app, remove them completely.
2435 * Otherwise, just revoke their system-level permissions.
2437 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2438 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2439 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2442 if (deletedPkg == null) {
2443 msg = "Updated system package " + deletedAppName
2444 + " no longer exists; it's data will be wiped";
2445 // Actual deletion of code and data will be handled by later
2446 // reconciliation step
2448 msg = "Updated system app + " + deletedAppName
2449 + " no longer present; removing system privileges for "
2452 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2454 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2455 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2457 logCriticalInfo(Log.WARN, msg);
2461 * Make sure all system apps that we expected to appear on
2462 * the userdata partition actually showed up. If they never
2463 * appeared, crawl back and revive the system version.
2465 for (int i = 0; i < mExpectingBetter.size(); i++) {
2466 final String packageName = mExpectingBetter.keyAt(i);
2467 if (!mPackages.containsKey(packageName)) {
2468 final File scanFile = mExpectingBetter.valueAt(i);
2470 logCriticalInfo(Log.WARN, "Expected better " + packageName
2471 + " but never showed up; reverting to system");
2473 int reparseFlags = mDefParseFlags;
2474 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2475 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2476 | PackageParser.PARSE_IS_SYSTEM_DIR
2477 | PackageParser.PARSE_IS_PRIVILEGED;
2478 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2479 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2480 | PackageParser.PARSE_IS_SYSTEM_DIR;
2481 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2482 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2483 | PackageParser.PARSE_IS_SYSTEM_DIR;
2484 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2485 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2486 | PackageParser.PARSE_IS_SYSTEM_DIR;
2488 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2492 mSettings.enableSystemPackageLPw(packageName);
2495 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2496 } catch (PackageManagerException e) {
2497 Slog.e(TAG, "Failed to parse original system package: "
2503 mExpectingBetter.clear();
2505 // Resolve the storage manager.
2506 mStorageManagerPackage = getStorageManagerPackageName();
2508 // Resolve protected action filters. Only the setup wizard is allowed to
2509 // have a high priority filter for these actions.
2510 mSetupWizardPackage = getSetupWizardPackageName();
2511 if (mProtectedFilters.size() > 0) {
2512 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2513 Slog.i(TAG, "No setup wizard;"
2514 + " All protected intents capped to priority 0");
2516 for (ActivityIntentInfo filter : mProtectedFilters) {
2517 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2518 if (DEBUG_FILTERS) {
2519 Slog.i(TAG, "Found setup wizard;"
2520 + " allow priority " + filter.getPriority() + ";"
2521 + " package: " + filter.activity.info.packageName
2522 + " activity: " + filter.activity.className
2523 + " priority: " + filter.getPriority());
2525 // skip setup wizard; allow it to keep the high priority filter
2528 Slog.w(TAG, "Protected action; cap priority to 0;"
2529 + " package: " + filter.activity.info.packageName
2530 + " activity: " + filter.activity.className
2531 + " origPrio: " + filter.getPriority());
2532 filter.setPriority(0);
2535 mDeferProtectedFilters = false;
2536 mProtectedFilters.clear();
2538 // Now that we know all of the shared libraries, update all clients to have
2539 // the correct library paths.
2540 updateAllSharedLibrariesLPw();
2542 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2543 // NOTE: We ignore potential failures here during a system scan (like
2544 // the rest of the commands above) because there's precious little we
2545 // can do about it. A settings error is reported, though.
2546 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2547 false /* boot complete */);
2550 // Now that we know all the packages we are keeping,
2551 // read and update their last usage times.
2552 mPackageUsage.read(mPackages);
2553 mCompilerStats.read();
2555 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2556 SystemClock.uptimeMillis());
2557 Slog.i(TAG, "Time to scan packages: "
2558 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2561 // If the platform SDK has changed since the last time we booted,
2562 // we need to re-grant app permission to catch any new ones that
2563 // appear. This is really a hack, and means that apps can in some
2564 // cases get permissions that the user didn't initially explicitly
2565 // allow... it would be nice to have some better way to handle
2567 int updateFlags = UPDATE_PERMISSIONS_ALL;
2568 if (ver.sdkVersion != mSdkVersion) {
2569 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2570 + mSdkVersion + "; regranting permissions for internal storage");
2571 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2573 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2574 ver.sdkVersion = mSdkVersion;
2576 // If this is the first boot or an update from pre-M, and it is a normal
2577 // boot, then we need to initialize the default preferred apps across
2578 // all defined users.
2579 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2580 for (UserInfo user : sUserManager.getUsers(true)) {
2581 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2582 applyFactoryDefaultBrowserLPw(user.id);
2583 primeDomainVerificationsLPw(user.id);
2587 // Prepare storage for system user really early during boot,
2588 // since core system apps like SettingsProvider and SystemUI
2589 // can't wait for user to start
2590 final int storageFlags;
2591 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2592 storageFlags = StorageManager.FLAG_STORAGE_DE;
2594 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2596 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2599 // If this is first boot after an OTA, and a normal boot, then
2600 // we need to clear code cache directories.
2601 // Note that we do *not* clear the application profiles. These remain valid
2602 // across OTAs and are used to drive profile verification (post OTA) and
2603 // profile compilation (without waiting to collect a fresh set of profiles).
2604 if (mIsUpgrade && !onlyCore) {
2605 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2606 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2607 final PackageSetting ps = mSettings.mPackages.valueAt(i);
2608 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2609 // No apps are running this early, so no need to freeze
2610 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2611 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2612 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2615 ver.fingerprint = Build.FINGERPRINT;
2618 checkDefaultBrowser();
2620 // clear only after permissions and other defaults have been updated
2621 mExistingSystemPackages.clear();
2622 mPromoteSystemApps = false;
2624 // All the changes are done during package scanning.
2625 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2627 // can downgrade to reader
2628 mSettings.writeLPr();
2630 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2631 // early on (before the package manager declares itself as early) because other
2632 // components in the system server might ask for package contexts for these apps.
2634 // Note that "onlyCore" in this context means the system is encrypted or encrypting
2635 // (i.e, that the data partition is unavailable).
2636 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2637 long start = System.nanoTime();
2638 List<PackageParser.Package> coreApps = new ArrayList<>();
2639 for (PackageParser.Package pkg : mPackages.values()) {
2645 int[] stats = performDexOptUpgrade(coreApps, false,
2646 getCompilerFilterForReason(REASON_CORE_APP));
2648 final int elapsedTimeSeconds =
2649 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2650 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2653 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2654 stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2658 // TODO: Should we log these stats to tron too ?
2659 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2660 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2661 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2662 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2665 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2666 SystemClock.uptimeMillis());
2669 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2670 mRequiredInstallerPackage = getRequiredInstallerLPr();
2671 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2672 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2673 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2674 mIntentFilterVerifierComponent);
2675 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2676 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2677 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2678 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2680 mRequiredVerifierPackage = null;
2681 mRequiredInstallerPackage = null;
2682 mRequiredUninstallerPackage = null;
2683 mIntentFilterVerifierComponent = null;
2684 mIntentFilterVerifier = null;
2685 mServicesSystemSharedLibraryPackageName = null;
2686 mSharedSystemSharedLibraryPackageName = null;
2689 mInstallerService = new PackageInstallerService(context, this);
2691 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2692 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2693 // both the installer and resolver must be present to enable ephemeral
2694 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2695 if (DEBUG_EPHEMERAL) {
2696 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2697 + " installer:" + ephemeralInstallerComponent);
2699 mEphemeralResolverComponent = ephemeralResolverComponent;
2700 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2701 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2702 mEphemeralResolverConnection =
2703 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2705 if (DEBUG_EPHEMERAL) {
2706 final String missingComponent =
2707 (ephemeralResolverComponent == null)
2708 ? (ephemeralInstallerComponent == null)
2709 ? "resolver and installer"
2712 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2714 mEphemeralResolverComponent = null;
2715 mEphemeralInstallerComponent = null;
2716 mEphemeralResolverConnection = null;
2719 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2720 } // synchronized (mPackages)
2721 } // synchronized (mInstallLock)
2723 // Now after opening every single application zip, make sure they
2724 // are all flushed. Not really needed, but keeps things nice and
2726 Runtime.getRuntime().gc();
2728 // The initial scanning above does many calls into installd while
2729 // holding the mPackages lock, but we're mostly interested in yelling
2730 // once we have a booted system.
2731 mInstaller.setWarnIfHeld(mPackages);
2733 // Expose private service for system components to use.
2734 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2738 public boolean isFirstBoot() {
2743 public boolean isOnlyCoreApps() {
2748 public boolean isUpgrade() {
2752 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2753 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2755 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2756 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2757 UserHandle.USER_SYSTEM);
2758 if (matches.size() == 1) {
2759 return matches.get(0).getComponentInfo().packageName;
2760 } else if (matches.size() == 0) {
2761 Log.e(TAG, "There should probably be a verifier, but, none were found");
2764 throw new RuntimeException("There must be exactly one verifier; found " + matches);
2767 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2768 synchronized (mPackages) {
2769 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2770 if (libraryEntry == null) {
2771 throw new IllegalStateException("Missing required shared library:" + libraryName);
2773 return libraryEntry.apk;
2777 private @NonNull String getRequiredInstallerLPr() {
2778 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2779 intent.addCategory(Intent.CATEGORY_DEFAULT);
2780 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2782 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2783 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2784 UserHandle.USER_SYSTEM);
2785 if (matches.size() == 1) {
2786 ResolveInfo resolveInfo = matches.get(0);
2787 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2788 throw new RuntimeException("The installer must be a privileged app");
2790 return matches.get(0).getComponentInfo().packageName;
2792 throw new RuntimeException("There must be exactly one installer; found " + matches);
2796 private @NonNull String getRequiredUninstallerLPr() {
2797 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2798 intent.addCategory(Intent.CATEGORY_DEFAULT);
2799 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2801 final ResolveInfo resolveInfo = resolveIntent(intent, null,
2802 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2803 UserHandle.USER_SYSTEM);
2804 if (resolveInfo == null ||
2805 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2806 throw new RuntimeException("There must be exactly one uninstaller; found "
2809 return resolveInfo.getComponentInfo().packageName;
2812 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2813 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2815 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2816 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2817 UserHandle.USER_SYSTEM);
2818 ResolveInfo best = null;
2819 final int N = matches.size();
2820 for (int i = 0; i < N; i++) {
2821 final ResolveInfo cur = matches.get(i);
2822 final String packageName = cur.getComponentInfo().packageName;
2823 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2824 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2828 if (best == null || cur.priority > best.priority) {
2834 return best.getComponentInfo().getComponentName();
2836 throw new RuntimeException("There must be at least one intent filter verifier");
2840 private @Nullable ComponentName getEphemeralResolverLPr() {
2841 final String[] packageArray =
2842 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2843 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2844 if (DEBUG_EPHEMERAL) {
2845 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2850 final int resolveFlags =
2851 MATCH_DIRECT_BOOT_AWARE
2852 | MATCH_DIRECT_BOOT_UNAWARE
2853 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2854 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2855 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2856 resolveFlags, UserHandle.USER_SYSTEM);
2858 final int N = resolvers.size();
2860 if (DEBUG_EPHEMERAL) {
2861 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2866 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2867 for (int i = 0; i < N; i++) {
2868 final ResolveInfo info = resolvers.get(i);
2870 if (info.serviceInfo == null) {
2874 final String packageName = info.serviceInfo.packageName;
2875 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2876 if (DEBUG_EPHEMERAL) {
2877 Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2878 + " pkg: " + packageName + ", info:" + info);
2883 if (DEBUG_EPHEMERAL) {
2884 Slog.v(TAG, "Ephemeral resolver found;"
2885 + " pkg: " + packageName + ", info:" + info);
2887 return new ComponentName(packageName, info.serviceInfo.name);
2889 if (DEBUG_EPHEMERAL) {
2890 Slog.v(TAG, "Ephemeral resolver NOT found");
2895 private @Nullable ComponentName getEphemeralInstallerLPr() {
2896 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2897 intent.addCategory(Intent.CATEGORY_DEFAULT);
2898 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2900 final int resolveFlags =
2901 MATCH_DIRECT_BOOT_AWARE
2902 | MATCH_DIRECT_BOOT_UNAWARE
2903 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2904 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2905 resolveFlags, UserHandle.USER_SYSTEM);
2906 if (matches.size() == 0) {
2908 } else if (matches.size() == 1) {
2909 return matches.get(0).getComponentInfo().getComponentName();
2911 throw new RuntimeException(
2912 "There must be at most one ephemeral installer; found " + matches);
2916 private void primeDomainVerificationsLPw(int userId) {
2917 if (DEBUG_DOMAIN_VERIFICATION) {
2918 Slog.d(TAG, "Priming domain verifications in user " + userId);
2921 SystemConfig systemConfig = SystemConfig.getInstance();
2922 ArraySet<String> packages = systemConfig.getLinkedApps();
2923 ArraySet<String> domains = new ArraySet<String>();
2925 for (String packageName : packages) {
2926 PackageParser.Package pkg = mPackages.get(packageName);
2928 if (!pkg.isSystemApp()) {
2929 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2934 for (PackageParser.Activity a : pkg.activities) {
2935 for (ActivityIntentInfo filter : a.intents) {
2936 if (hasValidDomains(filter)) {
2937 domains.addAll(filter.getHostsList());
2942 if (domains.size() > 0) {
2943 if (DEBUG_DOMAIN_VERIFICATION) {
2944 Slog.v(TAG, " + " + packageName);
2946 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2947 // state w.r.t. the formal app-linkage "no verification attempted" state;
2948 // and then 'always' in the per-user state actually used for intent resolution.
2949 final IntentFilterVerificationInfo ivi;
2950 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2951 new ArrayList<String>(domains));
2952 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2953 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2954 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2956 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2957 + "' does not handle web links");
2960 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2964 scheduleWritePackageRestrictionsLocked(userId);
2965 scheduleWriteSettingsLocked();
2968 private void applyFactoryDefaultBrowserLPw(int userId) {
2969 // The default browser app's package name is stored in a string resource,
2970 // with a product-specific overlay used for vendor customization.
2971 String browserPkg = mContext.getResources().getString(
2972 com.android.internal.R.string.default_browser);
2973 if (!TextUtils.isEmpty(browserPkg)) {
2974 // non-empty string => required to be a known package
2975 PackageSetting ps = mSettings.mPackages.get(browserPkg);
2977 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2980 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2984 // Nothing valid explicitly set? Make the factory-installed browser the explicit
2985 // default. If there's more than one, just leave everything alone.
2986 if (browserPkg == null) {
2987 calculateDefaultBrowserLPw(userId);
2991 private void calculateDefaultBrowserLPw(int userId) {
2992 List<String> allBrowsers = resolveAllBrowserApps(userId);
2993 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2994 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2997 private List<String> resolveAllBrowserApps(int userId) {
2998 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2999 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3000 PackageManager.MATCH_ALL, userId);
3002 final int count = list.size();
3003 List<String> result = new ArrayList<String>(count);
3004 for (int i=0; i<count; i++) {
3005 ResolveInfo info = list.get(i);
3006 if (info.activityInfo == null
3007 || !info.handleAllWebDataURI
3008 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3009 || result.contains(info.activityInfo.packageName)) {
3012 result.add(info.activityInfo.packageName);
3018 private boolean packageIsBrowser(String packageName, int userId) {
3019 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3020 PackageManager.MATCH_ALL, userId);
3021 final int N = list.size();
3022 for (int i = 0; i < N; i++) {
3023 ResolveInfo info = list.get(i);
3024 if (packageName.equals(info.activityInfo.packageName)) {
3031 private void checkDefaultBrowser() {
3032 final int myUserId = UserHandle.myUserId();
3033 final String packageName = getDefaultBrowserPackageName(myUserId);
3034 if (packageName != null) {
3035 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3037 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3038 synchronized (mPackages) {
3039 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
3046 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3047 throws RemoteException {
3049 return super.onTransact(code, data, reply, flags);
3050 } catch (RuntimeException e) {
3051 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3052 Slog.wtf(TAG, "Package Manager Crash", e);
3058 static int[] appendInts(int[] cur, int[] add) {
3059 if (add == null) return cur;
3060 if (cur == null) return add;
3061 final int N = add.length;
3062 for (int i=0; i<N; i++) {
3063 cur = appendInt(cur, add[i]);
3068 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3069 if (!sUserManager.exists(userId)) return null;
3073 final PackageParser.Package p = ps.pkg;
3078 final PermissionsState permissionsState = ps.getPermissionsState();
3080 // Compute GIDs only if requested
3081 final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3082 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3083 // Compute granted permissions only if package has requested permissions
3084 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3085 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3086 final PackageUserState state = ps.readUserState(userId);
3088 return PackageParser.generatePackageInfo(p, gids, flags,
3089 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3093 public void checkPackageStartable(String packageName, int userId) {
3094 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3096 synchronized (mPackages) {
3097 final PackageSetting ps = mSettings.mPackages.get(packageName);
3099 throw new SecurityException("Package " + packageName + " was not found!");
3102 if (!ps.getInstalled(userId)) {
3103 throw new SecurityException(
3104 "Package " + packageName + " was not installed for user " + userId + "!");
3107 if (mSafeMode && !ps.isSystem()) {
3108 throw new SecurityException("Package " + packageName + " not a system app!");
3111 if (mFrozenPackages.contains(packageName)) {
3112 throw new SecurityException("Package " + packageName + " is currently frozen!");
3115 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3116 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3117 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3123 public boolean isPackageAvailable(String packageName, int userId) {
3124 if (!sUserManager.exists(userId)) return false;
3125 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3126 false /* requireFullPermission */, false /* checkShell */, "is package available");
3127 synchronized (mPackages) {
3128 PackageParser.Package p = mPackages.get(packageName);
3130 final PackageSetting ps = (PackageSetting) p.mExtras;
3132 final PackageUserState state = ps.readUserState(userId);
3133 if (state != null) {
3134 return PackageParser.isAvailable(state);
3143 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3144 if (!sUserManager.exists(userId)) return null;
3145 flags = updateFlagsForPackage(flags, userId, packageName);
3146 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3147 false /* requireFullPermission */, false /* checkShell */, "get package info");
3150 synchronized (mPackages) {
3151 // Normalize package name to hanlde renamed packages
3152 packageName = normalizePackageNameLPr(packageName);
3154 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3155 PackageParser.Package p = null;
3156 if (matchFactoryOnly) {
3157 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3159 return generatePackageInfo(ps, flags, userId);
3163 p = mPackages.get(packageName);
3164 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3168 if (DEBUG_PACKAGE_INFO)
3169 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3171 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3173 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3174 final PackageSetting ps = mSettings.mPackages.get(packageName);
3175 return generatePackageInfo(ps, flags, userId);
3182 public String[] currentToCanonicalPackageNames(String[] names) {
3183 String[] out = new String[names.length];
3185 synchronized (mPackages) {
3186 for (int i=names.length-1; i>=0; i--) {
3187 PackageSetting ps = mSettings.mPackages.get(names[i]);
3188 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3195 public String[] canonicalToCurrentPackageNames(String[] names) {
3196 String[] out = new String[names.length];
3198 synchronized (mPackages) {
3199 for (int i=names.length-1; i>=0; i--) {
3200 String cur = mSettings.mRenamedPackages.get(names[i]);
3201 out[i] = cur != null ? cur : names[i];
3208 public int getPackageUid(String packageName, int flags, int userId) {
3209 if (!sUserManager.exists(userId)) return -1;
3210 flags = updateFlagsForPackage(flags, userId, packageName);
3211 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3212 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3215 synchronized (mPackages) {
3216 final PackageParser.Package p = mPackages.get(packageName);
3217 if (p != null && p.isMatch(flags)) {
3218 return UserHandle.getUid(userId, p.applicationInfo.uid);
3220 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3221 final PackageSetting ps = mSettings.mPackages.get(packageName);
3222 if (ps != null && ps.isMatch(flags)) {
3223 return UserHandle.getUid(userId, ps.appId);
3232 public int[] getPackageGids(String packageName, int flags, int userId) {
3233 if (!sUserManager.exists(userId)) return null;
3234 flags = updateFlagsForPackage(flags, userId, packageName);
3235 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3236 false /* requireFullPermission */, false /* checkShell */,
3240 synchronized (mPackages) {
3241 final PackageParser.Package p = mPackages.get(packageName);
3242 if (p != null && p.isMatch(flags)) {
3243 PackageSetting ps = (PackageSetting) p.mExtras;
3244 return ps.getPermissionsState().computeGids(userId);
3246 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3247 final PackageSetting ps = mSettings.mPackages.get(packageName);
3248 if (ps != null && ps.isMatch(flags)) {
3249 return ps.getPermissionsState().computeGids(userId);
3257 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3258 if (bp.perm != null) {
3259 return PackageParser.generatePermissionInfo(bp.perm, flags);
3261 PermissionInfo pi = new PermissionInfo();
3263 pi.packageName = bp.sourcePackage;
3264 pi.nonLocalizedLabel = bp.name;
3265 pi.protectionLevel = bp.protectionLevel;
3270 public PermissionInfo getPermissionInfo(String name, int flags) {
3272 synchronized (mPackages) {
3273 final BasePermission p = mSettings.mPermissions.get(name);
3275 return generatePermissionInfo(p, flags);
3282 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3285 synchronized (mPackages) {
3286 if (group != null && !mPermissionGroups.containsKey(group)) {
3287 // This is thrown as NameNotFoundException
3291 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3292 for (BasePermission p : mSettings.mPermissions.values()) {
3293 if (group == null) {
3294 if (p.perm == null || p.perm.info.group == null) {
3295 out.add(generatePermissionInfo(p, flags));
3298 if (p.perm != null && group.equals(p.perm.info.group)) {
3299 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3303 return new ParceledListSlice<>(out);
3308 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3310 synchronized (mPackages) {
3311 return PackageParser.generatePermissionGroupInfo(
3312 mPermissionGroups.get(name), flags);
3317 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3319 synchronized (mPackages) {
3320 final int N = mPermissionGroups.size();
3321 ArrayList<PermissionGroupInfo> out
3322 = new ArrayList<PermissionGroupInfo>(N);
3323 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3324 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3326 return new ParceledListSlice<>(out);
3330 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3332 if (!sUserManager.exists(userId)) return null;
3333 PackageSetting ps = mSettings.mPackages.get(packageName);
3335 if (ps.pkg == null) {
3336 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3337 if (pInfo != null) {
3338 return pInfo.applicationInfo;
3342 return PackageParser.generateApplicationInfo(ps.pkg, flags,
3343 ps.readUserState(userId), userId);
3349 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3350 if (!sUserManager.exists(userId)) return null;
3351 flags = updateFlagsForApplication(flags, userId, packageName);
3352 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3353 false /* requireFullPermission */, false /* checkShell */, "get application info");
3356 synchronized (mPackages) {
3357 // Normalize package name to hanlde renamed packages
3358 packageName = normalizePackageNameLPr(packageName);
3360 PackageParser.Package p = mPackages.get(packageName);
3361 if (DEBUG_PACKAGE_INFO) Log.v(
3362 TAG, "getApplicationInfo " + packageName
3365 PackageSetting ps = mSettings.mPackages.get(packageName);
3366 if (ps == null) return null;
3367 // Note: isEnabledLP() does not apply here - always return info
3368 return PackageParser.generateApplicationInfo(
3369 p, flags, ps.readUserState(userId), userId);
3371 if ("android".equals(packageName)||"system".equals(packageName)) {
3372 return mAndroidApplication;
3374 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3375 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3381 private String normalizePackageNameLPr(String packageName) {
3382 String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3383 return normalizedPackageName != null ? normalizedPackageName : packageName;
3387 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3388 final IPackageDataObserver observer) {
3389 mContext.enforceCallingOrSelfPermission(
3390 android.Manifest.permission.CLEAR_APP_CACHE, null);
3391 // Queue up an async operation since clearing cache may take a little while.
3392 mHandler.post(new Runnable() {
3394 mHandler.removeCallbacks(this);
3395 boolean success = true;
3396 synchronized (mInstallLock) {
3398 mInstaller.freeCache(volumeUuid, freeStorageSize);
3399 } catch (InstallerException e) {
3400 Slog.w(TAG, "Couldn't clear application caches: " + e);
3404 if (observer != null) {
3406 observer.onRemoveCompleted(null, success);
3407 } catch (RemoteException e) {
3408 Slog.w(TAG, "RemoveException when invoking call back");
3416 public void freeStorage(final String volumeUuid, final long freeStorageSize,
3417 final IntentSender pi) {
3418 mContext.enforceCallingOrSelfPermission(
3419 android.Manifest.permission.CLEAR_APP_CACHE, null);
3420 // Queue up an async operation since clearing cache may take a little while.
3421 mHandler.post(new Runnable() {
3423 mHandler.removeCallbacks(this);
3424 boolean success = true;
3425 synchronized (mInstallLock) {
3427 mInstaller.freeCache(volumeUuid, freeStorageSize);
3428 } catch (InstallerException e) {
3429 Slog.w(TAG, "Couldn't clear application caches: " + e);
3435 // Callback via pending intent
3436 int code = success ? 1 : 0;
3437 pi.sendIntent(null, code, null,
3439 } catch (SendIntentException e1) {
3440 Slog.i(TAG, "Failed to send pending intent");
3447 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3448 synchronized (mInstallLock) {
3450 mInstaller.freeCache(volumeUuid, freeStorageSize);
3451 } catch (InstallerException e) {
3452 throw new IOException("Failed to free enough space", e);
3458 * Update given flags based on encryption status of current user.
3460 private int updateFlags(int flags, int userId) {
3461 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3462 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3463 // Caller expressed an explicit opinion about what encryption
3464 // aware/unaware components they want to see, so fall through and
3465 // give them what they want
3467 // Caller expressed no opinion, so match based on user state
3468 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3469 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3471 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3477 private UserManagerInternal getUserManagerInternal() {
3478 if (mUserManagerInternal == null) {
3479 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3481 return mUserManagerInternal;
3485 * Update given flags when being used to request {@link PackageInfo}.
3487 private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3488 boolean triaged = true;
3489 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3490 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3491 // Caller is asking for component details, so they'd better be
3492 // asking for specific encryption matching behavior, or be triaged
3493 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3494 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3495 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3499 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3500 | PackageManager.MATCH_SYSTEM_ONLY
3501 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3504 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3505 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3506 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3508 return updateFlags(flags, userId);
3512 * Update given flags when being used to request {@link ApplicationInfo}.
3514 private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3515 return updateFlagsForPackage(flags, userId, cookie);
3519 * Update given flags when being used to request {@link ComponentInfo}.
3521 private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3522 if (cookie instanceof Intent) {
3523 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3524 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3528 boolean triaged = true;
3529 // Caller is asking for component details, so they'd better be
3530 // asking for specific encryption matching behavior, or be triaged
3531 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3532 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3533 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3536 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3537 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3538 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3541 return updateFlags(flags, userId);
3545 * Update given flags when being used to request {@link ResolveInfo}.
3547 int updateFlagsForResolve(int flags, int userId, Object cookie) {
3548 // Safe mode means we shouldn't match any third-party components
3550 flags |= PackageManager.MATCH_SYSTEM_ONLY;
3553 return updateFlagsForComponent(flags, userId, cookie);
3557 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3558 if (!sUserManager.exists(userId)) return null;
3559 flags = updateFlagsForComponent(flags, userId, component);
3560 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3561 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3562 synchronized (mPackages) {
3563 PackageParser.Activity a = mActivities.mActivities.get(component);
3565 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3566 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3567 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3568 if (ps == null) return null;
3569 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3572 if (mResolveComponentName.equals(component)) {
3573 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3574 new PackageUserState(), userId);
3581 public boolean activitySupportsIntent(ComponentName component, Intent intent,
3582 String resolvedType) {
3583 synchronized (mPackages) {
3584 if (component.equals(mResolveComponentName)) {
3585 // The resolver supports EVERYTHING!
3588 PackageParser.Activity a = mActivities.mActivities.get(component);
3592 for (int i=0; i<a.intents.size(); i++) {
3593 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3594 intent.getData(), intent.getCategories(), TAG) >= 0) {
3603 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3604 if (!sUserManager.exists(userId)) return null;
3605 flags = updateFlagsForComponent(flags, userId, component);
3606 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3607 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3608 synchronized (mPackages) {
3609 PackageParser.Activity a = mReceivers.mActivities.get(component);
3610 if (DEBUG_PACKAGE_INFO) Log.v(
3611 TAG, "getReceiverInfo " + component + ": " + a);
3612 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3613 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3614 if (ps == null) return null;
3615 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3623 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3624 if (!sUserManager.exists(userId)) return null;
3625 flags = updateFlagsForComponent(flags, userId, component);
3626 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3627 false /* requireFullPermission */, false /* checkShell */, "get service info");
3628 synchronized (mPackages) {
3629 PackageParser.Service s = mServices.mServices.get(component);
3630 if (DEBUG_PACKAGE_INFO) Log.v(
3631 TAG, "getServiceInfo " + component + ": " + s);
3632 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3633 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3634 if (ps == null) return null;
3635 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3643 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3644 if (!sUserManager.exists(userId)) return null;
3645 flags = updateFlagsForComponent(flags, userId, component);
3646 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3647 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3648 synchronized (mPackages) {
3649 PackageParser.Provider p = mProviders.mProviders.get(component);
3650 if (DEBUG_PACKAGE_INFO) Log.v(
3651 TAG, "getProviderInfo " + component + ": " + p);
3652 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3653 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3654 if (ps == null) return null;
3655 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3663 public String[] getSystemSharedLibraryNames() {
3665 synchronized (mPackages) {
3666 libSet = mSharedLibraries.keySet();
3667 int size = libSet.size();
3669 String[] libs = new String[size];
3670 libSet.toArray(libs);
3678 public @NonNull String getServicesSystemSharedLibraryPackageName() {
3679 synchronized (mPackages) {
3680 return mServicesSystemSharedLibraryPackageName;
3685 public @NonNull String getSharedSystemSharedLibraryPackageName() {
3686 synchronized (mPackages) {
3687 return mSharedSystemSharedLibraryPackageName;
3692 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3693 synchronized (mPackages) {
3694 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3696 final FeatureInfo fi = new FeatureInfo();
3697 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3698 FeatureInfo.GL_ES_VERSION_UNDEFINED);
3701 return new ParceledListSlice<>(res);
3706 public boolean hasSystemFeature(String name, int version) {
3707 synchronized (mPackages) {
3708 final FeatureInfo feat = mAvailableFeatures.get(name);
3712 return feat.version >= version;
3718 public int checkPermission(String permName, String pkgName, int userId) {
3719 if (!sUserManager.exists(userId)) {
3720 return PackageManager.PERMISSION_DENIED;
3723 synchronized (mPackages) {
3724 final PackageParser.Package p = mPackages.get(pkgName);
3725 if (p != null && p.mExtras != null) {
3726 final PackageSetting ps = (PackageSetting) p.mExtras;
3727 final PermissionsState permissionsState = ps.getPermissionsState();
3728 if (permissionsState.hasPermission(permName, userId)) {
3729 return PackageManager.PERMISSION_GRANTED;
3731 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3732 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3733 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3734 return PackageManager.PERMISSION_GRANTED;
3739 return PackageManager.PERMISSION_DENIED;
3743 public int checkUidPermission(String permName, int uid) {
3744 final int userId = UserHandle.getUserId(uid);
3746 if (!sUserManager.exists(userId)) {
3747 return PackageManager.PERMISSION_DENIED;
3750 synchronized (mPackages) {
3751 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3753 final SettingBase ps = (SettingBase) obj;
3754 final PermissionsState permissionsState = ps.getPermissionsState();
3755 if (permissionsState.hasPermission(permName, userId)) {
3756 return PackageManager.PERMISSION_GRANTED;
3758 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3759 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3760 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3761 return PackageManager.PERMISSION_GRANTED;
3764 ArraySet<String> perms = mSystemPermissions.get(uid);
3765 if (perms != null) {
3766 if (perms.contains(permName)) {
3767 return PackageManager.PERMISSION_GRANTED;
3769 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3770 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3771 return PackageManager.PERMISSION_GRANTED;
3777 return PackageManager.PERMISSION_DENIED;
3781 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3782 if (UserHandle.getCallingUserId() != userId) {
3783 mContext.enforceCallingPermission(
3784 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3785 "isPermissionRevokedByPolicy for user " + userId);
3788 if (checkPermission(permission, packageName, userId)
3789 == PackageManager.PERMISSION_GRANTED) {
3793 final long identity = Binder.clearCallingIdentity();
3795 final int flags = getPermissionFlags(permission, packageName, userId);
3796 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3798 Binder.restoreCallingIdentity(identity);
3803 public String getPermissionControllerPackageName() {
3804 synchronized (mPackages) {
3805 return mRequiredInstallerPackage;
3810 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3811 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3812 * @param checkShell whether to prevent shell from access if there's a debugging restriction
3813 * @param message the message to log on security exception
3815 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3816 boolean checkShell, String message) {
3817 enforceCrossUserPermission(
3820 requireFullPermission,
3826 private void enforceCrossUserPermission(int callingUid, int userId,
3827 boolean requireFullPermission, boolean checkShell,
3828 boolean requirePermissionWhenSameUser, String message) {
3830 throw new IllegalArgumentException("Invalid userId " + userId);
3833 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3835 if (!requirePermissionWhenSameUser && userId == UserHandle.getUserId(callingUid)) return;
3836 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3837 if (requireFullPermission) {
3838 mContext.enforceCallingOrSelfPermission(
3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3842 mContext.enforceCallingOrSelfPermission(
3843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3844 } catch (SecurityException se) {
3845 mContext.enforceCallingOrSelfPermission(
3846 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3852 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3853 if (callingUid == Process.SHELL_UID) {
3855 && sUserManager.hasUserRestriction(restriction, userHandle)) {
3856 throw new SecurityException("Shell does not have permission to access user "
3858 } else if (userHandle < 0) {
3859 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3860 + Debug.getCallers(3));
3865 private BasePermission findPermissionTreeLP(String permName) {
3866 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3867 if (permName.startsWith(bp.name) &&
3868 permName.length() > bp.name.length() &&
3869 permName.charAt(bp.name.length()) == '.') {
3876 private BasePermission checkPermissionTreeLP(String permName) {
3877 if (permName != null) {
3878 BasePermission bp = findPermissionTreeLP(permName);
3880 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3883 throw new SecurityException("Calling uid "
3884 + Binder.getCallingUid()
3885 + " is not allowed to add to permission tree "
3886 + bp.name + " owned by uid " + bp.uid);
3889 throw new SecurityException("No permission tree found for " + permName);
3892 static boolean compareStrings(CharSequence s1, CharSequence s2) {
3899 if (s1.getClass() != s2.getClass()) {
3902 return s1.equals(s2);
3905 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3906 if (pi1.icon != pi2.icon) return false;
3907 if (pi1.logo != pi2.logo) return false;
3908 if (pi1.protectionLevel != pi2.protectionLevel) return false;
3909 if (!compareStrings(pi1.name, pi2.name)) return false;
3910 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3911 // We'll take care of setting this one.
3912 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3913 // These are not currently stored in settings.
3914 //if (!compareStrings(pi1.group, pi2.group)) return false;
3915 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3916 //if (pi1.labelRes != pi2.labelRes) return false;
3917 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3921 int permissionInfoFootprint(PermissionInfo info) {
3922 int size = info.name.length();
3923 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3924 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3928 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3930 for (BasePermission perm : mSettings.mPermissions.values()) {
3931 if (perm.uid == tree.uid) {
3932 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3938 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3939 // We calculate the max size of permissions defined by this uid and throw
3940 // if that plus the size of 'info' would exceed our stated maximum.
3941 if (tree.uid != Process.SYSTEM_UID) {
3942 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3943 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3944 throw new SecurityException("Permission tree size cap exceeded");
3949 boolean addPermissionLocked(PermissionInfo info, boolean async) {
3950 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3951 throw new SecurityException("Label must be specified in permission");
3953 BasePermission tree = checkPermissionTreeLP(info.name);
3954 BasePermission bp = mSettings.mPermissions.get(info.name);
3955 boolean added = bp == null;
3956 boolean changed = true;
3957 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3959 enforcePermissionCapLocked(info, tree);
3960 bp = new BasePermission(info.name, tree.sourcePackage,
3961 BasePermission.TYPE_DYNAMIC);
3962 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3963 throw new SecurityException(
3964 "Not allowed to modify non-dynamic permission "
3967 if ((bp.perm == null) || (tree.perm == null)) {
3968 Slog.w(TAG, "Base or tree permission is null: " + bp.perm + ", " + tree.perm);
3971 if (bp.protectionLevel == fixedLevel
3972 && bp.perm.owner.equals(tree.perm.owner)
3973 && bp.uid == tree.uid
3974 && comparePermissionInfos(bp.perm.info, info)) {
3978 bp.protectionLevel = fixedLevel;
3979 info = new PermissionInfo(info);
3980 info.protectionLevel = fixedLevel;
3981 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3982 bp.perm.info.packageName = tree.perm.info.packageName;
3985 mSettings.mPermissions.put(info.name, bp);
3989 mSettings.writeLPr();
3991 scheduleWriteSettingsLocked();
3998 public boolean addPermission(PermissionInfo info) {
3999 synchronized (mPackages) {
4000 return addPermissionLocked(info, false);
4005 public boolean addPermissionAsync(PermissionInfo info) {
4006 synchronized (mPackages) {
4007 return addPermissionLocked(info, true);
4012 public void removePermission(String name) {
4013 synchronized (mPackages) {
4014 checkPermissionTreeLP(name);
4015 BasePermission bp = mSettings.mPermissions.get(name);
4017 if (bp.type != BasePermission.TYPE_DYNAMIC) {
4018 throw new SecurityException(
4019 "Not allowed to modify non-dynamic permission "
4022 mSettings.mPermissions.remove(name);
4023 mSettings.writeLPr();
4028 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4029 BasePermission bp) {
4030 int index = pkg.requestedPermissions.indexOf(bp.name);
4032 throw new SecurityException("Package " + pkg.packageName
4033 + " has not requested permission " + bp.name);
4035 if (!bp.isRuntime() && !bp.isDevelopment()) {
4036 throw new SecurityException("Permission " + bp.name
4037 + " is not a changeable permission type");
4042 public void grantRuntimePermission(String packageName, String name, final int userId) {
4043 if (!sUserManager.exists(userId)) {
4044 Log.e(TAG, "No such user:" + userId);
4048 mContext.enforceCallingOrSelfPermission(
4049 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4050 "grantRuntimePermission");
4052 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4053 true /* requireFullPermission */, true /* checkShell */,
4054 "grantRuntimePermission");
4057 final SettingBase sb;
4059 synchronized (mPackages) {
4060 final PackageParser.Package pkg = mPackages.get(packageName);
4062 throw new IllegalArgumentException("Unknown package: " + packageName);
4065 final BasePermission bp = mSettings.mPermissions.get(name);
4067 throw new IllegalArgumentException("Unknown permission: " + name);
4070 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4072 // If a permission review is required for legacy apps we represent
4073 // their permissions as always granted runtime ones since we need
4074 // to keep the review required permission flag per user while an
4075 // install permission's state is shared across all users.
4076 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4077 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4078 && bp.isRuntime()) {
4082 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4083 sb = (SettingBase) pkg.mExtras;
4085 throw new IllegalArgumentException("Unknown package: " + packageName);
4088 final PermissionsState permissionsState = sb.getPermissionsState();
4090 final int flags = permissionsState.getPermissionFlags(name, userId);
4091 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4092 throw new SecurityException("Cannot grant system fixed permission "
4093 + name + " for package " + packageName);
4096 if (bp.isDevelopment()) {
4097 // Development permissions must be handled specially, since they are not
4098 // normal runtime permissions. For now they apply to all users.
4099 if (permissionsState.grantInstallPermission(bp) !=
4100 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4101 scheduleWriteSettingsLocked();
4106 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4107 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4111 final int result = permissionsState.grantRuntimePermission(bp, userId);
4113 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4117 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4118 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4119 mHandler.post(new Runnable() {
4122 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4129 mOnPermissionChangeListeners.onPermissionsChanged(uid);
4131 // Not critical if that is lost - app has to request again.
4132 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4135 // Only need to do this if user is initialized. Otherwise it's a new user
4136 // and there are no processes running as the user yet and there's no need
4137 // to make an expensive call to remount processes for the changed permissions.
4138 if (READ_EXTERNAL_STORAGE.equals(name)
4139 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4140 final long token = Binder.clearCallingIdentity();
4142 if (sUserManager.isInitialized(userId)) {
4143 MountServiceInternal mountServiceInternal = LocalServices.getService(
4144 MountServiceInternal.class);
4145 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4148 Binder.restoreCallingIdentity(token);
4154 public void revokeRuntimePermission(String packageName, String name, int userId) {
4155 if (!sUserManager.exists(userId)) {
4156 Log.e(TAG, "No such user:" + userId);
4160 mContext.enforceCallingOrSelfPermission(
4161 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4162 "revokeRuntimePermission");
4164 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4165 true /* requireFullPermission */, true /* checkShell */,
4166 "revokeRuntimePermission");
4170 synchronized (mPackages) {
4171 final PackageParser.Package pkg = mPackages.get(packageName);
4173 throw new IllegalArgumentException("Unknown package: " + packageName);
4176 final BasePermission bp = mSettings.mPermissions.get(name);
4178 throw new IllegalArgumentException("Unknown permission: " + name);
4181 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4183 // If a permission review is required for legacy apps we represent
4184 // their permissions as always granted runtime ones since we need
4185 // to keep the review required permission flag per user while an
4186 // install permission's state is shared across all users.
4187 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4188 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4189 && bp.isRuntime()) {
4193 SettingBase sb = (SettingBase) pkg.mExtras;
4195 throw new IllegalArgumentException("Unknown package: " + packageName);
4198 final PermissionsState permissionsState = sb.getPermissionsState();
4200 final int flags = permissionsState.getPermissionFlags(name, userId);
4201 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4202 throw new SecurityException("Cannot revoke system fixed permission "
4203 + name + " for package " + packageName);
4206 if (bp.isDevelopment()) {
4207 // Development permissions must be handled specially, since they are not
4208 // normal runtime permissions. For now they apply to all users.
4209 if (permissionsState.revokeInstallPermission(bp) !=
4210 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4211 scheduleWriteSettingsLocked();
4216 if (permissionsState.revokeRuntimePermission(bp, userId) ==
4217 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4221 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4223 // Critical, after this call app should never have the permission.
4224 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4226 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4229 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4233 * We might auto-grant permissions if any permission of the group is already granted. Hence if
4234 * the group of a granted permission changes we need to revoke it to avoid having permissions of
4235 * the new group auto-granted.
4237 * @param newPackage The new package that was installed
4238 * @param oldPackage The old package that was updated
4239 * @param allPackageNames All package names
4241 private void revokeRuntimePermissionsIfGroupChanged(
4242 PackageParser.Package newPackage,
4243 PackageParser.Package oldPackage,
4244 ArrayList<String> allPackageNames) {
4245 final int numOldPackagePermissions = oldPackage.permissions.size();
4246 final ArrayMap<String, String> oldPermissionNameToGroupName
4247 = new ArrayMap<>(numOldPackagePermissions);
4249 for (int i = 0; i < numOldPackagePermissions; i++) {
4250 final PackageParser.Permission permission = oldPackage.permissions.get(i);
4252 if (permission.group != null) {
4253 oldPermissionNameToGroupName.put(permission.info.name,
4254 permission.group.info.name);
4258 final int numNewPackagePermissions = newPackage.permissions.size();
4259 for (int newPermissionNum = 0; newPermissionNum < numNewPackagePermissions;
4260 newPermissionNum++) {
4261 final PackageParser.Permission newPermission =
4262 newPackage.permissions.get(newPermissionNum);
4263 final int newProtection = newPermission.info.protectionLevel;
4265 if ((newProtection & PermissionInfo.PROTECTION_DANGEROUS) != 0) {
4266 final String permissionName = newPermission.info.name;
4267 final String newPermissionGroupName =
4268 newPermission.group == null ? null : newPermission.group.info.name;
4269 final String oldPermissionGroupName = oldPermissionNameToGroupName.get(
4272 if (newPermissionGroupName != null
4273 && !newPermissionGroupName.equals(oldPermissionGroupName)) {
4274 final List<UserInfo> users = mContext.getSystemService(UserManager.class)
4277 final int numUsers = users.size();
4278 for (int userNum = 0; userNum < numUsers; userNum++) {
4279 final int userId = users.get(userNum).id;
4280 final int numPackages = allPackageNames.size();
4281 for (int packageNum = 0; packageNum < numPackages; packageNum++) {
4282 final String packageName = allPackageNames.get(packageNum);
4284 if (checkPermission(permissionName, packageName, userId)
4285 == PackageManager.PERMISSION_GRANTED) {
4286 EventLog.writeEvent(0x534e4554, "72710897",
4287 newPackage.applicationInfo.uid,
4288 "Revoking permission", permissionName, "from package",
4289 packageName, "as the group changed from",
4290 oldPermissionGroupName, "to", newPermissionGroupName);
4293 revokeRuntimePermission(packageName, permissionName, userId);
4294 } catch (IllegalArgumentException e) {
4295 Slog.e(TAG, "Could not revoke " + permissionName + " from "
4308 public void resetRuntimePermissions() {
4309 mContext.enforceCallingOrSelfPermission(
4310 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4311 "revokeRuntimePermission");
4313 int callingUid = Binder.getCallingUid();
4314 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4315 mContext.enforceCallingOrSelfPermission(
4316 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4317 "resetRuntimePermissions");
4320 synchronized (mPackages) {
4321 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4322 for (int userId : UserManagerService.getInstance().getUserIds()) {
4323 final int packageCount = mPackages.size();
4324 for (int i = 0; i < packageCount; i++) {
4325 PackageParser.Package pkg = mPackages.valueAt(i);
4326 if (!(pkg.mExtras instanceof PackageSetting)) {
4329 PackageSetting ps = (PackageSetting) pkg.mExtras;
4330 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4337 public int getPermissionFlags(String name, String packageName, int userId) {
4338 if (!sUserManager.exists(userId)) {
4342 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4344 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4345 true /* requireFullPermission */, false /* checkShell */,
4346 "getPermissionFlags");
4348 synchronized (mPackages) {
4349 final PackageParser.Package pkg = mPackages.get(packageName);
4354 final BasePermission bp = mSettings.mPermissions.get(name);
4359 SettingBase sb = (SettingBase) pkg.mExtras;
4364 PermissionsState permissionsState = sb.getPermissionsState();
4365 return permissionsState.getPermissionFlags(name, userId);
4370 public void updatePermissionFlags(String name, String packageName, int flagMask,
4371 int flagValues, int userId) {
4372 if (!sUserManager.exists(userId)) {
4376 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4378 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4379 true /* requireFullPermission */, true /* checkShell */,
4380 "updatePermissionFlags");
4382 // Only the system can change these flags and nothing else.
4383 if (getCallingUid() != Process.SYSTEM_UID) {
4384 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4385 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4386 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4387 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4388 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4391 synchronized (mPackages) {
4392 final PackageParser.Package pkg = mPackages.get(packageName);
4394 throw new IllegalArgumentException("Unknown package: " + packageName);
4397 final BasePermission bp = mSettings.mPermissions.get(name);
4399 throw new IllegalArgumentException("Unknown permission: " + name);
4402 SettingBase sb = (SettingBase) pkg.mExtras;
4404 throw new IllegalArgumentException("Unknown package: " + packageName);
4407 PermissionsState permissionsState = sb.getPermissionsState();
4409 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4411 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4412 // Install and runtime permissions are stored in different places,
4413 // so figure out what permission changed and persist the change.
4414 if (permissionsState.getInstallPermissionState(name) != null) {
4415 scheduleWriteSettingsLocked();
4416 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4418 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4425 * Update the permission flags for all packages and runtime permissions of a user in order
4426 * to allow device or profile owner to remove POLICY_FIXED.
4429 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4430 if (!sUserManager.exists(userId)) {
4434 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4436 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4437 true /* requireFullPermission */, true /* checkShell */,
4438 "updatePermissionFlagsForAllApps");
4440 // Only the system can change system fixed flags.
4441 if (getCallingUid() != Process.SYSTEM_UID) {
4442 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4443 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4446 synchronized (mPackages) {
4447 boolean changed = false;
4448 final int packageCount = mPackages.size();
4449 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4450 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4451 SettingBase sb = (SettingBase) pkg.mExtras;
4455 PermissionsState permissionsState = sb.getPermissionsState();
4456 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4457 userId, flagMask, flagValues);
4460 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4465 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4466 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4467 != PackageManager.PERMISSION_GRANTED
4468 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4469 != PackageManager.PERMISSION_GRANTED) {
4470 throw new SecurityException(message + " requires "
4471 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4472 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4477 public boolean shouldShowRequestPermissionRationale(String permissionName,
4478 String packageName, int userId) {
4479 if (UserHandle.getCallingUserId() != userId) {
4480 mContext.enforceCallingPermission(
4481 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4482 "canShowRequestPermissionRationale for user " + userId);
4485 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4486 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4490 if (checkPermission(permissionName, packageName, userId)
4491 == PackageManager.PERMISSION_GRANTED) {
4497 final long identity = Binder.clearCallingIdentity();
4499 flags = getPermissionFlags(permissionName,
4500 packageName, userId);
4502 Binder.restoreCallingIdentity(identity);
4505 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4506 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4507 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4509 if ((flags & fixedFlags) != 0) {
4513 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4517 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4518 mContext.enforceCallingOrSelfPermission(
4519 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4520 "addOnPermissionsChangeListener");
4522 synchronized (mPackages) {
4523 mOnPermissionChangeListeners.addListenerLocked(listener);
4528 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4529 synchronized (mPackages) {
4530 mOnPermissionChangeListeners.removeListenerLocked(listener);
4535 public boolean isProtectedBroadcast(String actionName) {
4536 synchronized (mPackages) {
4537 if (mProtectedBroadcasts.contains(actionName)) {
4539 } else if (actionName != null) {
4540 // TODO: remove these terrible hacks
4541 if (actionName.startsWith("android.net.netmon.lingerExpired")
4542 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4543 || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4544 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4553 public int checkSignatures(String pkg1, String pkg2) {
4554 synchronized (mPackages) {
4555 final PackageParser.Package p1 = mPackages.get(pkg1);
4556 final PackageParser.Package p2 = mPackages.get(pkg2);
4557 if (p1 == null || p1.mExtras == null
4558 || p2 == null || p2.mExtras == null) {
4559 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4561 return compareSignatures(p1.mSignatures, p2.mSignatures);
4566 public int checkUidSignatures(int uid1, int uid2) {
4567 // Map to base uids.
4568 uid1 = UserHandle.getAppId(uid1);
4569 uid2 = UserHandle.getAppId(uid2);
4571 synchronized (mPackages) {
4574 Object obj = mSettings.getUserIdLPr(uid1);
4576 if (obj instanceof SharedUserSetting) {
4577 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4578 } else if (obj instanceof PackageSetting) {
4579 s1 = ((PackageSetting)obj).signatures.mSignatures;
4581 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4584 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4586 obj = mSettings.getUserIdLPr(uid2);
4588 if (obj instanceof SharedUserSetting) {
4589 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4590 } else if (obj instanceof PackageSetting) {
4591 s2 = ((PackageSetting)obj).signatures.mSignatures;
4593 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4596 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4598 return compareSignatures(s1, s2);
4603 * This method should typically only be used when granting or revoking
4604 * permissions, since the app may immediately restart after this call.
4606 * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4607 * guard your work against the app being relaunched.
4609 private void killUid(int appId, int userId, String reason) {
4610 final long identity = Binder.clearCallingIdentity();
4612 IActivityManager am = ActivityManagerNative.getDefault();
4615 am.killUid(appId, userId, reason);
4616 } catch (RemoteException e) {
4617 /* ignore - same process */
4621 Binder.restoreCallingIdentity(identity);
4626 * Compares two sets of signatures. Returns:
4628 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4630 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4632 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4634 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4636 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4638 static int compareSignatures(Signature[] s1, Signature[] s2) {
4641 ? PackageManager.SIGNATURE_NEITHER_SIGNED
4642 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4646 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4649 if (s1.length != s2.length) {
4650 return PackageManager.SIGNATURE_NO_MATCH;
4653 // Since both signature sets are of size 1, we can compare without HashSets.
4654 if (s1.length == 1) {
4655 return s1[0].equals(s2[0]) ?
4656 PackageManager.SIGNATURE_MATCH :
4657 PackageManager.SIGNATURE_NO_MATCH;
4660 ArraySet<Signature> set1 = new ArraySet<Signature>();
4661 for (Signature sig : s1) {
4664 ArraySet<Signature> set2 = new ArraySet<Signature>();
4665 for (Signature sig : s2) {
4668 // Make sure s2 contains all signatures in s1.
4669 if (set1.equals(set2)) {
4670 return PackageManager.SIGNATURE_MATCH;
4672 return PackageManager.SIGNATURE_NO_MATCH;
4676 * If the database version for this type of package (internal storage or
4677 * external storage) is less than the version where package signatures
4678 * were updated, return true.
4680 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4681 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4682 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4686 * Used for backward compatibility to make sure any packages with
4687 * certificate chains get upgraded to the new style. {@code existingSigs}
4688 * will be in the old format (since they were stored on disk from before the
4689 * system upgrade) and {@code scannedSigs} will be in the newer format.
4691 private int compareSignaturesCompat(PackageSignatures existingSigs,
4692 PackageParser.Package scannedPkg) {
4693 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4694 return PackageManager.SIGNATURE_NO_MATCH;
4697 ArraySet<Signature> existingSet = new ArraySet<Signature>();
4698 for (Signature sig : existingSigs.mSignatures) {
4699 existingSet.add(sig);
4701 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4702 for (Signature sig : scannedPkg.mSignatures) {
4704 Signature[] chainSignatures = sig.getChainSignatures();
4705 for (Signature chainSig : chainSignatures) {
4706 scannedCompatSet.add(chainSig);
4708 } catch (CertificateEncodingException e) {
4709 scannedCompatSet.add(sig);
4713 * Make sure the expanded scanned set contains all signatures in the
4716 if (scannedCompatSet.equals(existingSet)) {
4717 // Migrate the old signatures to the new scheme.
4718 existingSigs.assignSignatures(scannedPkg.mSignatures);
4719 // The new KeySets will be re-added later in the scanning process.
4720 synchronized (mPackages) {
4721 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4723 return PackageManager.SIGNATURE_MATCH;
4725 return PackageManager.SIGNATURE_NO_MATCH;
4728 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4729 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4730 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4733 private int compareSignaturesRecover(PackageSignatures existingSigs,
4734 PackageParser.Package scannedPkg) {
4735 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4736 return PackageManager.SIGNATURE_NO_MATCH;
4741 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4742 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4743 + scannedPkg.packageName);
4744 return PackageManager.SIGNATURE_MATCH;
4746 } catch (CertificateException e) {
4747 msg = e.getMessage();
4750 logCriticalInfo(Log.INFO,
4751 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4752 return PackageManager.SIGNATURE_NO_MATCH;
4756 public List<String> getAllPackages() {
4757 synchronized (mPackages) {
4758 return new ArrayList<String>(mPackages.keySet());
4763 public String[] getPackagesForUid(int uid) {
4764 uid = UserHandle.getAppId(uid);
4766 synchronized (mPackages) {
4767 Object obj = mSettings.getUserIdLPr(uid);
4768 if (obj instanceof SharedUserSetting) {
4769 final SharedUserSetting sus = (SharedUserSetting) obj;
4770 final int N = sus.packages.size();
4771 final String[] res = new String[N];
4772 for (int i = 0; i < N; i++) {
4773 res[i] = sus.packages.valueAt(i).name;
4776 } else if (obj instanceof PackageSetting) {
4777 final PackageSetting ps = (PackageSetting) obj;
4778 return new String[] { ps.name };
4785 public String getNameForUid(int uid) {
4787 synchronized (mPackages) {
4788 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4789 if (obj instanceof SharedUserSetting) {
4790 final SharedUserSetting sus = (SharedUserSetting) obj;
4791 return sus.name + ":" + sus.userId;
4792 } else if (obj instanceof PackageSetting) {
4793 final PackageSetting ps = (PackageSetting) obj;
4801 public int getUidForSharedUser(String sharedUserName) {
4802 if(sharedUserName == null) {
4806 synchronized (mPackages) {
4807 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4816 public int getFlagsForUid(int uid) {
4817 synchronized (mPackages) {
4818 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4819 if (obj instanceof SharedUserSetting) {
4820 final SharedUserSetting sus = (SharedUserSetting) obj;
4821 return sus.pkgFlags;
4822 } else if (obj instanceof PackageSetting) {
4823 final PackageSetting ps = (PackageSetting) obj;
4831 public int getPrivateFlagsForUid(int uid) {
4832 synchronized (mPackages) {
4833 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4834 if (obj instanceof SharedUserSetting) {
4835 final SharedUserSetting sus = (SharedUserSetting) obj;
4836 return sus.pkgPrivateFlags;
4837 } else if (obj instanceof PackageSetting) {
4838 final PackageSetting ps = (PackageSetting) obj;
4839 return ps.pkgPrivateFlags;
4846 public boolean isUidPrivileged(int uid) {
4847 uid = UserHandle.getAppId(uid);
4849 synchronized (mPackages) {
4850 Object obj = mSettings.getUserIdLPr(uid);
4851 if (obj instanceof SharedUserSetting) {
4852 final SharedUserSetting sus = (SharedUserSetting) obj;
4853 final Iterator<PackageSetting> it = sus.packages.iterator();
4854 while (it.hasNext()) {
4855 if (it.next().isPrivileged()) {
4859 } else if (obj instanceof PackageSetting) {
4860 final PackageSetting ps = (PackageSetting) obj;
4861 return ps.isPrivileged();
4868 public String[] getAppOpPermissionPackages(String permissionName) {
4869 synchronized (mPackages) {
4870 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4874 return pkgs.toArray(new String[pkgs.size()]);
4879 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4880 int flags, int userId) {
4882 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4884 if (!sUserManager.exists(userId)) return null;
4885 flags = updateFlagsForResolve(flags, userId, intent);
4886 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4887 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4889 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4890 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4894 final ResolveInfo bestChoice =
4895 chooseBestActivity(intent, resolvedType, flags, query, userId);
4898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4903 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4904 IntentFilter filter, int match, ComponentName activity) {
4905 final int userId = UserHandle.getCallingUserId();
4906 if (DEBUG_PREFERRED) {
4907 Log.v(TAG, "setLastChosenActivity intent=" + intent
4908 + " resolvedType=" + resolvedType
4910 + " filter=" + filter
4912 + " activity=" + activity);
4913 filter.dump(new PrintStreamPrinter(System.out), " ");
4915 intent.setComponent(null);
4916 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4918 // Find any earlier preferred or last chosen entries and nuke them
4919 findPreferredActivity(intent, resolvedType,
4920 flags, query, 0, false, true, false, userId);
4921 // Add the new activity as the last chosen for this filter
4922 addPreferredActivityInternal(filter, match, null, activity, false, userId,
4923 "Setting last chosen");
4927 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4928 final int userId = UserHandle.getCallingUserId();
4929 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4930 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4932 return findPreferredActivity(intent, resolvedType, flags, query, 0,
4933 false, false, false, userId);
4936 private boolean isEphemeralDisabled() {
4937 // ephemeral apps have been disabled across the board
4938 if (DISABLE_EPHEMERAL_APPS) {
4941 // system isn't up yet; can't read settings, so, assume no ephemeral apps
4942 if (!mSystemReady) {
4945 // we can't get a content resolver until the system is ready; these checks must happen last
4946 final ContentResolver resolver = mContext.getContentResolver();
4947 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4950 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4953 private boolean isEphemeralAllowed(
4954 Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4955 boolean skipPackageCheck) {
4956 // Short circuit and return early if possible.
4957 if (isEphemeralDisabled()) {
4960 final int callingUser = UserHandle.getCallingUserId();
4961 if (callingUser != UserHandle.USER_SYSTEM) {
4964 if (mEphemeralResolverConnection == null) {
4967 if (intent.getComponent() != null) {
4970 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4973 if (!skipPackageCheck && intent.getPackage() != null) {
4976 final boolean isWebUri = hasWebURI(intent);
4977 if (!isWebUri || intent.getData().getHost() == null) {
4980 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4981 synchronized (mPackages) {
4982 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4983 for (int n = 0; n < count; n++) {
4984 ResolveInfo info = resolvedActivities.get(n);
4985 String packageName = info.activityInfo.packageName;
4986 PackageSetting ps = mSettings.mPackages.get(packageName);
4988 // Try to get the status from User settings first
4989 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4990 int status = (int) (packedStatus >> 32);
4991 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4992 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4993 if (DEBUG_EPHEMERAL) {
4994 Slog.v(TAG, "DENY ephemeral apps;"
4995 + " pkg: " + packageName + ", status: " + status);
5002 // We've exhausted all ways to deny ephemeral application; let the system look for them.
5006 private static EphemeralResolveInfo getEphemeralResolveInfo(
5007 Context context, EphemeralResolverConnection resolverConnection, Intent intent,
5008 String resolvedType, int userId, String packageName) {
5009 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
5010 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
5011 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
5012 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
5013 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
5014 ephemeralPrefixCount);
5015 final int[] shaPrefix = digest.getDigestPrefix();
5016 final byte[][] digestBytes = digest.getDigestBytes();
5017 final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5018 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
5019 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5020 // No hash prefix match; there are no ephemeral apps for this domain.
5024 // Go in reverse order so we match the narrowest scope first.
5025 for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5026 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5027 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5030 final List<IntentFilter> filters = ephemeralApplication.getFilters();
5031 // No filters; this should never happen.
5032 if (filters.isEmpty()) {
5035 if (packageName != null
5036 && !packageName.equals(ephemeralApplication.getPackageName())) {
5039 // We have a domain match; resolve the filters to see if anything matches.
5040 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5041 for (int j = filters.size() - 1; j >= 0; --j) {
5042 final EphemeralResolveIntentInfo intentInfo =
5043 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5044 ephemeralResolver.addFilter(intentInfo);
5046 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5047 intent, resolvedType, false /*defaultOnly*/, userId);
5048 if (!matchedResolveInfoList.isEmpty()) {
5049 return matchedResolveInfoList.get(0);
5053 // Hash or filter mis-match; no ephemeral apps for this domain.
5057 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5058 int flags, List<ResolveInfo> query, int userId) {
5059 if (query != null) {
5060 final int N = query.size();
5062 return query.get(0);
5064 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5065 // If there is more than one activity with the same priority,
5066 // then let the user decide between them.
5067 ResolveInfo r0 = query.get(0);
5068 ResolveInfo r1 = query.get(1);
5069 if (DEBUG_INTENT_MATCHING || debug) {
5070 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5071 + r1.activityInfo.name + "=" + r1.priority);
5073 // If the first activity has a higher priority, or a different
5074 // default, then it is always desirable to pick it.
5075 if (r0.priority != r1.priority
5076 || r0.preferredOrder != r1.preferredOrder
5077 || r0.isDefault != r1.isDefault) {
5078 return query.get(0);
5080 // If we have saved a preference for a preferred activity for
5081 // this Intent, use that.
5082 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5083 flags, query, r0.priority, true, false, debug, userId);
5087 ri = new ResolveInfo(mResolveInfo);
5088 ri.activityInfo = new ActivityInfo(ri.activityInfo);
5089 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5090 // If all of the options come from the same package, show the application's
5091 // label and icon instead of the generic resolver's.
5092 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5093 // and then throw away the ResolveInfo itself, meaning that the caller loses
5094 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5095 // a fallback for this case; we only set the target package's resources on
5096 // the ResolveInfo, not the ActivityInfo.
5097 final String intentPackage = intent.getPackage();
5098 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5099 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5100 ri.resolvePackageName = intentPackage;
5101 if (userNeedsBadging(userId)) {
5102 ri.noResourceId = true;
5104 ri.icon = appi.icon;
5106 ri.iconResourceId = appi.icon;
5107 ri.labelRes = appi.labelRes;
5109 ri.activityInfo.applicationInfo = new ApplicationInfo(
5110 ri.activityInfo.applicationInfo);
5112 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5113 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5115 // Make sure that the resolver is displayable in car mode
5116 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5117 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5125 * Return true if the given list is not empty and all of its contents have
5126 * an activityInfo with the given package name.
5128 private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5129 if (ArrayUtils.isEmpty(list)) {
5132 for (int i = 0, N = list.size(); i < N; i++) {
5133 final ResolveInfo ri = list.get(i);
5134 final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5135 if (ai == null || !packageName.equals(ai.packageName)) {
5142 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5143 int flags, List<ResolveInfo> query, boolean debug, int userId) {
5144 final int N = query.size();
5145 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5147 // Get the list of persistent preferred activities that handle the intent
5148 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5149 List<PersistentPreferredActivity> pprefs = ppir != null
5150 ? ppir.queryIntent(intent, resolvedType,
5151 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5153 if (pprefs != null && pprefs.size() > 0) {
5154 final int M = pprefs.size();
5155 for (int i=0; i<M; i++) {
5156 final PersistentPreferredActivity ppa = pprefs.get(i);
5157 if (DEBUG_PREFERRED || debug) {
5158 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5159 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5160 + "\n component=" + ppa.mComponent);
5161 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5163 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5164 flags | MATCH_DISABLED_COMPONENTS, userId);
5165 if (DEBUG_PREFERRED || debug) {
5166 Slog.v(TAG, "Found persistent preferred activity:");
5168 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5170 Slog.v(TAG, " null");
5174 // This previously registered persistent preferred activity
5175 // component is no longer known. Ignore it and do NOT remove it.
5178 for (int j=0; j<N; j++) {
5179 final ResolveInfo ri = query.get(j);
5180 if (!ri.activityInfo.applicationInfo.packageName
5181 .equals(ai.applicationInfo.packageName)) {
5184 if (!ri.activityInfo.name.equals(ai.name)) {
5187 // Found a persistent preference that can handle the intent.
5188 if (DEBUG_PREFERRED || debug) {
5189 Slog.v(TAG, "Returning persistent preferred activity: " +
5190 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5199 // TODO: handle preferred activities missing while user has amnesia
5200 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5201 List<ResolveInfo> query, int priority, boolean always,
5202 boolean removeMatches, boolean debug, int userId) {
5203 if (!sUserManager.exists(userId)) return null;
5204 flags = updateFlagsForResolve(flags, userId, intent);
5206 synchronized (mPackages) {
5207 if (intent.getSelector() != null) {
5208 intent = intent.getSelector();
5210 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5212 // Try to find a matching persistent preferred activity.
5213 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5216 // If a persistent preferred activity matched, use it.
5221 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5222 // Get the list of preferred activities that handle the intent
5223 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5224 List<PreferredActivity> prefs = pir != null
5225 ? pir.queryIntent(intent, resolvedType,
5226 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5228 if (prefs != null && prefs.size() > 0) {
5229 boolean changed = false;
5231 // First figure out how good the original match set is.
5232 // We will only allow preferred activities that came
5233 // from the same match quality.
5236 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5238 final int N = query.size();
5239 for (int j=0; j<N; j++) {
5240 final ResolveInfo ri = query.get(j);
5241 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5242 + ": 0x" + Integer.toHexString(match));
5243 if (ri.match > match) {
5248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5249 + Integer.toHexString(match));
5251 match &= IntentFilter.MATCH_CATEGORY_MASK;
5252 final int M = prefs.size();
5253 for (int i=0; i<M; i++) {
5254 final PreferredActivity pa = prefs.get(i);
5255 if (DEBUG_PREFERRED || debug) {
5256 Slog.v(TAG, "Checking PreferredActivity ds="
5257 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5258 + "\n component=" + pa.mPref.mComponent);
5259 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5261 if (pa.mPref.mMatch != match) {
5262 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5263 + Integer.toHexString(pa.mPref.mMatch));
5266 // If it's not an "always" type preferred activity and that's what we're
5267 // looking for, skip it.
5268 if (always && !pa.mPref.mAlways) {
5269 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5272 final ActivityInfo ai = getActivityInfo(
5273 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5274 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5276 if (DEBUG_PREFERRED || debug) {
5277 Slog.v(TAG, "Found preferred activity:");
5279 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5281 Slog.v(TAG, " null");
5285 // This previously registered preferred activity
5286 // component is no longer known. Most likely an update
5287 // to the app was installed and in the new version this
5288 // component no longer exists. Clean it up by removing
5289 // it from the preferred activities list, and skip it.
5290 Slog.w(TAG, "Removing dangling preferred activity: "
5291 + pa.mPref.mComponent);
5292 pir.removeFilter(pa);
5296 for (int j=0; j<N; j++) {
5297 final ResolveInfo ri = query.get(j);
5298 if (!ri.activityInfo.applicationInfo.packageName
5299 .equals(ai.applicationInfo.packageName)) {
5302 if (!ri.activityInfo.name.equals(ai.name)) {
5306 if (removeMatches) {
5307 pir.removeFilter(pa);
5309 if (DEBUG_PREFERRED) {
5310 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5315 // Okay we found a previously set preferred or last chosen app.
5316 // If the result set is different from when this
5317 // was created, we need to clear it and re-ask the
5318 // user their preference, if we're looking for an "always" type entry.
5319 if (always && !pa.mPref.sameSet(query)) {
5320 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5321 + intent + " type " + resolvedType);
5322 if (DEBUG_PREFERRED) {
5323 Slog.v(TAG, "Removing preferred activity since set changed "
5324 + pa.mPref.mComponent);
5326 pir.removeFilter(pa);
5327 // Re-add the filter as a "last chosen" entry (!always)
5328 PreferredActivity lastChosen = new PreferredActivity(
5329 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5330 pir.addFilter(lastChosen);
5335 // Yay! Either the set matched or we're looking for the last chosen
5336 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5337 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5343 if (DEBUG_PREFERRED) {
5344 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5346 scheduleWritePackageRestrictionsLocked(userId);
5351 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5356 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5359 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5361 mContext.enforceCallingOrSelfPermission(
5362 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5363 List<CrossProfileIntentFilter> matches =
5364 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5365 if (matches != null) {
5366 int size = matches.size();
5367 for (int i = 0; i < size; i++) {
5368 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5371 if (hasWebURI(intent)) {
5372 // cross-profile app linking works only towards the parent.
5373 final UserInfo parent = getProfileParent(sourceUserId);
5374 synchronized(mPackages) {
5375 int flags = updateFlagsForResolve(0, parent.id, intent);
5376 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5377 intent, resolvedType, flags, sourceUserId, parent.id);
5378 return xpDomainInfo != null;
5384 private UserInfo getProfileParent(int userId) {
5385 final long identity = Binder.clearCallingIdentity();
5387 return sUserManager.getProfileParent(userId);
5389 Binder.restoreCallingIdentity(identity);
5393 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5394 String resolvedType, int userId) {
5395 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5396 if (resolver != null) {
5397 return resolver.queryIntent(intent, resolvedType, false, userId);
5403 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5404 String resolvedType, int flags, int userId) {
5406 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5408 return new ParceledListSlice<>(
5409 queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5411 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5415 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5416 String resolvedType, int flags, int userId) {
5417 if (!sUserManager.exists(userId)) return Collections.emptyList();
5418 flags = updateFlagsForResolve(flags, userId, intent);
5419 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5420 false /* requireFullPermission */, false /* checkShell */,
5421 "query intent activities");
5422 ComponentName comp = intent.getComponent();
5424 if (intent.getSelector() != null) {
5425 intent = intent.getSelector();
5426 comp = intent.getComponent();
5431 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5432 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5434 final ResolveInfo ri = new ResolveInfo();
5435 ri.activityInfo = ai;
5442 boolean sortResult = false;
5443 boolean addEphemeral = false;
5444 boolean matchEphemeralPackage = false;
5445 List<ResolveInfo> result;
5446 final String pkgName = intent.getPackage();
5447 synchronized (mPackages) {
5448 if (pkgName == null) {
5449 List<CrossProfileIntentFilter> matchingFilters =
5450 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5451 // Check for results that need to skip the current profile.
5452 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
5453 resolvedType, flags, userId);
5454 if (xpResolveInfo != null) {
5455 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5456 xpResult.add(xpResolveInfo);
5457 return filterIfNotSystemUser(xpResult, userId);
5460 // Check for results in the current profile.
5461 result = filterIfNotSystemUser(mActivities.queryIntent(
5462 intent, resolvedType, flags, userId), userId);
5464 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5466 // Check for cross profile results.
5467 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5468 xpResolveInfo = queryCrossProfileIntents(
5469 matchingFilters, intent, resolvedType, flags, userId,
5470 hasNonNegativePriorityResult);
5471 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5472 boolean isVisibleToUser = filterIfNotSystemUser(
5473 Collections.singletonList(xpResolveInfo), userId).size() > 0;
5474 if (isVisibleToUser) {
5475 result.add(xpResolveInfo);
5479 if (hasWebURI(intent)) {
5480 CrossProfileDomainInfo xpDomainInfo = null;
5481 final UserInfo parent = getProfileParent(userId);
5482 if (parent != null) {
5483 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5484 flags, userId, parent.id);
5486 if (xpDomainInfo != null) {
5487 if (xpResolveInfo != null) {
5488 // If we didn't remove it, the cross-profile ResolveInfo would be twice
5490 result.remove(xpResolveInfo);
5492 if (result.size() == 0 && !addEphemeral) {
5493 // No result in current profile, but found candidate in parent user.
5494 // And we are not going to add emphemeral app, so we can return the
5495 // result straight away.
5496 result.add(xpDomainInfo.resolveInfo);
5499 } else if (result.size() <= 1 && !addEphemeral) {
5500 // No result in parent user and <= 1 result in current profile, and we
5501 // are not going to add emphemeral app, so we can return the result without
5502 // further processing.
5505 // We have more than one candidate (combining results from current and parent
5506 // profile), so we need filtering and sorting.
5507 result = filterCandidatesWithDomainPreferredActivitiesLPr(
5508 intent, flags, result, xpDomainInfo, userId);
5512 final PackageParser.Package pkg = mPackages.get(pkgName);
5514 result = filterIfNotSystemUser(
5515 mActivities.queryIntentForPackage(
5516 intent, resolvedType, flags, pkg.activities, userId),
5519 // the caller wants to resolve for a particular package; however, there
5520 // were no installed results, so, try to find an ephemeral result
5521 addEphemeral = isEphemeralAllowed(
5522 intent, null /*result*/, userId, true /*skipPackageCheck*/);
5523 matchEphemeralPackage = true;
5524 result = new ArrayList<ResolveInfo>();
5529 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5530 final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5531 mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5532 matchEphemeralPackage ? pkgName : null);
5534 if (DEBUG_EPHEMERAL) {
5535 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5537 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5538 ephemeralInstaller.ephemeralResolveInfo = ai;
5539 // make sure this resolver is the default
5540 ephemeralInstaller.isDefault = true;
5541 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5542 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5543 // add a non-generic filter
5544 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5545 ephemeralInstaller.filter.addDataPath(
5546 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5547 result.add(ephemeralInstaller);
5549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5552 Collections.sort(result, mResolvePrioritySorter);
5557 private static class CrossProfileDomainInfo {
5558 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5559 ResolveInfo resolveInfo;
5560 /* Best domain verification status of the activities found in the other profile */
5561 int bestDomainVerificationStatus;
5564 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5565 String resolvedType, int flags, int sourceUserId, int parentUserId) {
5566 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5570 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5571 resolvedType, flags, parentUserId);
5573 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5576 CrossProfileDomainInfo result = null;
5577 int size = resultTargetUser.size();
5578 for (int i = 0; i < size; i++) {
5579 ResolveInfo riTargetUser = resultTargetUser.get(i);
5580 // Intent filter verification is only for filters that specify a host. So don't return
5581 // those that handle all web uris.
5582 if (riTargetUser.handleAllWebDataURI) {
5585 String packageName = riTargetUser.activityInfo.packageName;
5586 PackageSetting ps = mSettings.mPackages.get(packageName);
5590 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5591 int status = (int)(verificationState >> 32);
5592 if (result == null) {
5593 result = new CrossProfileDomainInfo();
5594 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5595 sourceUserId, parentUserId);
5596 result.bestDomainVerificationStatus = status;
5598 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5599 result.bestDomainVerificationStatus);
5602 // Don't consider matches with status NEVER across profiles.
5603 if (result != null && result.bestDomainVerificationStatus
5604 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5611 * Verification statuses are ordered from the worse to the best, except for
5612 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5614 private int bestDomainVerificationStatus(int status1, int status2) {
5615 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5618 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5621 return (int) MathUtils.max(status1, status2);
5624 private boolean isUserEnabled(int userId) {
5625 long callingId = Binder.clearCallingIdentity();
5627 UserInfo userInfo = sUserManager.getUserInfo(userId);
5628 return userInfo != null && userInfo.isEnabled();
5630 Binder.restoreCallingIdentity(callingId);
5635 * Filter out activities with systemUserOnly flag set, when current user is not System.
5637 * @return filtered list
5639 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5640 if (userId == UserHandle.USER_SYSTEM) {
5641 return resolveInfos;
5643 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5644 ResolveInfo info = resolveInfos.get(i);
5645 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5646 resolveInfos.remove(i);
5649 return resolveInfos;
5653 * @param resolveInfos list of resolve infos in descending priority order
5654 * @return if the list contains a resolve info with non-negative priority
5656 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5657 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5660 private static boolean hasWebURI(Intent intent) {
5661 if (intent.getData() == null) {
5664 final String scheme = intent.getScheme();
5665 if (TextUtils.isEmpty(scheme)) {
5668 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5671 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5672 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5674 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5676 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5677 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5681 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5682 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5683 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5684 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5685 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5686 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5688 synchronized (mPackages) {
5689 final int count = candidates.size();
5690 // First, try to use linked apps. Partition the candidates into four lists:
5691 // one for the final results, one for the "do not use ever", one for "undefined status"
5692 // and finally one for "browser app type".
5693 for (int n=0; n<count; n++) {
5694 ResolveInfo info = candidates.get(n);
5695 String packageName = info.activityInfo.packageName;
5696 PackageSetting ps = mSettings.mPackages.get(packageName);
5698 // Add to the special match all list (Browser use case)
5699 if (info.handleAllWebDataURI) {
5700 matchAllList.add(info);
5703 // Try to get the status from User settings first
5704 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5705 int status = (int)(packedStatus >> 32);
5706 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5707 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5708 if (DEBUG_DOMAIN_VERIFICATION) {
5709 Slog.i(TAG, " + always: " + info.activityInfo.packageName
5710 + " : linkgen=" + linkGeneration);
5712 // Use link-enabled generation as preferredOrder, i.e.
5713 // prefer newly-enabled over earlier-enabled.
5714 info.preferredOrder = linkGeneration;
5715 alwaysList.add(info);
5716 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5717 if (DEBUG_DOMAIN_VERIFICATION) {
5718 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
5720 neverList.add(info);
5721 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5722 if (DEBUG_DOMAIN_VERIFICATION) {
5723 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
5725 alwaysAskList.add(info);
5726 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5727 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5728 if (DEBUG_DOMAIN_VERIFICATION) {
5729 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
5731 undefinedList.add(info);
5736 // We'll want to include browser possibilities in a few cases
5737 boolean includeBrowser = false;
5739 // First try to add the "always" resolution(s) for the current user, if any
5740 if (alwaysList.size() > 0) {
5741 result.addAll(alwaysList);
5743 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5744 result.addAll(undefinedList);
5745 // Maybe add one for the other profile.
5746 if (xpDomainInfo != null && (
5747 xpDomainInfo.bestDomainVerificationStatus
5748 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5749 result.add(xpDomainInfo.resolveInfo);
5751 includeBrowser = true;
5754 // The presence of any 'always ask' alternatives means we'll also offer browsers.
5755 // If there were 'always' entries their preferred order has been set, so we also
5756 // back that off to make the alternatives equivalent
5757 if (alwaysAskList.size() > 0) {
5758 for (ResolveInfo i : result) {
5759 i.preferredOrder = 0;
5761 result.addAll(alwaysAskList);
5762 includeBrowser = true;
5765 if (includeBrowser) {
5766 // Also add browsers (all of them or only the default one)
5767 if (DEBUG_DOMAIN_VERIFICATION) {
5768 Slog.v(TAG, " ...including browsers in candidate set");
5770 if ((matchFlags & MATCH_ALL) != 0) {
5771 result.addAll(matchAllList);
5773 // Browser/generic handling case. If there's a default browser, go straight
5774 // to that (but only if there is no other higher-priority match).
5775 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5776 int maxMatchPrio = 0;
5777 ResolveInfo defaultBrowserMatch = null;
5778 final int numCandidates = matchAllList.size();
5779 for (int n = 0; n < numCandidates; n++) {
5780 ResolveInfo info = matchAllList.get(n);
5781 // track the highest overall match priority...
5782 if (info.priority > maxMatchPrio) {
5783 maxMatchPrio = info.priority;
5785 // ...and the highest-priority default browser match
5786 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5787 if (defaultBrowserMatch == null
5788 || (defaultBrowserMatch.priority < info.priority)) {
5790 Slog.v(TAG, "Considering default browser match " + info);
5792 defaultBrowserMatch = info;
5796 if (defaultBrowserMatch != null
5797 && defaultBrowserMatch.priority >= maxMatchPrio
5798 && !TextUtils.isEmpty(defaultBrowserPackageName))
5801 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5803 result.add(defaultBrowserMatch);
5805 result.addAll(matchAllList);
5809 // If there is nothing selected, add all candidates and remove the ones that the user
5810 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5811 if (result.size() == 0) {
5812 result.addAll(candidates);
5813 result.removeAll(neverList);
5817 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5818 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5820 for (ResolveInfo info : result) {
5821 Slog.v(TAG, " + " + info.activityInfo);
5827 // Returns a packed value as a long:
5829 // high 'int'-sized word: link status: undefined/ask/never/always.
5830 // low 'int'-sized word: relative priority among 'always' results.
5831 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5832 long result = ps.getDomainVerificationStatusForUser(userId);
5833 // if none available, get the master status
5834 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5835 if (ps.getIntentFilterVerificationInfo() != null) {
5836 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5842 private ResolveInfo querySkipCurrentProfileIntents(
5843 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5844 int flags, int sourceUserId) {
5845 if (matchingFilters != null) {
5846 int size = matchingFilters.size();
5847 for (int i = 0; i < size; i ++) {
5848 CrossProfileIntentFilter filter = matchingFilters.get(i);
5849 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5850 // Checking if there are activities in the target user that can handle the
5852 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5853 resolvedType, flags, sourceUserId);
5854 if (resolveInfo != null) {
5863 // Return matching ResolveInfo in target user if any.
5864 private ResolveInfo queryCrossProfileIntents(
5865 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5866 int flags, int sourceUserId, boolean matchInCurrentProfile) {
5867 if (matchingFilters != null) {
5868 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5869 // match the same intent. For performance reasons, it is better not to
5870 // run queryIntent twice for the same userId
5871 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5872 int size = matchingFilters.size();
5873 for (int i = 0; i < size; i++) {
5874 CrossProfileIntentFilter filter = matchingFilters.get(i);
5875 int targetUserId = filter.getTargetUserId();
5876 boolean skipCurrentProfile =
5877 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5878 boolean skipCurrentProfileIfNoMatchFound =
5879 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5880 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5881 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5882 // Checking if there are activities in the target user that can handle the
5884 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5885 resolvedType, flags, sourceUserId);
5886 if (resolveInfo != null) return resolveInfo;
5887 alreadyTriedUserIds.put(targetUserId, true);
5895 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5896 * will forward the intent to the filter's target user.
5897 * Otherwise, returns null.
5899 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5900 String resolvedType, int flags, int sourceUserId) {
5901 int targetUserId = filter.getTargetUserId();
5902 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5903 resolvedType, flags, targetUserId);
5904 if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5905 // If all the matches in the target profile are suspended, return null.
5906 for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5907 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5908 & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5909 return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5917 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5918 int sourceUserId, int targetUserId) {
5919 ResolveInfo forwardingResolveInfo = new ResolveInfo();
5920 long ident = Binder.clearCallingIdentity();
5921 boolean targetIsProfile;
5923 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5925 Binder.restoreCallingIdentity(ident);
5928 if (targetIsProfile) {
5929 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5931 className = FORWARD_INTENT_TO_PARENT;
5933 ComponentName forwardingActivityComponentName = new ComponentName(
5934 mAndroidApplication.packageName, className);
5935 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5937 if (!targetIsProfile) {
5938 forwardingActivityInfo.showUserIcon = targetUserId;
5939 forwardingResolveInfo.noResourceId = true;
5941 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5942 forwardingResolveInfo.priority = 0;
5943 forwardingResolveInfo.preferredOrder = 0;
5944 forwardingResolveInfo.match = 0;
5945 forwardingResolveInfo.isDefault = true;
5946 forwardingResolveInfo.filter = filter;
5947 forwardingResolveInfo.targetUserId = targetUserId;
5948 return forwardingResolveInfo;
5952 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5953 Intent[] specifics, String[] specificTypes, Intent intent,
5954 String resolvedType, int flags, int userId) {
5955 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5956 specificTypes, intent, resolvedType, flags, userId));
5959 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5960 Intent[] specifics, String[] specificTypes, Intent intent,
5961 String resolvedType, int flags, int userId) {
5962 if (!sUserManager.exists(userId)) return Collections.emptyList();
5963 flags = updateFlagsForResolve(flags, userId, intent);
5964 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5965 false /* requireFullPermission */, false /* checkShell */,
5966 "query intent activity options");
5967 final String resultsAction = intent.getAction();
5969 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5970 | PackageManager.GET_RESOLVED_FILTER, userId);
5972 if (DEBUG_INTENT_MATCHING) {
5973 Log.v(TAG, "Query " + intent + ": " + results);
5976 int specificsPos = 0;
5979 // todo: note that the algorithm used here is O(N^2). This
5980 // isn't a problem in our current environment, but if we start running
5981 // into situations where we have more than 5 or 10 matches then this
5982 // should probably be changed to something smarter...
5984 // First we go through and resolve each of the specific items
5985 // that were supplied, taking care of removing any corresponding
5986 // duplicate items in the generic resolve list.
5987 if (specifics != null) {
5988 for (int i=0; i<specifics.length; i++) {
5989 final Intent sintent = specifics[i];
5990 if (sintent == null) {
5994 if (DEBUG_INTENT_MATCHING) {
5995 Log.v(TAG, "Specific #" + i + ": " + sintent);
5998 String action = sintent.getAction();
5999 if (resultsAction != null && resultsAction.equals(action)) {
6000 // If this action was explicitly requested, then don't
6001 // remove things that have it.
6005 ResolveInfo ri = null;
6006 ActivityInfo ai = null;
6008 ComponentName comp = sintent.getComponent();
6012 specificTypes != null ? specificTypes[i] : null,
6017 if (ri == mResolveInfo) {
6018 // ACK! Must do something better with this.
6020 ai = ri.activityInfo;
6021 comp = new ComponentName(ai.applicationInfo.packageName,
6024 ai = getActivityInfo(comp, flags, userId);
6030 // Look for any generic query activities that are duplicates
6031 // of this specific one, and remove them from the results.
6032 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6035 for (j=specificsPos; j<N; j++) {
6036 ResolveInfo sri = results.get(j);
6037 if ((sri.activityInfo.name.equals(comp.getClassName())
6038 && sri.activityInfo.applicationInfo.packageName.equals(
6039 comp.getPackageName()))
6040 || (action != null && sri.filter.matchAction(action))) {
6042 if (DEBUG_INTENT_MATCHING) Log.v(
6043 TAG, "Removing duplicate item from " + j
6044 + " due to specific " + specificsPos);
6053 // Add this specific item to its proper place.
6055 ri = new ResolveInfo();
6056 ri.activityInfo = ai;
6058 results.add(specificsPos, ri);
6059 ri.specificIndex = i;
6064 // Now we go through the remaining generic results and remove any
6065 // duplicate actions that are found here.
6067 for (int i=specificsPos; i<N-1; i++) {
6068 final ResolveInfo rii = results.get(i);
6069 if (rii.filter == null) {
6073 // Iterate over all of the actions of this result's intent
6074 // filter... typically this should be just one.
6075 final Iterator<String> it = rii.filter.actionsIterator();
6079 while (it.hasNext()) {
6080 final String action = it.next();
6081 if (resultsAction != null && resultsAction.equals(action)) {
6082 // If this action was explicitly requested, then don't
6083 // remove things that have it.
6086 for (int j=i+1; j<N; j++) {
6087 final ResolveInfo rij = results.get(j);
6088 if (rij.filter != null && rij.filter.hasAction(action)) {
6090 if (DEBUG_INTENT_MATCHING) Log.v(
6091 TAG, "Removing duplicate item from " + j
6092 + " due to action " + action + " at " + i);
6099 // If the caller didn't request filter information, drop it now
6100 // so we don't have to marshall/unmarshall it.
6101 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6106 // Filter out the caller activity if so requested.
6107 if (caller != null) {
6109 for (int i=0; i<N; i++) {
6110 ActivityInfo ainfo = results.get(i).activityInfo;
6111 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6112 && caller.getClassName().equals(ainfo.name)) {
6119 // If the caller didn't request filter information,
6120 // drop them now so we don't have to
6121 // marshall/unmarshall it.
6122 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6124 for (int i=0; i<N; i++) {
6125 results.get(i).filter = null;
6129 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6134 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6135 String resolvedType, int flags, int userId) {
6136 return new ParceledListSlice<>(
6137 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6140 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6141 String resolvedType, int flags, int userId) {
6142 if (!sUserManager.exists(userId)) return Collections.emptyList();
6143 flags = updateFlagsForResolve(flags, userId, intent);
6144 ComponentName comp = intent.getComponent();
6146 if (intent.getSelector() != null) {
6147 intent = intent.getSelector();
6148 comp = intent.getComponent();
6152 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6153 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6155 ResolveInfo ri = new ResolveInfo();
6156 ri.activityInfo = ai;
6163 synchronized (mPackages) {
6164 String pkgName = intent.getPackage();
6165 if (pkgName == null) {
6166 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6168 final PackageParser.Package pkg = mPackages.get(pkgName);
6170 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6173 return Collections.emptyList();
6178 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6179 if (!sUserManager.exists(userId)) return null;
6180 flags = updateFlagsForResolve(flags, userId, intent);
6181 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6182 if (query != null) {
6183 if (query.size() >= 1) {
6184 // If there is more than one service with the same priority,
6185 // just arbitrarily pick the first one.
6186 return query.get(0);
6193 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6194 String resolvedType, int flags, int userId) {
6195 return new ParceledListSlice<>(
6196 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6199 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6200 String resolvedType, int flags, int userId) {
6201 if (!sUserManager.exists(userId)) return Collections.emptyList();
6202 flags = updateFlagsForResolve(flags, userId, intent);
6203 ComponentName comp = intent.getComponent();
6205 if (intent.getSelector() != null) {
6206 intent = intent.getSelector();
6207 comp = intent.getComponent();
6211 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6212 final ServiceInfo si = getServiceInfo(comp, flags, userId);
6214 final ResolveInfo ri = new ResolveInfo();
6215 ri.serviceInfo = si;
6222 synchronized (mPackages) {
6223 String pkgName = intent.getPackage();
6224 if (pkgName == null) {
6225 return mServices.queryIntent(intent, resolvedType, flags, userId);
6227 final PackageParser.Package pkg = mPackages.get(pkgName);
6229 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6232 return Collections.emptyList();
6237 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6238 String resolvedType, int flags, int userId) {
6239 return new ParceledListSlice<>(
6240 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6243 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6244 Intent intent, String resolvedType, int flags, int userId) {
6245 if (!sUserManager.exists(userId)) return Collections.emptyList();
6246 flags = updateFlagsForResolve(flags, userId, intent);
6247 ComponentName comp = intent.getComponent();
6249 if (intent.getSelector() != null) {
6250 intent = intent.getSelector();
6251 comp = intent.getComponent();
6255 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6256 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6258 final ResolveInfo ri = new ResolveInfo();
6259 ri.providerInfo = pi;
6266 synchronized (mPackages) {
6267 String pkgName = intent.getPackage();
6268 if (pkgName == null) {
6269 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6271 final PackageParser.Package pkg = mPackages.get(pkgName);
6273 return mProviders.queryIntentForPackage(
6274 intent, resolvedType, flags, pkg.providers, userId);
6276 return Collections.emptyList();
6281 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6282 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6283 flags = updateFlagsForPackage(flags, userId, null);
6284 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6285 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6286 false /* requireFullPermission */, false /* checkShell */,
6287 "get installed packages");
6290 synchronized (mPackages) {
6291 ArrayList<PackageInfo> list;
6292 if (listUninstalled) {
6293 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6294 for (PackageSetting ps : mSettings.mPackages.values()) {
6295 final PackageInfo pi;
6296 if (ps.pkg != null) {
6297 pi = generatePackageInfo(ps, flags, userId);
6299 pi = generatePackageInfo(ps, flags, userId);
6306 list = new ArrayList<PackageInfo>(mPackages.size());
6307 for (PackageParser.Package p : mPackages.values()) {
6308 final PackageInfo pi =
6309 generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6316 return new ParceledListSlice<PackageInfo>(list);
6320 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6321 String[] permissions, boolean[] tmp, int flags, int userId) {
6323 final PermissionsState permissionsState = ps.getPermissionsState();
6324 for (int i=0; i<permissions.length; i++) {
6325 final String permission = permissions[i];
6326 if (permissionsState.hasPermission(permission, userId)) {
6333 if (numMatch == 0) {
6336 final PackageInfo pi;
6337 if (ps.pkg != null) {
6338 pi = generatePackageInfo(ps, flags, userId);
6340 pi = generatePackageInfo(ps, flags, userId);
6342 // The above might return null in cases of uninstalled apps or install-state
6343 // skew across users/profiles.
6345 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6346 if (numMatch == permissions.length) {
6347 pi.requestedPermissions = permissions;
6349 pi.requestedPermissions = new String[numMatch];
6351 for (int i=0; i<permissions.length; i++) {
6353 pi.requestedPermissions[numMatch] = permissions[i];
6364 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6365 String[] permissions, int flags, int userId) {
6366 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6367 flags = updateFlagsForPackage(flags, userId, permissions);
6368 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6371 synchronized (mPackages) {
6372 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6373 boolean[] tmpBools = new boolean[permissions.length];
6374 if (listUninstalled) {
6375 for (PackageSetting ps : mSettings.mPackages.values()) {
6376 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6379 for (PackageParser.Package pkg : mPackages.values()) {
6380 PackageSetting ps = (PackageSetting)pkg.mExtras;
6382 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6388 return new ParceledListSlice<PackageInfo>(list);
6393 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6394 final int callingUid = Binder.getCallingUid();
6395 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6396 flags = updateFlagsForApplication(flags, userId, null);
6397 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6399 enforceCrossUserPermission(
6402 false /* requireFullPermission */,
6403 false /* checkShell */,
6404 "get installed application info");
6407 synchronized (mPackages) {
6408 ArrayList<ApplicationInfo> list;
6409 if (listUninstalled) {
6410 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6411 for (PackageSetting ps : mSettings.mPackages.values()) {
6413 if (ps.pkg != null) {
6414 ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6415 ps.readUserState(userId), userId);
6417 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6424 list = new ArrayList<ApplicationInfo>(mPackages.size());
6425 for (PackageParser.Package p : mPackages.values()) {
6426 if (p.mExtras != null) {
6427 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6428 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6436 return new ParceledListSlice<ApplicationInfo>(list);
6441 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6442 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6446 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6447 "getEphemeralApplications");
6448 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6449 true /* requireFullPermission */, false /* checkShell */,
6450 "getEphemeralApplications");
6451 synchronized (mPackages) {
6452 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6453 .getEphemeralApplicationsLPw(userId);
6454 if (ephemeralApps != null) {
6455 return new ParceledListSlice<>(ephemeralApps);
6462 public boolean isEphemeralApplication(String packageName, int userId) {
6463 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6464 true /* requireFullPermission */, false /* checkShell */,
6466 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6470 if (!isCallerSameApp(packageName)) {
6473 synchronized (mPackages) {
6474 PackageParser.Package pkg = mPackages.get(packageName);
6476 return pkg.applicationInfo.isEphemeralApp();
6483 public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6484 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6488 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6489 true /* requireFullPermission */, false /* checkShell */,
6491 if (!isCallerSameApp(packageName)) {
6494 synchronized (mPackages) {
6495 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6496 packageName, userId);
6501 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6502 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6506 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6507 true /* requireFullPermission */, true /* checkShell */,
6509 if (!isCallerSameApp(packageName)) {
6512 synchronized (mPackages) {
6513 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6514 packageName, cookie, userId);
6519 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6520 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6524 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6525 "getEphemeralApplicationIcon");
6526 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6527 true /* requireFullPermission */, false /* checkShell */,
6528 "getEphemeralApplicationIcon");
6529 synchronized (mPackages) {
6530 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6531 packageName, userId);
6535 private boolean isCallerSameApp(String packageName) {
6536 PackageParser.Package pkg = mPackages.get(packageName);
6538 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6542 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6543 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6546 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6547 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6550 synchronized (mPackages) {
6551 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6552 final int userId = UserHandle.getCallingUserId();
6553 while (i.hasNext()) {
6554 final PackageParser.Package p = i.next();
6555 if (p.applicationInfo == null) continue;
6557 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6558 && !p.applicationInfo.isDirectBootAware();
6559 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6560 && p.applicationInfo.isDirectBootAware();
6562 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6563 && (!mSafeMode || isSystemApp(p))
6564 && (matchesUnaware || matchesAware)) {
6565 PackageSetting ps = mSettings.mPackages.get(p.packageName);
6567 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6568 ps.readUserState(userId), userId);
6581 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6582 if (!sUserManager.exists(userId)) return null;
6583 flags = updateFlagsForComponent(flags, userId, name);
6585 synchronized (mPackages) {
6586 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6587 PackageSetting ps = provider != null
6588 ? mSettings.mPackages.get(provider.owner.packageName)
6591 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6592 ? PackageParser.generateProviderInfo(provider, flags,
6593 ps.readUserState(userId), userId)
6602 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6604 synchronized (mPackages) {
6605 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6606 .entrySet().iterator();
6607 final int userId = UserHandle.getCallingUserId();
6608 while (i.hasNext()) {
6609 Map.Entry<String, PackageParser.Provider> entry = i.next();
6610 PackageParser.Provider p = entry.getValue();
6611 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6613 if (ps != null && p.syncable
6614 && (!mSafeMode || (p.info.applicationInfo.flags
6615 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6616 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6617 ps.readUserState(userId), userId);
6619 outNames.add(entry.getKey());
6628 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6629 int uid, int flags) {
6630 final int userId = processName != null ? UserHandle.getUserId(uid)
6631 : UserHandle.getCallingUserId();
6632 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6633 flags = updateFlagsForComponent(flags, userId, processName);
6635 ArrayList<ProviderInfo> finalList = null;
6637 synchronized (mPackages) {
6638 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6639 while (i.hasNext()) {
6640 final PackageParser.Provider p = i.next();
6641 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6642 if (ps != null && p.info.authority != null
6643 && (processName == null
6644 || (p.info.processName.equals(processName)
6645 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6646 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6647 if (finalList == null) {
6648 finalList = new ArrayList<ProviderInfo>(3);
6650 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6651 ps.readUserState(userId), userId);
6653 finalList.add(info);
6659 if (finalList != null) {
6660 Collections.sort(finalList, mProviderInitOrderSorter);
6661 return new ParceledListSlice<ProviderInfo>(finalList);
6664 return ParceledListSlice.emptyList();
6668 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6670 synchronized (mPackages) {
6671 final PackageParser.Instrumentation i = mInstrumentation.get(name);
6672 return PackageParser.generateInstrumentationInfo(i, flags);
6677 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6678 String targetPackage, int flags) {
6679 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6682 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6684 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6687 synchronized (mPackages) {
6688 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6689 while (i.hasNext()) {
6690 final PackageParser.Instrumentation p = i.next();
6691 if (targetPackage == null
6692 || targetPackage.equals(p.info.targetPackage)) {
6693 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6705 private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6706 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6707 if (overlays == null) {
6708 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6711 for (PackageParser.Package opkg : overlays.values()) {
6712 // Not much to do if idmap fails: we already logged the error
6713 // and we certainly don't want to abort installation of pkg simply
6714 // because an overlay didn't fit properly. For these reasons,
6715 // ignore the return value of createIdmapForPackagePairLI.
6716 createIdmapForPackagePairLI(pkg, opkg);
6720 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6721 PackageParser.Package opkg) {
6722 if (!opkg.mTrustedOverlay) {
6723 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6724 opkg.baseCodePath + ": overlay not trusted");
6727 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6728 if (overlaySet == null) {
6729 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6730 opkg.baseCodePath + " but target package has no known overlays");
6733 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6734 // TODO: generate idmap for split APKs
6736 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6737 } catch (InstallerException e) {
6738 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6739 + opkg.baseCodePath);
6742 PackageParser.Package[] overlayArray =
6743 overlaySet.values().toArray(new PackageParser.Package[0]);
6744 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6745 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6746 return p1.mOverlayPriority - p2.mOverlayPriority;
6749 Arrays.sort(overlayArray, cmp);
6751 pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6753 for (PackageParser.Package p : overlayArray) {
6754 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6759 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6762 scanDirLI(dir, parseFlags, scanFlags, currentTime);
6764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6768 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6769 final File[] files = dir.listFiles();
6770 if (ArrayUtils.isEmpty(files)) {
6771 Log.d(TAG, "No files in app dir " + dir);
6775 if (DEBUG_PACKAGE_SCANNING) {
6776 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6777 + " flags=0x" + Integer.toHexString(parseFlags));
6780 for (File file : files) {
6781 final boolean isPackage = (isApkFile(file) || file.isDirectory())
6782 && !PackageInstallerService.isStageName(file.getName());
6784 // Ignore entries which are not packages
6788 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6789 scanFlags, currentTime, null);
6790 } catch (PackageManagerException e) {
6791 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6793 // Delete invalid userdata apps
6794 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6795 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6796 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6797 removeCodePathLI(file);
6803 private static File getSettingsProblemFile() {
6804 File dataDir = Environment.getDataDirectory();
6805 File systemDir = new File(dataDir, "system");
6806 File fname = new File(systemDir, "uiderrors.txt");
6810 static void reportSettingsProblem(int priority, String msg) {
6811 logCriticalInfo(priority, msg);
6814 static void logCriticalInfo(int priority, String msg) {
6815 Slog.println(priority, TAG, msg);
6816 EventLogTags.writePmCriticalInfo(msg);
6818 File fname = getSettingsProblemFile();
6819 FileOutputStream out = new FileOutputStream(fname, true);
6820 PrintWriter pw = new FastPrintWriter(out);
6821 SimpleDateFormat formatter = new SimpleDateFormat();
6822 String dateString = formatter.format(new Date(System.currentTimeMillis()));
6823 pw.println(dateString + ": " + msg);
6825 FileUtils.setPermissions(
6827 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6829 } catch (java.io.IOException e) {
6833 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6834 if (srcFile.isDirectory()) {
6835 final File baseFile = new File(pkg.baseCodePath);
6836 long maxModifiedTime = baseFile.lastModified();
6837 if (pkg.splitCodePaths != null) {
6838 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6839 final File splitFile = new File(pkg.splitCodePaths[i]);
6840 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6843 return maxModifiedTime;
6845 return srcFile.lastModified();
6848 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6849 final int policyFlags) throws PackageManagerException {
6850 // When upgrading from pre-N MR1, verify the package time stamp using the package
6851 // directory and not the APK file.
6852 final long lastModifiedTime = mIsPreNMR1Upgrade
6853 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6855 && ps.codePath.equals(srcFile)
6856 && ps.timeStamp == lastModifiedTime
6857 && !isCompatSignatureUpdateNeeded(pkg)
6858 && !isRecoverSignatureUpdateNeeded(pkg)) {
6859 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6860 KeySetManagerService ksms = mSettings.mKeySetManagerService;
6861 ArraySet<PublicKey> signingKs;
6862 synchronized (mPackages) {
6863 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6865 if (ps.signatures.mSignatures != null
6866 && ps.signatures.mSignatures.length != 0
6867 && signingKs != null) {
6868 // Optimization: reuse the existing cached certificates
6869 // if the package appears to be unchanged.
6870 pkg.mSignatures = ps.signatures.mSignatures;
6871 pkg.mSigningKeys = signingKs;
6875 Slog.w(TAG, "PackageSetting for " + ps.name
6876 + " is missing signatures. Collecting certs again to recover them.");
6878 Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6882 PackageParser.collectCertificates(pkg, policyFlags);
6883 } catch (PackageParserException e) {
6884 throw PackageManagerException.from(e);
6889 * Traces a package scan.
6890 * @see #scanPackageLI(File, int, int, long, UserHandle)
6892 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6893 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6894 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6896 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6903 * Scans a package and returns the newly parsed package.
6904 * Returns {@code null} in case of errors and the error code is stored in mLastScanError
6906 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6907 long currentTime, UserHandle user) throws PackageManagerException {
6908 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6909 PackageParser pp = new PackageParser();
6910 pp.setSeparateProcesses(mSeparateProcesses);
6911 pp.setOnlyCoreApps(mOnlyCore);
6912 pp.setDisplayMetrics(mMetrics);
6914 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6915 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6918 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6919 final PackageParser.Package pkg;
6921 pkg = pp.parsePackage(scanFile, parseFlags);
6922 } catch (PackageParserException e) {
6923 throw PackageManagerException.from(e);
6925 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6928 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6932 * Scans a package and returns the newly parsed package.
6933 * @throws PackageManagerException on a parse error.
6935 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6936 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6937 throws PackageManagerException {
6938 // If the package has children and this is the first dive in the function
6939 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6940 // packages (parent and children) would be successfully scanned before the
6941 // actual scan since scanning mutates internal state and we want to atomically
6942 // install the package and its children.
6943 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6944 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6945 scanFlags |= SCAN_CHECK_ONLY;
6948 scanFlags &= ~SCAN_CHECK_ONLY;
6952 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6953 scanFlags, currentTime, user);
6955 // Scan the children
6956 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6957 for (int i = 0; i < childCount; i++) {
6958 PackageParser.Package childPackage = pkg.childPackages.get(i);
6959 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6964 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6965 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6972 * Scans a package and returns the newly parsed package.
6973 * @throws PackageManagerException on a parse error.
6975 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6976 int policyFlags, int scanFlags, long currentTime, UserHandle user)
6977 throws PackageManagerException {
6978 PackageSetting ps = null;
6979 PackageSetting updatedPkg;
6981 synchronized (mPackages) {
6982 // Look to see if we already know about this package.
6983 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6984 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6985 // This package has been renamed to its original name. Let's
6987 ps = mSettings.peekPackageLPr(oldName);
6989 // If there was no original package, see one for the real package name.
6991 ps = mSettings.peekPackageLPr(pkg.packageName);
6993 // Check to see if this package could be hiding/updating a system
6994 // package. Must look for it either under the original or real
6995 // package name depending on our state.
6996 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6997 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6999 // If this is a package we don't know about on the system partition, we
7000 // may need to remove disabled child packages on the system partition
7001 // or may need to not add child packages if the parent apk is updated
7002 // on the data partition and no longer defines this child package.
7003 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7004 // If this is a parent package for an updated system app and this system
7005 // app got an OTA update which no longer defines some of the child packages
7006 // we have to prune them from the disabled system packages.
7007 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7008 if (disabledPs != null) {
7009 final int scannedChildCount = (pkg.childPackages != null)
7010 ? pkg.childPackages.size() : 0;
7011 final int disabledChildCount = disabledPs.childPackageNames != null
7012 ? disabledPs.childPackageNames.size() : 0;
7013 for (int i = 0; i < disabledChildCount; i++) {
7014 String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7015 boolean disabledPackageAvailable = false;
7016 for (int j = 0; j < scannedChildCount; j++) {
7017 PackageParser.Package childPkg = pkg.childPackages.get(j);
7018 if (childPkg.packageName.equals(disabledChildPackageName)) {
7019 disabledPackageAvailable = true;
7023 if (!disabledPackageAvailable) {
7024 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7031 boolean updatedPkgBetter = false;
7032 // First check if this is a system package that may involve an update
7033 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7034 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7035 // it needs to drop FLAG_PRIVILEGED.
7036 if (locationIsPrivileged(scanFile)) {
7037 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7039 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7042 if (ps != null && !ps.codePath.equals(scanFile)) {
7043 // The path has changed from what was last scanned... check the
7044 // version of the new path against what we have stored to determine
7046 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7047 if (pkg.mVersionCode <= ps.versionCode) {
7048 // The system package has been updated and the code path does not match
7049 // Ignore entry. Skip it.
7050 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7051 + " ignored: updated version " + ps.versionCode
7052 + " better than this " + pkg.mVersionCode);
7053 if (!updatedPkg.codePath.equals(scanFile)) {
7054 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7055 + ps.name + " changing from " + updatedPkg.codePathString
7056 + " to " + scanFile);
7057 updatedPkg.codePath = scanFile;
7058 updatedPkg.codePathString = scanFile.toString();
7059 updatedPkg.resourcePath = scanFile;
7060 updatedPkg.resourcePathString = scanFile.toString();
7062 updatedPkg.pkg = pkg;
7063 updatedPkg.versionCode = pkg.mVersionCode;
7065 // Update the disabled system child packages to point to the package too.
7066 final int childCount = updatedPkg.childPackageNames != null
7067 ? updatedPkg.childPackageNames.size() : 0;
7068 for (int i = 0; i < childCount; i++) {
7069 String childPackageName = updatedPkg.childPackageNames.get(i);
7070 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7072 if (updatedChildPkg != null) {
7073 updatedChildPkg.pkg = pkg;
7074 updatedChildPkg.versionCode = pkg.mVersionCode;
7078 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7079 + scanFile + " ignored: updated version " + ps.versionCode
7080 + " better than this " + pkg.mVersionCode);
7082 // The current app on the system partition is better than
7083 // what we have updated to on the data partition; switch
7084 // back to the system partition version.
7085 // At this point, its safely assumed that package installation for
7086 // apps in system partition will go through. If not there won't be a working
7087 // version of the app
7089 synchronized (mPackages) {
7090 // Just remove the loaded entries from package lists.
7091 mPackages.remove(ps.name);
7094 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7095 + " reverting from " + ps.codePathString
7096 + ": new version " + pkg.mVersionCode
7097 + " better than installed " + ps.versionCode);
7099 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7100 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7101 synchronized (mInstallLock) {
7102 args.cleanUpResourcesLI();
7104 synchronized (mPackages) {
7105 mSettings.enableSystemPackageLPw(ps.name);
7107 updatedPkgBetter = true;
7112 if (updatedPkg != null) {
7113 // An updated system app will not have the PARSE_IS_SYSTEM flag set
7115 policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7117 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7118 // flag set initially
7119 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7120 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7124 // Verify certificates against what was last scanned
7125 collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7128 * A new system app appeared, but we already had a non-system one of the
7129 * same name installed earlier.
7131 boolean shouldHideSystemApp = false;
7132 if (updatedPkg == null && ps != null
7133 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7135 * Check to make sure the signatures match first. If they don't,
7136 * wipe the installed application and its data.
7138 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7139 != PackageManager.SIGNATURE_MATCH) {
7140 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7141 + " signatures don't match existing userdata copy; removing");
7142 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7143 "scanPackageInternalLI")) {
7144 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7149 * If the newly-added system app is an older version than the
7150 * already installed version, hide it. It will be scanned later
7151 * and re-added like an update.
7153 if (pkg.mVersionCode <= ps.versionCode) {
7154 shouldHideSystemApp = true;
7155 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7156 + " but new version " + pkg.mVersionCode + " better than installed "
7157 + ps.versionCode + "; hiding system");
7160 * The newly found system app is a newer version that the
7161 * one previously installed. Simply remove the
7162 * already-installed application and replace it with our own
7163 * while keeping the application data.
7165 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7166 + " reverting from " + ps.codePathString + ": new version "
7167 + pkg.mVersionCode + " better than installed " + ps.versionCode);
7168 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7169 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7170 synchronized (mInstallLock) {
7171 args.cleanUpResourcesLI();
7177 // The apk is forward locked (not public) if its code and resources
7178 // are kept in different files. (except for app in either system or
7180 // TODO grab this value from PackageSettings
7181 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7182 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7183 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7187 // TODO: extend to support forward-locked splits
7188 String resourcePath = null;
7189 String baseResourcePath = null;
7190 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7191 if (ps != null && ps.resourcePathString != null) {
7192 resourcePath = ps.resourcePathString;
7193 baseResourcePath = ps.resourcePathString;
7195 // Should not happen at all. Just log an error.
7196 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7199 resourcePath = pkg.codePath;
7200 baseResourcePath = pkg.baseCodePath;
7203 // Set application objects path explicitly.
7204 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7205 pkg.setApplicationInfoCodePath(pkg.codePath);
7206 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7207 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7208 pkg.setApplicationInfoResourcePath(resourcePath);
7209 pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7210 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7212 // Note that we invoke the following method only if we are about to unpack an application
7213 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7214 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7217 * If the system app should be overridden by a previously installed
7218 * data, hide the system app now and let the /data/app scan pick it up
7221 if (shouldHideSystemApp) {
7222 synchronized (mPackages) {
7223 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7230 private static String fixProcessName(String defProcessName,
7231 String processName, int uid) {
7232 if (processName == null) {
7233 return defProcessName;
7238 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7239 throws PackageManagerException {
7240 if (pkgSetting.signatures.mSignatures != null) {
7241 // Already existing package. Make sure signatures match
7242 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7243 == PackageManager.SIGNATURE_MATCH;
7245 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7246 == PackageManager.SIGNATURE_MATCH;
7249 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7250 == PackageManager.SIGNATURE_MATCH;
7253 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7254 + pkg.packageName + " signatures do not match the "
7255 + "previously installed version; ignoring!");
7259 // Check for shared user signatures
7260 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7261 // Already existing package. Make sure signatures match
7262 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7263 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7265 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7266 == PackageManager.SIGNATURE_MATCH;
7269 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7270 == PackageManager.SIGNATURE_MATCH;
7273 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7274 "Package " + pkg.packageName
7275 + " has no signatures that match those in shared user "
7276 + pkgSetting.sharedUser.name + "; ignoring!");
7282 * Enforces that only the system UID or root's UID can call a method exposed
7285 * @param message used as message if SecurityException is thrown
7286 * @throws SecurityException if the caller is not system or root
7288 private static final void enforceSystemOrRoot(String message) {
7289 final int uid = Binder.getCallingUid();
7290 if (uid != Process.SYSTEM_UID && uid != 0) {
7291 throw new SecurityException(message);
7296 public void performFstrimIfNeeded() {
7297 enforceSystemOrRoot("Only the system can request fstrim");
7299 // Before everything else, see whether we need to fstrim.
7301 IMountService ms = PackageHelper.getMountService();
7303 boolean doTrim = false;
7304 final long interval = android.provider.Settings.Global.getLong(
7305 mContext.getContentResolver(),
7306 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7307 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7309 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7310 if (timeSinceLast > interval) {
7312 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7313 + "; running immediately");
7317 final boolean dexOptDialogShown;
7318 synchronized (mPackages) {
7319 dexOptDialogShown = mDexOptDialogShown;
7321 if (!isFirstBoot() && dexOptDialogShown) {
7323 ActivityManagerNative.getDefault().showBootMessage(
7324 mContext.getResources().getString(
7325 R.string.android_upgrading_fstrim), true);
7326 } catch (RemoteException e) {
7329 ms.runMaintenance();
7332 Slog.e(TAG, "Mount service unavailable!");
7334 } catch (RemoteException e) {
7335 // Can't happen; MountService is local
7340 public void updatePackagesIfNeeded() {
7341 enforceSystemOrRoot("Only the system can request package update");
7343 // We need to re-extract after an OTA.
7344 boolean causeUpgrade = isUpgrade();
7346 // First boot or factory reset.
7347 // Note: we also handle devices that are upgrading to N right now as if it is their
7348 // first boot, as they do not have profile data.
7349 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7351 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7352 boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7354 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7358 List<PackageParser.Package> pkgs;
7359 synchronized (mPackages) {
7360 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7363 final long startTime = System.nanoTime();
7364 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7365 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7367 final int elapsedTimeSeconds =
7368 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7370 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7371 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7372 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7373 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7374 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7378 * Performs dexopt on the set of packages in {@code packages} and returns an int array
7379 * containing statistics about the invocation. The array consists of three elements,
7380 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7381 * and {@code numberOfPackagesFailed}.
7383 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7384 String compilerFilter) {
7386 int numberOfPackagesVisited = 0;
7387 int numberOfPackagesOptimized = 0;
7388 int numberOfPackagesSkipped = 0;
7389 int numberOfPackagesFailed = 0;
7390 final int numberOfPackagesToDexopt = pkgs.size();
7392 for (PackageParser.Package pkg : pkgs) {
7393 numberOfPackagesVisited++;
7395 if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7397 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7399 numberOfPackagesSkipped++;
7404 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7405 numberOfPackagesToDexopt + ": " + pkg.packageName);
7410 ActivityManagerNative.getDefault().showBootMessage(
7411 mContext.getResources().getString(R.string.android_upgrading_apk,
7412 numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7413 } catch (RemoteException e) {
7415 synchronized (mPackages) {
7416 mDexOptDialogShown = true;
7420 // If the OTA updates a system app which was previously preopted to a non-preopted state
7421 // the app might end up being verified at runtime. That's because by default the apps
7422 // are verify-profile but for preopted apps there's no profile.
7423 // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7424 // that before the OTA the app was preopted) the app gets compiled with a non-profile
7425 // filter (by default interpret-only).
7426 // Note that at this stage unused apps are already filtered.
7427 if (isSystemApp(pkg) &&
7428 DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7429 !Environment.getReferenceProfile(pkg.packageName).exists()) {
7430 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7433 // checkProfiles is false to avoid merging profiles during boot which
7434 // might interfere with background compilation (b/28612421).
7435 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7436 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7437 // trade-off worth doing to save boot time work.
7438 int dexOptStatus = performDexOptTraced(pkg.packageName,
7439 false /* checkProfiles */,
7442 switch (dexOptStatus) {
7443 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7444 numberOfPackagesOptimized++;
7446 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7447 numberOfPackagesSkipped++;
7449 case PackageDexOptimizer.DEX_OPT_FAILED:
7450 numberOfPackagesFailed++;
7453 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7458 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7459 numberOfPackagesFailed };
7463 public void notifyPackageUse(String packageName, int reason) {
7464 synchronized (mPackages) {
7465 PackageParser.Package p = mPackages.get(packageName);
7469 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7473 // TODO: this is not used nor needed. Delete it.
7475 public boolean performDexOptIfNeeded(String packageName) {
7476 int dexOptStatus = performDexOptTraced(packageName,
7477 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7478 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7482 public boolean performDexOpt(String packageName,
7483 boolean checkProfiles, int compileReason, boolean force) {
7484 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7485 getCompilerFilterForReason(compileReason), force);
7486 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7490 public boolean performDexOptMode(String packageName,
7491 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7492 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7493 targetCompilerFilter, force);
7494 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7497 private int performDexOptTraced(String packageName,
7498 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7501 return performDexOptInternal(packageName, checkProfiles,
7502 targetCompilerFilter, force);
7504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7508 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7509 // if the package can now be considered up to date for the given filter.
7510 private int performDexOptInternal(String packageName,
7511 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7512 PackageParser.Package p;
7513 synchronized (mPackages) {
7514 p = mPackages.get(packageName);
7516 // Package could not be found. Report failure.
7517 return PackageDexOptimizer.DEX_OPT_FAILED;
7519 mPackageUsage.maybeWriteAsync(mPackages);
7520 mCompilerStats.maybeWriteAsync();
7522 long callingId = Binder.clearCallingIdentity();
7524 synchronized (mInstallLock) {
7525 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7526 targetCompilerFilter, force);
7529 Binder.restoreCallingIdentity(callingId);
7533 public ArraySet<String> getOptimizablePackages() {
7534 ArraySet<String> pkgs = new ArraySet<String>();
7535 synchronized (mPackages) {
7536 for (PackageParser.Package p : mPackages.values()) {
7537 if (PackageDexOptimizer.canOptimizePackage(p)) {
7538 pkgs.add(p.packageName);
7545 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7546 boolean checkProfiles, String targetCompilerFilter,
7548 // Select the dex optimizer based on the force parameter.
7549 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7550 // allocate an object here.
7551 PackageDexOptimizer pdo = force
7552 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7553 : mPackageDexOptimizer;
7555 // Optimize all dependencies first. Note: we ignore the return value and march on
7557 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7558 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7559 if (!deps.isEmpty()) {
7560 for (PackageParser.Package depPackage : deps) {
7561 // TODO: Analyze and investigate if we (should) profile libraries.
7562 // Currently this will do a full compilation of the library by default.
7563 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7564 false /* checkProfiles */,
7565 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7566 getOrCreateCompilerPackageStats(depPackage));
7569 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7570 targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7573 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7574 if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7575 ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7576 Set<String> collectedNames = new HashSet<>();
7577 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7583 return Collections.emptyList();
7587 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7588 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7589 if (!collectedNames.contains(p.packageName)) {
7590 collectedNames.add(p.packageName);
7593 if (p.usesLibraries != null) {
7594 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7596 if (p.usesOptionalLibraries != null) {
7597 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7603 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7604 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7605 for (String libName : libs) {
7606 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7607 if (libPkg != null) {
7608 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7613 private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7614 synchronized (mPackages) {
7615 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7616 if (lib != null && lib.apk != null) {
7617 return mPackages.get(lib.apk);
7623 public void shutdown() {
7624 mPackageUsage.writeNow(mPackages);
7625 mCompilerStats.writeNow();
7629 public void dumpProfiles(String packageName) {
7630 PackageParser.Package pkg;
7631 synchronized (mPackages) {
7632 pkg = mPackages.get(packageName);
7634 throw new IllegalArgumentException("Unknown package: " + packageName);
7637 /* Only the shell, root, or the app user should be able to dump profiles. */
7638 int callingUid = Binder.getCallingUid();
7639 if (callingUid != Process.SHELL_UID &&
7640 callingUid != Process.ROOT_UID &&
7641 callingUid != pkg.applicationInfo.uid) {
7642 throw new SecurityException("dumpProfiles");
7645 synchronized (mInstallLock) {
7646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7647 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7649 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7650 String gid = Integer.toString(sharedGid);
7651 String codePaths = TextUtils.join(";", allCodePaths);
7652 mInstaller.dumpProfiles(gid, packageName, codePaths);
7653 } catch (InstallerException e) {
7654 Slog.w(TAG, "Failed to dump profiles", e);
7656 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7661 public void forceDexOpt(String packageName) {
7662 enforceSystemOrRoot("forceDexOpt");
7664 PackageParser.Package pkg;
7665 synchronized (mPackages) {
7666 pkg = mPackages.get(packageName);
7668 throw new IllegalArgumentException("Unknown package: " + packageName);
7672 synchronized (mInstallLock) {
7673 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7675 // Whoever is calling forceDexOpt wants a fully compiled package.
7676 // Don't use profiles since that may cause compilation to be skipped.
7677 final int res = performDexOptInternalWithDependenciesLI(pkg,
7678 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7681 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7682 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7683 throw new IllegalStateException("Failed to dexopt: " + res);
7688 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7689 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7690 Slog.w(TAG, "Unable to update from " + oldPkg.name
7691 + " to " + newPkg.packageName
7692 + ": old package not in system partition");
7694 } else if (mPackages.get(oldPkg.name) != null) {
7695 Slog.w(TAG, "Unable to update from " + oldPkg.name
7696 + " to " + newPkg.packageName
7697 + ": old package still exists");
7703 void removeCodePathLI(File codePath) {
7704 if (codePath.isDirectory()) {
7706 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7707 } catch (InstallerException e) {
7708 Slog.w(TAG, "Failed to remove code path", e);
7715 private int[] resolveUserIds(int userId) {
7716 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7719 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7721 Slog.wtf(TAG, "Package was null!", new Throwable());
7724 clearAppDataLeafLIF(pkg, userId, flags);
7725 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7726 for (int i = 0; i < childCount; i++) {
7727 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7731 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7732 final PackageSetting ps;
7733 synchronized (mPackages) {
7734 ps = mSettings.mPackages.get(pkg.packageName);
7736 for (int realUserId : resolveUserIds(userId)) {
7737 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7739 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7741 } catch (InstallerException e) {
7742 Slog.w(TAG, String.valueOf(e));
7747 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7749 Slog.wtf(TAG, "Package was null!", new Throwable());
7752 destroyAppDataLeafLIF(pkg, userId, flags);
7753 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7754 for (int i = 0; i < childCount; i++) {
7755 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7759 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7760 final PackageSetting ps;
7761 synchronized (mPackages) {
7762 ps = mSettings.mPackages.get(pkg.packageName);
7764 for (int realUserId : resolveUserIds(userId)) {
7765 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7767 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7769 } catch (InstallerException e) {
7770 Slog.w(TAG, String.valueOf(e));
7775 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7777 Slog.wtf(TAG, "Package was null!", new Throwable());
7780 destroyAppProfilesLeafLIF(pkg);
7781 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7782 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7783 for (int i = 0; i < childCount; i++) {
7784 destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7785 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7786 true /* removeBaseMarker */);
7790 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7791 boolean removeBaseMarker) {
7792 if (pkg.isForwardLocked()) {
7796 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7798 path = PackageManagerServiceUtils.realpath(new File(path));
7799 } catch (IOException e) {
7800 // TODO: Should we return early here ?
7801 Slog.w(TAG, "Failed to get canonical path", e);
7805 final String useMarker = path.replace('/', '@');
7806 for (int realUserId : resolveUserIds(userId)) {
7807 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7808 if (removeBaseMarker) {
7809 File foreignUseMark = new File(profileDir, useMarker);
7810 if (foreignUseMark.exists()) {
7811 if (!foreignUseMark.delete()) {
7812 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7818 File[] markers = profileDir.listFiles();
7819 if (markers != null) {
7820 final String searchString = "@" + pkg.packageName + "@";
7821 // We also delete all markers that contain the package name we're
7822 // uninstalling. These are associated with secondary dex-files belonging
7823 // to the package. Reconstructing the path of these dex files is messy
7825 for (File marker : markers) {
7826 if (marker.getName().indexOf(searchString) > 0) {
7827 if (!marker.delete()) {
7828 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7838 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7840 mInstaller.destroyAppProfiles(pkg.packageName);
7841 } catch (InstallerException e) {
7842 Slog.w(TAG, String.valueOf(e));
7846 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7848 Slog.wtf(TAG, "Package was null!", new Throwable());
7851 clearAppProfilesLeafLIF(pkg);
7852 // We don't remove the base foreign use marker when clearing profiles because
7853 // we will rename it when the app is updated. Unlike the actual profile contents,
7854 // the foreign use marker is good across installs.
7855 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7856 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7857 for (int i = 0; i < childCount; i++) {
7858 clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7862 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7864 mInstaller.clearAppProfiles(pkg.packageName);
7865 } catch (InstallerException e) {
7866 Slog.w(TAG, String.valueOf(e));
7870 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7871 long lastUpdateTime) {
7872 // Set parent install/update time
7873 PackageSetting ps = (PackageSetting) pkg.mExtras;
7875 ps.firstInstallTime = firstInstallTime;
7876 ps.lastUpdateTime = lastUpdateTime;
7878 // Set children install/update time
7879 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7880 for (int i = 0; i < childCount; i++) {
7881 PackageParser.Package childPkg = pkg.childPackages.get(i);
7882 ps = (PackageSetting) childPkg.mExtras;
7884 ps.firstInstallTime = firstInstallTime;
7885 ps.lastUpdateTime = lastUpdateTime;
7890 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7891 PackageParser.Package changingLib) {
7892 if (file.path != null) {
7893 usesLibraryFiles.add(file.path);
7896 PackageParser.Package p = mPackages.get(file.apk);
7897 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7898 // If we are doing this while in the middle of updating a library apk,
7899 // then we need to make sure to use that new apk for determining the
7900 // dependencies here. (We haven't yet finished committing the new apk
7901 // to the package manager state.)
7902 if (p == null || p.packageName.equals(changingLib.packageName)) {
7907 usesLibraryFiles.addAll(p.getAllCodePaths());
7911 private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7912 PackageParser.Package changingLib) throws PackageManagerException {
7913 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7914 final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7915 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7916 for (int i=0; i<N; i++) {
7917 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7919 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7920 "Package " + pkg.packageName + " requires unavailable shared library "
7921 + pkg.usesLibraries.get(i) + "; failing!");
7923 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7925 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7926 for (int i=0; i<N; i++) {
7927 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7929 Slog.w(TAG, "Package " + pkg.packageName
7930 + " desires unavailable shared library "
7931 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7933 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7936 N = usesLibraryFiles.size();
7938 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7940 pkg.usesLibraryFiles = null;
7945 private static boolean hasString(List<String> list, List<String> which) {
7949 for (int i=list.size()-1; i>=0; i--) {
7950 for (int j=which.size()-1; j>=0; j--) {
7951 if (which.get(j).equals(list.get(i))) {
7959 private void updateAllSharedLibrariesLPw() {
7960 for (PackageParser.Package pkg : mPackages.values()) {
7962 updateSharedLibrariesLPw(pkg, null);
7963 } catch (PackageManagerException e) {
7964 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7969 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7970 PackageParser.Package changingPkg) {
7971 ArrayList<PackageParser.Package> res = null;
7972 for (PackageParser.Package pkg : mPackages.values()) {
7973 if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7974 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7976 res = new ArrayList<PackageParser.Package>();
7980 updateSharedLibrariesLPw(pkg, changingPkg);
7981 } catch (PackageManagerException e) {
7982 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7990 * Derive the value of the {@code cpuAbiOverride} based on the provided
7991 * value and an optional stored value from the package settings.
7993 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7994 String cpuAbiOverride = null;
7996 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7997 cpuAbiOverride = null;
7998 } else if (abiOverride != null) {
7999 cpuAbiOverride = abiOverride;
8000 } else if (settings != null) {
8001 cpuAbiOverride = settings.cpuAbiOverrideString;
8004 return cpuAbiOverride;
8007 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8008 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8009 throws PackageManagerException {
8010 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8011 // If the package has children and this is the first dive in the function
8012 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8013 // whether all packages (parent and children) would be successfully scanned
8014 // before the actual scan since scanning mutates internal state and we want
8015 // to atomically install the package and its children.
8016 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8017 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8018 scanFlags |= SCAN_CHECK_ONLY;
8021 scanFlags &= ~SCAN_CHECK_ONLY;
8024 final PackageParser.Package scannedPkg;
8027 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8028 // Scan the children
8029 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8030 for (int i = 0; i < childCount; i++) {
8031 PackageParser.Package childPkg = pkg.childPackages.get(i);
8032 scanPackageLI(childPkg, policyFlags,
8033 scanFlags, currentTime, user);
8036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8039 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8040 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8046 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8047 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8048 boolean success = false;
8050 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8055 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8056 // DELETE_DATA_ON_FAILURES is only used by frozen paths
8057 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8058 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8059 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8065 * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8067 private static boolean apkHasCode(String fileName) {
8068 StrictJarFile jarFile = null;
8070 jarFile = new StrictJarFile(fileName,
8071 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8072 return jarFile.findEntry("classes.dex") != null;
8073 } catch (IOException ignore) {
8076 if (jarFile != null) {
8079 } catch (IOException ignore) {}
8085 * Enforces code policy for the package. This ensures that if an APK has
8086 * declared hasCode="true" in its manifest that the APK actually contains
8089 * @throws PackageManagerException If bytecode could not be found when it should exist
8091 private static void enforceCodePolicy(PackageParser.Package pkg)
8092 throws PackageManagerException {
8093 final boolean shouldHaveCode =
8094 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8095 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8096 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8097 "Package " + pkg.baseCodePath + " code is missing");
8100 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8101 for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8102 final boolean splitShouldHaveCode =
8103 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8104 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8105 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8106 "Package " + pkg.splitCodePaths[i] + " code is missing");
8112 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8113 final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8114 throws PackageManagerException {
8115 final File scanFile = new File(pkg.codePath);
8116 if (pkg.applicationInfo.getCodePath() == null ||
8117 pkg.applicationInfo.getResourcePath() == null) {
8118 // Bail out. The resource and code paths haven't been set.
8119 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8120 "Code and resource paths haven't been set correctly");
8124 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8125 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8126 if (pkg.applicationInfo.isDirectBootAware()) {
8127 // we're direct boot aware; set for all components
8128 for (PackageParser.Service s : pkg.services) {
8129 s.info.encryptionAware = s.info.directBootAware = true;
8131 for (PackageParser.Provider p : pkg.providers) {
8132 p.info.encryptionAware = p.info.directBootAware = true;
8134 for (PackageParser.Activity a : pkg.activities) {
8135 a.info.encryptionAware = a.info.directBootAware = true;
8137 for (PackageParser.Activity r : pkg.receivers) {
8138 r.info.encryptionAware = r.info.directBootAware = true;
8142 // Only allow system apps to be flagged as core apps.
8143 pkg.coreApp = false;
8144 // clear flags not applicable to regular apps
8145 pkg.applicationInfo.privateFlags &=
8146 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8147 pkg.applicationInfo.privateFlags &=
8148 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8150 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8152 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8153 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8156 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8157 enforceCodePolicy(pkg);
8160 if (mCustomResolverComponentName != null &&
8161 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8162 setUpCustomResolverActivity(pkg);
8165 if (pkg.packageName.equals("android")) {
8166 synchronized (mPackages) {
8167 if (mAndroidApplication != null) {
8168 Slog.w(TAG, "*************************************************");
8169 Slog.w(TAG, "Core android package being redefined. Skipping.");
8170 Slog.w(TAG, " file=" + scanFile);
8171 Slog.w(TAG, "*************************************************");
8172 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8173 "Core android package being redefined. Skipping.");
8176 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8177 // Set up information for our fall-back user intent resolution activity.
8178 mPlatformPackage = pkg;
8179 pkg.mVersionCode = mSdkVersion;
8180 mAndroidApplication = pkg.applicationInfo;
8182 if (!mResolverReplaced) {
8183 mResolveActivity.applicationInfo = mAndroidApplication;
8184 mResolveActivity.name = ResolverActivity.class.getName();
8185 mResolveActivity.packageName = mAndroidApplication.packageName;
8186 mResolveActivity.processName = "system:ui";
8187 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8188 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8189 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8190 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8191 mResolveActivity.exported = true;
8192 mResolveActivity.enabled = true;
8193 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8194 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8195 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8196 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8197 | ActivityInfo.CONFIG_ORIENTATION
8198 | ActivityInfo.CONFIG_KEYBOARD
8199 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8200 mResolveInfo.activityInfo = mResolveActivity;
8201 mResolveInfo.priority = 0;
8202 mResolveInfo.preferredOrder = 0;
8203 mResolveInfo.match = 0;
8204 mResolveComponentName = new ComponentName(
8205 mAndroidApplication.packageName, mResolveActivity.name);
8211 if (DEBUG_PACKAGE_SCANNING) {
8212 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8213 Log.d(TAG, "Scanning package " + pkg.packageName);
8216 final PackageParser.Package oldPkg;
8218 synchronized (mPackages) {
8219 if (mPackages.containsKey(pkg.packageName)
8220 || mSharedLibraries.containsKey(pkg.packageName)) {
8221 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8222 "Application package " + pkg.packageName
8223 + " already installed. Skipping duplicate.");
8226 final PackageSetting oldPkgSetting = mSettings.peekPackageLPr(pkg.packageName);
8227 if (oldPkgSetting == null) {
8230 oldPkg = oldPkgSetting.pkg;
8233 // If we're only installing presumed-existing packages, require that the
8234 // scanned APK is both already known and at the path previously established
8235 // for it. Previously unknown packages we pick up normally, but if we have an
8236 // a priori expectation about this package's install presence, enforce it.
8237 // With a singular exception for new system packages. When an OTA contains
8238 // a new system package, we allow the codepath to change from a system location
8239 // to the user-installed location. If we don't allow this change, any newer,
8240 // user-installed version of the application will be ignored.
8241 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8242 if (mExpectingBetter.containsKey(pkg.packageName)) {
8243 logCriticalInfo(Log.WARN,
8244 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8246 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8247 if (known != null) {
8248 if (DEBUG_PACKAGE_SCANNING) {
8249 Log.d(TAG, "Examining " + pkg.codePath
8250 + " and requiring known paths " + known.codePathString
8251 + " & " + known.resourcePathString);
8253 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8254 || !pkg.applicationInfo.getResourcePath().equals(
8255 known.resourcePathString)) {
8256 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8257 "Application package " + pkg.packageName
8258 + " found at " + pkg.applicationInfo.getCodePath()
8259 + " but expected at " + known.codePathString
8267 // Initialize package source and resource directories
8268 File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8269 File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8271 SharedUserSetting suid = null;
8272 PackageSetting pkgSetting = null;
8274 if (!isSystemApp(pkg)) {
8275 // Only system apps can use these features.
8276 pkg.mOriginalPackages = null;
8277 pkg.mRealPackage = null;
8278 pkg.mAdoptPermissions = null;
8281 // Getting the package setting may have a side-effect, so if we
8282 // are only checking if scan would succeed, stash a copy of the
8283 // old setting to restore at the end.
8284 PackageSetting nonMutatedPs = null;
8287 synchronized (mPackages) {
8288 if (pkg.mSharedUserId != null) {
8289 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8291 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8292 "Creating application package " + pkg.packageName
8293 + " for shared user failed");
8295 if (DEBUG_PACKAGE_SCANNING) {
8296 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8297 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8298 + "): packages=" + suid.packages);
8302 // Check if we are renaming from an original package name.
8303 PackageSetting origPackage = null;
8304 String realName = null;
8305 if (pkg.mOriginalPackages != null) {
8306 // This package may need to be renamed to a previously
8307 // installed name. Let's check on that...
8308 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8309 if (pkg.mOriginalPackages.contains(renamed)) {
8310 // This package had originally been installed as the
8311 // original name, and we have already taken care of
8312 // transitioning to the new one. Just update the new
8313 // one to continue using the old name.
8314 realName = pkg.mRealPackage;
8315 if (!pkg.packageName.equals(renamed)) {
8316 // Callers into this function may have already taken
8317 // care of renaming the package; only do it here if
8318 // it is not already done.
8319 pkg.setPackageName(renamed);
8323 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8324 if ((origPackage = mSettings.peekPackageLPr(
8325 pkg.mOriginalPackages.get(i))) != null) {
8326 // We do have the package already installed under its
8327 // original name... should we use it?
8328 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8329 // New package is not compatible with original.
8332 } else if (origPackage.sharedUser != null) {
8333 // Make sure uid is compatible between packages.
8334 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8335 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8336 + " to " + pkg.packageName + ": old uid "
8337 + origPackage.sharedUser.name
8338 + " differs from " + pkg.mSharedUserId);
8342 // TODO: Add case when shared user id is added [b/28144775]
8344 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8345 + pkg.packageName + " to old name " + origPackage.name);
8353 if (mTransferedPackages.contains(pkg.packageName)) {
8354 Slog.w(TAG, "Package " + pkg.packageName
8355 + " was transferred to another, but its .apk remains");
8358 // See comments in nonMutatedPs declaration
8359 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8360 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8361 if (foundPs != null) {
8362 nonMutatedPs = new PackageSetting(foundPs);
8366 // Just create the setting, don't add it yet. For already existing packages
8367 // the PkgSetting exists already and doesn't have to be created.
8368 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8369 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8370 pkg.applicationInfo.primaryCpuAbi,
8371 pkg.applicationInfo.secondaryCpuAbi,
8372 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8374 if (pkgSetting == null) {
8375 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8376 "Creating application package " + pkg.packageName + " failed");
8379 if (pkgSetting.origPackage != null) {
8380 // If we are first transitioning from an original package,
8381 // fix up the new package's name now. We need to do this after
8382 // looking up the package under its new name, so getPackageLP
8383 // can take care of fiddling things correctly.
8384 pkg.setPackageName(origPackage.name);
8386 // File a report about this.
8387 String msg = "New package " + pkgSetting.realName
8388 + " renamed to replace old package " + pkgSetting.name;
8389 reportSettingsProblem(Log.WARN, msg);
8391 // Make a note of it.
8392 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8393 mTransferedPackages.add(origPackage.name);
8396 // No longer need to retain this.
8397 pkgSetting.origPackage = null;
8400 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8401 // Make a note of it.
8402 mTransferedPackages.add(pkg.packageName);
8405 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8406 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8409 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8410 // Check all shared libraries and map to their actual file path.
8411 // We only do this here for apps not on a system dir, because those
8412 // are the only ones that can fail an install due to this. We
8413 // will take care of the system apps by updating all of their
8414 // library paths after the scan is done.
8415 updateSharedLibrariesLPw(pkg, null);
8418 if (mFoundPolicyFile) {
8419 SELinuxMMAC.assignSeinfoValue(pkg);
8422 pkg.applicationInfo.uid = pkgSetting.appId;
8423 pkg.mExtras = pkgSetting;
8424 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8425 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8426 // We just determined the app is signed correctly, so bring
8427 // over the latest parsed certs.
8428 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8430 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8431 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8432 "Package " + pkg.packageName + " upgrade keys do not match the "
8433 + "previously installed version");
8435 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8436 String msg = "System package " + pkg.packageName
8437 + " signature changed; retaining data.";
8438 reportSettingsProblem(Log.WARN, msg);
8443 verifySignaturesLP(pkgSetting, pkg);
8444 // We just determined the app is signed correctly, so bring
8445 // over the latest parsed certs.
8446 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8447 } catch (PackageManagerException e) {
8448 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8451 // The signature has changed, but this package is in the system
8452 // image... let's recover!
8453 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8454 // However... if this package is part of a shared user, but it
8455 // doesn't match the signature of the shared user, let's fail.
8456 // What this means is that you can't change the signatures
8457 // associated with an overall shared user, which doesn't seem all
8458 // that unreasonable.
8459 if (pkgSetting.sharedUser != null) {
8460 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8461 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8462 throw new PackageManagerException(
8463 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8464 "Signature mismatch for shared user: "
8465 + pkgSetting.sharedUser);
8468 // File a report about this.
8469 String msg = "System package " + pkg.packageName
8470 + " signature changed; retaining data.";
8471 reportSettingsProblem(Log.WARN, msg);
8474 // Verify that this new package doesn't have any content providers
8475 // that conflict with existing packages. Only do this if the
8476 // package isn't already installed, since we don't want to break
8477 // things that are installed.
8478 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8479 final int N = pkg.providers.size();
8481 for (i=0; i<N; i++) {
8482 PackageParser.Provider p = pkg.providers.get(i);
8483 if (p.info.authority != null) {
8484 String names[] = p.info.authority.split(";");
8485 for (int j = 0; j < names.length; j++) {
8486 if (mProvidersByAuthority.containsKey(names[j])) {
8487 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8488 final String otherPackageName =
8489 ((other != null && other.getComponentName() != null) ?
8490 other.getComponentName().getPackageName() : "?");
8491 throw new PackageManagerException(
8492 INSTALL_FAILED_CONFLICTING_PROVIDER,
8493 "Can't install because provider name " + names[j]
8494 + " (in package " + pkg.applicationInfo.packageName
8495 + ") is already used by " + otherPackageName);
8502 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8503 // This package wants to adopt ownership of permissions from
8505 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8506 final String origName = pkg.mAdoptPermissions.get(i);
8507 final PackageSetting orig = mSettings.peekPackageLPr(origName);
8509 if (verifyPackageUpdateLPr(orig, pkg)) {
8510 Slog.i(TAG, "Adopting permissions from " + origName + " to "
8512 mSettings.transferPermissionsLPw(origName, pkg.packageName);
8519 final String pkgName = pkg.packageName;
8521 final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8522 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8523 pkg.applicationInfo.processName = fixProcessName(
8524 pkg.applicationInfo.packageName,
8525 pkg.applicationInfo.processName,
8526 pkg.applicationInfo.uid);
8528 if (pkg != mPlatformPackage) {
8529 // Get all of our default paths setup
8530 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8533 final String path = scanFile.getPath();
8534 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8536 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8537 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8539 // Some system apps still use directory structure for native libraries
8540 // in which case we might end up not detecting abi solely based on apk
8541 // structure. Try to detect abi based on directory structure.
8542 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8543 pkg.applicationInfo.primaryCpuAbi == null) {
8544 setBundledAppAbisAndRoots(pkg, pkgSetting);
8545 setNativeLibraryPaths(pkg);
8549 if ((scanFlags & SCAN_MOVE) != 0) {
8550 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8551 // but we already have this packages package info in the PackageSetting. We just
8552 // use that and derive the native library path based on the new codepath.
8553 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8554 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8557 // Set native library paths again. For moves, the path will be updated based on the
8558 // ABIs we've determined above. For non-moves, the path will be updated based on the
8559 // ABIs we determined during compilation, but the path will depend on the final
8560 // package path (after the rename away from the stage path).
8561 setNativeLibraryPaths(pkg);
8564 // This is a special case for the "system" package, where the ABI is
8565 // dictated by the zygote configuration (and init.rc). We should keep track
8566 // of this ABI so that we can deal with "normal" applications that run under
8567 // the same UID correctly.
8568 if (mPlatformPackage == pkg) {
8569 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8570 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8573 // If there's a mismatch between the abi-override in the package setting
8574 // and the abiOverride specified for the install. Warn about this because we
8575 // would've already compiled the app without taking the package setting into
8577 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8578 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8579 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8580 " for package " + pkg.packageName);
8584 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8585 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8586 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8588 // Copy the derived override back to the parsed package, so that we can
8589 // update the package settings accordingly.
8590 pkg.cpuAbiOverride = cpuAbiOverride;
8592 if (DEBUG_ABI_SELECTION) {
8593 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8594 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8595 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8598 // Push the derived path down into PackageSettings so we know what to
8599 // clean up at uninstall time.
8600 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8602 if (DEBUG_ABI_SELECTION) {
8603 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8604 " primary=" + pkg.applicationInfo.primaryCpuAbi +
8605 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8608 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8609 // We don't do this here during boot because we can do it all
8610 // at once after scanning all existing packages.
8612 // We also do this *before* we perform dexopt on this package, so that
8613 // we can avoid redundant dexopts, and also to make sure we've got the
8614 // code and package path correct.
8615 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8616 pkg, true /* boot complete */);
8619 if (mFactoryTest && pkg.requestedPermissions.contains(
8620 android.Manifest.permission.FACTORY_TEST)) {
8621 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8624 if (isSystemApp(pkg)) {
8625 pkgSetting.isOrphaned = true;
8628 ArrayList<PackageParser.Package> clientLibPkgs = null;
8630 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8631 if (nonMutatedPs != null) {
8632 synchronized (mPackages) {
8633 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8639 // Only privileged apps and updated privileged apps can add child packages.
8640 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8641 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8642 throw new PackageManagerException("Only privileged apps and updated "
8643 + "privileged apps can add child packages. Ignoring package "
8646 final int childCount = pkg.childPackages.size();
8647 for (int i = 0; i < childCount; i++) {
8648 PackageParser.Package childPkg = pkg.childPackages.get(i);
8649 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8650 childPkg.packageName)) {
8651 throw new PackageManagerException("Cannot override a child package of "
8652 + "another disabled system app. Ignoring package " + pkg.packageName);
8658 synchronized (mPackages) {
8659 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8660 // Only system apps can add new shared libraries.
8661 if (pkg.libraryNames != null) {
8662 for (int i=0; i<pkg.libraryNames.size(); i++) {
8663 String name = pkg.libraryNames.get(i);
8664 boolean allowed = false;
8665 if (pkg.isUpdatedSystemApp()) {
8666 // New library entries can only be added through the
8667 // system image. This is important to get rid of a lot
8668 // of nasty edge cases: for example if we allowed a non-
8669 // system update of the app to add a library, then uninstalling
8670 // the update would make the library go away, and assumptions
8671 // we made such as through app install filtering would now
8672 // have allowed apps on the device which aren't compatible
8673 // with it. Better to just have the restriction here, be
8674 // conservative, and create many fewer cases that can negatively
8675 // impact the user experience.
8676 final PackageSetting sysPs = mSettings
8677 .getDisabledSystemPkgLPr(pkg.packageName);
8678 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8679 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8680 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8690 if (!mSharedLibraries.containsKey(name)) {
8691 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8692 } else if (!name.equals(pkg.packageName)) {
8693 Slog.w(TAG, "Package " + pkg.packageName + " library "
8694 + name + " already exists; skipping");
8697 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8698 + name + " that is not declared on system image; skipping");
8701 if ((scanFlags & SCAN_BOOTING) == 0) {
8702 // If we are not booting, we need to update any applications
8703 // that are clients of our shared library. If we are booting,
8704 // this will all be done once the scan is complete.
8705 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8711 if ((scanFlags & SCAN_BOOTING) != 0) {
8712 // No apps can run during boot scan, so they don't need to be frozen
8713 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8714 // Caller asked to not kill app, so it's probably not frozen
8715 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8716 // Caller asked us to ignore frozen check for some reason; they
8717 // probably didn't know the package name
8719 // We're doing major surgery on this package, so it better be frozen
8720 // right now to keep it from launching
8721 checkPackageFrozen(pkgName);
8724 // Also need to kill any apps that are dependent on the library.
8725 if (clientLibPkgs != null) {
8726 for (int i=0; i<clientLibPkgs.size(); i++) {
8727 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8728 killApplication(clientPkg.applicationInfo.packageName,
8729 clientPkg.applicationInfo.uid, "update lib");
8733 // Make sure we're not adding any bogus keyset info
8734 KeySetManagerService ksms = mSettings.mKeySetManagerService;
8735 ksms.assertScannedPackageValid(pkg);
8738 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8740 boolean createIdmapFailed = false;
8741 synchronized (mPackages) {
8742 // We don't expect installation to fail beyond this point
8744 if (pkgSetting.pkg != null) {
8745 // Note that |user| might be null during the initial boot scan. If a codePath
8746 // for an app has changed during a boot scan, it's due to an app update that's
8747 // part of the system partition and marker changes must be applied to all users.
8748 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8749 (user != null) ? user : UserHandle.ALL);
8752 // Add the new setting to mSettings
8753 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8754 // Add the new setting to mPackages
8755 mPackages.put(pkg.applicationInfo.packageName, pkg);
8756 // Make sure we don't accidentally delete its data.
8757 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8758 while (iter.hasNext()) {
8759 PackageCleanItem item = iter.next();
8760 if (pkgName.equals(item.packageName)) {
8765 // Take care of first install / last update times.
8766 if (currentTime != 0) {
8767 if (pkgSetting.firstInstallTime == 0) {
8768 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8769 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8770 pkgSetting.lastUpdateTime = currentTime;
8772 } else if (pkgSetting.firstInstallTime == 0) {
8773 // We need *something*. Take time time stamp of the file.
8774 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8775 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8776 if (scanFileTime != pkgSetting.timeStamp) {
8777 // A package on the system image has changed; consider this
8779 pkgSetting.lastUpdateTime = scanFileTime;
8783 // Add the package's KeySets to the global KeySetManagerService
8784 ksms.addScannedPackageLPw(pkg);
8786 int N = pkg.providers.size();
8787 StringBuilder r = null;
8789 for (i=0; i<N; i++) {
8790 PackageParser.Provider p = pkg.providers.get(i);
8791 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8792 p.info.processName, pkg.applicationInfo.uid);
8793 mProviders.addProvider(p);
8794 p.syncable = p.info.isSyncable;
8795 if (p.info.authority != null) {
8796 String names[] = p.info.authority.split(";");
8797 p.info.authority = null;
8798 for (int j = 0; j < names.length; j++) {
8799 if (j == 1 && p.syncable) {
8800 // We only want the first authority for a provider to possibly be
8801 // syncable, so if we already added this provider using a different
8802 // authority clear the syncable flag. We copy the provider before
8803 // changing it because the mProviders object contains a reference
8804 // to a provider that we don't want to change.
8805 // Only do this for the second authority since the resulting provider
8806 // object can be the same for all future authorities for this provider.
8807 p = new PackageParser.Provider(p);
8810 if (!mProvidersByAuthority.containsKey(names[j])) {
8811 mProvidersByAuthority.put(names[j], p);
8812 if (p.info.authority == null) {
8813 p.info.authority = names[j];
8815 p.info.authority = p.info.authority + ";" + names[j];
8817 if (DEBUG_PACKAGE_SCANNING) {
8818 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8819 Log.d(TAG, "Registered content provider: " + names[j]
8820 + ", className = " + p.info.name + ", isSyncable = "
8821 + p.info.isSyncable);
8824 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8825 Slog.w(TAG, "Skipping provider name " + names[j] +
8826 " (in package " + pkg.applicationInfo.packageName +
8827 "): name already used by "
8828 + ((other != null && other.getComponentName() != null)
8829 ? other.getComponentName().getPackageName() : "?"));
8833 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8835 r = new StringBuilder(256);
8839 r.append(p.info.name);
8843 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
8846 N = pkg.services.size();
8848 for (i=0; i<N; i++) {
8849 PackageParser.Service s = pkg.services.get(i);
8850 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8851 s.info.processName, pkg.applicationInfo.uid);
8852 mServices.addService(s);
8853 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8855 r = new StringBuilder(256);
8859 r.append(s.info.name);
8863 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
8866 N = pkg.receivers.size();
8868 for (i=0; i<N; i++) {
8869 PackageParser.Activity a = pkg.receivers.get(i);
8870 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8871 a.info.processName, pkg.applicationInfo.uid);
8872 mReceivers.addActivity(a, "receiver");
8873 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8875 r = new StringBuilder(256);
8879 r.append(a.info.name);
8883 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
8886 N = pkg.activities.size();
8888 for (i=0; i<N; i++) {
8889 PackageParser.Activity a = pkg.activities.get(i);
8890 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8891 a.info.processName, pkg.applicationInfo.uid);
8892 mActivities.addActivity(a, "activity");
8893 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8895 r = new StringBuilder(256);
8899 r.append(a.info.name);
8903 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
8906 N = pkg.permissionGroups.size();
8908 for (i=0; i<N; i++) {
8909 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8910 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8911 final String curPackageName = cur == null ? null : cur.info.packageName;
8912 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8913 if (cur == null || isPackageUpdate) {
8914 mPermissionGroups.put(pg.info.name, pg);
8915 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8917 r = new StringBuilder(256);
8921 if (isPackageUpdate) {
8924 r.append(pg.info.name);
8927 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8928 + pg.info.packageName + " ignored: original from "
8929 + cur.info.packageName);
8930 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8932 r = new StringBuilder(256);
8937 r.append(pg.info.name);
8942 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
8945 N = pkg.permissions.size();
8947 for (i=0; i<N; i++) {
8948 PackageParser.Permission p = pkg.permissions.get(i);
8950 // Assume by default that we did not install this permission into the system.
8951 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8953 // Now that permission groups have a special meaning, we ignore permission
8954 // groups for legacy apps to prevent unexpected behavior. In particular,
8955 // permissions for one app being granted to someone just becase they happen
8956 // to be in a group defined by another app (before this had no implications).
8957 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8958 p.group = mPermissionGroups.get(p.info.group);
8959 // Warn for a permission in an unknown group.
8960 if (p.info.group != null && p.group == null) {
8961 Slog.w(TAG, "Permission " + p.info.name + " from package "
8962 + p.info.packageName + " in an unknown group " + p.info.group);
8966 ArrayMap<String, BasePermission> permissionMap =
8967 p.tree ? mSettings.mPermissionTrees
8968 : mSettings.mPermissions;
8969 BasePermission bp = permissionMap.get(p.info.name);
8971 // Allow system apps to redefine non-system permissions
8972 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8973 final boolean currentOwnerIsSystem = (bp.perm != null
8974 && isSystemApp(bp.perm.owner));
8975 if (isSystemApp(p.owner)) {
8976 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8977 // It's a built-in permission and no owner, take ownership now
8978 bp.packageSetting = pkgSetting;
8980 bp.uid = pkg.applicationInfo.uid;
8981 bp.sourcePackage = p.info.packageName;
8982 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8983 } else if (!currentOwnerIsSystem) {
8984 String msg = "New decl " + p.owner + " of permission "
8985 + p.info.name + " is system; overriding " + bp.sourcePackage;
8986 reportSettingsProblem(Log.WARN, msg);
8993 bp = new BasePermission(p.info.name, p.info.packageName,
8994 BasePermission.TYPE_NORMAL);
8995 permissionMap.put(p.info.name, bp);
8998 if (bp.perm == null) {
8999 if (bp.sourcePackage == null
9000 || bp.sourcePackage.equals(p.info.packageName)) {
9001 BasePermission tree = findPermissionTreeLP(p.info.name);
9003 || tree.sourcePackage.equals(p.info.packageName)) {
9004 bp.packageSetting = pkgSetting;
9006 bp.uid = pkg.applicationInfo.uid;
9007 bp.sourcePackage = p.info.packageName;
9008 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9009 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9011 r = new StringBuilder(256);
9015 r.append(p.info.name);
9018 Slog.w(TAG, "Permission " + p.info.name + " from package "
9019 + p.info.packageName + " ignored: base tree "
9020 + tree.name + " is from package "
9021 + tree.sourcePackage);
9024 Slog.w(TAG, "Permission " + p.info.name + " from package "
9025 + p.info.packageName + " ignored: original from "
9026 + bp.sourcePackage);
9028 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9030 r = new StringBuilder(256);
9035 r.append(p.info.name);
9038 bp.protectionLevel = p.info.protectionLevel;
9043 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
9046 N = pkg.instrumentation.size();
9048 for (i=0; i<N; i++) {
9049 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9050 a.info.packageName = pkg.applicationInfo.packageName;
9051 a.info.sourceDir = pkg.applicationInfo.sourceDir;
9052 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9053 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9054 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9055 a.info.dataDir = pkg.applicationInfo.dataDir;
9056 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9057 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9059 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9060 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9061 mInstrumentation.put(a.getComponentName(), a);
9062 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9064 r = new StringBuilder(256);
9068 r.append(a.info.name);
9072 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
9075 if (pkg.protectedBroadcasts != null) {
9076 N = pkg.protectedBroadcasts.size();
9077 for (i=0; i<N; i++) {
9078 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9082 pkgSetting.setTimeStamp(scanFileTime);
9084 // Create idmap files for pairs of (packages, overlay packages).
9085 // Note: "android", ie framework-res.apk, is handled by native layers.
9086 if (pkg.mOverlayTarget != null) {
9087 // This is an overlay package.
9088 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9089 if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9090 mOverlays.put(pkg.mOverlayTarget,
9091 new ArrayMap<String, PackageParser.Package>());
9093 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9094 map.put(pkg.packageName, pkg);
9095 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9096 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9097 createIdmapFailed = true;
9100 } else if (mOverlays.containsKey(pkg.packageName) &&
9101 !pkg.packageName.equals("android")) {
9102 // This is a regular package, with one or more known overlay packages.
9103 createIdmapsForPackageLI(pkg);
9106 if (oldPkg != null) {
9107 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
9108 // revokation from this method might need to kill apps which need the
9109 // mPackages lock on a different thread. This would dead lock.
9111 // Hence create a copy of all package names and pass it into
9112 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
9113 // revoked. If a new package is added before the async code runs the permission
9114 // won't be granted yet, hence new packages are no problem.
9115 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
9117 AsyncTask.execute(new Runnable() {
9119 revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg, allPackageNames);
9125 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9127 if (createIdmapFailed) {
9128 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9129 "scanPackageLI failed to createIdmap");
9134 private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9135 PackageParser.Package update, UserHandle user) {
9136 if (existing.applicationInfo == null || update.applicationInfo == null) {
9137 // This isn't due to an app installation.
9141 final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9142 final File newCodePath = new File(update.applicationInfo.getCodePath());
9144 // The codePath hasn't changed, so there's nothing for us to do.
9145 if (Objects.equals(oldCodePath, newCodePath)) {
9149 File canonicalNewCodePath;
9151 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9152 } catch (IOException e) {
9153 Slog.w(TAG, "Failed to get canonical path.", e);
9157 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9158 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9159 // that the last component of the path (i.e, the name) doesn't need canonicalization
9160 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9161 // but may change in the future. Hopefully this function won't exist at that point.
9162 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9163 oldCodePath.getName());
9165 // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9167 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9168 if (!oldMarkerPrefix.endsWith("@")) {
9169 oldMarkerPrefix += "@";
9171 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9172 if (!newMarkerPrefix.endsWith("@")) {
9173 newMarkerPrefix += "@";
9176 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9177 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9178 for (String updatedPath : updatedPaths) {
9179 String updatedPathName = new File(updatedPath).getName();
9180 markerSuffixes.add(updatedPathName.replace('/', '@'));
9183 for (int userId : resolveUserIds(user.getIdentifier())) {
9184 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9186 for (String markerSuffix : markerSuffixes) {
9187 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9188 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9189 if (oldForeignUseMark.exists()) {
9191 Os.rename(oldForeignUseMark.getAbsolutePath(),
9192 newForeignUseMark.getAbsolutePath());
9193 } catch (ErrnoException e) {
9194 Slog.w(TAG, "Failed to rename foreign use marker", e);
9195 oldForeignUseMark.delete();
9203 * Derive the ABI of a non-system package located at {@code scanFile}. This information
9204 * is derived purely on the basis of the contents of {@code scanFile} and
9205 * {@code cpuAbiOverride}.
9207 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9209 private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9210 String cpuAbiOverride, boolean extractLibs)
9211 throws PackageManagerException {
9212 // TODO: We can probably be smarter about this stuff. For installed apps,
9213 // we can calculate this information at install time once and for all. For
9214 // system apps, we can probably assume that this information doesn't change
9215 // after the first boot scan. As things stand, we do lots of unnecessary work.
9217 // Give ourselves some initial paths; we'll come back for another
9218 // pass once we've determined ABI below.
9219 setNativeLibraryPaths(pkg);
9221 // We would never need to extract libs for forward-locked and external packages,
9222 // since the container service will do it for us. We shouldn't attempt to
9223 // extract libs from system app when it was not updated.
9224 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9225 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9226 extractLibs = false;
9229 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9230 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9232 NativeLibraryHelper.Handle handle = null;
9234 handle = NativeLibraryHelper.Handle.create(pkg);
9235 // TODO(multiArch): This can be null for apps that didn't go through the
9236 // usual installation process. We can calculate it again, like we
9237 // do during install time.
9239 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9241 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9243 // Null out the abis so that they can be recalculated.
9244 pkg.applicationInfo.primaryCpuAbi = null;
9245 pkg.applicationInfo.secondaryCpuAbi = null;
9246 if (isMultiArch(pkg.applicationInfo)) {
9247 // Warn if we've set an abiOverride for multi-lib packages..
9248 // By definition, we need to copy both 32 and 64 bit libraries for
9250 if (pkg.cpuAbiOverride != null
9251 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9252 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9255 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9256 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9257 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9259 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9260 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9261 useIsaSpecificSubdirs);
9263 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9267 maybeThrowExceptionForMultiArchCopy(
9268 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9270 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9272 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9273 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9274 useIsaSpecificSubdirs);
9276 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9280 maybeThrowExceptionForMultiArchCopy(
9281 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9284 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9288 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9290 if (pkg.use32bitAbi) {
9291 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9292 pkg.applicationInfo.primaryCpuAbi = abi;
9294 pkg.applicationInfo.secondaryCpuAbi = abi;
9297 pkg.applicationInfo.primaryCpuAbi = abi;
9302 String[] abiList = (cpuAbiOverride != null) ?
9303 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9305 // Enable gross and lame hacks for apps that are built with old
9306 // SDK tools. We must scan their APKs for renderscript bitcode and
9307 // not launch them if it's present. Don't bother checking on devices
9308 // that don't have 64 bit support.
9309 boolean needsRenderScriptOverride = false;
9310 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9311 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9312 abiList = Build.SUPPORTED_32_BIT_ABIS;
9313 needsRenderScriptOverride = true;
9318 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9319 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9321 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9324 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9325 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9326 "Error unpackaging native libs for app, errorCode=" + copyRet);
9330 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9331 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9332 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9333 } else if (needsRenderScriptOverride) {
9334 pkg.applicationInfo.primaryCpuAbi = abiList[0];
9337 } catch (IOException ioe) {
9338 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9340 IoUtils.closeQuietly(handle);
9343 // Now that we've calculated the ABIs and determined if it's an internal app,
9344 // we will go ahead and populate the nativeLibraryPath.
9345 setNativeLibraryPaths(pkg);
9349 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9350 * i.e, so that all packages can be run inside a single process if required.
9352 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9353 * this function will either try and make the ABI for all packages in {@code packagesForUser}
9354 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9355 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9356 * updating a package that belongs to a shared user.
9358 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9359 * adds unnecessary complexity.
9361 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9362 PackageParser.Package scannedPackage, boolean bootComplete) {
9363 String requiredInstructionSet = null;
9364 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9365 requiredInstructionSet = VMRuntime.getInstructionSet(
9366 scannedPackage.applicationInfo.primaryCpuAbi);
9369 PackageSetting requirer = null;
9370 for (PackageSetting ps : packagesForUser) {
9371 // If packagesForUser contains scannedPackage, we skip it. This will happen
9372 // when scannedPackage is an update of an existing package. Without this check,
9373 // we will never be able to change the ABI of any package belonging to a shared
9374 // user, even if it's compatible with other packages.
9375 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9376 if (ps.primaryCpuAbiString == null) {
9380 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9381 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9382 // We have a mismatch between instruction sets (say arm vs arm64) warn about
9383 // this but there's not much we can do.
9384 String errorMessage = "Instruction set mismatch, "
9385 + ((requirer == null) ? "[caller]" : requirer)
9386 + " requires " + requiredInstructionSet + " whereas " + ps
9387 + " requires " + instructionSet;
9388 Slog.w(TAG, errorMessage);
9391 if (requiredInstructionSet == null) {
9392 requiredInstructionSet = instructionSet;
9398 if (requiredInstructionSet != null) {
9400 if (requirer != null) {
9401 // requirer != null implies that either scannedPackage was null or that scannedPackage
9402 // did not require an ABI, in which case we have to adjust scannedPackage to match
9403 // the ABI of the set (which is the same as requirer's ABI)
9404 adjustedAbi = requirer.primaryCpuAbiString;
9405 if (scannedPackage != null) {
9406 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9409 // requirer == null implies that we're updating all ABIs in the set to
9410 // match scannedPackage.
9411 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
9414 for (PackageSetting ps : packagesForUser) {
9415 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9416 if (ps.primaryCpuAbiString != null) {
9420 ps.primaryCpuAbiString = adjustedAbi;
9421 if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9422 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9423 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9424 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9426 + (requirer == null ? "null" : requirer.pkg.packageName)
9427 + ", scannedPackage="
9428 + (scannedPackage != null ? scannedPackage.packageName : "null")
9431 mInstaller.rmdex(ps.codePathString,
9432 getDexCodeInstructionSet(getPreferredInstructionSet()));
9433 } catch (InstallerException ignored) {
9441 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9442 synchronized (mPackages) {
9443 mResolverReplaced = true;
9444 // Set up information for custom user intent resolution activity.
9445 mResolveActivity.applicationInfo = pkg.applicationInfo;
9446 mResolveActivity.name = mCustomResolverComponentName.getClassName();
9447 mResolveActivity.packageName = pkg.applicationInfo.packageName;
9448 mResolveActivity.processName = pkg.applicationInfo.packageName;
9449 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9450 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9451 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9452 mResolveActivity.theme = 0;
9453 mResolveActivity.exported = true;
9454 mResolveActivity.enabled = true;
9455 mResolveInfo.activityInfo = mResolveActivity;
9456 mResolveInfo.priority = 0;
9457 mResolveInfo.preferredOrder = 0;
9458 mResolveInfo.match = 0;
9459 mResolveComponentName = mCustomResolverComponentName;
9460 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9461 mResolveComponentName);
9465 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9466 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9468 // Set up information for ephemeral installer activity
9469 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9470 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9471 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9472 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9473 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9474 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9475 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9476 mEphemeralInstallerActivity.theme = 0;
9477 mEphemeralInstallerActivity.exported = true;
9478 mEphemeralInstallerActivity.enabled = true;
9479 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9480 mEphemeralInstallerInfo.priority = 0;
9481 mEphemeralInstallerInfo.preferredOrder = 1;
9482 mEphemeralInstallerInfo.isDefault = true;
9483 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9484 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9486 if (DEBUG_EPHEMERAL) {
9487 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9491 private static String calculateBundledApkRoot(final String codePathString) {
9492 final File codePath = new File(codePathString);
9493 final File codeRoot;
9494 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9495 codeRoot = Environment.getRootDirectory();
9496 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9497 codeRoot = Environment.getOemDirectory();
9498 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9499 codeRoot = Environment.getVendorDirectory();
9501 // Unrecognized code path; take its top real segment as the apk root:
9502 // e.g. /something/app/blah.apk => /something
9504 File f = codePath.getCanonicalFile();
9505 File parent = f.getParentFile(); // non-null because codePath is a file
9507 while ((tmp = parent.getParentFile()) != null) {
9512 Slog.w(TAG, "Unrecognized code path "
9513 + codePath + " - using " + codeRoot);
9514 } catch (IOException e) {
9515 // Can't canonicalize the code path -- shenanigans?
9516 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9517 return Environment.getRootDirectory().getPath();
9520 return codeRoot.getPath();
9524 * Derive and set the location of native libraries for the given package,
9525 * which varies depending on where and how the package was installed.
9527 private void setNativeLibraryPaths(PackageParser.Package pkg) {
9528 final ApplicationInfo info = pkg.applicationInfo;
9529 final String codePath = pkg.codePath;
9530 final File codeFile = new File(codePath);
9531 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9532 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9534 info.nativeLibraryRootDir = null;
9535 info.nativeLibraryRootRequiresIsa = false;
9536 info.nativeLibraryDir = null;
9537 info.secondaryNativeLibraryDir = null;
9539 if (isApkFile(codeFile)) {
9540 // Monolithic install
9542 // If "/system/lib64/apkname" exists, assume that is the per-package
9543 // native library directory to use; otherwise use "/system/lib/apkname".
9544 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9545 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9546 getPrimaryInstructionSet(info));
9548 // This is a bundled system app so choose the path based on the ABI.
9549 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9550 // is just the default path.
9551 final String apkName = deriveCodePathName(codePath);
9552 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9553 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9554 apkName).getAbsolutePath();
9556 if (info.secondaryCpuAbi != null) {
9557 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9558 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9559 secondaryLibDir, apkName).getAbsolutePath();
9561 } else if (asecApp) {
9562 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9565 final String apkName = deriveCodePathName(codePath);
9566 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9570 info.nativeLibraryRootRequiresIsa = false;
9571 info.nativeLibraryDir = info.nativeLibraryRootDir;
9574 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9575 info.nativeLibraryRootRequiresIsa = true;
9577 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9578 getPrimaryInstructionSet(info)).getAbsolutePath();
9580 if (info.secondaryCpuAbi != null) {
9581 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9582 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9588 * Calculate the abis and roots for a bundled app. These can uniquely
9589 * be determined from the contents of the system partition, i.e whether
9590 * it contains 64 or 32 bit shared libraries etc. We do not validate any
9591 * of this information, and instead assume that the system was built
9594 private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9595 PackageSetting pkgSetting) {
9596 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9598 // If "/system/lib64/apkname" exists, assume that is the per-package
9599 // native library directory to use; otherwise use "/system/lib/apkname".
9600 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9601 setBundledAppAbi(pkg, apkRoot, apkName);
9602 // pkgSetting might be null during rescan following uninstall of updates
9603 // to a bundled app, so accommodate that possibility. The settings in
9604 // that case will be established later from the parsed package.
9606 // If the settings aren't null, sync them up with what we've just derived.
9607 // note that apkRoot isn't stored in the package settings.
9608 if (pkgSetting != null) {
9609 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9610 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9615 * Deduces the ABI of a bundled app and sets the relevant fields on the
9616 * parsed pkg object.
9618 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9619 * under which system libraries are installed.
9620 * @param apkName the name of the installed package.
9622 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9623 final File codeFile = new File(pkg.codePath);
9625 final boolean has64BitLibs;
9626 final boolean has32BitLibs;
9627 if (isApkFile(codeFile)) {
9628 // Monolithic install
9629 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9630 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9633 final File rootDir = new File(codeFile, LIB_DIR_NAME);
9634 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9635 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9636 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9637 has64BitLibs = (new File(rootDir, isa)).exists();
9639 has64BitLibs = false;
9641 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9642 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9643 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9644 has32BitLibs = (new File(rootDir, isa)).exists();
9646 has32BitLibs = false;
9650 if (has64BitLibs && !has32BitLibs) {
9651 // The package has 64 bit libs, but not 32 bit libs. Its primary
9652 // ABI should be 64 bit. We can safely assume here that the bundled
9653 // native libraries correspond to the most preferred ABI in the list.
9655 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9656 pkg.applicationInfo.secondaryCpuAbi = null;
9657 } else if (has32BitLibs && !has64BitLibs) {
9658 // The package has 32 bit libs but not 64 bit libs. Its primary
9659 // ABI should be 32 bit.
9661 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9662 pkg.applicationInfo.secondaryCpuAbi = null;
9663 } else if (has32BitLibs && has64BitLibs) {
9664 // The application has both 64 and 32 bit bundled libraries. We check
9665 // here that the app declares multiArch support, and warn if it doesn't.
9667 // We will be lenient here and record both ABIs. The primary will be the
9668 // ABI that's higher on the list, i.e, a device that's configured to prefer
9669 // 64 bit apps will see a 64 bit primary ABI,
9671 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9672 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9675 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9676 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9677 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9679 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9680 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9683 pkg.applicationInfo.primaryCpuAbi = null;
9684 pkg.applicationInfo.secondaryCpuAbi = null;
9688 private void killApplication(String pkgName, int appId, String reason) {
9689 killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9692 private void killApplication(String pkgName, int appId, int userId, String reason) {
9693 // Request the ActivityManager to kill the process(only for existing packages)
9694 // so that we do not end up in a confused state while the user is still using the older
9695 // version of the application while the new one gets installed.
9696 final long token = Binder.clearCallingIdentity();
9698 IActivityManager am = ActivityManagerNative.getDefault();
9701 am.killApplication(pkgName, appId, userId, reason);
9702 } catch (RemoteException e) {
9706 Binder.restoreCallingIdentity(token);
9710 private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9711 // Remove the parent package setting
9712 PackageSetting ps = (PackageSetting) pkg.mExtras;
9714 removePackageLI(ps, chatty);
9716 // Remove the child package setting
9717 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9718 for (int i = 0; i < childCount; i++) {
9719 PackageParser.Package childPkg = pkg.childPackages.get(i);
9720 ps = (PackageSetting) childPkg.mExtras;
9722 removePackageLI(ps, chatty);
9727 void removePackageLI(PackageSetting ps, boolean chatty) {
9728 if (DEBUG_INSTALL) {
9730 Log.d(TAG, "Removing package " + ps.name);
9734 synchronized (mPackages) {
9735 mPackages.remove(ps.name);
9736 final PackageParser.Package pkg = ps.pkg;
9738 cleanPackageDataStructuresLILPw(pkg, chatty);
9743 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9744 if (DEBUG_INSTALL) {
9746 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9750 synchronized (mPackages) {
9751 // Remove the parent package
9752 mPackages.remove(pkg.applicationInfo.packageName);
9753 cleanPackageDataStructuresLILPw(pkg, chatty);
9755 // Remove the child packages
9756 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9757 for (int i = 0; i < childCount; i++) {
9758 PackageParser.Package childPkg = pkg.childPackages.get(i);
9759 mPackages.remove(childPkg.applicationInfo.packageName);
9760 cleanPackageDataStructuresLILPw(childPkg, chatty);
9765 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9766 int N = pkg.providers.size();
9767 StringBuilder r = null;
9769 for (i=0; i<N; i++) {
9770 PackageParser.Provider p = pkg.providers.get(i);
9771 mProviders.removeProvider(p);
9772 if (p.info.authority == null) {
9774 /* There was another ContentProvider with this authority when
9775 * this app was installed so this authority is null,
9776 * Ignore it as we don't have to unregister the provider.
9780 String names[] = p.info.authority.split(";");
9781 for (int j = 0; j < names.length; j++) {
9782 if (mProvidersByAuthority.get(names[j]) == p) {
9783 mProvidersByAuthority.remove(names[j]);
9786 Log.d(TAG, "Unregistered content provider: " + names[j]
9787 + ", className = " + p.info.name + ", isSyncable = "
9788 + p.info.isSyncable);
9792 if (DEBUG_REMOVE && chatty) {
9794 r = new StringBuilder(256);
9798 r.append(p.info.name);
9802 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
9805 N = pkg.services.size();
9807 for (i=0; i<N; i++) {
9808 PackageParser.Service s = pkg.services.get(i);
9809 mServices.removeService(s);
9812 r = new StringBuilder(256);
9816 r.append(s.info.name);
9820 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
9823 N = pkg.receivers.size();
9825 for (i=0; i<N; i++) {
9826 PackageParser.Activity a = pkg.receivers.get(i);
9827 mReceivers.removeActivity(a, "receiver");
9828 if (DEBUG_REMOVE && chatty) {
9830 r = new StringBuilder(256);
9834 r.append(a.info.name);
9838 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
9841 N = pkg.activities.size();
9843 for (i=0; i<N; i++) {
9844 PackageParser.Activity a = pkg.activities.get(i);
9845 mActivities.removeActivity(a, "activity");
9846 if (DEBUG_REMOVE && chatty) {
9848 r = new StringBuilder(256);
9852 r.append(a.info.name);
9856 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
9859 N = pkg.permissions.size();
9861 for (i=0; i<N; i++) {
9862 PackageParser.Permission p = pkg.permissions.get(i);
9863 BasePermission bp = mSettings.mPermissions.get(p.info.name);
9865 bp = mSettings.mPermissionTrees.get(p.info.name);
9867 if (bp != null && bp.perm == p) {
9869 if (DEBUG_REMOVE && chatty) {
9871 r = new StringBuilder(256);
9875 r.append(p.info.name);
9878 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9879 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9880 if (appOpPkgs != null) {
9881 appOpPkgs.remove(pkg.packageName);
9886 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9889 N = pkg.requestedPermissions.size();
9891 for (i=0; i<N; i++) {
9892 String perm = pkg.requestedPermissions.get(i);
9893 BasePermission bp = mSettings.mPermissions.get(perm);
9894 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9895 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9896 if (appOpPkgs != null) {
9897 appOpPkgs.remove(pkg.packageName);
9898 if (appOpPkgs.isEmpty()) {
9899 mAppOpPermissionPackages.remove(perm);
9905 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9908 N = pkg.instrumentation.size();
9910 for (i=0; i<N; i++) {
9911 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9912 mInstrumentation.remove(a.getComponentName());
9913 if (DEBUG_REMOVE && chatty) {
9915 r = new StringBuilder(256);
9919 r.append(a.info.name);
9923 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
9927 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9928 // Only system apps can hold shared libraries.
9929 if (pkg.libraryNames != null) {
9930 for (i=0; i<pkg.libraryNames.size(); i++) {
9931 String name = pkg.libraryNames.get(i);
9932 SharedLibraryEntry cur = mSharedLibraries.get(name);
9933 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9934 mSharedLibraries.remove(name);
9935 if (DEBUG_REMOVE && chatty) {
9937 r = new StringBuilder(256);
9948 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
9952 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9953 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9954 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9961 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9962 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9963 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9965 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9966 // Update the parent permissions
9967 updatePermissionsLPw(pkg.packageName, pkg, flags);
9968 // Update the child permissions
9969 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9970 for (int i = 0; i < childCount; i++) {
9971 PackageParser.Package childPkg = pkg.childPackages.get(i);
9972 updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9976 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9978 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9979 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9982 private void updatePermissionsLPw(String changingPkg,
9983 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9984 // Make sure there are no dangling permission trees.
9985 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9986 while (it.hasNext()) {
9987 final BasePermission bp = it.next();
9988 if (bp.packageSetting == null) {
9989 // We may not yet have parsed the package, so just see if
9990 // we still know about its settings.
9991 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9993 if (bp.packageSetting == null) {
9994 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9995 + " from package " + bp.sourcePackage);
9997 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9998 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9999 Slog.i(TAG, "Removing old permission tree: " + bp.name
10000 + " from package " + bp.sourcePackage);
10001 flags |= UPDATE_PERMISSIONS_ALL;
10007 // Make sure all dynamic permissions have been assigned to a package,
10008 // and make sure there are no dangling permissions.
10009 it = mSettings.mPermissions.values().iterator();
10010 while (it.hasNext()) {
10011 final BasePermission bp = it.next();
10012 if (bp.type == BasePermission.TYPE_DYNAMIC) {
10013 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10014 + bp.name + " pkg=" + bp.sourcePackage
10015 + " info=" + bp.pendingInfo);
10016 if (bp.packageSetting == null && bp.pendingInfo != null) {
10017 final BasePermission tree = findPermissionTreeLP(bp.name);
10018 if (tree != null && tree.perm != null) {
10019 bp.packageSetting = tree.packageSetting;
10020 bp.perm = new PackageParser.Permission(tree.perm.owner,
10021 new PermissionInfo(bp.pendingInfo));
10022 bp.perm.info.packageName = tree.perm.info.packageName;
10023 bp.perm.info.name = bp.name;
10028 if (bp.packageSetting == null) {
10029 // We may not yet have parsed the package, so just see if
10030 // we still know about its settings.
10031 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10033 if (bp.packageSetting == null) {
10034 Slog.w(TAG, "Removing dangling permission: " + bp.name
10035 + " from package " + bp.sourcePackage);
10037 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10038 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10039 Slog.i(TAG, "Removing old permission: " + bp.name
10040 + " from package " + bp.sourcePackage);
10041 flags |= UPDATE_PERMISSIONS_ALL;
10047 // Now update the permissions for all packages, in particular
10048 // replace the granted permissions of the system packages.
10049 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10050 for (PackageParser.Package pkg : mPackages.values()) {
10051 if (pkg != pkgInfo) {
10052 // Only replace for packages on requested volume
10053 final String volumeUuid = getVolumeUuidForPackage(pkg);
10054 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10055 && Objects.equals(replaceVolumeUuid, volumeUuid);
10056 grantPermissionsLPw(pkg, replace, changingPkg);
10061 if (pkgInfo != null) {
10062 // Only replace for packages on requested volume
10063 final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10064 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10065 && Objects.equals(replaceVolumeUuid, volumeUuid);
10066 grantPermissionsLPw(pkgInfo, replace, changingPkg);
10070 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10071 String packageOfInterest) {
10072 // IMPORTANT: There are two types of permissions: install and runtime.
10073 // Install time permissions are granted when the app is installed to
10074 // all device users and users added in the future. Runtime permissions
10075 // are granted at runtime explicitly to specific users. Normal and signature
10076 // protected permissions are install time permissions. Dangerous permissions
10077 // are install permissions if the app's target SDK is Lollipop MR1 or older,
10078 // otherwise they are runtime permissions. This function does not manage
10079 // runtime permissions except for the case an app targeting Lollipop MR1
10080 // being upgraded to target a newer SDK, in which case dangerous permissions
10081 // are transformed from install time to runtime ones.
10083 final PackageSetting ps = (PackageSetting) pkg.mExtras;
10088 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10090 PermissionsState permissionsState = ps.getPermissionsState();
10091 PermissionsState origPermissions = permissionsState;
10093 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10095 boolean runtimePermissionsRevoked = false;
10096 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10098 boolean changedInstallPermission = false;
10101 ps.installPermissionsFixed = false;
10102 if (!ps.isSharedUser()) {
10103 origPermissions = new PermissionsState(permissionsState);
10104 permissionsState.reset();
10106 // We need to know only about runtime permission changes since the
10107 // calling code always writes the install permissions state but
10108 // the runtime ones are written only if changed. The only cases of
10109 // changed runtime permissions here are promotion of an install to
10110 // runtime and revocation of a runtime from a shared user.
10111 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10112 ps.sharedUser, UserManagerService.getInstance().getUserIds());
10113 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10114 runtimePermissionsRevoked = true;
10119 permissionsState.setGlobalGids(mGlobalGids);
10121 final int N = pkg.requestedPermissions.size();
10122 for (int i=0; i<N; i++) {
10123 final String name = pkg.requestedPermissions.get(i);
10124 final BasePermission bp = mSettings.mPermissions.get(name);
10126 if (DEBUG_INSTALL) {
10127 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10130 if (bp == null || bp.packageSetting == null) {
10131 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10132 Slog.w(TAG, "Unknown permission " + name
10133 + " in package " + pkg.packageName);
10138 final String perm = bp.name;
10139 boolean allowedSig = false;
10140 int grant = GRANT_DENIED;
10142 // Keep track of app op permissions.
10143 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10144 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10145 if (pkgs == null) {
10146 pkgs = new ArraySet<>();
10147 mAppOpPermissionPackages.put(bp.name, pkgs);
10149 pkgs.add(pkg.packageName);
10152 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10153 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10154 >= Build.VERSION_CODES.M;
10156 case PermissionInfo.PROTECTION_NORMAL: {
10157 // For all apps normal permissions are install time ones.
10158 grant = GRANT_INSTALL;
10161 case PermissionInfo.PROTECTION_DANGEROUS: {
10162 // If a permission review is required for legacy apps we represent
10163 // their permissions as always granted runtime ones since we need
10164 // to keep the review required permission flag per user while an
10165 // install permission's state is shared across all users.
10166 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10167 && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10168 // For legacy apps dangerous permissions are install time ones.
10169 grant = GRANT_INSTALL;
10170 } else if (origPermissions.hasInstallPermission(bp.name)) {
10171 // For legacy apps that became modern, install becomes runtime.
10172 grant = GRANT_UPGRADE;
10173 } else if (mPromoteSystemApps
10175 && mExistingSystemPackages.contains(ps.name)) {
10176 // For legacy system apps, install becomes runtime.
10177 // We cannot check hasInstallPermission() for system apps since those
10178 // permissions were granted implicitly and not persisted pre-M.
10179 grant = GRANT_UPGRADE;
10181 // For modern apps keep runtime permissions unchanged.
10182 grant = GRANT_RUNTIME;
10186 case PermissionInfo.PROTECTION_SIGNATURE: {
10187 // For all apps signature permissions are install time ones.
10188 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10190 grant = GRANT_INSTALL;
10195 if (DEBUG_INSTALL) {
10196 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10199 if (grant != GRANT_DENIED) {
10200 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10201 // If this is an existing, non-system package, then
10202 // we can't add any new permissions to it.
10203 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10204 // Except... if this is a permission that was added
10205 // to the platform (note: need to only do this when
10206 // updating the platform).
10207 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10208 grant = GRANT_DENIED;
10214 case GRANT_INSTALL: {
10215 // Revoke this as runtime permission to handle the case of
10216 // a runtime permission being downgraded to an install one.
10217 // Also in permission review mode we keep dangerous permissions
10219 for (int userId : UserManagerService.getInstance().getUserIds()) {
10220 if (origPermissions.getRuntimePermissionState(
10221 bp.name, userId) != null) {
10222 // Revoke the runtime permission and clear the flags.
10223 origPermissions.revokeRuntimePermission(bp, userId);
10224 origPermissions.updatePermissionFlags(bp, userId,
10225 PackageManager.MASK_PERMISSION_FLAGS, 0);
10226 // If we revoked a permission permission, we have to write.
10227 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10228 changedRuntimePermissionUserIds, userId);
10231 // Grant an install permission.
10232 if (permissionsState.grantInstallPermission(bp) !=
10233 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10234 changedInstallPermission = true;
10238 case GRANT_RUNTIME: {
10239 // Grant previously granted runtime permissions.
10240 for (int userId : UserManagerService.getInstance().getUserIds()) {
10241 PermissionState permissionState = origPermissions
10242 .getRuntimePermissionState(bp.name, userId);
10243 int flags = permissionState != null
10244 ? permissionState.getFlags() : 0;
10245 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10246 // Don't propagate the permission in a permission review mode if
10247 // the former was revoked, i.e. marked to not propagate on upgrade.
10248 // Note that in a permission review mode install permissions are
10249 // represented as constantly granted runtime ones since we need to
10250 // keep a per user state associated with the permission. Also the
10251 // revoke on upgrade flag is no longer applicable and is reset.
10252 final boolean revokeOnUpgrade = (flags & PackageManager
10253 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10254 if (revokeOnUpgrade) {
10255 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10256 // Since we changed the flags, we have to write.
10257 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10258 changedRuntimePermissionUserIds, userId);
10260 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10261 if (permissionsState.grantRuntimePermission(bp, userId) ==
10262 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10263 // If we cannot put the permission as it was,
10264 // we have to write.
10265 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10266 changedRuntimePermissionUserIds, userId);
10270 // If the app supports runtime permissions no need for a review.
10271 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10272 && appSupportsRuntimePermissions
10273 && (flags & PackageManager
10274 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10275 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10276 // Since we changed the flags, we have to write.
10277 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10278 changedRuntimePermissionUserIds, userId);
10280 } else if ((mPermissionReviewRequired
10281 || Build.PERMISSIONS_REVIEW_REQUIRED)
10282 && !appSupportsRuntimePermissions) {
10283 // For legacy apps that need a permission review, every new
10284 // runtime permission is granted but it is pending a review.
10285 // We also need to review only platform defined runtime
10286 // permissions as these are the only ones the platform knows
10287 // how to disable the API to simulate revocation as legacy
10288 // apps don't expect to run with revoked permissions.
10289 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10290 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10291 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10292 // We changed the flags, hence have to write.
10293 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10294 changedRuntimePermissionUserIds, userId);
10297 if (permissionsState.grantRuntimePermission(bp, userId)
10298 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10299 // We changed the permission, hence have to write.
10300 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10301 changedRuntimePermissionUserIds, userId);
10304 // Propagate the permission flags.
10305 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10309 case GRANT_UPGRADE: {
10310 // Grant runtime permissions for a previously held install permission.
10311 PermissionState permissionState = origPermissions
10312 .getInstallPermissionState(bp.name);
10313 final int flags = permissionState != null ? permissionState.getFlags() : 0;
10315 if (origPermissions.revokeInstallPermission(bp)
10316 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10317 // We will be transferring the permission flags, so clear them.
10318 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10319 PackageManager.MASK_PERMISSION_FLAGS, 0);
10320 changedInstallPermission = true;
10323 // If the permission is not to be promoted to runtime we ignore it and
10324 // also its other flags as they are not applicable to install permissions.
10325 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10326 for (int userId : currentUserIds) {
10327 if (permissionsState.grantRuntimePermission(bp, userId) !=
10328 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10329 // Transfer the permission flags.
10330 permissionsState.updatePermissionFlags(bp, userId,
10332 // If we granted the permission, we have to write.
10333 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10334 changedRuntimePermissionUserIds, userId);
10341 if (packageOfInterest == null
10342 || packageOfInterest.equals(pkg.packageName)) {
10343 Slog.w(TAG, "Not granting permission " + perm
10344 + " to package " + pkg.packageName
10345 + " because it was previously installed without");
10350 if (permissionsState.revokeInstallPermission(bp) !=
10351 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10352 // Also drop the permission flags.
10353 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10354 PackageManager.MASK_PERMISSION_FLAGS, 0);
10355 changedInstallPermission = true;
10356 Slog.i(TAG, "Un-granting permission " + perm
10357 + " from package " + pkg.packageName
10358 + " (protectionLevel=" + bp.protectionLevel
10359 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10361 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10362 // Don't print warning for app op permissions, since it is fine for them
10363 // not to be granted, there is a UI for the user to decide.
10364 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10365 Slog.w(TAG, "Not granting permission " + perm
10366 + " to package " + pkg.packageName
10367 + " (protectionLevel=" + bp.protectionLevel
10368 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10375 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10376 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10377 // This is the first that we have heard about this package, so the
10378 // permissions we have now selected are fixed until explicitly
10380 ps.installPermissionsFixed = true;
10383 // Persist the runtime permissions state for users with changes. If permissions
10384 // were revoked because no app in the shared user declares them we have to
10385 // write synchronously to avoid losing runtime permissions state.
10386 for (int userId : changedRuntimePermissionUserIds) {
10387 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10393 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10394 boolean allowed = false;
10395 final int NP = PackageParser.NEW_PERMISSIONS.length;
10396 for (int ip=0; ip<NP; ip++) {
10397 final PackageParser.NewPermissionInfo npi
10398 = PackageParser.NEW_PERMISSIONS[ip];
10399 if (npi.name.equals(perm)
10400 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10402 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10403 + pkg.packageName);
10410 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10411 BasePermission bp, PermissionsState origPermissions) {
10413 allowed = (compareSignatures(
10414 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10415 == PackageManager.SIGNATURE_MATCH)
10416 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10417 == PackageManager.SIGNATURE_MATCH);
10418 if (!allowed && (bp.protectionLevel
10419 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10420 if (isSystemApp(pkg)) {
10421 // For updated system applications, a system permission
10422 // is granted only if it had been defined by the original application.
10423 if (pkg.isUpdatedSystemApp()) {
10424 final PackageSetting sysPs = mSettings
10425 .getDisabledSystemPkgLPr(pkg.packageName);
10426 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10427 // If the original was granted this permission, we take
10428 // that grant decision as read and propagate it to the
10430 if (sysPs.isPrivileged()) {
10434 // The system apk may have been updated with an older
10435 // version of the one on the data partition, but which
10436 // granted a new system permission that it didn't have
10437 // before. In this case we do want to allow the app to
10438 // now get the new permission if the ancestral apk is
10439 // privileged to get it.
10440 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10441 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10442 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10448 // Also if a privileged parent package on the system image or any of
10449 // its children requested a privileged permission, the updated child
10450 // packages can also get the permission.
10451 if (pkg.parentPackage != null) {
10452 final PackageSetting disabledSysParentPs = mSettings
10453 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10454 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10455 && disabledSysParentPs.isPrivileged()) {
10456 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10458 } else if (disabledSysParentPs.pkg.childPackages != null) {
10459 final int count = disabledSysParentPs.pkg.childPackages.size();
10460 for (int i = 0; i < count; i++) {
10461 PackageParser.Package disabledSysChildPkg =
10462 disabledSysParentPs.pkg.childPackages.get(i);
10463 if (isPackageRequestingPermission(disabledSysChildPkg,
10474 allowed = isPrivilegedApp(pkg);
10479 if (!allowed && (bp.protectionLevel
10480 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10481 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10482 // If this was a previously normal/dangerous permission that got moved
10483 // to a system permission as part of the runtime permission redesign, then
10484 // we still want to blindly grant it to old apps.
10487 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10488 && pkg.packageName.equals(mRequiredInstallerPackage)) {
10489 // If this permission is to be granted to the system installer and
10490 // this app is an installer, then it gets the permission.
10493 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10494 && pkg.packageName.equals(mRequiredVerifierPackage)) {
10495 // If this permission is to be granted to the system verifier and
10496 // this app is a verifier, then it gets the permission.
10499 if (!allowed && (bp.protectionLevel
10500 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10501 && isSystemApp(pkg)) {
10502 // Any pre-installed system app is allowed to get this permission.
10505 if (!allowed && (bp.protectionLevel
10506 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10507 // For development permissions, a development permission
10508 // is granted only if it was already granted.
10509 allowed = origPermissions.hasInstallPermission(perm);
10511 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10512 && pkg.packageName.equals(mSetupWizardPackage)) {
10513 // If this permission is to be granted to the system setup wizard and
10514 // this app is a setup wizard, then it gets the permission.
10521 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10522 final int permCount = pkg.requestedPermissions.size();
10523 for (int j = 0; j < permCount; j++) {
10524 String requestedPermission = pkg.requestedPermissions.get(j);
10525 if (permission.equals(requestedPermission)) {
10532 final class ActivityIntentResolver
10533 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10534 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10535 boolean defaultOnly, int userId) {
10536 if (!sUserManager.exists(userId)) return null;
10537 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10538 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10541 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10543 if (!sUserManager.exists(userId)) return null;
10545 return super.queryIntent(intent, resolvedType,
10546 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10549 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10550 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10551 if (!sUserManager.exists(userId)) return null;
10552 if (packageActivities == null) {
10556 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10557 final int N = packageActivities.size();
10558 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10559 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10561 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10562 for (int i = 0; i < N; ++i) {
10563 intentFilters = packageActivities.get(i).intents;
10564 if (intentFilters != null && intentFilters.size() > 0) {
10565 PackageParser.ActivityIntentInfo[] array =
10566 new PackageParser.ActivityIntentInfo[intentFilters.size()];
10567 intentFilters.toArray(array);
10568 listCut.add(array);
10571 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10575 * Finds a privileged activity that matches the specified activity names.
10577 private PackageParser.Activity findMatchingActivity(
10578 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10579 for (PackageParser.Activity sysActivity : activityList) {
10580 if (sysActivity.info.name.equals(activityInfo.name)) {
10581 return sysActivity;
10583 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10584 return sysActivity;
10586 if (sysActivity.info.targetActivity != null) {
10587 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10588 return sysActivity;
10590 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10591 return sysActivity;
10598 public class IterGenerator<E> {
10599 public Iterator<E> generate(ActivityIntentInfo info) {
10604 public class ActionIterGenerator extends IterGenerator<String> {
10606 public Iterator<String> generate(ActivityIntentInfo info) {
10607 return info.actionsIterator();
10611 public class CategoriesIterGenerator extends IterGenerator<String> {
10613 public Iterator<String> generate(ActivityIntentInfo info) {
10614 return info.categoriesIterator();
10618 public class SchemesIterGenerator extends IterGenerator<String> {
10620 public Iterator<String> generate(ActivityIntentInfo info) {
10621 return info.schemesIterator();
10625 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10627 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10628 return info.authoritiesIterator();
10633 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10634 * MODIFIED. Do not pass in a list that should not be changed.
10636 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10637 IterGenerator<T> generator, Iterator<T> searchIterator) {
10638 // loop through the set of actions; every one must be found in the intent filter
10639 while (searchIterator.hasNext()) {
10640 // we must have at least one filter in the list to consider a match
10641 if (intentList.size() == 0) {
10645 final T searchAction = searchIterator.next();
10647 // loop through the set of intent filters
10648 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10649 while (intentIter.hasNext()) {
10650 final ActivityIntentInfo intentInfo = intentIter.next();
10651 boolean selectionFound = false;
10653 // loop through the intent filter's selection criteria; at least one
10654 // of them must match the searched criteria
10655 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10656 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10657 final T intentSelection = intentSelectionIter.next();
10658 if (intentSelection != null && intentSelection.equals(searchAction)) {
10659 selectionFound = true;
10664 // the selection criteria wasn't found in this filter's set; this filter
10665 // is not a potential match
10666 if (!selectionFound) {
10667 intentIter.remove();
10673 private boolean isProtectedAction(ActivityIntentInfo filter) {
10674 final Iterator<String> actionsIter = filter.actionsIterator();
10675 while (actionsIter != null && actionsIter.hasNext()) {
10676 final String filterAction = actionsIter.next();
10677 if (PROTECTED_ACTIONS.contains(filterAction)) {
10685 * Adjusts the priority of the given intent filter according to policy.
10688 * <li>The priority for non privileged applications is capped to '0'</li>
10689 * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10690 * <li>The priority for unbundled updates to privileged applications is capped to the
10691 * priority defined on the system partition</li>
10694 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10695 * allowed to obtain any priority on any action.
10697 private void adjustPriority(
10698 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10699 // nothing to do; priority is fine as-is
10700 if (intent.getPriority() <= 0) {
10704 final ActivityInfo activityInfo = intent.activity.info;
10705 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10707 final boolean privilegedApp =
10708 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10709 if (!privilegedApp) {
10710 // non-privileged applications can never define a priority >0
10711 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10712 + " package: " + applicationInfo.packageName
10713 + " activity: " + intent.activity.className
10714 + " origPrio: " + intent.getPriority());
10715 intent.setPriority(0);
10719 if (systemActivities == null) {
10720 // the system package is not disabled; we're parsing the system partition
10721 if (isProtectedAction(intent)) {
10722 if (mDeferProtectedFilters) {
10723 // We can't deal with these just yet. No component should ever obtain a
10724 // >0 priority for a protected actions, with ONE exception -- the setup
10725 // wizard. The setup wizard, however, cannot be known until we're able to
10726 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10727 // until all intent filters have been processed. Chicken, meet egg.
10728 // Let the filter temporarily have a high priority and rectify the
10729 // priorities after all system packages have been scanned.
10730 mProtectedFilters.add(intent);
10731 if (DEBUG_FILTERS) {
10732 Slog.i(TAG, "Protected action; save for later;"
10733 + " package: " + applicationInfo.packageName
10734 + " activity: " + intent.activity.className
10735 + " origPrio: " + intent.getPriority());
10739 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10740 Slog.i(TAG, "No setup wizard;"
10741 + " All protected intents capped to priority 0");
10743 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10744 if (DEBUG_FILTERS) {
10745 Slog.i(TAG, "Found setup wizard;"
10746 + " allow priority " + intent.getPriority() + ";"
10747 + " package: " + intent.activity.info.packageName
10748 + " activity: " + intent.activity.className
10749 + " priority: " + intent.getPriority());
10751 // setup wizard gets whatever it wants
10754 Slog.w(TAG, "Protected action; cap priority to 0;"
10755 + " package: " + intent.activity.info.packageName
10756 + " activity: " + intent.activity.className
10757 + " origPrio: " + intent.getPriority());
10758 intent.setPriority(0);
10762 // privileged apps on the system image get whatever priority they request
10766 // privileged app unbundled update ... try to find the same activity
10767 final PackageParser.Activity foundActivity =
10768 findMatchingActivity(systemActivities, activityInfo);
10769 if (foundActivity == null) {
10770 // this is a new activity; it cannot obtain >0 priority
10771 if (DEBUG_FILTERS) {
10772 Slog.i(TAG, "New activity; cap priority to 0;"
10773 + " package: " + applicationInfo.packageName
10774 + " activity: " + intent.activity.className
10775 + " origPrio: " + intent.getPriority());
10777 intent.setPriority(0);
10781 // found activity, now check for filter equivalence
10783 // a shallow copy is enough; we modify the list, not its contents
10784 final List<ActivityIntentInfo> intentListCopy =
10785 new ArrayList<>(foundActivity.intents);
10786 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10788 // find matching action subsets
10789 final Iterator<String> actionsIterator = intent.actionsIterator();
10790 if (actionsIterator != null) {
10791 getIntentListSubset(
10792 intentListCopy, new ActionIterGenerator(), actionsIterator);
10793 if (intentListCopy.size() == 0) {
10794 // no more intents to match; we're not equivalent
10795 if (DEBUG_FILTERS) {
10796 Slog.i(TAG, "Mismatched action; cap priority to 0;"
10797 + " package: " + applicationInfo.packageName
10798 + " activity: " + intent.activity.className
10799 + " origPrio: " + intent.getPriority());
10801 intent.setPriority(0);
10806 // find matching category subsets
10807 final Iterator<String> categoriesIterator = intent.categoriesIterator();
10808 if (categoriesIterator != null) {
10809 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10810 categoriesIterator);
10811 if (intentListCopy.size() == 0) {
10812 // no more intents to match; we're not equivalent
10813 if (DEBUG_FILTERS) {
10814 Slog.i(TAG, "Mismatched category; cap priority to 0;"
10815 + " package: " + applicationInfo.packageName
10816 + " activity: " + intent.activity.className
10817 + " origPrio: " + intent.getPriority());
10819 intent.setPriority(0);
10824 // find matching schemes subsets
10825 final Iterator<String> schemesIterator = intent.schemesIterator();
10826 if (schemesIterator != null) {
10827 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10829 if (intentListCopy.size() == 0) {
10830 // no more intents to match; we're not equivalent
10831 if (DEBUG_FILTERS) {
10832 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10833 + " package: " + applicationInfo.packageName
10834 + " activity: " + intent.activity.className
10835 + " origPrio: " + intent.getPriority());
10837 intent.setPriority(0);
10842 // find matching authorities subsets
10843 final Iterator<IntentFilter.AuthorityEntry>
10844 authoritiesIterator = intent.authoritiesIterator();
10845 if (authoritiesIterator != null) {
10846 getIntentListSubset(intentListCopy,
10847 new AuthoritiesIterGenerator(),
10848 authoritiesIterator);
10849 if (intentListCopy.size() == 0) {
10850 // no more intents to match; we're not equivalent
10851 if (DEBUG_FILTERS) {
10852 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10853 + " package: " + applicationInfo.packageName
10854 + " activity: " + intent.activity.className
10855 + " origPrio: " + intent.getPriority());
10857 intent.setPriority(0);
10862 // we found matching filter(s); app gets the max priority of all intents
10863 int cappedPriority = 0;
10864 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10865 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10867 if (intent.getPriority() > cappedPriority) {
10868 if (DEBUG_FILTERS) {
10869 Slog.i(TAG, "Found matching filter(s);"
10870 + " cap priority to " + cappedPriority + ";"
10871 + " package: " + applicationInfo.packageName
10872 + " activity: " + intent.activity.className
10873 + " origPrio: " + intent.getPriority());
10875 intent.setPriority(cappedPriority);
10878 // all this for nothing; the requested priority was <= what was on the system
10881 public final void addActivity(PackageParser.Activity a, String type) {
10882 mActivities.put(a.getComponentName(), a);
10883 if (DEBUG_SHOW_INFO)
10885 TAG, " " + type + " " +
10886 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10887 if (DEBUG_SHOW_INFO)
10888 Log.v(TAG, " Class=" + a.info.name);
10889 final int NI = a.intents.size();
10890 for (int j=0; j<NI; j++) {
10891 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10892 if ("activity".equals(type)) {
10893 final PackageSetting ps =
10894 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10895 final List<PackageParser.Activity> systemActivities =
10896 ps != null && ps.pkg != null ? ps.pkg.activities : null;
10897 adjustPriority(systemActivities, intent);
10899 if (DEBUG_SHOW_INFO) {
10900 Log.v(TAG, " IntentFilter:");
10901 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10903 if (!intent.debugCheck()) {
10904 Log.w(TAG, "==> For Activity " + a.info.name);
10910 public final void removeActivity(PackageParser.Activity a, String type) {
10911 mActivities.remove(a.getComponentName());
10912 if (DEBUG_SHOW_INFO) {
10913 Log.v(TAG, " " + type + " "
10914 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10915 : a.info.name) + ":");
10916 Log.v(TAG, " Class=" + a.info.name);
10918 final int NI = a.intents.size();
10919 for (int j=0; j<NI; j++) {
10920 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10921 if (DEBUG_SHOW_INFO) {
10922 Log.v(TAG, " IntentFilter:");
10923 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10925 removeFilter(intent);
10930 protected boolean allowFilterResult(
10931 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10932 ActivityInfo filterAi = filter.activity.info;
10933 for (int i=dest.size()-1; i>=0; i--) {
10934 ActivityInfo destAi = dest.get(i).activityInfo;
10935 if (destAi.name == filterAi.name
10936 && destAi.packageName == filterAi.packageName) {
10944 protected ActivityIntentInfo[] newArray(int size) {
10945 return new ActivityIntentInfo[size];
10949 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10950 if (!sUserManager.exists(userId)) return true;
10951 PackageParser.Package p = filter.activity.owner;
10953 PackageSetting ps = (PackageSetting)p.mExtras;
10955 // System apps are never considered stopped for purposes of
10956 // filtering, because there may be no way for the user to
10957 // actually re-launch them.
10958 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10959 && ps.getStopped(userId);
10966 protected boolean isPackageForFilter(String packageName,
10967 PackageParser.ActivityIntentInfo info) {
10968 return packageName.equals(info.activity.owner.packageName);
10972 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10973 int match, int userId) {
10974 if (!sUserManager.exists(userId)) return null;
10975 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10978 final PackageParser.Activity activity = info.activity;
10979 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10983 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10984 ps.readUserState(userId), userId);
10988 final ResolveInfo res = new ResolveInfo();
10989 res.activityInfo = ai;
10990 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10993 if (info != null) {
10994 res.handleAllWebDataURI = info.handleAllWebDataURI();
10996 res.priority = info.getPriority();
10997 res.preferredOrder = activity.owner.mPreferredOrder;
10998 //System.out.println("Result: " + res.activityInfo.className +
10999 // " = " + res.priority);
11001 res.isDefault = info.hasDefault;
11002 res.labelRes = info.labelRes;
11003 res.nonLocalizedLabel = info.nonLocalizedLabel;
11004 if (userNeedsBadging(userId)) {
11005 res.noResourceId = true;
11007 res.icon = info.icon;
11009 res.iconResourceId = info.icon;
11010 res.system = res.activityInfo.applicationInfo.isSystemApp();
11015 protected void sortResults(List<ResolveInfo> results) {
11016 Collections.sort(results, mResolvePrioritySorter);
11020 protected void dumpFilter(PrintWriter out, String prefix,
11021 PackageParser.ActivityIntentInfo filter) {
11022 out.print(prefix); out.print(
11023 Integer.toHexString(System.identityHashCode(filter.activity)));
11025 filter.activity.printComponentShortName(out);
11026 out.print(" filter ");
11027 out.println(Integer.toHexString(System.identityHashCode(filter)));
11031 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11032 return filter.activity;
11035 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11036 PackageParser.Activity activity = (PackageParser.Activity)label;
11037 out.print(prefix); out.print(
11038 Integer.toHexString(System.identityHashCode(activity)));
11040 activity.printComponentShortName(out);
11042 out.print(" ("); out.print(count); out.print(" filters)");
11047 // Keys are String (activity class name), values are Activity.
11048 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11049 = new ArrayMap<ComponentName, PackageParser.Activity>();
11050 private int mFlags;
11053 private final class ServiceIntentResolver
11054 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11055 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11056 boolean defaultOnly, int userId) {
11057 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11058 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11061 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11063 if (!sUserManager.exists(userId)) return null;
11065 return super.queryIntent(intent, resolvedType,
11066 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11069 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11070 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11071 if (!sUserManager.exists(userId)) return null;
11072 if (packageServices == null) {
11076 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11077 final int N = packageServices.size();
11078 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11079 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11081 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11082 for (int i = 0; i < N; ++i) {
11083 intentFilters = packageServices.get(i).intents;
11084 if (intentFilters != null && intentFilters.size() > 0) {
11085 PackageParser.ServiceIntentInfo[] array =
11086 new PackageParser.ServiceIntentInfo[intentFilters.size()];
11087 intentFilters.toArray(array);
11088 listCut.add(array);
11091 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11094 public final void addService(PackageParser.Service s) {
11095 mServices.put(s.getComponentName(), s);
11096 if (DEBUG_SHOW_INFO) {
11098 + (s.info.nonLocalizedLabel != null
11099 ? s.info.nonLocalizedLabel : s.info.name) + ":");
11100 Log.v(TAG, " Class=" + s.info.name);
11102 final int NI = s.intents.size();
11104 for (j=0; j<NI; j++) {
11105 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11106 if (DEBUG_SHOW_INFO) {
11107 Log.v(TAG, " IntentFilter:");
11108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11110 if (!intent.debugCheck()) {
11111 Log.w(TAG, "==> For Service " + s.info.name);
11117 public final void removeService(PackageParser.Service s) {
11118 mServices.remove(s.getComponentName());
11119 if (DEBUG_SHOW_INFO) {
11120 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
11121 ? s.info.nonLocalizedLabel : s.info.name) + ":");
11122 Log.v(TAG, " Class=" + s.info.name);
11124 final int NI = s.intents.size();
11126 for (j=0; j<NI; j++) {
11127 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11128 if (DEBUG_SHOW_INFO) {
11129 Log.v(TAG, " IntentFilter:");
11130 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11132 removeFilter(intent);
11137 protected boolean allowFilterResult(
11138 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11139 ServiceInfo filterSi = filter.service.info;
11140 for (int i=dest.size()-1; i>=0; i--) {
11141 ServiceInfo destAi = dest.get(i).serviceInfo;
11142 if (destAi.name == filterSi.name
11143 && destAi.packageName == filterSi.packageName) {
11151 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11152 return new PackageParser.ServiceIntentInfo[size];
11156 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11157 if (!sUserManager.exists(userId)) return true;
11158 PackageParser.Package p = filter.service.owner;
11160 PackageSetting ps = (PackageSetting)p.mExtras;
11162 // System apps are never considered stopped for purposes of
11163 // filtering, because there may be no way for the user to
11164 // actually re-launch them.
11165 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11166 && ps.getStopped(userId);
11173 protected boolean isPackageForFilter(String packageName,
11174 PackageParser.ServiceIntentInfo info) {
11175 return packageName.equals(info.service.owner.packageName);
11179 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11180 int match, int userId) {
11181 if (!sUserManager.exists(userId)) return null;
11182 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11183 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11186 final PackageParser.Service service = info.service;
11187 PackageSetting ps = (PackageSetting) service.owner.mExtras;
11191 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11192 ps.readUserState(userId), userId);
11196 final ResolveInfo res = new ResolveInfo();
11197 res.serviceInfo = si;
11198 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11199 res.filter = filter;
11201 res.priority = info.getPriority();
11202 res.preferredOrder = service.owner.mPreferredOrder;
11204 res.isDefault = info.hasDefault;
11205 res.labelRes = info.labelRes;
11206 res.nonLocalizedLabel = info.nonLocalizedLabel;
11207 res.icon = info.icon;
11208 res.system = res.serviceInfo.applicationInfo.isSystemApp();
11213 protected void sortResults(List<ResolveInfo> results) {
11214 Collections.sort(results, mResolvePrioritySorter);
11218 protected void dumpFilter(PrintWriter out, String prefix,
11219 PackageParser.ServiceIntentInfo filter) {
11220 out.print(prefix); out.print(
11221 Integer.toHexString(System.identityHashCode(filter.service)));
11223 filter.service.printComponentShortName(out);
11224 out.print(" filter ");
11225 out.println(Integer.toHexString(System.identityHashCode(filter)));
11229 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11230 return filter.service;
11233 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11234 PackageParser.Service service = (PackageParser.Service)label;
11235 out.print(prefix); out.print(
11236 Integer.toHexString(System.identityHashCode(service)));
11238 service.printComponentShortName(out);
11240 out.print(" ("); out.print(count); out.print(" filters)");
11245 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11246 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11247 // final List<ResolveInfo> retList = Lists.newArrayList();
11248 // while (i.hasNext()) {
11249 // final ResolveInfo resolveInfo = (ResolveInfo) i;
11250 // if (isEnabledLP(resolveInfo.serviceInfo)) {
11251 // retList.add(resolveInfo);
11257 // Keys are String (activity class name), values are Activity.
11258 private final ArrayMap<ComponentName, PackageParser.Service> mServices
11259 = new ArrayMap<ComponentName, PackageParser.Service>();
11260 private int mFlags;
11263 private final class ProviderIntentResolver
11264 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11265 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11266 boolean defaultOnly, int userId) {
11267 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11268 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11271 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11273 if (!sUserManager.exists(userId))
11276 return super.queryIntent(intent, resolvedType,
11277 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11280 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11281 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11282 if (!sUserManager.exists(userId))
11284 if (packageProviders == null) {
11288 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11289 final int N = packageProviders.size();
11290 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11291 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11293 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11294 for (int i = 0; i < N; ++i) {
11295 intentFilters = packageProviders.get(i).intents;
11296 if (intentFilters != null && intentFilters.size() > 0) {
11297 PackageParser.ProviderIntentInfo[] array =
11298 new PackageParser.ProviderIntentInfo[intentFilters.size()];
11299 intentFilters.toArray(array);
11300 listCut.add(array);
11303 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11306 public final void addProvider(PackageParser.Provider p) {
11307 if (mProviders.containsKey(p.getComponentName())) {
11308 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11312 mProviders.put(p.getComponentName(), p);
11313 if (DEBUG_SHOW_INFO) {
11315 + (p.info.nonLocalizedLabel != null
11316 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11317 Log.v(TAG, " Class=" + p.info.name);
11319 final int NI = p.intents.size();
11321 for (j = 0; j < NI; j++) {
11322 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11323 if (DEBUG_SHOW_INFO) {
11324 Log.v(TAG, " IntentFilter:");
11325 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11327 if (!intent.debugCheck()) {
11328 Log.w(TAG, "==> For Provider " + p.info.name);
11334 public final void removeProvider(PackageParser.Provider p) {
11335 mProviders.remove(p.getComponentName());
11336 if (DEBUG_SHOW_INFO) {
11337 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
11338 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11339 Log.v(TAG, " Class=" + p.info.name);
11341 final int NI = p.intents.size();
11343 for (j = 0; j < NI; j++) {
11344 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11345 if (DEBUG_SHOW_INFO) {
11346 Log.v(TAG, " IntentFilter:");
11347 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11349 removeFilter(intent);
11354 protected boolean allowFilterResult(
11355 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11356 ProviderInfo filterPi = filter.provider.info;
11357 for (int i = dest.size() - 1; i >= 0; i--) {
11358 ProviderInfo destPi = dest.get(i).providerInfo;
11359 if (destPi.name == filterPi.name
11360 && destPi.packageName == filterPi.packageName) {
11368 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11369 return new PackageParser.ProviderIntentInfo[size];
11373 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11374 if (!sUserManager.exists(userId))
11376 PackageParser.Package p = filter.provider.owner;
11378 PackageSetting ps = (PackageSetting) p.mExtras;
11380 // System apps are never considered stopped for purposes of
11381 // filtering, because there may be no way for the user to
11382 // actually re-launch them.
11383 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11384 && ps.getStopped(userId);
11391 protected boolean isPackageForFilter(String packageName,
11392 PackageParser.ProviderIntentInfo info) {
11393 return packageName.equals(info.provider.owner.packageName);
11397 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11398 int match, int userId) {
11399 if (!sUserManager.exists(userId))
11401 final PackageParser.ProviderIntentInfo info = filter;
11402 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11405 final PackageParser.Provider provider = info.provider;
11406 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11410 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11411 ps.readUserState(userId), userId);
11415 final ResolveInfo res = new ResolveInfo();
11416 res.providerInfo = pi;
11417 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11418 res.filter = filter;
11420 res.priority = info.getPriority();
11421 res.preferredOrder = provider.owner.mPreferredOrder;
11423 res.isDefault = info.hasDefault;
11424 res.labelRes = info.labelRes;
11425 res.nonLocalizedLabel = info.nonLocalizedLabel;
11426 res.icon = info.icon;
11427 res.system = res.providerInfo.applicationInfo.isSystemApp();
11432 protected void sortResults(List<ResolveInfo> results) {
11433 Collections.sort(results, mResolvePrioritySorter);
11437 protected void dumpFilter(PrintWriter out, String prefix,
11438 PackageParser.ProviderIntentInfo filter) {
11441 Integer.toHexString(System.identityHashCode(filter.provider)));
11443 filter.provider.printComponentShortName(out);
11444 out.print(" filter ");
11445 out.println(Integer.toHexString(System.identityHashCode(filter)));
11449 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11450 return filter.provider;
11453 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11454 PackageParser.Provider provider = (PackageParser.Provider)label;
11455 out.print(prefix); out.print(
11456 Integer.toHexString(System.identityHashCode(provider)));
11458 provider.printComponentShortName(out);
11460 out.print(" ("); out.print(count); out.print(" filters)");
11465 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11466 = new ArrayMap<ComponentName, PackageParser.Provider>();
11467 private int mFlags;
11470 private static final class EphemeralIntentResolver
11471 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11473 * The result that has the highest defined order. Ordering applies on a
11474 * per-package basis. Mapping is from package name to Pair of order and
11475 * EphemeralResolveInfo.
11477 * NOTE: This is implemented as a field variable for convenience and efficiency.
11478 * By having a field variable, we're able to track filter ordering as soon as
11479 * a non-zero order is defined. Otherwise, multiple loops across the result set
11480 * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11481 * this needs to be contained entirely within {@link #filterResults()}.
11483 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11486 protected EphemeralResolveIntentInfo[] newArray(int size) {
11487 return new EphemeralResolveIntentInfo[size];
11491 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11496 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11498 if (!sUserManager.exists(userId)) {
11501 final String packageName = info.getEphemeralResolveInfo().getPackageName();
11502 final Integer order = info.getOrder();
11503 final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11504 mOrderResult.get(packageName);
11505 // ordering is enabled and this item's order isn't high enough
11506 if (lastOrderResult != null && lastOrderResult.first >= order) {
11509 final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11511 // non-zero order, enable ordering
11512 mOrderResult.put(packageName, new Pair<>(order, res));
11518 protected void filterResults(List<EphemeralResolveInfo> results) {
11519 // only do work if ordering is enabled [most of the time it won't be]
11520 if (mOrderResult.size() == 0) {
11523 int resultSize = results.size();
11524 for (int i = 0; i < resultSize; i++) {
11525 final EphemeralResolveInfo info = results.get(i);
11526 final String packageName = info.getPackageName();
11527 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11528 if (savedInfo == null) {
11529 // package doesn't having ordering
11532 if (savedInfo.second == info) {
11533 // circled back to the highest ordered item; remove from order list
11534 mOrderResult.remove(savedInfo);
11535 if (mOrderResult.size() == 0) {
11536 // no more ordered items
11541 // item has a worse order, remove it from the result list
11549 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11550 new Comparator<ResolveInfo>() {
11551 public int compare(ResolveInfo r1, ResolveInfo r2) {
11552 int v1 = r1.priority;
11553 int v2 = r2.priority;
11554 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11556 return (v1 > v2) ? -1 : 1;
11558 v1 = r1.preferredOrder;
11559 v2 = r2.preferredOrder;
11561 return (v1 > v2) ? -1 : 1;
11563 if (r1.isDefault != r2.isDefault) {
11564 return r1.isDefault ? -1 : 1;
11568 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11570 return (v1 > v2) ? -1 : 1;
11572 if (r1.system != r2.system) {
11573 return r1.system ? -1 : 1;
11575 if (r1.activityInfo != null) {
11576 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11578 if (r1.serviceInfo != null) {
11579 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11581 if (r1.providerInfo != null) {
11582 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11588 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11589 new Comparator<ProviderInfo>() {
11590 public int compare(ProviderInfo p1, ProviderInfo p2) {
11591 final int v1 = p1.initOrder;
11592 final int v2 = p2.initOrder;
11593 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11597 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11598 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11599 final int[] userIds) {
11600 mHandler.post(new Runnable() {
11602 public void run() {
11604 final IActivityManager am = ActivityManagerNative.getDefault();
11605 if (am == null) return;
11606 final int[] resolvedUserIds;
11607 if (userIds == null) {
11608 resolvedUserIds = am.getRunningUserIds();
11610 resolvedUserIds = userIds;
11612 for (int id : resolvedUserIds) {
11613 final Intent intent = new Intent(action,
11614 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11615 if (extras != null) {
11616 intent.putExtras(extras);
11618 if (targetPkg != null) {
11619 intent.setPackage(targetPkg);
11621 // Modify the UID when posting to other users
11622 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11623 if (uid > 0 && UserHandle.getUserId(uid) != id) {
11624 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11625 intent.putExtra(Intent.EXTRA_UID, uid);
11627 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11628 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11629 if (DEBUG_BROADCASTS) {
11630 RuntimeException here = new RuntimeException("here");
11631 here.fillInStackTrace();
11632 Slog.d(TAG, "Sending to user " + id + ": "
11633 + intent.toShortString(false, true, false, false)
11634 + " " + intent.getExtras(), here);
11636 am.broadcastIntent(null, intent, null, finishedReceiver,
11637 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11638 null, finishedReceiver != null, false, id);
11640 } catch (RemoteException ex) {
11647 * Check if the external storage media is available. This is true if there
11648 * is a mounted external storage medium or if the external storage is
11651 private boolean isExternalMediaAvailable() {
11652 return mMediaMounted || Environment.isExternalStorageEmulated();
11656 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11658 synchronized (mPackages) {
11659 if (!isExternalMediaAvailable()) {
11660 // If the external storage is no longer mounted at this point,
11661 // the caller may not have been able to delete all of this
11662 // packages files and can not delete any more. Bail.
11665 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11666 if (lastPackage != null) {
11667 pkgs.remove(lastPackage);
11669 if (pkgs.size() > 0) {
11670 return pkgs.get(0);
11676 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11677 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11678 userId, andCode ? 1 : 0, packageName);
11679 if (mSystemReady) {
11680 msg.sendToTarget();
11682 if (mPostSystemReadyMessages == null) {
11683 mPostSystemReadyMessages = new ArrayList<>();
11685 mPostSystemReadyMessages.add(msg);
11689 void startCleaningPackages() {
11691 if (!isExternalMediaAvailable()) {
11694 synchronized (mPackages) {
11695 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11699 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11700 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11701 IActivityManager am = ActivityManagerNative.getDefault();
11704 am.startService(null, intent, null, mContext.getOpPackageName(),
11705 UserHandle.USER_SYSTEM);
11706 } catch (RemoteException e) {
11712 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11713 int installFlags, String installerPackageName, int userId) {
11714 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11716 final int callingUid = Binder.getCallingUid();
11717 enforceCrossUserPermission(callingUid, userId,
11718 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11720 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11722 if (observer != null) {
11723 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11725 } catch (RemoteException re) {
11730 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11731 installFlags |= PackageManager.INSTALL_FROM_ADB;
11734 // Caller holds INSTALL_PACKAGES permission, so we're less strict
11735 // about installerPackageName.
11737 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11738 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11742 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11743 user = UserHandle.ALL;
11745 user = new UserHandle(userId);
11748 // Only system components can circumvent runtime permissions when installing.
11749 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11750 && mContext.checkCallingOrSelfPermission(Manifest.permission
11751 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11752 throw new SecurityException("You need the "
11753 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11754 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11757 final File originFile = new File(originPath);
11758 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11760 final Message msg = mHandler.obtainMessage(INIT_COPY);
11761 final VerificationInfo verificationInfo = new VerificationInfo(
11762 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11763 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11764 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11765 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11766 null /*certificates*/);
11767 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11770 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11771 System.identityHashCode(msg.obj));
11772 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11773 System.identityHashCode(msg.obj));
11775 mHandler.sendMessage(msg);
11778 void installStage(String packageName, File stagedDir, String stagedCid,
11779 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11780 String installerPackageName, int installerUid, UserHandle user,
11781 Certificate[][] certificates) {
11782 if (DEBUG_EPHEMERAL) {
11783 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11784 Slog.d(TAG, "Ephemeral install of " + packageName);
11787 final VerificationInfo verificationInfo = new VerificationInfo(
11788 sessionParams.originatingUri, sessionParams.referrerUri,
11789 sessionParams.originatingUid, installerUid);
11791 final OriginInfo origin;
11792 if (stagedDir != null) {
11793 origin = OriginInfo.fromStagedFile(stagedDir);
11795 origin = OriginInfo.fromStagedContainer(stagedCid);
11798 final Message msg = mHandler.obtainMessage(INIT_COPY);
11799 final InstallParams params = new InstallParams(origin, null, observer,
11800 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11801 verificationInfo, user, sessionParams.abiOverride,
11802 sessionParams.grantedRuntimePermissions, certificates);
11803 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11806 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11807 System.identityHashCode(msg.obj));
11808 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11809 System.identityHashCode(msg.obj));
11811 mHandler.sendMessage(msg);
11814 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11816 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11817 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11820 private void sendPackageAddedForUser(String packageName, boolean isSystem,
11821 int appId, int userId) {
11822 Bundle extras = new Bundle(1);
11823 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11825 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11826 packageName, extras, 0, null, null, new int[] {userId});
11828 IActivityManager am = ActivityManagerNative.getDefault();
11829 if (isSystem && am.isUserRunning(userId, 0)) {
11830 // The just-installed/enabled app is bundled on the system, so presumed
11831 // to be able to run automatically without needing an explicit launch.
11832 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11833 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11834 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11835 .setPackage(packageName);
11836 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11837 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11839 } catch (RemoteException e) {
11840 // shouldn't happen
11841 Slog.w(TAG, "Unable to bootstrap installed package", e);
11846 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11848 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11849 PackageSetting pkgSetting;
11850 final int uid = Binder.getCallingUid();
11851 enforceCrossUserPermission(uid, userId,
11852 true /* requireFullPermission */, true /* checkShell */,
11853 "setApplicationHiddenSetting for user " + userId);
11855 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11856 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11860 long callingId = Binder.clearCallingIdentity();
11862 boolean sendAdded = false;
11863 boolean sendRemoved = false;
11865 synchronized (mPackages) {
11866 pkgSetting = mSettings.mPackages.get(packageName);
11867 if (pkgSetting == null) {
11870 // Do not allow "android" is being disabled
11871 if ("android".equals(packageName)) {
11872 Slog.w(TAG, "Cannot hide package: android");
11875 // Only allow protected packages to hide themselves.
11876 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11877 && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11878 Slog.w(TAG, "Not hiding protected package: " + packageName);
11882 if (pkgSetting.getHidden(userId) != hidden) {
11883 pkgSetting.setHidden(hidden, userId);
11884 mSettings.writePackageRestrictionsLPr(userId);
11886 sendRemoved = true;
11893 sendPackageAddedForUser(packageName, pkgSetting, userId);
11897 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11899 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11903 Binder.restoreCallingIdentity(callingId);
11908 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11910 final PackageRemovedInfo info = new PackageRemovedInfo();
11911 info.removedPackage = packageName;
11912 info.removedUsers = new int[] {userId};
11913 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11914 info.sendPackageRemovedBroadcasts(true /*killApp*/);
11917 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11918 if (pkgList.length > 0) {
11919 Bundle extras = new Bundle(1);
11920 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11922 sendPackageBroadcast(
11923 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11924 : Intent.ACTION_PACKAGES_UNSUSPENDED,
11925 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11926 new int[] {userId});
11931 * Returns true if application is not found or there was an error. Otherwise it returns
11932 * the hidden state of the package for the given user.
11935 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11936 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11937 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11938 true /* requireFullPermission */, false /* checkShell */,
11939 "getApplicationHidden for user " + userId);
11940 PackageSetting pkgSetting;
11941 long callingId = Binder.clearCallingIdentity();
11944 synchronized (mPackages) {
11945 pkgSetting = mSettings.mPackages.get(packageName);
11946 if (pkgSetting == null) {
11949 return pkgSetting.getHidden(userId);
11952 Binder.restoreCallingIdentity(callingId);
11960 public int installExistingPackageAsUser(String packageName, int userId) {
11961 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11963 PackageSetting pkgSetting;
11964 final int uid = Binder.getCallingUid();
11965 enforceCrossUserPermission(uid, userId,
11966 true /* requireFullPermission */, true /* checkShell */,
11967 "installExistingPackage for user " + userId);
11968 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11969 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11972 long callingId = Binder.clearCallingIdentity();
11974 boolean installed = false;
11977 synchronized (mPackages) {
11978 pkgSetting = mSettings.mPackages.get(packageName);
11979 if (pkgSetting == null) {
11980 return PackageManager.INSTALL_FAILED_INVALID_URI;
11982 if (!pkgSetting.getInstalled(userId)) {
11983 pkgSetting.setInstalled(true, userId);
11984 pkgSetting.setHidden(false, userId);
11985 mSettings.writePackageRestrictionsLPr(userId);
11991 if (pkgSetting.pkg != null) {
11992 synchronized (mInstallLock) {
11993 // We don't need to freeze for a brand new install
11994 prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11997 sendPackageAddedForUser(packageName, pkgSetting, userId);
12000 Binder.restoreCallingIdentity(callingId);
12003 return PackageManager.INSTALL_SUCCEEDED;
12006 boolean isUserRestricted(int userId, String restrictionKey) {
12007 Bundle restrictions = sUserManager.getUserRestrictions(userId);
12008 if (restrictions.getBoolean(restrictionKey, false)) {
12009 Log.w(TAG, "User is restricted: " + restrictionKey);
12016 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12018 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12019 enforceCrossUserPermission(Binder.getCallingUid(), userId,
12020 true /* requireFullPermission */, true /* checkShell */,
12021 "setPackagesSuspended for user " + userId);
12023 if (ArrayUtils.isEmpty(packageNames)) {
12024 return packageNames;
12027 // List of package names for whom the suspended state has changed.
12028 List<String> changedPackages = new ArrayList<>(packageNames.length);
12029 // List of package names for whom the suspended state is not set as requested in this
12031 List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12032 long callingId = Binder.clearCallingIdentity();
12034 for (int i = 0; i < packageNames.length; i++) {
12035 String packageName = packageNames[i];
12036 boolean changed = false;
12038 synchronized (mPackages) {
12039 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12040 if (pkgSetting == null) {
12041 Slog.w(TAG, "Could not find package setting for package \"" + packageName
12042 + "\". Skipping suspending/un-suspending.");
12043 unactionedPackages.add(packageName);
12046 appId = pkgSetting.appId;
12047 if (pkgSetting.getSuspended(userId) != suspended) {
12048 if (!canSuspendPackageForUserLocked(packageName, userId)) {
12049 unactionedPackages.add(packageName);
12052 pkgSetting.setSuspended(suspended, userId);
12053 mSettings.writePackageRestrictionsLPr(userId);
12055 changedPackages.add(packageName);
12059 if (changed && suspended) {
12060 killApplication(packageName, UserHandle.getUid(userId, appId),
12061 "suspending package");
12065 Binder.restoreCallingIdentity(callingId);
12068 if (!changedPackages.isEmpty()) {
12069 sendPackagesSuspendedForUser(changedPackages.toArray(
12070 new String[changedPackages.size()]), userId, suspended);
12073 return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12077 public boolean isPackageSuspendedForUser(String packageName, int userId) {
12078 enforceCrossUserPermission(Binder.getCallingUid(), userId,
12079 true /* requireFullPermission */, false /* checkShell */,
12080 "isPackageSuspendedForUser for user " + userId);
12081 synchronized (mPackages) {
12082 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12083 if (pkgSetting == null) {
12084 throw new IllegalArgumentException("Unknown target package: " + packageName);
12086 return pkgSetting.getSuspended(userId);
12090 private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12091 if (isPackageDeviceAdmin(packageName, userId)) {
12092 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12093 + "\": has an active device admin");
12097 String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12098 if (packageName.equals(activeLauncherPackageName)) {
12099 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12100 + "\": contains the active launcher");
12104 if (packageName.equals(mRequiredInstallerPackage)) {
12105 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12106 + "\": required for package installation");
12110 if (packageName.equals(mRequiredUninstallerPackage)) {
12111 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12112 + "\": required for package uninstallation");
12116 if (packageName.equals(mRequiredVerifierPackage)) {
12117 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12118 + "\": required for package verification");
12122 if (packageName.equals(getDefaultDialerPackageName(userId))) {
12123 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12124 + "\": is the default dialer");
12128 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12129 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12130 + "\": protected package");
12137 private String getActiveLauncherPackageName(int userId) {
12138 Intent intent = new Intent(Intent.ACTION_MAIN);
12139 intent.addCategory(Intent.CATEGORY_HOME);
12140 ResolveInfo resolveInfo = resolveIntent(
12142 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12143 PackageManager.MATCH_DEFAULT_ONLY,
12146 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12149 private String getDefaultDialerPackageName(int userId) {
12150 synchronized (mPackages) {
12151 return mSettings.getDefaultDialerPackageNameLPw(userId);
12156 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12157 mContext.enforceCallingOrSelfPermission(
12158 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12159 "Only package verification agents can verify applications");
12161 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12162 final PackageVerificationResponse response = new PackageVerificationResponse(
12163 verificationCode, Binder.getCallingUid());
12165 msg.obj = response;
12166 mHandler.sendMessage(msg);
12170 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12171 long millisecondsToDelay) {
12172 mContext.enforceCallingOrSelfPermission(
12173 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12174 "Only package verification agents can extend verification timeouts");
12176 final PackageVerificationState state = mPendingVerification.get(id);
12177 final PackageVerificationResponse response = new PackageVerificationResponse(
12178 verificationCodeAtTimeout, Binder.getCallingUid());
12180 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12181 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12183 if (millisecondsToDelay < 0) {
12184 millisecondsToDelay = 0;
12186 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12187 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12188 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12191 if ((state != null) && !state.timeoutExtended()) {
12192 state.extendTimeout();
12194 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12196 msg.obj = response;
12197 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12201 private void broadcastPackageVerified(int verificationId, Uri packageUri,
12202 int verificationCode, UserHandle user) {
12203 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12204 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12205 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12206 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12207 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12209 mContext.sendBroadcastAsUser(intent, user,
12210 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12213 private ComponentName matchComponentForVerifier(String packageName,
12214 List<ResolveInfo> receivers) {
12215 ActivityInfo targetReceiver = null;
12217 final int NR = receivers.size();
12218 for (int i = 0; i < NR; i++) {
12219 final ResolveInfo info = receivers.get(i);
12220 if (info.activityInfo == null) {
12224 if (packageName.equals(info.activityInfo.packageName)) {
12225 targetReceiver = info.activityInfo;
12230 if (targetReceiver == null) {
12234 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12237 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12238 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12239 if (pkgInfo.verifiers.length == 0) {
12243 final int N = pkgInfo.verifiers.length;
12244 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12245 for (int i = 0; i < N; i++) {
12246 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12248 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12250 if (comp == null) {
12254 final int verifierUid = getUidForVerifier(verifierInfo);
12255 if (verifierUid == -1) {
12259 if (DEBUG_VERIFY) {
12260 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12261 + " with the correct signature");
12263 sufficientVerifiers.add(comp);
12264 verificationState.addSufficientVerifier(verifierUid);
12267 return sufficientVerifiers;
12270 private int getUidForVerifier(VerifierInfo verifierInfo) {
12271 synchronized (mPackages) {
12272 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12275 } else if (pkg.mSignatures.length != 1) {
12276 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12277 + " has more than one signature; ignoring");
12282 * If the public key of the package's signature does not match
12283 * our expected public key, then this is a different package and
12287 final byte[] expectedPublicKey;
12289 final Signature verifierSig = pkg.mSignatures[0];
12290 final PublicKey publicKey = verifierSig.getPublicKey();
12291 expectedPublicKey = publicKey.getEncoded();
12292 } catch (CertificateException e) {
12296 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12298 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12299 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12300 + " does not have the expected public key; ignoring");
12304 return pkg.applicationInfo.uid;
12309 public void finishPackageInstall(int token, boolean didLaunch) {
12310 enforceSystemOrRoot("Only the system is allowed to finish installs");
12312 if (DEBUG_INSTALL) {
12313 Slog.v(TAG, "BM finishing package install for " + token);
12315 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12317 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12318 mHandler.sendMessage(msg);
12322 * Get the verification agent timeout.
12324 * @return verification timeout in milliseconds
12326 private long getVerificationTimeout() {
12327 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12328 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12329 DEFAULT_VERIFICATION_TIMEOUT);
12333 * Get the default verification agent response code.
12335 * @return default verification response code
12337 private int getDefaultVerificationResponse() {
12338 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12339 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12340 DEFAULT_VERIFICATION_RESPONSE);
12344 * Check whether or not package verification has been enabled.
12346 * @return true if verification should be performed
12348 private boolean isVerificationEnabled(int userId, int installFlags) {
12349 if (!DEFAULT_VERIFY_ENABLE) {
12352 // Ephemeral apps don't get the full verification treatment
12353 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12354 if (DEBUG_EPHEMERAL) {
12355 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12360 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12362 // Check if installing from ADB
12363 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12364 // Do not run verification in a test harness environment
12365 if (ActivityManager.isRunningInTestHarness()) {
12368 if (ensureVerifyAppsEnabled) {
12371 // Check if the developer does not want package verification for ADB installs
12372 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12373 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12378 if (ensureVerifyAppsEnabled) {
12382 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12383 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12387 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12388 throws RemoteException {
12389 mContext.enforceCallingOrSelfPermission(
12390 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12391 "Only intentfilter verification agents can verify applications");
12393 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12394 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12395 Binder.getCallingUid(), verificationCode, failedDomains);
12397 msg.obj = response;
12398 mHandler.sendMessage(msg);
12402 public int getIntentVerificationStatus(String packageName, int userId) {
12403 synchronized (mPackages) {
12404 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12409 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12410 mContext.enforceCallingOrSelfPermission(
12411 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12413 boolean result = false;
12414 synchronized (mPackages) {
12415 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12418 scheduleWritePackageRestrictionsLocked(userId);
12424 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12425 String packageName) {
12426 synchronized (mPackages) {
12427 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12432 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12433 if (TextUtils.isEmpty(packageName)) {
12434 return ParceledListSlice.emptyList();
12436 synchronized (mPackages) {
12437 PackageParser.Package pkg = mPackages.get(packageName);
12438 if (pkg == null || pkg.activities == null) {
12439 return ParceledListSlice.emptyList();
12441 final int count = pkg.activities.size();
12442 ArrayList<IntentFilter> result = new ArrayList<>();
12443 for (int n=0; n<count; n++) {
12444 PackageParser.Activity activity = pkg.activities.get(n);
12445 if (activity.intents != null && activity.intents.size() > 0) {
12446 result.addAll(activity.intents);
12449 return new ParceledListSlice<>(result);
12454 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12455 mContext.enforceCallingOrSelfPermission(
12456 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12458 synchronized (mPackages) {
12459 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12460 if (packageName != null) {
12461 result |= updateIntentVerificationStatus(packageName,
12462 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12464 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12465 packageName, userId);
12472 public String getDefaultBrowserPackageName(int userId) {
12473 synchronized (mPackages) {
12474 return mSettings.getDefaultBrowserPackageNameLPw(userId);
12479 * Get the "allow unknown sources" setting.
12481 * @return the current "allow unknown sources" setting
12483 private int getUnknownSourcesSettings() {
12484 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12485 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12490 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12491 final int uid = Binder.getCallingUid();
12493 synchronized (mPackages) {
12494 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12495 if (targetPackageSetting == null) {
12496 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12499 PackageSetting installerPackageSetting;
12500 if (installerPackageName != null) {
12501 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12502 if (installerPackageSetting == null) {
12503 throw new IllegalArgumentException("Unknown installer package: "
12504 + installerPackageName);
12507 installerPackageSetting = null;
12510 Signature[] callerSignature;
12511 Object obj = mSettings.getUserIdLPr(uid);
12513 if (obj instanceof SharedUserSetting) {
12514 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12515 } else if (obj instanceof PackageSetting) {
12516 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12518 throw new SecurityException("Bad object " + obj + " for uid " + uid);
12521 throw new SecurityException("Unknown calling UID: " + uid);
12524 // Verify: can't set installerPackageName to a package that is
12525 // not signed with the same cert as the caller.
12526 if (installerPackageSetting != null) {
12527 if (compareSignatures(callerSignature,
12528 installerPackageSetting.signatures.mSignatures)
12529 != PackageManager.SIGNATURE_MATCH) {
12530 throw new SecurityException(
12531 "Caller does not have same cert as new installer package "
12532 + installerPackageName);
12536 // Verify: if target already has an installer package, it must
12537 // be signed with the same cert as the caller.
12538 if (targetPackageSetting.installerPackageName != null) {
12539 PackageSetting setting = mSettings.mPackages.get(
12540 targetPackageSetting.installerPackageName);
12541 // If the currently set package isn't valid, then it's always
12542 // okay to change it.
12543 if (setting != null) {
12544 if (compareSignatures(callerSignature,
12545 setting.signatures.mSignatures)
12546 != PackageManager.SIGNATURE_MATCH) {
12547 throw new SecurityException(
12548 "Caller does not have same cert as old installer package "
12549 + targetPackageSetting.installerPackageName);
12555 targetPackageSetting.installerPackageName = installerPackageName;
12556 if (installerPackageName != null) {
12557 mSettings.mInstallerPackages.add(installerPackageName);
12559 scheduleWriteSettingsLocked();
12563 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12564 // Queue up an async operation since the package installation may take a little while.
12565 mHandler.post(new Runnable() {
12566 public void run() {
12567 mHandler.removeCallbacks(this);
12568 // Result object to be returned
12569 PackageInstalledInfo res = new PackageInstalledInfo();
12570 res.setReturnCode(currentStatus);
12573 res.removedInfo = null;
12574 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12575 args.doPreInstall(res.returnCode);
12576 synchronized (mInstallLock) {
12577 installPackageTracedLI(args, res);
12579 args.doPostInstall(res.returnCode, res.uid);
12582 // A restore should be performed at this point if (a) the install
12583 // succeeded, (b) the operation is not an update, and (c) the new
12584 // package has not opted out of backup participation.
12585 final boolean update = res.removedInfo != null
12586 && res.removedInfo.removedPackage != null;
12587 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12588 boolean doRestore = !update
12589 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12591 // Set up the post-install work request bookkeeping. This will be used
12592 // and cleaned up by the post-install event handling regardless of whether
12593 // there's a restore pass performed. Token values are >= 1.
12595 if (mNextInstallToken < 0) mNextInstallToken = 1;
12596 token = mNextInstallToken++;
12598 PostInstallData data = new PostInstallData(args, res);
12599 mRunningInstalls.put(token, data);
12600 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12602 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12603 // Pass responsibility to the Backup Manager. It will perform a
12604 // restore if appropriate, then pass responsibility back to the
12605 // Package Manager to run the post-install observer callbacks
12607 IBackupManager bm = IBackupManager.Stub.asInterface(
12608 ServiceManager.getService(Context.BACKUP_SERVICE));
12610 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12611 + " to BM for possible restore");
12612 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12614 // TODO: http://b/22388012
12615 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12616 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12620 } catch (RemoteException e) {
12621 // can't happen; the backup manager is local
12622 } catch (Exception e) {
12623 Slog.e(TAG, "Exception trying to enqueue restore", e);
12627 Slog.e(TAG, "Backup Manager not found!");
12633 // No restore possible, or the Backup Manager was mysteriously not
12634 // available -- just fire the post-install work request directly.
12635 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12637 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12639 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12640 mHandler.sendMessage(msg);
12647 * Callback from PackageSettings whenever an app is first transitioned out of the
12648 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if
12649 * the app was "launched" for a restoreAtInstall operation. Therefore we check
12650 * here whether the app is the target of an ongoing install, and only send the
12651 * broadcast immediately if it is not in that state. If it *is* undergoing a restore,
12652 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12655 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12656 // Serialize this with the rest of the install-process message chain. In the
12657 // restore-at-install case, this Runnable will necessarily run before the
12658 // POST_INSTALL message is processed, so the contents of mRunningInstalls
12659 // are coherent. In the non-restore case, the app has already completed install
12660 // and been launched through some other means, so it is not in a problematic
12661 // state for observers to see the FIRST_LAUNCH signal.
12662 mHandler.post(new Runnable() {
12664 public void run() {
12665 for (int i = 0; i < mRunningInstalls.size(); i++) {
12666 final PostInstallData data = mRunningInstalls.valueAt(i);
12667 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12670 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12671 // right package; but is it for the right user?
12672 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12673 if (userId == data.res.newUsers[uIndex]) {
12674 if (DEBUG_BACKUP) {
12675 Slog.i(TAG, "Package " + pkgName
12676 + " being restored so deferring FIRST_LAUNCH");
12683 // didn't find it, so not being restored
12684 if (DEBUG_BACKUP) {
12685 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12687 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12692 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12693 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12694 installerPkg, null, userIds);
12697 private abstract class HandlerParams {
12698 private static final int MAX_RETRIES = 4;
12701 * Number of times startCopy() has been attempted and had a non-fatal
12704 private int mRetries = 0;
12706 /** User handle for the user requesting the information or installation. */
12707 private final UserHandle mUser;
12708 String traceMethod;
12711 HandlerParams(UserHandle user) {
12715 UserHandle getUser() {
12719 HandlerParams setTraceMethod(String traceMethod) {
12720 this.traceMethod = traceMethod;
12724 HandlerParams setTraceCookie(int traceCookie) {
12725 this.traceCookie = traceCookie;
12729 final boolean startCopy() {
12732 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12734 if (++mRetries > MAX_RETRIES) {
12735 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12736 mHandler.sendEmptyMessage(MCS_GIVE_UP);
12737 handleServiceError();
12743 } catch (RemoteException e) {
12744 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12745 mHandler.sendEmptyMessage(MCS_RECONNECT);
12748 handleReturnCode();
12752 final void serviceError() {
12753 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12754 handleServiceError();
12755 handleReturnCode();
12758 abstract void handleStartCopy() throws RemoteException;
12759 abstract void handleServiceError();
12760 abstract void handleReturnCode();
12763 class MeasureParams extends HandlerParams {
12764 private final PackageStats mStats;
12765 private boolean mSuccess;
12767 private final IPackageStatsObserver mObserver;
12769 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12770 super(new UserHandle(stats.userHandle));
12771 mObserver = observer;
12776 public String toString() {
12777 return "MeasureParams{"
12778 + Integer.toHexString(System.identityHashCode(this))
12779 + " " + mStats.packageName + "}";
12783 void handleStartCopy() throws RemoteException {
12784 synchronized (mInstallLock) {
12785 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12789 boolean mounted = false;
12791 final String status = Environment.getExternalStorageState();
12792 mounted = (Environment.MEDIA_MOUNTED.equals(status)
12793 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12794 } catch (Exception e) {
12798 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12800 mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12801 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12803 mStats.externalDataSize = calculateDirectorySize(mContainerService,
12804 userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12806 // Always subtract cache size, since it's a subdirectory
12807 mStats.externalDataSize -= mStats.externalCacheSize;
12809 mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12810 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12812 mStats.externalObbSize = calculateDirectorySize(mContainerService,
12813 userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12819 void handleReturnCode() {
12820 if (mObserver != null) {
12822 mObserver.onGetStatsCompleted(mStats, mSuccess);
12823 } catch (RemoteException e) {
12824 Slog.i(TAG, "Observer no longer exists.");
12830 void handleServiceError() {
12831 Slog.e(TAG, "Could not measure application " + mStats.packageName
12832 + " external storage");
12836 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12837 throws RemoteException {
12839 for (File path : paths) {
12840 result += mcs.calculateDirectorySize(path.getAbsolutePath());
12845 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12846 for (File path : paths) {
12848 mcs.clearDirectory(path.getAbsolutePath());
12849 } catch (RemoteException e) {
12854 static class OriginInfo {
12856 * Location where install is coming from, before it has been
12857 * copied/renamed into place. This could be a single monolithic APK
12858 * file, or a cluster directory. This location may be untrusted.
12864 * Flag indicating that {@link #file} or {@link #cid} has already been
12865 * staged, meaning downstream users don't need to defensively copy the
12868 final boolean staged;
12871 * Flag indicating that {@link #file} or {@link #cid} is an already
12872 * installed app that is being moved.
12874 final boolean existing;
12876 final String resolvedPath;
12877 final File resolvedFile;
12879 static OriginInfo fromNothing() {
12880 return new OriginInfo(null, null, false, false);
12883 static OriginInfo fromUntrustedFile(File file) {
12884 return new OriginInfo(file, null, false, false);
12887 static OriginInfo fromExistingFile(File file) {
12888 return new OriginInfo(file, null, false, true);
12891 static OriginInfo fromStagedFile(File file) {
12892 return new OriginInfo(file, null, true, false);
12895 static OriginInfo fromStagedContainer(String cid) {
12896 return new OriginInfo(null, cid, true, false);
12899 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12902 this.staged = staged;
12903 this.existing = existing;
12906 resolvedPath = PackageHelper.getSdDir(cid);
12907 resolvedFile = new File(resolvedPath);
12908 } else if (file != null) {
12909 resolvedPath = file.getAbsolutePath();
12910 resolvedFile = file;
12912 resolvedPath = null;
12913 resolvedFile = null;
12918 static class MoveInfo {
12920 final String fromUuid;
12921 final String toUuid;
12922 final String packageName;
12923 final String dataAppName;
12925 final String seinfo;
12926 final int targetSdkVersion;
12928 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12929 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12930 this.moveId = moveId;
12931 this.fromUuid = fromUuid;
12932 this.toUuid = toUuid;
12933 this.packageName = packageName;
12934 this.dataAppName = dataAppName;
12935 this.appId = appId;
12936 this.seinfo = seinfo;
12937 this.targetSdkVersion = targetSdkVersion;
12941 static class VerificationInfo {
12942 /** A constant used to indicate that a uid value is not present. */
12943 public static final int NO_UID = -1;
12945 /** URI referencing where the package was downloaded from. */
12946 final Uri originatingUri;
12948 /** HTTP referrer URI associated with the originatingURI. */
12949 final Uri referrer;
12951 /** UID of the application that the install request originated from. */
12952 final int originatingUid;
12954 /** UID of application requesting the install */
12955 final int installerUid;
12957 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12958 this.originatingUri = originatingUri;
12959 this.referrer = referrer;
12960 this.originatingUid = originatingUid;
12961 this.installerUid = installerUid;
12965 class InstallParams extends HandlerParams {
12966 final OriginInfo origin;
12967 final MoveInfo move;
12968 final IPackageInstallObserver2 observer;
12970 final String installerPackageName;
12971 final String volumeUuid;
12972 private InstallArgs mArgs;
12974 final String packageAbiOverride;
12975 final String[] grantedRuntimePermissions;
12976 final VerificationInfo verificationInfo;
12977 final Certificate[][] certificates;
12979 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12980 int installFlags, String installerPackageName, String volumeUuid,
12981 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12982 String[] grantedPermissions, Certificate[][] certificates) {
12984 this.origin = origin;
12986 this.observer = observer;
12987 this.installFlags = installFlags;
12988 this.installerPackageName = installerPackageName;
12989 this.volumeUuid = volumeUuid;
12990 this.verificationInfo = verificationInfo;
12991 this.packageAbiOverride = packageAbiOverride;
12992 this.grantedRuntimePermissions = grantedPermissions;
12993 this.certificates = certificates;
12997 public String toString() {
12998 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12999 + " file=" + origin.file + " cid=" + origin.cid + "}";
13002 private int installLocationPolicy(PackageInfoLite pkgLite) {
13003 String packageName = pkgLite.packageName;
13004 int installLocation = pkgLite.installLocation;
13005 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13007 synchronized (mPackages) {
13008 // Currently installed package which the new package is attempting to replace or
13009 // null if no such package is installed.
13010 PackageParser.Package installedPkg = mPackages.get(packageName);
13011 // Package which currently owns the data which the new package will own if installed.
13012 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13013 // will be null whereas dataOwnerPkg will contain information about the package
13014 // which was uninstalled while keeping its data.
13015 PackageParser.Package dataOwnerPkg = installedPkg;
13016 if (dataOwnerPkg == null) {
13017 PackageSetting ps = mSettings.mPackages.get(packageName);
13019 dataOwnerPkg = ps.pkg;
13023 if (dataOwnerPkg != null) {
13024 // If installed, the package will get access to data left on the device by its
13025 // predecessor. As a security measure, this is permited only if this is not a
13026 // version downgrade or if the predecessor package is marked as debuggable and
13027 // a downgrade is explicitly requested.
13029 // On debuggable platform builds, downgrades are permitted even for
13030 // non-debuggable packages to make testing easier. Debuggable platform builds do
13031 // not offer security guarantees and thus it's OK to disable some security
13032 // mechanisms to make debugging/testing easier on those builds. However, even on
13033 // debuggable builds downgrades of packages are permitted only if requested via
13034 // installFlags. This is because we aim to keep the behavior of debuggable
13035 // platform builds as close as possible to the behavior of non-debuggable
13036 // platform builds.
13037 final boolean downgradeRequested =
13038 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13039 final boolean packageDebuggable =
13040 (dataOwnerPkg.applicationInfo.flags
13041 & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13042 final boolean downgradePermitted =
13043 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13044 if (!downgradePermitted) {
13046 checkDowngrade(dataOwnerPkg, pkgLite);
13047 } catch (PackageManagerException e) {
13048 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13049 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13054 if (installedPkg != null) {
13055 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13056 // Check for updated system application.
13057 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13059 Slog.w(TAG, "Cannot install update to system app on sdcard");
13060 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13062 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13065 // Install flag overrides everything.
13066 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13068 // If current upgrade specifies particular preference
13069 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13070 // Application explicitly specified internal.
13071 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13072 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13073 // App explictly prefers external. Let policy decide
13075 // Prefer previous location
13076 if (isExternal(installedPkg)) {
13077 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13079 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13083 // Invalid install. Return error code
13084 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13088 // All the special cases have been taken care of.
13089 // Return result based on recommended install location.
13091 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13093 return pkgLite.recommendedInstallLocation;
13097 * Invoke remote method to get package information and install
13098 * location values. Override install location based on default
13099 * policy if needed and then create install arguments based
13100 * on the install location.
13102 public void handleStartCopy() throws RemoteException {
13103 int ret = PackageManager.INSTALL_SUCCEEDED;
13105 // If we're already staged, we've firmly committed to an install location
13106 if (origin.staged) {
13107 if (origin.file != null) {
13108 installFlags |= PackageManager.INSTALL_INTERNAL;
13109 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13110 } else if (origin.cid != null) {
13111 installFlags |= PackageManager.INSTALL_EXTERNAL;
13112 installFlags &= ~PackageManager.INSTALL_INTERNAL;
13114 throw new IllegalStateException("Invalid stage location");
13118 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13119 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13120 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13121 PackageInfoLite pkgLite = null;
13123 if (onInt && onSd) {
13124 // Check if both bits are set.
13125 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13126 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13127 } else if (onSd && ephemeral) {
13128 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external");
13129 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13131 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13132 packageAbiOverride);
13134 if (DEBUG_EPHEMERAL && ephemeral) {
13135 Slog.v(TAG, "pkgLite for install: " + pkgLite);
13139 * If we have too little free space, try to free cache
13140 * before giving up.
13142 if (!origin.staged && pkgLite.recommendedInstallLocation
13143 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13144 // TODO: focus freeing disk space on the target device
13145 final StorageManager storage = StorageManager.from(mContext);
13146 final long lowThreshold = storage.getStorageLowBytes(
13147 Environment.getDataDirectory());
13149 final long sizeBytes = mContainerService.calculateInstalledSize(
13150 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13153 mInstaller.freeCache(null, sizeBytes + lowThreshold);
13154 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13155 installFlags, packageAbiOverride);
13156 } catch (InstallerException e) {
13157 Slog.w(TAG, "Failed to free cache", e);
13161 * The cache free must have deleted the file we
13162 * downloaded to install.
13164 * TODO: fix the "freeCache" call to not delete
13165 * the file we care about.
13167 if (pkgLite.recommendedInstallLocation
13168 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13169 pkgLite.recommendedInstallLocation
13170 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13175 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13176 int loc = pkgLite.recommendedInstallLocation;
13177 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13178 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13179 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13180 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13181 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13182 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13183 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13184 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13185 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13186 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13187 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13188 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13190 // Override with defaults if needed.
13191 loc = installLocationPolicy(pkgLite);
13192 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13193 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13194 } else if (!onSd && !onInt) {
13195 // Override install location with flags
13196 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13197 // Set the flag to install on external media.
13198 installFlags |= PackageManager.INSTALL_EXTERNAL;
13199 installFlags &= ~PackageManager.INSTALL_INTERNAL;
13200 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13201 if (DEBUG_EPHEMERAL) {
13202 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13204 installFlags |= PackageManager.INSTALL_EPHEMERAL;
13205 installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13206 |PackageManager.INSTALL_INTERNAL);
13208 // Make sure the flag for installing on external
13210 installFlags |= PackageManager.INSTALL_INTERNAL;
13211 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13217 final InstallArgs args = createInstallArgs(this);
13220 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13221 // TODO: http://b/22976637
13222 // Apps installed for "all" users use the device owner to verify the app
13223 UserHandle verifierUser = getUser();
13224 if (verifierUser == UserHandle.ALL) {
13225 verifierUser = UserHandle.SYSTEM;
13229 * Determine if we have any installed package verifiers. If we
13230 * do, then we'll defer to them to verify the packages.
13232 final int requiredUid = mRequiredVerifierPackage == null ? -1
13233 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13234 verifierUser.getIdentifier());
13235 if (!origin.existing && requiredUid != -1
13236 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13237 final Intent verification = new Intent(
13238 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13239 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13240 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13241 PACKAGE_MIME_TYPE);
13242 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13244 // Query all live verifiers based on current user state
13245 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13246 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13248 if (DEBUG_VERIFY) {
13249 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13250 + verification.toString() + " with " + pkgLite.verifiers.length
13251 + " optional verifiers");
13254 final int verificationId = mPendingVerificationToken++;
13256 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13258 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13259 installerPackageName);
13261 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13264 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13265 pkgLite.packageName);
13267 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13268 pkgLite.versionCode);
13270 if (verificationInfo != null) {
13271 if (verificationInfo.originatingUri != null) {
13272 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13273 verificationInfo.originatingUri);
13275 if (verificationInfo.referrer != null) {
13276 verification.putExtra(Intent.EXTRA_REFERRER,
13277 verificationInfo.referrer);
13279 if (verificationInfo.originatingUid >= 0) {
13280 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13281 verificationInfo.originatingUid);
13283 if (verificationInfo.installerUid >= 0) {
13284 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13285 verificationInfo.installerUid);
13289 final PackageVerificationState verificationState = new PackageVerificationState(
13290 requiredUid, args);
13292 mPendingVerification.append(verificationId, verificationState);
13294 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13295 receivers, verificationState);
13298 * If any sufficient verifiers were listed in the package
13299 * manifest, attempt to ask them.
13301 if (sufficientVerifiers != null) {
13302 final int N = sufficientVerifiers.size();
13304 Slog.i(TAG, "Additional verifiers required, but none installed.");
13305 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13307 for (int i = 0; i < N; i++) {
13308 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13310 final Intent sufficientIntent = new Intent(verification);
13311 sufficientIntent.setComponent(verifierComponent);
13312 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13317 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13318 mRequiredVerifierPackage, receivers);
13319 if (ret == PackageManager.INSTALL_SUCCEEDED
13320 && mRequiredVerifierPackage != null) {
13321 Trace.asyncTraceBegin(
13322 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13324 * Send the intent to the required verification agent,
13325 * but only start the verification timeout after the
13326 * target BroadcastReceivers have run.
13328 verification.setComponent(requiredVerifierComponent);
13329 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13330 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13331 new BroadcastReceiver() {
13333 public void onReceive(Context context, Intent intent) {
13334 final Message msg = mHandler
13335 .obtainMessage(CHECK_PENDING_VERIFICATION);
13336 msg.arg1 = verificationId;
13337 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13339 }, null, 0, null, null);
13342 * We don't want the copy to proceed until verification
13343 * succeeds, so null out this field.
13349 * No package verification is enabled, so immediately start
13350 * the remote call to initiate copy using temporary file.
13352 ret = args.copyApk(mContainerService, true);
13360 void handleReturnCode() {
13361 // If mArgs is null, then MCS couldn't be reached. When it
13362 // reconnects, it will try again to install. At that point, this
13364 if (mArgs != null) {
13365 processPendingInstall(mArgs, mRet);
13370 void handleServiceError() {
13371 mArgs = createInstallArgs(this);
13372 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13375 public boolean isForwardLocked() {
13376 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13381 * Used during creation of InstallArgs
13383 * @param installFlags package installation flags
13384 * @return true if should be installed on external storage
13386 private static boolean installOnExternalAsec(int installFlags) {
13387 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13390 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13397 * Used during creation of InstallArgs
13399 * @param installFlags package installation flags
13400 * @return true if should be installed as forward locked
13402 private static boolean installForwardLocked(int installFlags) {
13403 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13406 private InstallArgs createInstallArgs(InstallParams params) {
13407 if (params.move != null) {
13408 return new MoveInstallArgs(params);
13409 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13410 return new AsecInstallArgs(params);
13412 return new FileInstallArgs(params);
13417 * Create args that describe an existing installed package. Typically used
13418 * when cleaning up old installs, or used as a move source.
13420 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13421 String resourcePath, String[] instructionSets) {
13422 final boolean isInAsec;
13423 if (installOnExternalAsec(installFlags)) {
13424 /* Apps on SD card are always in ASEC containers. */
13426 } else if (installForwardLocked(installFlags)
13427 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13429 * Forward-locked apps are only in ASEC containers if they're the
13438 return new AsecInstallArgs(codePath, instructionSets,
13439 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13441 return new FileInstallArgs(codePath, resourcePath, instructionSets);
13445 static abstract class InstallArgs {
13446 /** @see InstallParams#origin */
13447 final OriginInfo origin;
13448 /** @see InstallParams#move */
13449 final MoveInfo move;
13451 final IPackageInstallObserver2 observer;
13452 // Always refers to PackageManager flags only
13453 final int installFlags;
13454 final String installerPackageName;
13455 final String volumeUuid;
13456 final UserHandle user;
13457 final String abiOverride;
13458 final String[] installGrantPermissions;
13459 /** If non-null, drop an async trace when the install completes */
13460 final String traceMethod;
13461 final int traceCookie;
13462 final Certificate[][] certificates;
13464 // The list of instruction sets supported by this app. This is currently
13465 // only used during the rmdex() phase to clean up resources. We can get rid of this
13466 // if we move dex files under the common app path.
13467 /* nullable */ String[] instructionSets;
13469 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13470 int installFlags, String installerPackageName, String volumeUuid,
13471 UserHandle user, String[] instructionSets,
13472 String abiOverride, String[] installGrantPermissions,
13473 String traceMethod, int traceCookie, Certificate[][] certificates) {
13474 this.origin = origin;
13476 this.installFlags = installFlags;
13477 this.observer = observer;
13478 this.installerPackageName = installerPackageName;
13479 this.volumeUuid = volumeUuid;
13481 this.instructionSets = instructionSets;
13482 this.abiOverride = abiOverride;
13483 this.installGrantPermissions = installGrantPermissions;
13484 this.traceMethod = traceMethod;
13485 this.traceCookie = traceCookie;
13486 this.certificates = certificates;
13489 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13490 abstract int doPreInstall(int status);
13493 * Rename package into final resting place. All paths on the given
13494 * scanned package should be updated to reflect the rename.
13496 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13497 abstract int doPostInstall(int status, int uid);
13499 /** @see PackageSettingBase#codePathString */
13500 abstract String getCodePath();
13501 /** @see PackageSettingBase#resourcePathString */
13502 abstract String getResourcePath();
13504 // Need installer lock especially for dex file removal.
13505 abstract void cleanUpResourcesLI();
13506 abstract boolean doPostDeleteLI(boolean delete);
13509 * Called before the source arguments are copied. This is used mostly
13510 * for MoveParams when it needs to read the source file to put it in the
13514 return PackageManager.INSTALL_SUCCEEDED;
13518 * Called after the source arguments are copied. This is used mostly for
13519 * MoveParams when it needs to read the source file to put it in the
13522 int doPostCopy(int uid) {
13523 return PackageManager.INSTALL_SUCCEEDED;
13526 protected boolean isFwdLocked() {
13527 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13530 protected boolean isExternalAsec() {
13531 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13534 protected boolean isEphemeral() {
13535 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13538 UserHandle getUser() {
13543 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13544 if (!allCodePaths.isEmpty()) {
13545 if (instructionSets == null) {
13546 throw new IllegalStateException("instructionSet == null");
13548 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13549 for (String codePath : allCodePaths) {
13550 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13552 mInstaller.rmdex(codePath, dexCodeInstructionSet);
13553 } catch (InstallerException ignored) {
13561 * Logic to handle installation of non-ASEC applications, including copying
13562 * and renaming logic.
13564 class FileInstallArgs extends InstallArgs {
13565 private File codeFile;
13566 private File resourceFile;
13568 // Example topology:
13569 // /data/app/com.example/base.apk
13570 // /data/app/com.example/split_foo.apk
13571 // /data/app/com.example/lib/arm/libfoo.so
13572 // /data/app/com.example/lib/arm64/libfoo.so
13573 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13576 FileInstallArgs(InstallParams params) {
13577 super(params.origin, params.move, params.observer, params.installFlags,
13578 params.installerPackageName, params.volumeUuid,
13579 params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13580 params.grantedRuntimePermissions,
13581 params.traceMethod, params.traceCookie, params.certificates);
13582 if (isFwdLocked()) {
13583 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13587 /** Existing install */
13588 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13589 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13590 null, null, null, 0, null /*certificates*/);
13591 this.codeFile = (codePath != null) ? new File(codePath) : null;
13592 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13595 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13598 return doCopyApk(imcs, temp);
13600 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13604 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13605 if (origin.staged) {
13606 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13607 codeFile = origin.file;
13608 resourceFile = origin.file;
13609 return PackageManager.INSTALL_SUCCEEDED;
13613 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13614 final File tempDir =
13615 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13616 codeFile = tempDir;
13617 resourceFile = tempDir;
13618 } catch (IOException e) {
13619 Slog.w(TAG, "Failed to create copy file: " + e);
13620 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13623 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13625 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13626 if (!FileUtils.isValidExtFilename(name)) {
13627 throw new IllegalArgumentException("Invalid filename: " + name);
13630 final File file = new File(codeFile, name);
13631 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13632 O_RDWR | O_CREAT, 0644);
13633 Os.chmod(file.getAbsolutePath(), 0644);
13634 return new ParcelFileDescriptor(fd);
13635 } catch (ErrnoException e) {
13636 throw new RemoteException("Failed to open: " + e.getMessage());
13641 int ret = PackageManager.INSTALL_SUCCEEDED;
13642 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13643 if (ret != PackageManager.INSTALL_SUCCEEDED) {
13644 Slog.e(TAG, "Failed to copy package");
13648 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13649 NativeLibraryHelper.Handle handle = null;
13651 handle = NativeLibraryHelper.Handle.create(codeFile);
13652 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13654 } catch (IOException e) {
13655 Slog.e(TAG, "Copying native libraries failed", e);
13656 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13658 IoUtils.closeQuietly(handle);
13664 int doPreInstall(int status) {
13665 if (status != PackageManager.INSTALL_SUCCEEDED) {
13671 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13672 if (status != PackageManager.INSTALL_SUCCEEDED) {
13677 final File targetDir = codeFile.getParentFile();
13678 final File beforeCodeFile = codeFile;
13679 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13681 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13683 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13684 } catch (ErrnoException e) {
13685 Slog.w(TAG, "Failed to rename", e);
13689 if (!SELinux.restoreconRecursive(afterCodeFile)) {
13690 Slog.w(TAG, "Failed to restorecon");
13694 // Reflect the rename internally
13695 codeFile = afterCodeFile;
13696 resourceFile = afterCodeFile;
13698 // Reflect the rename in scanned details
13699 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13700 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13701 afterCodeFile, pkg.baseCodePath));
13702 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13703 afterCodeFile, pkg.splitCodePaths));
13705 // Reflect the rename in app info
13706 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13707 pkg.setApplicationInfoCodePath(pkg.codePath);
13708 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13709 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13710 pkg.setApplicationInfoResourcePath(pkg.codePath);
13711 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13712 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13717 int doPostInstall(int status, int uid) {
13718 if (status != PackageManager.INSTALL_SUCCEEDED) {
13725 String getCodePath() {
13726 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13730 String getResourcePath() {
13731 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13734 private boolean cleanUp() {
13735 if (codeFile == null || !codeFile.exists()) {
13739 removeCodePathLI(codeFile);
13741 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13742 resourceFile.delete();
13748 void cleanUpResourcesLI() {
13749 // Try enumerating all code paths before deleting
13750 List<String> allCodePaths = Collections.EMPTY_LIST;
13751 if (codeFile != null && codeFile.exists()) {
13753 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13754 allCodePaths = pkg.getAllCodePaths();
13755 } catch (PackageParserException e) {
13756 // Ignored; we tried our best
13761 removeDexFiles(allCodePaths, instructionSets);
13764 boolean doPostDeleteLI(boolean delete) {
13765 // XXX err, shouldn't we respect the delete flag?
13766 cleanUpResourcesLI();
13771 private boolean isAsecExternal(String cid) {
13772 final String asecPath = PackageHelper.getSdFilesystem(cid);
13773 return !asecPath.startsWith(mAsecInternalPath);
13776 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13777 PackageManagerException {
13779 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13780 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13781 throw new PackageManagerException(copyRet, message);
13787 * Extract the MountService "container ID" from the full code path of an
13790 static String cidFromCodePath(String fullCodePath) {
13791 int eidx = fullCodePath.lastIndexOf("/");
13792 String subStr1 = fullCodePath.substring(0, eidx);
13793 int sidx = subStr1.lastIndexOf("/");
13794 return subStr1.substring(sidx+1, eidx);
13798 * Logic to handle installation of ASEC applications, including copying and
13801 class AsecInstallArgs extends InstallArgs {
13802 static final String RES_FILE_NAME = "pkg.apk";
13803 static final String PUBLIC_RES_FILE_NAME = "res.zip";
13806 String packagePath;
13807 String resourcePath;
13810 AsecInstallArgs(InstallParams params) {
13811 super(params.origin, params.move, params.observer, params.installFlags,
13812 params.installerPackageName, params.volumeUuid,
13813 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13814 params.grantedRuntimePermissions,
13815 params.traceMethod, params.traceCookie, params.certificates);
13818 /** Existing install */
13819 AsecInstallArgs(String fullCodePath, String[] instructionSets,
13820 boolean isExternal, boolean isForwardLocked) {
13821 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13822 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13823 instructionSets, null, null, null, 0, null /*certificates*/);
13824 // Hackily pretend we're still looking at a full code path
13825 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13826 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13829 // Extract cid from fullCodePath
13830 int eidx = fullCodePath.lastIndexOf("/");
13831 String subStr1 = fullCodePath.substring(0, eidx);
13832 int sidx = subStr1.lastIndexOf("/");
13833 cid = subStr1.substring(sidx+1, eidx);
13834 setMountPath(subStr1);
13837 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13838 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13839 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13840 instructionSets, null, null, null, 0, null /*certificates*/);
13842 setMountPath(PackageHelper.getSdDir(cid));
13845 void createCopyFile() {
13846 cid = mInstallerService.allocateExternalStageCidLegacy();
13849 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13850 if (origin.staged && origin.cid != null) {
13851 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13853 setMountPath(PackageHelper.getSdDir(cid));
13854 return PackageManager.INSTALL_SUCCEEDED;
13861 * Pre-emptively destroy the container since it's destroyed if
13862 * copying fails due to it existing anyway.
13864 PackageHelper.destroySdDir(cid);
13867 final String newMountPath = imcs.copyPackageToContainer(
13868 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13869 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13871 if (newMountPath != null) {
13872 setMountPath(newMountPath);
13873 return PackageManager.INSTALL_SUCCEEDED;
13875 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13880 String getCodePath() {
13881 return packagePath;
13885 String getResourcePath() {
13886 return resourcePath;
13889 int doPreInstall(int status) {
13890 if (status != PackageManager.INSTALL_SUCCEEDED) {
13891 // Destroy container
13892 PackageHelper.destroySdDir(cid);
13894 boolean mounted = PackageHelper.isContainerMounted(cid);
13896 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13897 Process.SYSTEM_UID);
13898 if (newMountPath != null) {
13899 setMountPath(newMountPath);
13901 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13908 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13909 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13910 String newMountPath = null;
13911 if (PackageHelper.isContainerMounted(cid)) {
13912 // Unmount the container
13913 if (!PackageHelper.unMountSdDir(cid)) {
13914 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13918 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13919 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13920 " which might be stale. Will try to clean up.");
13921 // Clean up the stale container and proceed to recreate.
13922 if (!PackageHelper.destroySdDir(newCacheId)) {
13923 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13926 // Successfully cleaned up stale container. Try to rename again.
13927 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13928 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13929 + " inspite of cleaning it up.");
13933 if (!PackageHelper.isContainerMounted(newCacheId)) {
13934 Slog.w(TAG, "Mounting container " + newCacheId);
13935 newMountPath = PackageHelper.mountSdDir(newCacheId,
13936 getEncryptKey(), Process.SYSTEM_UID);
13938 newMountPath = PackageHelper.getSdDir(newCacheId);
13940 if (newMountPath == null) {
13941 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
13944 Log.i(TAG, "Succesfully renamed " + cid +
13945 " to " + newCacheId +
13946 " at new path: " + newMountPath);
13949 final File beforeCodeFile = new File(packagePath);
13950 setMountPath(newMountPath);
13951 final File afterCodeFile = new File(packagePath);
13953 // Reflect the rename in scanned details
13954 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13955 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13956 afterCodeFile, pkg.baseCodePath));
13957 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13958 afterCodeFile, pkg.splitCodePaths));
13960 // Reflect the rename in app info
13961 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13962 pkg.setApplicationInfoCodePath(pkg.codePath);
13963 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13964 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13965 pkg.setApplicationInfoResourcePath(pkg.codePath);
13966 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13967 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13972 private void setMountPath(String mountPath) {
13973 final File mountFile = new File(mountPath);
13975 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13976 if (monolithicFile.exists()) {
13977 packagePath = monolithicFile.getAbsolutePath();
13978 if (isFwdLocked()) {
13979 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13981 resourcePath = packagePath;
13984 packagePath = mountFile.getAbsolutePath();
13985 resourcePath = packagePath;
13989 int doPostInstall(int status, int uid) {
13990 if (status != PackageManager.INSTALL_SUCCEEDED) {
13993 final int groupOwner;
13994 final String protectedFile;
13995 if (isFwdLocked()) {
13996 groupOwner = UserHandle.getSharedAppGid(uid);
13997 protectedFile = RES_FILE_NAME;
14000 protectedFile = null;
14003 if (uid < Process.FIRST_APPLICATION_UID
14004 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14005 Slog.e(TAG, "Failed to finalize " + cid);
14006 PackageHelper.destroySdDir(cid);
14007 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14010 boolean mounted = PackageHelper.isContainerMounted(cid);
14012 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14018 private void cleanUp() {
14019 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14021 // Destroy secure container
14022 PackageHelper.destroySdDir(cid);
14025 private List<String> getAllCodePaths() {
14026 final File codeFile = new File(getCodePath());
14027 if (codeFile != null && codeFile.exists()) {
14029 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14030 return pkg.getAllCodePaths();
14031 } catch (PackageParserException e) {
14032 // Ignored; we tried our best
14035 return Collections.EMPTY_LIST;
14038 void cleanUpResourcesLI() {
14039 // Enumerate all code paths before deleting
14040 cleanUpResourcesLI(getAllCodePaths());
14043 private void cleanUpResourcesLI(List<String> allCodePaths) {
14045 removeDexFiles(allCodePaths, instructionSets);
14048 String getPackageName() {
14049 return getAsecPackageName(cid);
14052 boolean doPostDeleteLI(boolean delete) {
14053 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14054 final List<String> allCodePaths = getAllCodePaths();
14055 boolean mounted = PackageHelper.isContainerMounted(cid);
14058 if (PackageHelper.unMountSdDir(cid)) {
14062 if (!mounted && delete) {
14063 cleanUpResourcesLI(allCodePaths);
14070 if (isFwdLocked()) {
14071 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14072 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14073 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14077 return PackageManager.INSTALL_SUCCEEDED;
14081 int doPostCopy(int uid) {
14082 if (isFwdLocked()) {
14083 if (uid < Process.FIRST_APPLICATION_UID
14084 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14086 Slog.e(TAG, "Failed to finalize " + cid);
14087 PackageHelper.destroySdDir(cid);
14088 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14092 return PackageManager.INSTALL_SUCCEEDED;
14097 * Logic to handle movement of existing installed applications.
14099 class MoveInstallArgs extends InstallArgs {
14100 private File codeFile;
14101 private File resourceFile;
14104 MoveInstallArgs(InstallParams params) {
14105 super(params.origin, params.move, params.observer, params.installFlags,
14106 params.installerPackageName, params.volumeUuid,
14107 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14108 params.grantedRuntimePermissions,
14109 params.traceMethod, params.traceCookie, params.certificates);
14112 int copyApk(IMediaContainerService imcs, boolean temp) {
14113 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14114 + move.fromUuid + " to " + move.toUuid);
14115 synchronized (mInstaller) {
14117 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14118 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14119 } catch (InstallerException e) {
14120 Slog.w(TAG, "Failed to move app", e);
14121 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14125 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14126 resourceFile = codeFile;
14127 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14129 return PackageManager.INSTALL_SUCCEEDED;
14132 int doPreInstall(int status) {
14133 if (status != PackageManager.INSTALL_SUCCEEDED) {
14134 cleanUp(move.toUuid);
14139 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14140 if (status != PackageManager.INSTALL_SUCCEEDED) {
14141 cleanUp(move.toUuid);
14145 // Reflect the move in app info
14146 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14147 pkg.setApplicationInfoCodePath(pkg.codePath);
14148 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14149 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14150 pkg.setApplicationInfoResourcePath(pkg.codePath);
14151 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14152 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14157 int doPostInstall(int status, int uid) {
14158 if (status == PackageManager.INSTALL_SUCCEEDED) {
14159 cleanUp(move.fromUuid);
14161 cleanUp(move.toUuid);
14167 String getCodePath() {
14168 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14172 String getResourcePath() {
14173 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14176 private boolean cleanUp(String volumeUuid) {
14177 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14179 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14180 final int[] userIds = sUserManager.getUserIds();
14181 synchronized (mInstallLock) {
14182 // Clean up both app data and code
14183 // All package moves are frozen until finished
14184 for (int userId : userIds) {
14186 mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14187 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14188 } catch (InstallerException e) {
14189 Slog.w(TAG, String.valueOf(e));
14192 removeCodePathLI(codeFile);
14197 void cleanUpResourcesLI() {
14198 throw new UnsupportedOperationException();
14201 boolean doPostDeleteLI(boolean delete) {
14202 throw new UnsupportedOperationException();
14206 static String getAsecPackageName(String packageCid) {
14207 int idx = packageCid.lastIndexOf("-");
14211 return packageCid.substring(0, idx);
14214 // Utility method used to create code paths based on package name and available index.
14215 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14216 String idxStr = "";
14218 // Fall back to default value of idx=1 if prefix is not
14219 // part of oldCodePath
14220 if (oldCodePath != null) {
14221 String subStr = oldCodePath;
14222 // Drop the suffix right away
14223 if (suffix != null && subStr.endsWith(suffix)) {
14224 subStr = subStr.substring(0, subStr.length() - suffix.length());
14226 // If oldCodePath already contains prefix find out the
14227 // ending index to either increment or decrement.
14228 int sidx = subStr.lastIndexOf(prefix);
14230 subStr = subStr.substring(sidx + prefix.length());
14231 if (subStr != null) {
14232 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14233 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14236 idx = Integer.parseInt(subStr);
14242 } catch(NumberFormatException e) {
14247 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14248 return prefix + idxStr;
14251 private File getNextCodePath(File targetDir, String packageName) {
14255 result = new File(targetDir, packageName + "-" + suffix);
14257 } while (result.exists());
14261 // Utility method that returns the relative package path with respect
14262 // to the installation directory. Like say for /data/data/com.test-1.apk
14263 // string com.test-1 is returned.
14264 static String deriveCodePathName(String codePath) {
14265 if (codePath == null) {
14268 final File codeFile = new File(codePath);
14269 final String name = codeFile.getName();
14270 if (codeFile.isDirectory()) {
14272 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14273 final int lastDot = name.lastIndexOf('.');
14274 return name.substring(0, lastDot);
14276 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14281 static class PackageInstalledInfo {
14284 // The set of users that originally had this package installed.
14286 // The set of users that now have this package installed.
14288 PackageParser.Package pkg;
14291 PackageRemovedInfo removedInfo;
14292 ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14294 public void setError(int code, String msg) {
14295 setReturnCode(code);
14296 setReturnMessage(msg);
14300 public void setError(String msg, PackageParserException e) {
14301 setReturnCode(e.error);
14302 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14303 Slog.w(TAG, msg, e);
14306 public void setError(String msg, PackageManagerException e) {
14307 returnCode = e.error;
14308 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14309 Slog.w(TAG, msg, e);
14312 public void setReturnCode(int returnCode) {
14313 this.returnCode = returnCode;
14314 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14315 for (int i = 0; i < childCount; i++) {
14316 addedChildPackages.valueAt(i).returnCode = returnCode;
14320 private void setReturnMessage(String returnMsg) {
14321 this.returnMsg = returnMsg;
14322 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14323 for (int i = 0; i < childCount; i++) {
14324 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14328 // In some error cases we want to convey more info back to the observer
14329 String origPackage;
14330 String origPermission;
14334 * Install a non-existing package.
14336 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14337 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14338 PackageInstalledInfo res) {
14339 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14341 // Remember this for later, in case we need to rollback this install
14342 String pkgName = pkg.packageName;
14344 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14346 synchronized(mPackages) {
14347 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14348 // A package with the same name is already installed, though
14349 // it has been renamed to an older name. The package we
14350 // are trying to install should be installed as an update to
14351 // the existing one, but that has not been requested, so bail.
14352 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14353 + " without first uninstalling package running as "
14354 + mSettings.mRenamedPackages.get(pkgName));
14357 if (mPackages.containsKey(pkgName)) {
14358 // Don't allow installation over an existing package with the same name.
14359 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14360 + " without first uninstalling.");
14366 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14367 System.currentTimeMillis(), user);
14369 updateSettingsLI(newPackage, installerPackageName, null, res, user);
14371 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14372 prepareAppDataAfterInstallLIF(newPackage);
14375 // Remove package from internal structures, but keep around any
14376 // data that might have already existed
14377 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14378 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14380 } catch (PackageManagerException e) {
14381 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14384 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14387 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14388 // Can't rotate keys during boot or if sharedUser.
14389 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14390 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14393 // app is using upgradeKeySets; make sure all are valid
14394 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14395 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14396 for (int i = 0; i < upgradeKeySets.length; i++) {
14397 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14398 Slog.wtf(TAG, "Package "
14399 + (oldPs.name != null ? oldPs.name : "<null>")
14400 + " contains upgrade-key-set reference to unknown key-set: "
14401 + upgradeKeySets[i]
14402 + " reverting to signatures check.");
14409 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14410 // Upgrade keysets are being used. Determine if new package has a superset of the
14412 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14413 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14414 for (int i = 0; i < upgradeKeySets.length; i++) {
14415 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14416 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14423 private static void updateDigest(MessageDigest digest, File file) throws IOException {
14424 try (DigestInputStream digestStream =
14425 new DigestInputStream(new FileInputStream(file), digest)) {
14426 while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14430 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14431 UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14432 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14434 final PackageParser.Package oldPackage;
14435 final String pkgName = pkg.packageName;
14436 final int[] allUsers;
14437 final int[] installedUsers;
14439 synchronized(mPackages) {
14440 oldPackage = mPackages.get(pkgName);
14441 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14443 // don't allow upgrade to target a release SDK from a pre-release SDK
14444 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14445 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14446 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14447 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14448 if (oldTargetsPreRelease
14449 && !newTargetsPreRelease
14450 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14451 Slog.w(TAG, "Can't install package targeting released sdk");
14452 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14456 // don't allow an upgrade from full to ephemeral
14457 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14458 if (isEphemeral && !oldIsEphemeral) {
14459 // can't downgrade from full to ephemeral
14460 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14461 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14465 // verify signatures are valid
14466 final PackageSetting ps = mSettings.mPackages.get(pkgName);
14467 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14468 if (!checkUpgradeKeySetLP(ps, pkg)) {
14469 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14470 "New package not signed by keys specified by upgrade-keysets: "
14475 // default to original signature matching
14476 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14477 != PackageManager.SIGNATURE_MATCH) {
14478 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14479 "New package has a different signature: " + pkgName);
14484 // don't allow a system upgrade unless the upgrade hash matches
14485 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14486 byte[] digestBytes = null;
14488 final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14489 updateDigest(digest, new File(pkg.baseCodePath));
14490 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14491 for (String path : pkg.splitCodePaths) {
14492 updateDigest(digest, new File(path));
14495 digestBytes = digest.digest();
14496 } catch (NoSuchAlgorithmException | IOException e) {
14497 res.setError(INSTALL_FAILED_INVALID_APK,
14498 "Could not compute hash: " + pkgName);
14501 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14502 res.setError(INSTALL_FAILED_INVALID_APK,
14503 "New package fails restrict-update check: " + pkgName);
14506 // retain upgrade restriction
14507 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14510 // Check for shared user id changes
14511 String invalidPackageName =
14512 getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14513 if (invalidPackageName != null) {
14514 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14515 "Package " + invalidPackageName + " tried to change user "
14516 + oldPackage.mSharedUserId);
14520 // In case of rollback, remember per-user/profile install state
14521 allUsers = sUserManager.getUserIds();
14522 installedUsers = ps.queryInstalledUsers(allUsers, true);
14525 // Update what is removed
14526 res.removedInfo = new PackageRemovedInfo();
14527 res.removedInfo.uid = oldPackage.applicationInfo.uid;
14528 res.removedInfo.removedPackage = oldPackage.packageName;
14529 res.removedInfo.isUpdate = true;
14530 res.removedInfo.origUsers = installedUsers;
14531 final int childCount = (oldPackage.childPackages != null)
14532 ? oldPackage.childPackages.size() : 0;
14533 for (int i = 0; i < childCount; i++) {
14534 boolean childPackageUpdated = false;
14535 PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14536 if (res.addedChildPackages != null) {
14537 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14538 if (childRes != null) {
14539 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14540 childRes.removedInfo.removedPackage = childPkg.packageName;
14541 childRes.removedInfo.isUpdate = true;
14542 childPackageUpdated = true;
14545 if (!childPackageUpdated) {
14546 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14547 childRemovedRes.removedPackage = childPkg.packageName;
14548 childRemovedRes.isUpdate = false;
14549 childRemovedRes.dataRemoved = true;
14550 synchronized (mPackages) {
14551 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14552 if (childPs != null) {
14553 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14556 if (res.removedInfo.removedChildPackages == null) {
14557 res.removedInfo.removedChildPackages = new ArrayMap<>();
14559 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14563 boolean sysPkg = (isSystemApp(oldPackage));
14565 // Set the system/privileged flags as needed
14566 final boolean privileged =
14567 (oldPackage.applicationInfo.privateFlags
14568 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14569 final int systemPolicyFlags = policyFlags
14570 | PackageParser.PARSE_IS_SYSTEM
14571 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14573 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14574 user, allUsers, installerPackageName, res);
14576 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14577 user, allUsers, installerPackageName, res);
14581 public List<String> getPreviousCodePaths(String packageName) {
14582 final PackageSetting ps = mSettings.mPackages.get(packageName);
14583 final List<String> result = new ArrayList<String>();
14584 if (ps != null && ps.oldCodePaths != null) {
14585 result.addAll(ps.oldCodePaths);
14590 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14591 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14592 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14593 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14596 String pkgName = deletedPackage.packageName;
14597 boolean deletedPkg = true;
14598 boolean addedPkg = false;
14599 boolean updatedSettings = false;
14600 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14601 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14602 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14604 final long origUpdateTime = (pkg.mExtras != null)
14605 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14607 // First delete the existing package while retaining the data directory
14608 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14609 res.removedInfo, true, pkg)) {
14610 // If the existing package wasn't successfully deleted
14611 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14612 deletedPkg = false;
14614 // Successfully deleted the old package; proceed with replace.
14616 // If deleted package lived in a container, give users a chance to
14617 // relinquish resources before killing.
14618 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14619 if (DEBUG_INSTALL) {
14620 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14622 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14623 final ArrayList<String> pkgList = new ArrayList<String>(1);
14624 pkgList.add(deletedPackage.applicationInfo.packageName);
14625 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14628 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14629 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14630 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14633 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14634 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14635 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14637 // Update the in-memory copy of the previous code paths.
14638 PackageSetting ps = mSettings.mPackages.get(pkgName);
14640 if (ps.oldCodePaths == null) {
14641 ps.oldCodePaths = new ArraySet<>();
14643 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14644 if (deletedPackage.splitCodePaths != null) {
14645 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14648 ps.oldCodePaths = null;
14650 if (ps.childPackageNames != null) {
14651 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14652 final String childPkgName = ps.childPackageNames.get(i);
14653 final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14654 childPs.oldCodePaths = ps.oldCodePaths;
14657 prepareAppDataAfterInstallLIF(newPackage);
14659 } catch (PackageManagerException e) {
14660 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14664 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14665 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14667 // Revert all internal state mutations and added folders for the failed install
14669 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14670 res.removedInfo, true, null);
14673 // Restore the old package
14675 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14676 File restoreFile = new File(deletedPackage.codePath);
14677 // Parse old package
14678 boolean oldExternal = isExternal(deletedPackage);
14679 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
14680 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14681 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14682 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14684 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14686 } catch (PackageManagerException e) {
14687 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14692 synchronized (mPackages) {
14693 // Ensure the installer package name up to date
14694 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14696 // Update permissions for restored package
14697 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14699 mSettings.writeLPr();
14702 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14705 synchronized (mPackages) {
14706 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14708 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14709 if (res.removedInfo.removedChildPackages != null) {
14710 final int childCount = res.removedInfo.removedChildPackages.size();
14711 // Iterate in reverse as we may modify the collection
14712 for (int i = childCount - 1; i >= 0; i--) {
14713 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14714 if (res.addedChildPackages.containsKey(childPackageName)) {
14715 res.removedInfo.removedChildPackages.removeAt(i);
14717 PackageRemovedInfo childInfo = res.removedInfo
14718 .removedChildPackages.valueAt(i);
14719 childInfo.removedForAllUsers = mPackages.get(
14720 childInfo.removedPackage) == null;
14729 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14730 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14731 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14732 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14733 + ", old=" + deletedPackage);
14735 final boolean disabledSystem;
14737 // Remove existing system package
14738 removePackageLI(deletedPackage, true);
14740 synchronized (mPackages) {
14741 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14743 if (!disabledSystem) {
14744 // We didn't need to disable the .apk as a current system package,
14745 // which means we are replacing another update that is already
14746 // installed. We need to make sure to delete the older one's .apk.
14747 res.removedInfo.args = createInstallArgsForExisting(0,
14748 deletedPackage.applicationInfo.getCodePath(),
14749 deletedPackage.applicationInfo.getResourcePath(),
14750 getAppDexInstructionSets(deletedPackage.applicationInfo));
14752 res.removedInfo.args = null;
14755 // Successfully disabled the old package. Now proceed with re-installation
14756 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14757 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14758 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14760 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14761 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14762 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14764 PackageParser.Package newPackage = null;
14766 // Add the package to the internal data structures
14767 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14769 // Set the update and install times
14770 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14771 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14772 System.currentTimeMillis());
14774 // Update the package dynamic state if succeeded
14775 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14776 // Now that the install succeeded make sure we remove data
14777 // directories for any child package the update removed.
14778 final int deletedChildCount = (deletedPackage.childPackages != null)
14779 ? deletedPackage.childPackages.size() : 0;
14780 final int newChildCount = (newPackage.childPackages != null)
14781 ? newPackage.childPackages.size() : 0;
14782 for (int i = 0; i < deletedChildCount; i++) {
14783 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14784 boolean childPackageDeleted = true;
14785 for (int j = 0; j < newChildCount; j++) {
14786 PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14787 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14788 childPackageDeleted = false;
14792 if (childPackageDeleted) {
14793 PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14794 deletedChildPkg.packageName);
14795 if (ps != null && res.removedInfo.removedChildPackages != null) {
14796 PackageRemovedInfo removedChildRes = res.removedInfo
14797 .removedChildPackages.get(deletedChildPkg.packageName);
14798 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14799 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14804 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14805 prepareAppDataAfterInstallLIF(newPackage);
14807 } catch (PackageManagerException e) {
14808 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14809 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14812 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14813 // Re installation failed. Restore old information
14814 // Remove new pkg information
14815 if (newPackage != null) {
14816 removeInstalledPackageLI(newPackage, true);
14818 // Add back the old system package
14820 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14821 } catch (PackageManagerException e) {
14822 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14825 synchronized (mPackages) {
14826 if (disabledSystem) {
14827 enableSystemPackageLPw(deletedPackage);
14830 // Ensure the installer package name up to date
14831 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14833 // Update permissions for restored package
14834 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14836 mSettings.writeLPr();
14839 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14840 + " after failed upgrade");
14845 * Checks whether the parent or any of the child packages have a change shared
14846 * user. For a package to be a valid update the shred users of the parent and
14847 * the children should match. We may later support changing child shared users.
14848 * @param oldPkg The updated package.
14849 * @param newPkg The update package.
14850 * @return The shared user that change between the versions.
14852 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14853 PackageParser.Package newPkg) {
14854 // Check parent shared user
14855 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14856 return newPkg.packageName;
14858 // Check child shared users
14859 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14860 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14861 for (int i = 0; i < newChildCount; i++) {
14862 PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14863 // If this child was present, did it have the same shared user?
14864 for (int j = 0; j < oldChildCount; j++) {
14865 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14866 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14867 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14868 return newChildPkg.packageName;
14875 private void removeNativeBinariesLI(PackageSetting ps) {
14876 // Remove the lib path for the parent package
14878 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14879 // Remove the lib path for the child packages
14880 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14881 for (int i = 0; i < childCount; i++) {
14882 PackageSetting childPs = null;
14883 synchronized (mPackages) {
14884 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14886 if (childPs != null) {
14887 NativeLibraryHelper.removeNativeBinariesLI(childPs
14888 .legacyNativeLibraryPathString);
14894 private void enableSystemPackageLPw(PackageParser.Package pkg) {
14895 // Enable the parent package
14896 mSettings.enableSystemPackageLPw(pkg.packageName);
14897 // Enable the child packages
14898 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14899 for (int i = 0; i < childCount; i++) {
14900 PackageParser.Package childPkg = pkg.childPackages.get(i);
14901 mSettings.enableSystemPackageLPw(childPkg.packageName);
14905 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14906 PackageParser.Package newPkg) {
14907 // Disable the parent package (parent always replaced)
14908 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14909 // Disable the child packages
14910 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14911 for (int i = 0; i < childCount; i++) {
14912 PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14913 final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14914 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14919 private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14920 String installerPackageName) {
14921 // Enable the parent package
14922 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14923 // Enable the child packages
14924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14925 for (int i = 0; i < childCount; i++) {
14926 PackageParser.Package childPkg = pkg.childPackages.get(i);
14927 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14931 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14932 // Collect all used permissions in the UID
14933 ArraySet<String> usedPermissions = new ArraySet<>();
14934 final int packageCount = su.packages.size();
14935 for (int i = 0; i < packageCount; i++) {
14936 PackageSetting ps = su.packages.valueAt(i);
14937 if (ps.pkg == null) {
14940 final int requestedPermCount = ps.pkg.requestedPermissions.size();
14941 for (int j = 0; j < requestedPermCount; j++) {
14942 String permission = ps.pkg.requestedPermissions.get(j);
14943 BasePermission bp = mSettings.mPermissions.get(permission);
14945 usedPermissions.add(permission);
14950 PermissionsState permissionsState = su.getPermissionsState();
14951 // Prune install permissions
14952 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14953 final int installPermCount = installPermStates.size();
14954 for (int i = installPermCount - 1; i >= 0; i--) {
14955 PermissionState permissionState = installPermStates.get(i);
14956 if (!usedPermissions.contains(permissionState.getName())) {
14957 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14959 permissionsState.revokeInstallPermission(bp);
14960 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14961 PackageManager.MASK_PERMISSION_FLAGS, 0);
14966 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14968 // Prune runtime permissions
14969 for (int userId : allUserIds) {
14970 List<PermissionState> runtimePermStates = permissionsState
14971 .getRuntimePermissionStates(userId);
14972 final int runtimePermCount = runtimePermStates.size();
14973 for (int i = runtimePermCount - 1; i >= 0; i--) {
14974 PermissionState permissionState = runtimePermStates.get(i);
14975 if (!usedPermissions.contains(permissionState.getName())) {
14976 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14978 permissionsState.revokeRuntimePermission(bp, userId);
14979 permissionsState.updatePermissionFlags(bp, userId,
14980 PackageManager.MASK_PERMISSION_FLAGS, 0);
14981 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14982 runtimePermissionChangedUserIds, userId);
14988 return runtimePermissionChangedUserIds;
14991 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14992 int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14993 // Update the parent package setting
14994 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14996 // Update the child packages setting
14997 final int childCount = (newPackage.childPackages != null)
14998 ? newPackage.childPackages.size() : 0;
14999 for (int i = 0; i < childCount; i++) {
15000 PackageParser.Package childPackage = newPackage.childPackages.get(i);
15001 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15002 updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15003 childRes.origUsers, childRes, user);
15007 private void updateSettingsInternalLI(PackageParser.Package newPackage,
15008 String installerPackageName, int[] allUsers, int[] installedForUsers,
15009 PackageInstalledInfo res, UserHandle user) {
15010 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15012 String pkgName = newPackage.packageName;
15013 synchronized (mPackages) {
15014 //write settings. the installStatus will be incomplete at this stage.
15015 //note that the new package setting would have already been
15016 //added to mPackages. It hasn't been persisted yet.
15017 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15018 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15019 mSettings.writeLPr();
15020 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15023 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15024 synchronized (mPackages) {
15025 updatePermissionsLPw(newPackage.packageName, newPackage,
15026 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15027 ? UPDATE_PERMISSIONS_ALL : 0));
15028 // For system-bundled packages, we assume that installing an upgraded version
15029 // of the package implies that the user actually wants to run that new code,
15030 // so we enable the package.
15031 PackageSetting ps = mSettings.mPackages.get(pkgName);
15032 final int userId = user.getIdentifier();
15034 if (isSystemApp(newPackage)) {
15035 if (DEBUG_INSTALL) {
15036 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15038 // Enable system package for requested users
15039 if (res.origUsers != null) {
15040 for (int origUserId : res.origUsers) {
15041 if (userId == UserHandle.USER_ALL || userId == origUserId) {
15042 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15043 origUserId, installerPackageName);
15047 // Also convey the prior install/uninstall state
15048 if (allUsers != null && installedForUsers != null) {
15049 for (int currentUserId : allUsers) {
15050 final boolean installed = ArrayUtils.contains(
15051 installedForUsers, currentUserId);
15052 if (DEBUG_INSTALL) {
15053 Slog.d(TAG, " user " + currentUserId + " => " + installed);
15055 ps.setInstalled(installed, currentUserId);
15057 // these install state changes will be persisted in the
15058 // upcoming call to mSettings.writeLPr().
15061 // It's implied that when a user requests installation, they want the app to be
15062 // installed and enabled.
15063 if (userId != UserHandle.USER_ALL) {
15064 ps.setInstalled(true, userId);
15065 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15068 res.name = pkgName;
15069 res.uid = newPackage.applicationInfo.uid;
15070 res.pkg = newPackage;
15071 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15072 mSettings.setInstallerPackageName(pkgName, installerPackageName);
15073 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15074 //to update install status
15075 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15076 mSettings.writeLPr();
15077 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15080 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15083 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15085 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15086 installPackageLI(args, res);
15088 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15092 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15093 final int installFlags = args.installFlags;
15094 final String installerPackageName = args.installerPackageName;
15095 final String volumeUuid = args.volumeUuid;
15096 final File tmpPackageFile = new File(args.getCodePath());
15097 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15098 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15099 || (args.volumeUuid != null));
15100 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15101 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15102 boolean replace = false;
15103 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15104 if (args.move != null) {
15105 // moving a complete application; perform an initial scan on the new install location
15106 scanFlags |= SCAN_INITIAL;
15108 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15109 scanFlags |= SCAN_DONT_KILL_APP;
15112 // Result object to be returned
15113 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15115 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15118 if (ephemeral && (forwardLocked || onExternal)) {
15119 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15120 + " external=" + onExternal);
15121 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15125 // Retrieve PackageSettings and parse package
15126 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15127 | PackageParser.PARSE_ENFORCE_CODE
15128 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15129 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15130 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15131 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15132 PackageParser pp = new PackageParser();
15133 pp.setSeparateProcesses(mSeparateProcesses);
15134 pp.setDisplayMetrics(mMetrics);
15136 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15137 final PackageParser.Package pkg;
15139 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15140 } catch (PackageParserException e) {
15141 res.setError("Failed parse during installPackageLI", e);
15144 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15147 // If we are installing a clustered package add results for the children
15148 if (pkg.childPackages != null) {
15149 synchronized (mPackages) {
15150 final int childCount = pkg.childPackages.size();
15151 for (int i = 0; i < childCount; i++) {
15152 PackageParser.Package childPkg = pkg.childPackages.get(i);
15153 PackageInstalledInfo childRes = new PackageInstalledInfo();
15154 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15155 childRes.pkg = childPkg;
15156 childRes.name = childPkg.packageName;
15157 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15158 if (childPs != null) {
15159 childRes.origUsers = childPs.queryInstalledUsers(
15160 sUserManager.getUserIds(), true);
15162 if ((mPackages.containsKey(childPkg.packageName))) {
15163 childRes.removedInfo = new PackageRemovedInfo();
15164 childRes.removedInfo.removedPackage = childPkg.packageName;
15166 if (res.addedChildPackages == null) {
15167 res.addedChildPackages = new ArrayMap<>();
15169 res.addedChildPackages.put(childPkg.packageName, childRes);
15174 // If package doesn't declare API override, mark that we have an install
15175 // time CPU ABI override.
15176 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15177 pkg.cpuAbiOverride = args.abiOverride;
15180 String pkgName = res.name = pkg.packageName;
15181 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15182 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15183 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15189 // either use what we've been given or parse directly from the APK
15190 if (args.certificates != null) {
15192 PackageParser.populateCertificates(pkg, args.certificates);
15193 } catch (PackageParserException e) {
15194 // there was something wrong with the certificates we were given;
15195 // try to pull them from the APK
15196 PackageParser.collectCertificates(pkg, parseFlags);
15199 PackageParser.collectCertificates(pkg, parseFlags);
15201 } catch (PackageParserException e) {
15202 res.setError("Failed collect during installPackageLI", e);
15206 // Get rid of all references to package scan path via parser.
15208 String oldCodePath = null;
15209 boolean systemApp = false;
15210 synchronized (mPackages) {
15211 // Check if installing already existing package
15212 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15213 String oldName = mSettings.mRenamedPackages.get(pkgName);
15214 if (pkg.mOriginalPackages != null
15215 && pkg.mOriginalPackages.contains(oldName)
15216 && mPackages.containsKey(oldName)) {
15217 // This package is derived from an original package,
15218 // and this device has been updating from that original
15219 // name. We must continue using the original name, so
15220 // rename the new package here.
15221 pkg.setPackageName(oldName);
15222 pkgName = pkg.packageName;
15224 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15225 + oldName + " pkgName=" + pkgName);
15226 } else if (mPackages.containsKey(pkgName)) {
15227 // This package, under its official name, already exists
15228 // on the device; we should replace it.
15230 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15233 // Child packages are installed through the parent package
15234 if (pkg.parentPackage != null) {
15235 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15236 "Package " + pkg.packageName + " is child of package "
15237 + pkg.parentPackage.parentPackage + ". Child packages "
15238 + "can be updated only through the parent package.");
15243 // Prevent apps opting out from runtime permissions
15244 PackageParser.Package oldPackage = mPackages.get(pkgName);
15245 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15246 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15247 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15248 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15249 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15250 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15251 + " doesn't support runtime permissions but the old"
15252 + " target SDK " + oldTargetSdk + " does.");
15256 // Prevent installing of child packages
15257 if (oldPackage.parentPackage != null) {
15258 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15259 "Package " + pkg.packageName + " is child of package "
15260 + oldPackage.parentPackage + ". Child packages "
15261 + "can be updated only through the parent package.");
15267 PackageSetting ps = mSettings.mPackages.get(pkgName);
15269 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15271 // Quick sanity check that we're signed correctly if updating;
15272 // we'll check this again later when scanning, but we want to
15273 // bail early here before tripping over redefined permissions.
15274 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15275 if (!checkUpgradeKeySetLP(ps, pkg)) {
15276 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15277 + pkg.packageName + " upgrade keys do not match the "
15278 + "previously installed version");
15283 verifySignaturesLP(ps, pkg);
15284 } catch (PackageManagerException e) {
15285 res.setError(e.error, e.getMessage());
15290 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15291 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15292 systemApp = (ps.pkg.applicationInfo.flags &
15293 ApplicationInfo.FLAG_SYSTEM) != 0;
15295 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15298 // Check whether the newly-scanned package wants to define an already-defined perm
15299 int N = pkg.permissions.size();
15300 for (int i = N-1; i >= 0; i--) {
15301 PackageParser.Permission perm = pkg.permissions.get(i);
15302 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15304 // If the defining package is signed with our cert, it's okay. This
15305 // also includes the "updating the same package" case, of course.
15306 // "updating same package" could also involve key-rotation.
15307 final boolean sigsOk;
15308 if (bp.sourcePackage.equals(pkg.packageName)
15309 && (bp.packageSetting instanceof PackageSetting)
15310 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15312 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15314 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15315 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15318 // If the owning package is the system itself, we log but allow
15319 // install to proceed; we fail the install on all other permission
15321 if (!bp.sourcePackage.equals("android")) {
15322 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15323 + pkg.packageName + " attempting to redeclare permission "
15324 + perm.info.name + " already owned by " + bp.sourcePackage);
15325 res.origPermission = perm.info.name;
15326 res.origPackage = bp.sourcePackage;
15329 Slog.w(TAG, "Package " + pkg.packageName
15330 + " attempting to redeclare system permission "
15331 + perm.info.name + "; ignoring new declaration");
15332 pkg.permissions.remove(i);
15334 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15335 // Prevent apps to change protection level to dangerous from any other
15336 // type as this would allow a privilege escalation where an app adds a
15337 // normal/signature permission in other app's group and later redefines
15338 // it as dangerous leading to the group auto-grant.
15339 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15340 == PermissionInfo.PROTECTION_DANGEROUS) {
15341 if (bp != null && !bp.isRuntime()) {
15342 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15343 + "non-runtime permission " + perm.info.name
15344 + " to runtime; keeping old protection level");
15345 perm.info.protectionLevel = bp.protectionLevel;
15355 // Abort update; system app can't be replaced with app on sdcard
15356 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15357 "Cannot install updates to system apps on sdcard");
15359 } else if (ephemeral) {
15360 // Abort update; system app can't be replaced with an ephemeral app
15361 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15362 "Cannot update a system app with an ephemeral app");
15367 if (args.move != null) {
15368 // We did an in-place move, so dex is ready to roll
15369 scanFlags |= SCAN_NO_DEX;
15370 scanFlags |= SCAN_MOVE;
15372 synchronized (mPackages) {
15373 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15375 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15376 "Missing settings for moved package " + pkgName);
15379 // We moved the entire application as-is, so bring over the
15380 // previously derived ABI information.
15381 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15382 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15385 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15386 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15387 scanFlags |= SCAN_NO_DEX;
15390 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15391 args.abiOverride : pkg.cpuAbiOverride);
15392 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15393 true /* extract libs */);
15394 } catch (PackageManagerException pme) {
15395 Slog.e(TAG, "Error deriving application ABI", pme);
15396 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15400 // Shared libraries for the package need to be updated.
15401 synchronized (mPackages) {
15403 updateSharedLibrariesLPw(pkg, null);
15404 } catch (PackageManagerException e) {
15405 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15408 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15409 // Do not run PackageDexOptimizer through the local performDexOpt
15410 // method because `pkg` may not be in `mPackages` yet.
15412 // Also, don't fail application installs if the dexopt step fails.
15413 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15414 null /* instructionSets */, false /* checkProfiles */,
15415 getCompilerFilterForReason(REASON_INSTALL),
15416 getOrCreateCompilerPackageStats(pkg));
15417 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15419 // Notify BackgroundDexOptService that the package has been changed.
15420 // If this is an update of a package which used to fail to compile,
15421 // BDOS will remove it from its blacklist.
15422 BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15425 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15426 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15430 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15432 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15433 "installPackageLI")) {
15435 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15436 installerPackageName, res);
15438 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15439 args.user, installerPackageName, volumeUuid, res);
15442 synchronized (mPackages) {
15443 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15445 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15448 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15449 for (int i = 0; i < childCount; i++) {
15450 PackageParser.Package childPkg = pkg.childPackages.get(i);
15451 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15452 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15453 if (childPs != null) {
15454 childRes.newUsers = childPs.queryInstalledUsers(
15455 sUserManager.getUserIds(), true);
15461 private void startIntentFilterVerifications(int userId, boolean replacing,
15462 PackageParser.Package pkg) {
15463 if (mIntentFilterVerifierComponent == null) {
15464 Slog.w(TAG, "No IntentFilter verification will not be done as "
15465 + "there is no IntentFilterVerifier available!");
15469 final int verifierUid = getPackageUid(
15470 mIntentFilterVerifierComponent.getPackageName(),
15471 MATCH_DEBUG_TRIAGED_MISSING,
15472 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15474 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15475 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15476 mHandler.sendMessage(msg);
15478 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15479 for (int i = 0; i < childCount; i++) {
15480 PackageParser.Package childPkg = pkg.childPackages.get(i);
15481 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15482 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15483 mHandler.sendMessage(msg);
15487 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15488 PackageParser.Package pkg) {
15489 int size = pkg.activities.size();
15491 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15492 "No activity, so no need to verify any IntentFilter!");
15496 final boolean hasDomainURLs = hasDomainURLs(pkg);
15497 if (!hasDomainURLs) {
15498 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15499 "No domain URLs, so no need to verify any IntentFilter!");
15503 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15504 + " if any IntentFilter from the " + size
15505 + " Activities needs verification ...");
15508 final String packageName = pkg.packageName;
15510 synchronized (mPackages) {
15511 // If this is a new install and we see that we've already run verification for this
15512 // package, we have nothing to do: it means the state was restored from backup.
15514 IntentFilterVerificationInfo ivi =
15515 mSettings.getIntentFilterVerificationLPr(packageName);
15517 if (DEBUG_DOMAIN_VERIFICATION) {
15518 Slog.i(TAG, "Package " + packageName+ " already verified: status="
15519 + ivi.getStatusString());
15525 // If any filters need to be verified, then all need to be.
15526 boolean needToVerify = false;
15527 for (PackageParser.Activity a : pkg.activities) {
15528 for (ActivityIntentInfo filter : a.intents) {
15529 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15530 if (DEBUG_DOMAIN_VERIFICATION) {
15531 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15533 needToVerify = true;
15539 if (needToVerify) {
15540 final int verificationId = mIntentFilterVerificationToken++;
15541 for (PackageParser.Activity a : pkg.activities) {
15542 for (ActivityIntentInfo filter : a.intents) {
15543 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15544 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15545 "Verification needed for IntentFilter:" + filter.toString());
15546 mIntentFilterVerifier.addOneIntentFilterVerification(
15547 verifierUid, userId, verificationId, filter, packageName);
15556 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15557 + " IntentFilter verification" + (count > 1 ? "s" : "")
15558 + " for userId:" + userId);
15559 mIntentFilterVerifier.startVerifications(userId);
15561 if (DEBUG_DOMAIN_VERIFICATION) {
15562 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15567 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15568 final ComponentName cn = filter.activity.getComponentName();
15569 final String packageName = cn.getPackageName();
15571 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15576 int status = ivi.getStatus();
15578 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15579 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15588 private static boolean isMultiArch(ApplicationInfo info) {
15589 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15592 private static boolean isExternal(PackageParser.Package pkg) {
15593 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15596 private static boolean isExternal(PackageSetting ps) {
15597 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15600 private static boolean isEphemeral(PackageParser.Package pkg) {
15601 return pkg.applicationInfo.isEphemeralApp();
15604 private static boolean isEphemeral(PackageSetting ps) {
15605 return ps.pkg != null && isEphemeral(ps.pkg);
15608 private static boolean isSystemApp(PackageParser.Package pkg) {
15609 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15612 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15613 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15616 private static boolean hasDomainURLs(PackageParser.Package pkg) {
15617 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15620 private static boolean isSystemApp(PackageSetting ps) {
15621 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15624 private static boolean isUpdatedSystemApp(PackageSetting ps) {
15625 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15628 private int packageFlagsToInstallFlags(PackageSetting ps) {
15629 int installFlags = 0;
15630 if (isEphemeral(ps)) {
15631 installFlags |= PackageManager.INSTALL_EPHEMERAL;
15633 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15634 // This existing package was an external ASEC install when we have
15635 // the external flag without a UUID
15636 installFlags |= PackageManager.INSTALL_EXTERNAL;
15638 if (ps.isForwardLocked()) {
15639 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15641 return installFlags;
15644 private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15645 if (isExternal(pkg)) {
15646 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15647 return StorageManager.UUID_PRIMARY_PHYSICAL;
15649 return pkg.volumeUuid;
15652 return StorageManager.UUID_PRIVATE_INTERNAL;
15656 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15657 if (isExternal(pkg)) {
15658 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15659 return mSettings.getExternalVersion();
15661 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15664 return mSettings.getInternalVersion();
15668 private void deleteTempPackageFiles() {
15669 final FilenameFilter filter = new FilenameFilter() {
15670 public boolean accept(File dir, String name) {
15671 return name.startsWith("vmdl") && name.endsWith(".tmp");
15674 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15680 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15682 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15687 public void deletePackage(final String packageName,
15688 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15689 mContext.enforceCallingOrSelfPermission(
15690 android.Manifest.permission.DELETE_PACKAGES, null);
15691 Preconditions.checkNotNull(packageName);
15692 Preconditions.checkNotNull(observer);
15693 final int uid = Binder.getCallingUid();
15694 if (!isOrphaned(packageName)
15695 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15697 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15698 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15699 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15700 observer.onUserActionRequired(intent);
15701 } catch (RemoteException re) {
15705 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15706 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15707 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15708 mContext.enforceCallingOrSelfPermission(
15709 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15710 "deletePackage for user " + userId);
15713 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15715 observer.onPackageDeleted(packageName,
15716 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15717 } catch (RemoteException re) {
15722 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15724 observer.onPackageDeleted(packageName,
15725 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15726 } catch (RemoteException re) {
15731 if (DEBUG_REMOVE) {
15732 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15733 + " deleteAllUsers: " + deleteAllUsers );
15735 // Queue up an async operation since the package deletion may take a little while.
15736 mHandler.post(new Runnable() {
15737 public void run() {
15738 mHandler.removeCallbacks(this);
15740 if (!deleteAllUsers) {
15741 returnCode = deletePackageX(packageName, userId, deleteFlags);
15743 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15744 // If nobody is blocking uninstall, proceed with delete for all users
15745 if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15746 returnCode = deletePackageX(packageName, userId, deleteFlags);
15748 // Otherwise uninstall individually for users with blockUninstalls=false
15749 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15750 for (int userId : users) {
15751 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15752 returnCode = deletePackageX(packageName, userId, userFlags);
15753 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15754 Slog.w(TAG, "Package delete failed for user " + userId
15755 + ", returnCode " + returnCode);
15759 // The app has only been marked uninstalled for certain users.
15760 // We still need to report that delete was blocked
15761 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15765 observer.onPackageDeleted(packageName, returnCode, null);
15766 } catch (RemoteException e) {
15767 Log.i(TAG, "Observer no longer exists.");
15773 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15774 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15775 || callingUid == Process.SYSTEM_UID) {
15778 final int callingUserId = UserHandle.getUserId(callingUid);
15779 // If the caller installed the pkgName, then allow it to silently uninstall.
15780 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15784 // Allow package verifier to silently uninstall.
15785 if (mRequiredVerifierPackage != null &&
15786 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15790 // Allow package uninstaller to silently uninstall.
15791 if (mRequiredUninstallerPackage != null &&
15792 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15796 // Allow storage manager to silently uninstall.
15797 if (mStorageManagerPackage != null &&
15798 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15804 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15805 int[] result = EMPTY_INT_ARRAY;
15806 for (int userId : userIds) {
15807 if (getBlockUninstallForUser(packageName, userId)) {
15808 result = ArrayUtils.appendInt(result, userId);
15815 public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15816 final int callingUid = Binder.getCallingUid();
15817 if (checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid)
15818 != PERMISSION_GRANTED) {
15819 EventLog.writeEvent(0x534e4554, "128599183", -1, "");
15820 throw new SecurityException(android.Manifest.permission.MANAGE_USERS
15821 + " permission is required to call this API");
15823 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15826 private boolean isPackageDeviceAdmin(String packageName, int userId) {
15827 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15828 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15831 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15832 /* callingUserOnly =*/ false);
15833 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15834 : deviceOwnerComponentName.getPackageName();
15835 // Does the package contains the device owner?
15836 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise,
15837 // this check is probably not needed, since DO should be registered as a device
15838 // admin on some user too. (Original bug for this: b/17657954)
15839 if (packageName.equals(deviceOwnerPackageName)) {
15842 // Does it contain a device admin for any user?
15844 if (userId == UserHandle.USER_ALL) {
15845 users = sUserManager.getUserIds();
15847 users = new int[]{userId};
15849 for (int i = 0; i < users.length; ++i) {
15850 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15855 } catch (RemoteException e) {
15860 private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15861 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15865 * This method is an internal method that could be get invoked either
15866 * to delete an installed package or to clean up a failed installation.
15867 * After deleting an installed package, a broadcast is sent to notify any
15868 * listeners that the package has been removed. For cleaning up a failed
15869 * installation, the broadcast is not necessary since the package's
15870 * installation wouldn't have sent the initial broadcast either
15871 * The key steps in deleting a package are
15872 * deleting the package information in internal structures like mPackages,
15873 * deleting the packages base directories through installd
15874 * updating mSettings to reflect current status
15875 * persisting settings for later use
15876 * sending a broadcast if necessary
15878 private int deletePackageX(String packageName, int userId, int deleteFlags) {
15879 final PackageRemovedInfo info = new PackageRemovedInfo();
15882 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15883 ? UserHandle.USER_ALL : userId;
15885 if (isPackageDeviceAdmin(packageName, removeUser)) {
15886 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15887 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15890 PackageSetting uninstalledPs = null;
15892 // for the uninstall-updates case and restricted profiles, remember the per-
15893 // user handle installed state
15895 synchronized (mPackages) {
15896 uninstalledPs = mSettings.mPackages.get(packageName);
15897 if (uninstalledPs == null) {
15898 Slog.w(TAG, "Not removing non-existent package " + packageName);
15899 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15901 allUsers = sUserManager.getUserIds();
15902 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15905 final int freezeUser;
15906 if (isUpdatedSystemApp(uninstalledPs)
15907 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15908 // We're downgrading a system app, which will apply to all users, so
15909 // freeze them all during the downgrade
15910 freezeUser = UserHandle.USER_ALL;
15912 freezeUser = removeUser;
15915 synchronized (mInstallLock) {
15916 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15917 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15918 deleteFlags, "deletePackageX")) {
15919 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15920 deleteFlags | REMOVE_CHATTY, info, true, null);
15922 synchronized (mPackages) {
15924 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15930 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15931 info.sendPackageRemovedBroadcasts(killApp);
15932 info.sendSystemPackageUpdatedBroadcasts();
15933 info.sendSystemPackageAppearedBroadcasts();
15935 // Force a gc here.
15936 Runtime.getRuntime().gc();
15937 // Delete the resources here after sending the broadcast to let
15938 // other processes clean up before deleting resources.
15939 if (info.args != null) {
15940 synchronized (mInstallLock) {
15941 info.args.doPostDeleteLI(true);
15945 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15948 class PackageRemovedInfo {
15949 String removedPackage;
15951 int removedAppId = -1;
15953 int[] removedUsers = null;
15954 boolean isRemovedPackageSystemUpdate = false;
15956 boolean dataRemoved;
15957 boolean removedForAllUsers;
15958 // Clean up resources deleted packages.
15959 InstallArgs args = null;
15960 ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15961 ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15963 void sendPackageRemovedBroadcasts(boolean killApp) {
15964 sendPackageRemovedBroadcastInternal(killApp);
15965 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15966 for (int i = 0; i < childCount; i++) {
15967 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15968 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15972 void sendSystemPackageUpdatedBroadcasts() {
15973 if (isRemovedPackageSystemUpdate) {
15974 sendSystemPackageUpdatedBroadcastsInternal();
15975 final int childCount = (removedChildPackages != null)
15976 ? removedChildPackages.size() : 0;
15977 for (int i = 0; i < childCount; i++) {
15978 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15979 if (childInfo.isRemovedPackageSystemUpdate) {
15980 childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15986 void sendSystemPackageAppearedBroadcasts() {
15987 final int packageCount = (appearedChildPackages != null)
15988 ? appearedChildPackages.size() : 0;
15989 for (int i = 0; i < packageCount; i++) {
15990 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15991 for (int userId : installedInfo.newUsers) {
15992 sendPackageAddedForUser(installedInfo.name, true,
15993 UserHandle.getAppId(installedInfo.uid), userId);
15998 private void sendSystemPackageUpdatedBroadcastsInternal() {
15999 Bundle extras = new Bundle(2);
16000 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16001 extras.putBoolean(Intent.EXTRA_REPLACING, true);
16002 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16003 extras, 0, null, null, null);
16004 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16005 extras, 0, null, null, null);
16006 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16007 null, 0, removedPackage, null, null);
16010 private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16011 Bundle extras = new Bundle(2);
16012 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16013 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16014 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16015 if (isUpdate || isRemovedPackageSystemUpdate) {
16016 extras.putBoolean(Intent.EXTRA_REPLACING, true);
16018 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16019 if (removedPackage != null) {
16020 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16021 extras, 0, null, null, removedUsers);
16022 if (dataRemoved && !isRemovedPackageSystemUpdate) {
16023 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16024 removedPackage, extras, 0, null, null, removedUsers);
16027 if (removedAppId >= 0) {
16028 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16035 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16036 * flag is not set, the data directory is removed as well.
16037 * make sure this flag is set for partially installed apps. If not its meaningless to
16038 * delete a partially installed application.
16040 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16041 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16042 String packageName = ps.name;
16043 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16044 // Retrieve object to delete permissions for shared user later on
16045 final PackageParser.Package deletedPkg;
16046 final PackageSetting deletedPs;
16048 synchronized (mPackages) {
16049 deletedPkg = mPackages.get(packageName);
16050 deletedPs = mSettings.mPackages.get(packageName);
16051 if (outInfo != null) {
16052 outInfo.removedPackage = packageName;
16053 outInfo.removedUsers = deletedPs != null
16054 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16059 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16061 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16062 final PackageParser.Package resolvedPkg;
16063 if (deletedPkg != null) {
16064 resolvedPkg = deletedPkg;
16066 // We don't have a parsed package when it lives on an ejected
16067 // adopted storage device, so fake something together
16068 resolvedPkg = new PackageParser.Package(ps.name);
16069 resolvedPkg.setVolumeUuid(ps.volumeUuid);
16071 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16072 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16073 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16074 if (outInfo != null) {
16075 outInfo.dataRemoved = true;
16077 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16081 synchronized (mPackages) {
16082 if (deletedPs != null) {
16083 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16084 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16085 clearDefaultBrowserIfNeeded(packageName);
16086 if (outInfo != null) {
16087 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16088 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16090 updatePermissionsLPw(deletedPs.name, null, 0);
16091 if (deletedPs.sharedUser != null) {
16092 // Remove permissions associated with package. Since runtime
16093 // permissions are per user we have to kill the removed package
16094 // or packages running under the shared user of the removed
16095 // package if revoking the permissions requested only by the removed
16096 // package is successful and this causes a change in gids.
16097 for (int userId : UserManagerService.getInstance().getUserIds()) {
16098 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16100 if (userIdToKill == UserHandle.USER_ALL
16101 || userIdToKill >= UserHandle.USER_SYSTEM) {
16102 // If gids changed for this user, kill all affected packages.
16103 mHandler.post(new Runnable() {
16105 public void run() {
16106 // This has to happen with no lock held.
16107 killApplication(deletedPs.name, deletedPs.appId,
16108 KILL_APP_REASON_GIDS_CHANGED);
16115 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16117 // make sure to preserve per-user disabled state if this removal was just
16118 // a downgrade of a system app to the factory package
16119 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16120 if (DEBUG_REMOVE) {
16121 Slog.d(TAG, "Propagating install state across downgrade");
16123 for (int userId : allUserHandles) {
16124 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16125 if (DEBUG_REMOVE) {
16126 Slog.d(TAG, " user " + userId + " => " + installed);
16128 ps.setInstalled(installed, userId);
16132 // can downgrade to reader
16133 if (writeSettings) {
16134 // Save settings now
16135 mSettings.writeLPr();
16138 if (outInfo != null) {
16139 // A user ID was deleted here. Go through all users and remove it
16141 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16145 static boolean locationIsPrivileged(File path) {
16147 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16148 .getCanonicalPath();
16149 return path.getCanonicalPath().startsWith(privilegedAppDir);
16150 } catch (IOException e) {
16151 Slog.e(TAG, "Unable to access code path " + path);
16157 * Tries to delete system package.
16159 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16160 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16161 boolean writeSettings) {
16162 if (deletedPs.parentPackageName != null) {
16163 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16167 final boolean applyUserRestrictions
16168 = (allUserHandles != null) && (outInfo.origUsers != null);
16169 final PackageSetting disabledPs;
16170 // Confirm if the system package has been updated
16171 // An updated system app can be deleted. This will also have to restore
16172 // the system pkg from system partition
16174 synchronized (mPackages) {
16175 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16178 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16179 + " disabledPs=" + disabledPs);
16181 if (disabledPs == null) {
16182 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16184 } else if (DEBUG_REMOVE) {
16185 Slog.d(TAG, "Deleting system pkg from data partition");
16188 if (DEBUG_REMOVE) {
16189 if (applyUserRestrictions) {
16190 Slog.d(TAG, "Remembering install states:");
16191 for (int userId : allUserHandles) {
16192 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16193 Slog.d(TAG, " u=" + userId + " inst=" + finstalled);
16198 // Delete the updated package
16199 outInfo.isRemovedPackageSystemUpdate = true;
16200 if (outInfo.removedChildPackages != null) {
16201 final int childCount = (deletedPs.childPackageNames != null)
16202 ? deletedPs.childPackageNames.size() : 0;
16203 for (int i = 0; i < childCount; i++) {
16204 String childPackageName = deletedPs.childPackageNames.get(i);
16205 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16206 .contains(childPackageName)) {
16207 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16209 if (childInfo != null) {
16210 childInfo.isRemovedPackageSystemUpdate = true;
16216 if (disabledPs.versionCode < deletedPs.versionCode) {
16217 // Delete data for downgrades
16218 flags &= ~PackageManager.DELETE_KEEP_DATA;
16220 // Preserve data by setting flag
16221 flags |= PackageManager.DELETE_KEEP_DATA;
16224 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16225 outInfo, writeSettings, disabledPs.pkg);
16231 synchronized (mPackages) {
16232 // Reinstate the old system package
16233 enableSystemPackageLPw(disabledPs.pkg);
16234 // Remove any native libraries from the upgraded package.
16235 removeNativeBinariesLI(deletedPs);
16238 // Install the system package
16239 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16240 int parseFlags = mDefParseFlags
16241 | PackageParser.PARSE_MUST_BE_APK
16242 | PackageParser.PARSE_IS_SYSTEM
16243 | PackageParser.PARSE_IS_SYSTEM_DIR;
16244 if (locationIsPrivileged(disabledPs.codePath)) {
16245 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16248 final PackageParser.Package newPkg;
16250 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16251 } catch (PackageManagerException e) {
16252 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16257 // update shared libraries for the newly re-installed system package
16258 updateSharedLibrariesLPw(newPkg, null);
16259 } catch (PackageManagerException e) {
16260 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16263 prepareAppDataAfterInstallLIF(newPkg);
16266 synchronized (mPackages) {
16267 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16269 // Propagate the permissions state as we do not want to drop on the floor
16270 // runtime permissions. The update permissions method below will take
16271 // care of removing obsolete permissions and grant install permissions.
16272 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16273 updatePermissionsLPw(newPkg.packageName, newPkg,
16274 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16276 if (applyUserRestrictions) {
16277 if (DEBUG_REMOVE) {
16278 Slog.d(TAG, "Propagating install state across reinstall");
16280 for (int userId : allUserHandles) {
16281 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16282 if (DEBUG_REMOVE) {
16283 Slog.d(TAG, " user " + userId + " => " + installed);
16285 ps.setInstalled(installed, userId);
16287 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16289 // Regardless of writeSettings we need to ensure that this restriction
16290 // state propagation is persisted
16291 mSettings.writeAllUsersPackageRestrictionsLPr();
16293 // can downgrade to reader here
16294 if (writeSettings) {
16295 mSettings.writeLPr();
16301 private boolean deleteInstalledPackageLIF(PackageSetting ps,
16302 boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16303 PackageRemovedInfo outInfo, boolean writeSettings,
16304 PackageParser.Package replacingPackage) {
16305 synchronized (mPackages) {
16306 if (outInfo != null) {
16307 outInfo.uid = ps.appId;
16310 if (outInfo != null && outInfo.removedChildPackages != null) {
16311 final int childCount = (ps.childPackageNames != null)
16312 ? ps.childPackageNames.size() : 0;
16313 for (int i = 0; i < childCount; i++) {
16314 String childPackageName = ps.childPackageNames.get(i);
16315 PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16316 if (childPs == null) {
16319 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16321 if (childInfo != null) {
16322 childInfo.uid = childPs.appId;
16328 // Delete package data from internal structures and also remove data if flag is set
16329 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16331 // Delete the child packages data
16332 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16333 for (int i = 0; i < childCount; i++) {
16334 PackageSetting childPs;
16335 synchronized (mPackages) {
16336 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16338 if (childPs != null) {
16339 PackageRemovedInfo childOutInfo = (outInfo != null
16340 && outInfo.removedChildPackages != null)
16341 ? outInfo.removedChildPackages.get(childPs.name) : null;
16342 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16343 && (replacingPackage != null
16344 && !replacingPackage.hasChildPackage(childPs.name))
16345 ? flags & ~DELETE_KEEP_DATA : flags;
16346 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16347 deleteFlags, writeSettings);
16351 // Delete application code and resources only for parent packages
16352 if (ps.parentPackageName == null) {
16353 if (deleteCodeAndResources && (outInfo != null)) {
16354 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16355 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16356 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16364 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16366 mContext.enforceCallingOrSelfPermission(
16367 android.Manifest.permission.DELETE_PACKAGES, null);
16368 synchronized (mPackages) {
16369 PackageSetting ps = mSettings.mPackages.get(packageName);
16371 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16374 if (!ps.getInstalled(userId)) {
16375 // Can't block uninstall for an app that is not installed or enabled.
16376 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16379 ps.setBlockUninstall(blockUninstall, userId);
16380 mSettings.writePackageRestrictionsLPr(userId);
16386 public boolean getBlockUninstallForUser(String packageName, int userId) {
16387 synchronized (mPackages) {
16388 PackageSetting ps = mSettings.mPackages.get(packageName);
16390 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16393 return ps.getBlockUninstall(userId);
16398 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16399 int callingUid = Binder.getCallingUid();
16400 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16401 throw new SecurityException(
16402 "setRequiredForSystemUser can only be run by the system or root");
16404 synchronized (mPackages) {
16405 PackageSetting ps = mSettings.mPackages.get(packageName);
16407 Log.w(TAG, "Package doesn't exist: " + packageName);
16410 if (systemUserApp) {
16411 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16413 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16415 mSettings.writeLPr();
16421 * This method handles package deletion in general
16423 private boolean deletePackageLIF(String packageName, UserHandle user,
16424 boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16425 PackageRemovedInfo outInfo, boolean writeSettings,
16426 PackageParser.Package replacingPackage) {
16427 if (packageName == null) {
16428 Slog.w(TAG, "Attempt to delete null packageName.");
16432 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16436 synchronized (mPackages) {
16437 ps = mSettings.mPackages.get(packageName);
16439 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16443 if (ps.parentPackageName != null && (!isSystemApp(ps)
16444 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16445 if (DEBUG_REMOVE) {
16446 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16447 + ((user == null) ? UserHandle.USER_ALL : user));
16449 final int removedUserId = (user != null) ? user.getIdentifier()
16450 : UserHandle.USER_ALL;
16451 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16454 markPackageUninstalledForUserLPw(ps, user);
16455 scheduleWritePackageRestrictionsLocked(user);
16460 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16461 && user.getIdentifier() != UserHandle.USER_ALL)) {
16462 // The caller is asking that the package only be deleted for a single
16463 // user. To do this, we just mark its uninstalled state and delete
16464 // its data. If this is a system app, we only allow this to happen if
16465 // they have set the special DELETE_SYSTEM_APP which requests different
16466 // semantics than normal for uninstalling system apps.
16467 markPackageUninstalledForUserLPw(ps, user);
16469 if (!isSystemApp(ps)) {
16470 // Do not uninstall the APK if an app should be cached
16471 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16472 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16473 // Other user still have this package installed, so all
16474 // we need to do is clear this user's data and save that
16475 // it is uninstalled.
16476 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16477 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16480 scheduleWritePackageRestrictionsLocked(user);
16483 // We need to set it back to 'installed' so the uninstall
16484 // broadcasts will be sent correctly.
16485 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16486 ps.setInstalled(true, user.getIdentifier());
16489 // This is a system app, so we assume that the
16490 // other users still have this package installed, so all
16491 // we need to do is clear this user's data and save that
16492 // it is uninstalled.
16493 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16494 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16497 scheduleWritePackageRestrictionsLocked(user);
16502 // If we are deleting a composite package for all users, keep track
16503 // of result for each child.
16504 if (ps.childPackageNames != null && outInfo != null) {
16505 synchronized (mPackages) {
16506 final int childCount = ps.childPackageNames.size();
16507 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16508 for (int i = 0; i < childCount; i++) {
16509 String childPackageName = ps.childPackageNames.get(i);
16510 PackageRemovedInfo childInfo = new PackageRemovedInfo();
16511 childInfo.removedPackage = childPackageName;
16512 outInfo.removedChildPackages.put(childPackageName, childInfo);
16513 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16514 if (childPs != null) {
16515 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16521 boolean ret = false;
16522 if (isSystemApp(ps)) {
16523 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16524 // When an updated system application is deleted we delete the existing resources
16525 // as well and fall back to existing code in system partition
16526 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16528 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16529 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16530 outInfo, writeSettings, replacingPackage);
16533 // Take a note whether we deleted the package for all users
16534 if (outInfo != null) {
16535 outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16536 if (outInfo.removedChildPackages != null) {
16537 synchronized (mPackages) {
16538 final int childCount = outInfo.removedChildPackages.size();
16539 for (int i = 0; i < childCount; i++) {
16540 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16541 if (childInfo != null) {
16542 childInfo.removedForAllUsers = mPackages.get(
16543 childInfo.removedPackage) == null;
16548 // If we uninstalled an update to a system app there may be some
16549 // child packages that appeared as they are declared in the system
16550 // app but were not declared in the update.
16551 if (isSystemApp(ps)) {
16552 synchronized (mPackages) {
16553 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16554 final int childCount = (updatedPs.childPackageNames != null)
16555 ? updatedPs.childPackageNames.size() : 0;
16556 for (int i = 0; i < childCount; i++) {
16557 String childPackageName = updatedPs.childPackageNames.get(i);
16558 if (outInfo.removedChildPackages == null
16559 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16560 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16561 if (childPs == null) {
16564 PackageInstalledInfo installRes = new PackageInstalledInfo();
16565 installRes.name = childPackageName;
16566 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16567 installRes.pkg = mPackages.get(childPackageName);
16568 installRes.uid = childPs.pkg.applicationInfo.uid;
16569 if (outInfo.appearedChildPackages == null) {
16570 outInfo.appearedChildPackages = new ArrayMap<>();
16572 outInfo.appearedChildPackages.put(childPackageName, installRes);
16582 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16583 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16584 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16585 for (int nextUserId : userIds) {
16586 if (DEBUG_REMOVE) {
16587 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16589 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16590 false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16591 false /*hidden*/, false /*suspended*/, null, null, null,
16592 false /*blockUninstall*/,
16593 ps.readUserState(nextUserId).domainVerificationStatus, 0);
16597 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16598 PackageRemovedInfo outInfo) {
16599 final PackageParser.Package pkg;
16600 synchronized (mPackages) {
16601 pkg = mPackages.get(ps.name);
16604 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16605 : new int[] {userId};
16606 for (int nextUserId : userIds) {
16607 if (DEBUG_REMOVE) {
16608 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16612 destroyAppDataLIF(pkg, userId,
16613 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16614 destroyAppProfilesLIF(pkg, userId);
16615 removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16616 schedulePackageCleaning(ps.name, nextUserId, false);
16617 synchronized (mPackages) {
16618 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16619 scheduleWritePackageRestrictionsLocked(nextUserId);
16621 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16625 if (outInfo != null) {
16626 outInfo.removedPackage = ps.name;
16627 outInfo.removedAppId = ps.appId;
16628 outInfo.removedUsers = userIds;
16634 private final class ClearStorageConnection implements ServiceConnection {
16635 IMediaContainerService mContainerService;
16638 public void onServiceConnected(ComponentName name, IBinder service) {
16639 synchronized (this) {
16640 mContainerService = IMediaContainerService.Stub.asInterface(service);
16646 public void onServiceDisconnected(ComponentName name) {
16650 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16651 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16653 final boolean mounted;
16654 if (Environment.isExternalStorageEmulated()) {
16657 final String status = Environment.getExternalStorageState();
16659 mounted = status.equals(Environment.MEDIA_MOUNTED)
16660 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16667 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16669 if (userId == UserHandle.USER_ALL) {
16670 users = sUserManager.getUserIds();
16672 users = new int[] { userId };
16674 final ClearStorageConnection conn = new ClearStorageConnection();
16675 if (mContext.bindServiceAsUser(
16676 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16678 for (int curUser : users) {
16679 long timeout = SystemClock.uptimeMillis() + 5000;
16680 synchronized (conn) {
16682 while (conn.mContainerService == null &&
16683 (now = SystemClock.uptimeMillis()) < timeout) {
16685 conn.wait(timeout - now);
16686 } catch (InterruptedException e) {
16690 if (conn.mContainerService == null) {
16694 final UserEnvironment userEnv = new UserEnvironment(curUser);
16695 clearDirectory(conn.mContainerService,
16696 userEnv.buildExternalStorageAppCacheDirs(packageName));
16698 clearDirectory(conn.mContainerService,
16699 userEnv.buildExternalStorageAppDataDirs(packageName));
16700 clearDirectory(conn.mContainerService,
16701 userEnv.buildExternalStorageAppMediaDirs(packageName));
16705 mContext.unbindService(conn);
16711 public void clearApplicationProfileData(String packageName) {
16712 enforceSystemOrRoot("Only the system can clear all profile data");
16714 final PackageParser.Package pkg;
16715 synchronized (mPackages) {
16716 pkg = mPackages.get(packageName);
16719 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16720 synchronized (mInstallLock) {
16721 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16722 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16723 true /* removeBaseMarker */);
16729 public void clearApplicationUserData(final String packageName,
16730 final IPackageDataObserver observer, final int userId) {
16731 mContext.enforceCallingOrSelfPermission(
16732 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16734 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16735 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16737 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16738 throw new SecurityException("Cannot clear data for a protected package: "
16741 // Queue up an async operation since the package deletion may take a little while.
16742 mHandler.post(new Runnable() {
16743 public void run() {
16744 mHandler.removeCallbacks(this);
16745 final boolean succeeded;
16746 try (PackageFreezer freezer = freezePackage(packageName,
16747 "clearApplicationUserData")) {
16748 synchronized (mInstallLock) {
16749 succeeded = clearApplicationUserDataLIF(packageName, userId);
16751 clearExternalStorageDataSync(packageName, userId, true);
16754 // invoke DeviceStorageMonitor's update method to clear any notifications
16755 DeviceStorageMonitorInternal dsm = LocalServices
16756 .getService(DeviceStorageMonitorInternal.class);
16761 if(observer != null) {
16763 observer.onRemoveCompleted(packageName, succeeded);
16764 } catch (RemoteException e) {
16765 Log.i(TAG, "Observer no longer exists.");
16767 } //end if observer
16772 private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16773 if (packageName == null) {
16774 Slog.w(TAG, "Attempt to delete null packageName.");
16778 // Try finding details about the requested package
16779 PackageParser.Package pkg;
16780 synchronized (mPackages) {
16781 pkg = mPackages.get(packageName);
16783 final PackageSetting ps = mSettings.mPackages.get(packageName);
16790 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16794 PackageSetting ps = (PackageSetting) pkg.mExtras;
16795 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16798 clearAppDataLIF(pkg, userId,
16799 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16801 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16802 removeKeystoreDataIfNeeded(userId, appId);
16804 UserManagerInternal umInternal = getUserManagerInternal();
16806 if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16807 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16808 } else if (umInternal.isUserRunning(userId)) {
16809 flags = StorageManager.FLAG_STORAGE_DE;
16813 prepareAppDataContentsLIF(pkg, userId, flags);
16819 * Reverts user permission state changes (permissions and flags) in
16820 * all packages for a given user.
16822 * @param userId The device user for which to do a reset.
16824 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16825 final int packageCount = mPackages.size();
16826 for (int i = 0; i < packageCount; i++) {
16827 PackageParser.Package pkg = mPackages.valueAt(i);
16828 PackageSetting ps = (PackageSetting) pkg.mExtras;
16829 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16833 private void resetNetworkPolicies(int userId) {
16834 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16838 * Reverts user permission state changes (permissions and flags).
16840 * @param ps The package for which to reset.
16841 * @param userId The device user for which to do a reset.
16843 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16844 final PackageSetting ps, final int userId) {
16845 if (ps.pkg == null) {
16849 // These are flags that can change base on user actions.
16850 final int userSettableMask = FLAG_PERMISSION_USER_SET
16851 | FLAG_PERMISSION_USER_FIXED
16852 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16853 | FLAG_PERMISSION_REVIEW_REQUIRED;
16855 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16856 | FLAG_PERMISSION_POLICY_FIXED;
16858 boolean writeInstallPermissions = false;
16859 boolean writeRuntimePermissions = false;
16861 final int permissionCount = ps.pkg.requestedPermissions.size();
16862 for (int i = 0; i < permissionCount; i++) {
16863 String permission = ps.pkg.requestedPermissions.get(i);
16865 BasePermission bp = mSettings.mPermissions.get(permission);
16870 // If shared user we just reset the state to which only this app contributed.
16871 if (ps.sharedUser != null) {
16872 boolean used = false;
16873 final int packageCount = ps.sharedUser.packages.size();
16874 for (int j = 0; j < packageCount; j++) {
16875 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16876 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16877 && pkg.pkg.requestedPermissions.contains(permission)) {
16887 PermissionsState permissionsState = ps.getPermissionsState();
16889 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16891 // Always clear the user settable flags.
16892 final boolean hasInstallState = permissionsState.getInstallPermissionState(
16894 // If permission review is enabled and this is a legacy app, mark the
16895 // permission as requiring a review as this is the initial state.
16897 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16898 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16899 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16901 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16902 if (hasInstallState) {
16903 writeInstallPermissions = true;
16905 writeRuntimePermissions = true;
16909 // Below is only runtime permission handling.
16910 if (!bp.isRuntime()) {
16914 // Never clobber system or policy.
16915 if ((oldFlags & policyOrSystemFlags) != 0) {
16919 // If this permission was granted by default, make sure it is.
16920 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16921 if (permissionsState.grantRuntimePermission(bp, userId)
16922 != PERMISSION_OPERATION_FAILURE) {
16923 writeRuntimePermissions = true;
16925 // If permission review is enabled the permissions for a legacy apps
16926 // are represented as constantly granted runtime ones, so don't revoke.
16927 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16928 // Otherwise, reset the permission.
16929 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16930 switch (revokeResult) {
16931 case PERMISSION_OPERATION_SUCCESS:
16932 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16933 writeRuntimePermissions = true;
16934 final int appId = ps.appId;
16935 mHandler.post(new Runnable() {
16937 public void run() {
16938 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16946 // Synchronously write as we are taking permissions away.
16947 if (writeRuntimePermissions) {
16948 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16951 // Synchronously write as we are taking permissions away.
16952 if (writeInstallPermissions) {
16953 mSettings.writeLPr();
16958 * Remove entries from the keystore daemon. Will only remove it if the
16959 * {@code appId} is valid.
16961 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16966 final KeyStore keyStore = KeyStore.getInstance();
16967 if (keyStore != null) {
16968 if (userId == UserHandle.USER_ALL) {
16969 for (final int individual : sUserManager.getUserIds()) {
16970 keyStore.clearUid(UserHandle.getUid(individual, appId));
16973 keyStore.clearUid(UserHandle.getUid(userId, appId));
16976 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16981 public void deleteApplicationCacheFiles(final String packageName,
16982 final IPackageDataObserver observer) {
16983 final int userId = UserHandle.getCallingUserId();
16984 deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16988 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16989 final IPackageDataObserver observer) {
16990 mContext.enforceCallingOrSelfPermission(
16991 android.Manifest.permission.DELETE_CACHE_FILES, null);
16992 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16993 /* requireFullPermission= */ true, /* checkShell= */ false,
16994 "delete application cache files");
16996 final PackageParser.Package pkg;
16997 synchronized (mPackages) {
16998 pkg = mPackages.get(packageName);
17001 // Queue up an async operation since the package deletion may take a little while.
17002 mHandler.post(new Runnable() {
17003 public void run() {
17004 synchronized (mInstallLock) {
17005 final int flags = StorageManager.FLAG_STORAGE_DE
17006 | StorageManager.FLAG_STORAGE_CE;
17007 // We're only clearing cache files, so we don't care if the
17008 // app is unfrozen and still able to run
17009 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17010 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17012 clearExternalStorageDataSync(packageName, userId, false);
17013 if (observer != null) {
17015 observer.onRemoveCompleted(packageName, true);
17016 } catch (RemoteException e) {
17017 Log.i(TAG, "Observer no longer exists.");
17025 public void getPackageSizeInfo(final String packageName, int userHandle,
17026 final IPackageStatsObserver observer) {
17027 mContext.enforceCallingOrSelfPermission(
17028 android.Manifest.permission.GET_PACKAGE_SIZE, null);
17029 if (packageName == null) {
17030 throw new IllegalArgumentException("Attempt to get size of null packageName");
17033 PackageStats stats = new PackageStats(packageName, userHandle);
17036 * Queue up an async operation since the package measurement may take a
17039 Message msg = mHandler.obtainMessage(INIT_COPY);
17040 msg.obj = new MeasureParams(stats, observer);
17041 mHandler.sendMessage(msg);
17044 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17045 final PackageSetting ps;
17046 synchronized (mPackages) {
17047 ps = mSettings.mPackages.get(packageName);
17049 Slog.w(TAG, "Failed to find settings for " + packageName);
17054 mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17056 ps.getCeDataInode(userId), ps.codePathString, stats);
17057 } catch (InstallerException e) {
17058 Slog.w(TAG, String.valueOf(e));
17062 // For now, ignore code size of packages on system partition
17063 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17064 stats.codeSize = 0;
17070 private int getUidTargetSdkVersionLockedLPr(int uid) {
17071 Object obj = mSettings.getUserIdLPr(uid);
17072 if (obj instanceof SharedUserSetting) {
17073 final SharedUserSetting sus = (SharedUserSetting) obj;
17074 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17075 final Iterator<PackageSetting> it = sus.packages.iterator();
17076 while (it.hasNext()) {
17077 final PackageSetting ps = it.next();
17078 if (ps.pkg != null) {
17079 int v = ps.pkg.applicationInfo.targetSdkVersion;
17080 if (v < vers) vers = v;
17084 } else if (obj instanceof PackageSetting) {
17085 final PackageSetting ps = (PackageSetting) obj;
17086 if (ps.pkg != null) {
17087 return ps.pkg.applicationInfo.targetSdkVersion;
17090 return Build.VERSION_CODES.CUR_DEVELOPMENT;
17094 public void addPreferredActivity(IntentFilter filter, int match,
17095 ComponentName[] set, ComponentName activity, int userId) {
17096 addPreferredActivityInternal(filter, match, set, activity, true, userId,
17097 "Adding preferred");
17100 private void addPreferredActivityInternal(IntentFilter filter, int match,
17101 ComponentName[] set, ComponentName activity, boolean always, int userId,
17104 int callingUid = Binder.getCallingUid();
17105 enforceCrossUserPermission(callingUid, userId,
17106 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17107 if (filter.countActions() == 0) {
17108 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17111 synchronized (mPackages) {
17112 if (mContext.checkCallingOrSelfPermission(
17113 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17114 != PackageManager.PERMISSION_GRANTED) {
17115 if (getUidTargetSdkVersionLockedLPr(callingUid)
17116 < Build.VERSION_CODES.FROYO) {
17117 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17121 mContext.enforceCallingOrSelfPermission(
17122 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17125 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17126 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17128 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17129 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17130 scheduleWritePackageRestrictionsLocked(userId);
17131 postPreferredActivityChangedBroadcast(userId);
17135 private void postPreferredActivityChangedBroadcast(int userId) {
17136 mHandler.post(() -> {
17137 final IActivityManager am = ActivityManagerNative.getDefault();
17142 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17143 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17145 am.broadcastIntent(null, intent, null, null,
17146 0, null, null, null, android.app.AppOpsManager.OP_NONE,
17147 null, false, false, userId);
17148 } catch (RemoteException e) {
17154 public void replacePreferredActivity(IntentFilter filter, int match,
17155 ComponentName[] set, ComponentName activity, int userId) {
17156 if (filter.countActions() != 1) {
17157 throw new IllegalArgumentException(
17158 "replacePreferredActivity expects filter to have only 1 action.");
17160 if (filter.countDataAuthorities() != 0
17161 || filter.countDataPaths() != 0
17162 || filter.countDataSchemes() > 1
17163 || filter.countDataTypes() != 0) {
17164 throw new IllegalArgumentException(
17165 "replacePreferredActivity expects filter to have no data authorities, " +
17166 "paths, or types; and at most one scheme.");
17169 final int callingUid = Binder.getCallingUid();
17170 enforceCrossUserPermission(callingUid, userId,
17171 true /* requireFullPermission */, false /* checkShell */,
17172 "replace preferred activity");
17173 synchronized (mPackages) {
17174 if (mContext.checkCallingOrSelfPermission(
17175 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17176 != PackageManager.PERMISSION_GRANTED) {
17177 if (getUidTargetSdkVersionLockedLPr(callingUid)
17178 < Build.VERSION_CODES.FROYO) {
17179 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17180 + Binder.getCallingUid());
17183 mContext.enforceCallingOrSelfPermission(
17184 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17187 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17189 // Get all of the existing entries that exactly match this filter.
17190 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17191 if (existing != null && existing.size() == 1) {
17192 PreferredActivity cur = existing.get(0);
17193 if (DEBUG_PREFERRED) {
17194 Slog.i(TAG, "Checking replace of preferred:");
17195 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17196 if (!cur.mPref.mAlways) {
17197 Slog.i(TAG, " -- CUR; not mAlways!");
17199 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
17200 Slog.i(TAG, " -- CUR: mSet="
17201 + Arrays.toString(cur.mPref.mSetComponents));
17202 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
17203 Slog.i(TAG, " -- NEW: mMatch="
17204 + (match&IntentFilter.MATCH_CATEGORY_MASK));
17205 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
17206 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
17209 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17210 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17211 && cur.mPref.sameSet(set)) {
17212 // Setting the preferred activity to what it happens to be already
17213 if (DEBUG_PREFERRED) {
17214 Slog.i(TAG, "Replacing with same preferred activity "
17215 + cur.mPref.mShortComponent + " for user "
17217 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17223 if (existing != null) {
17224 if (DEBUG_PREFERRED) {
17225 Slog.i(TAG, existing.size() + " existing preferred matches for:");
17226 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17228 for (int i = 0; i < existing.size(); i++) {
17229 PreferredActivity pa = existing.get(i);
17230 if (DEBUG_PREFERRED) {
17231 Slog.i(TAG, "Removing existing preferred activity "
17232 + pa.mPref.mComponent + ":");
17233 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
17235 pir.removeFilter(pa);
17239 addPreferredActivityInternal(filter, match, set, activity, true, userId,
17240 "Replacing preferred");
17245 public void clearPackagePreferredActivities(String packageName) {
17246 final int uid = Binder.getCallingUid();
17248 synchronized (mPackages) {
17249 PackageParser.Package pkg = mPackages.get(packageName);
17250 if (pkg == null || pkg.applicationInfo.uid != uid) {
17251 if (mContext.checkCallingOrSelfPermission(
17252 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17253 != PackageManager.PERMISSION_GRANTED) {
17254 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17255 < Build.VERSION_CODES.FROYO) {
17256 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17257 + Binder.getCallingUid());
17260 mContext.enforceCallingOrSelfPermission(
17261 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17265 int user = UserHandle.getCallingUserId();
17266 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17267 scheduleWritePackageRestrictionsLocked(user);
17272 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17273 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17274 ArrayList<PreferredActivity> removed = null;
17275 boolean changed = false;
17276 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17277 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17278 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17279 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17282 Iterator<PreferredActivity> it = pir.filterIterator();
17283 while (it.hasNext()) {
17284 PreferredActivity pa = it.next();
17285 // Mark entry for removal only if it matches the package name
17286 // and the entry is of type "always".
17287 if (packageName == null ||
17288 (pa.mPref.mComponent.getPackageName().equals(packageName)
17289 && pa.mPref.mAlways)) {
17290 if (removed == null) {
17291 removed = new ArrayList<PreferredActivity>();
17296 if (removed != null) {
17297 for (int j=0; j<removed.size(); j++) {
17298 PreferredActivity pa = removed.get(j);
17299 pir.removeFilter(pa);
17305 postPreferredActivityChangedBroadcast(userId);
17310 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17311 private void clearIntentFilterVerificationsLPw(int userId) {
17312 final int packageCount = mPackages.size();
17313 for (int i = 0; i < packageCount; i++) {
17314 PackageParser.Package pkg = mPackages.valueAt(i);
17315 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17319 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17320 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17321 if (userId == UserHandle.USER_ALL) {
17322 if (mSettings.removeIntentFilterVerificationLPw(packageName,
17323 sUserManager.getUserIds())) {
17324 for (int oneUserId : sUserManager.getUserIds()) {
17325 scheduleWritePackageRestrictionsLocked(oneUserId);
17329 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17330 scheduleWritePackageRestrictionsLocked(userId);
17335 void clearDefaultBrowserIfNeeded(String packageName) {
17336 for (int oneUserId : sUserManager.getUserIds()) {
17337 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17338 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17339 if (packageName.equals(defaultBrowserPackageName)) {
17340 setDefaultBrowserPackageName(null, oneUserId);
17346 public void resetApplicationPreferences(int userId) {
17347 mContext.enforceCallingOrSelfPermission(
17348 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17349 final long identity = Binder.clearCallingIdentity();
17352 synchronized (mPackages) {
17353 clearPackagePreferredActivitiesLPw(null, userId);
17354 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17355 // TODO: We have to reset the default SMS and Phone. This requires
17356 // significant refactoring to keep all default apps in the package
17357 // manager (cleaner but more work) or have the services provide
17358 // callbacks to the package manager to request a default app reset.
17359 applyFactoryDefaultBrowserLPw(userId);
17360 clearIntentFilterVerificationsLPw(userId);
17361 primeDomainVerificationsLPw(userId);
17362 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17363 scheduleWritePackageRestrictionsLocked(userId);
17365 resetNetworkPolicies(userId);
17367 Binder.restoreCallingIdentity(identity);
17372 public int getPreferredActivities(List<IntentFilter> outFilters,
17373 List<ComponentName> outActivities, String packageName) {
17376 final int userId = UserHandle.getCallingUserId();
17378 synchronized (mPackages) {
17379 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17381 final Iterator<PreferredActivity> it = pir.filterIterator();
17382 while (it.hasNext()) {
17383 final PreferredActivity pa = it.next();
17384 if (packageName == null
17385 || (pa.mPref.mComponent.getPackageName().equals(packageName)
17386 && pa.mPref.mAlways)) {
17387 if (outFilters != null) {
17388 outFilters.add(new IntentFilter(pa));
17390 if (outActivities != null) {
17391 outActivities.add(pa.mPref.mComponent);
17402 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17404 int callingUid = Binder.getCallingUid();
17405 if (callingUid != Process.SYSTEM_UID) {
17406 throw new SecurityException(
17407 "addPersistentPreferredActivity can only be run by the system");
17409 if (filter.countActions() == 0) {
17410 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17413 synchronized (mPackages) {
17414 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17416 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17417 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17418 new PersistentPreferredActivity(filter, activity));
17419 scheduleWritePackageRestrictionsLocked(userId);
17420 postPreferredActivityChangedBroadcast(userId);
17425 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17426 int callingUid = Binder.getCallingUid();
17427 if (callingUid != Process.SYSTEM_UID) {
17428 throw new SecurityException(
17429 "clearPackagePersistentPreferredActivities can only be run by the system");
17431 ArrayList<PersistentPreferredActivity> removed = null;
17432 boolean changed = false;
17433 synchronized (mPackages) {
17434 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17435 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17436 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17438 if (userId != thisUserId) {
17441 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17442 while (it.hasNext()) {
17443 PersistentPreferredActivity ppa = it.next();
17444 // Mark entry for removal only if it matches the package name.
17445 if (ppa.mComponent.getPackageName().equals(packageName)) {
17446 if (removed == null) {
17447 removed = new ArrayList<PersistentPreferredActivity>();
17452 if (removed != null) {
17453 for (int j=0; j<removed.size(); j++) {
17454 PersistentPreferredActivity ppa = removed.get(j);
17455 ppir.removeFilter(ppa);
17462 scheduleWritePackageRestrictionsLocked(userId);
17463 postPreferredActivityChangedBroadcast(userId);
17469 * Common machinery for picking apart a restored XML blob and passing
17470 * it to a caller-supplied functor to be applied to the running system.
17472 private void restoreFromXml(XmlPullParser parser, int userId,
17473 String expectedStartTag, BlobXmlRestorer functor)
17474 throws IOException, XmlPullParserException {
17476 while ((type = parser.next()) != XmlPullParser.START_TAG
17477 && type != XmlPullParser.END_DOCUMENT) {
17479 if (type != XmlPullParser.START_TAG) {
17480 // oops didn't find a start tag?!
17481 if (DEBUG_BACKUP) {
17482 Slog.e(TAG, "Didn't find start tag during restore");
17486 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17487 // this is supposed to be TAG_PREFERRED_BACKUP
17488 if (!expectedStartTag.equals(parser.getName())) {
17489 if (DEBUG_BACKUP) {
17490 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17495 // skip interfering stuff, then we're aligned with the backing implementation
17496 while ((type = parser.next()) == XmlPullParser.TEXT) { }
17497 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17498 functor.apply(parser, userId);
17501 private interface BlobXmlRestorer {
17502 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17506 * Non-Binder method, support for the backup/restore mechanism: write the
17507 * full set of preferred activities in its canonical XML format. Returns the
17508 * XML output as a byte array, or null if there is none.
17511 public byte[] getPreferredActivityBackup(int userId) {
17512 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17513 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17516 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17518 final XmlSerializer serializer = new FastXmlSerializer();
17519 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17520 serializer.startDocument(null, true);
17521 serializer.startTag(null, TAG_PREFERRED_BACKUP);
17523 synchronized (mPackages) {
17524 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17527 serializer.endTag(null, TAG_PREFERRED_BACKUP);
17528 serializer.endDocument();
17529 serializer.flush();
17530 } catch (Exception e) {
17531 if (DEBUG_BACKUP) {
17532 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17537 return dataStream.toByteArray();
17541 public void restorePreferredActivities(byte[] backup, int userId) {
17542 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17543 throw new SecurityException("Only the system may call restorePreferredActivities()");
17547 final XmlPullParser parser = Xml.newPullParser();
17548 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17549 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17550 new BlobXmlRestorer() {
17552 public void apply(XmlPullParser parser, int userId)
17553 throws XmlPullParserException, IOException {
17554 synchronized (mPackages) {
17555 mSettings.readPreferredActivitiesLPw(parser, userId);
17559 } catch (Exception e) {
17560 if (DEBUG_BACKUP) {
17561 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17567 * Non-Binder method, support for the backup/restore mechanism: write the
17568 * default browser (etc) settings in its canonical XML format. Returns the default
17569 * browser XML representation as a byte array, or null if there is none.
17572 public byte[] getDefaultAppsBackup(int userId) {
17573 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17574 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17577 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17579 final XmlSerializer serializer = new FastXmlSerializer();
17580 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17581 serializer.startDocument(null, true);
17582 serializer.startTag(null, TAG_DEFAULT_APPS);
17584 synchronized (mPackages) {
17585 mSettings.writeDefaultAppsLPr(serializer, userId);
17588 serializer.endTag(null, TAG_DEFAULT_APPS);
17589 serializer.endDocument();
17590 serializer.flush();
17591 } catch (Exception e) {
17592 if (DEBUG_BACKUP) {
17593 Slog.e(TAG, "Unable to write default apps for backup", e);
17598 return dataStream.toByteArray();
17602 public void restoreDefaultApps(byte[] backup, int userId) {
17603 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17604 throw new SecurityException("Only the system may call restoreDefaultApps()");
17608 final XmlPullParser parser = Xml.newPullParser();
17609 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17610 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17611 new BlobXmlRestorer() {
17613 public void apply(XmlPullParser parser, int userId)
17614 throws XmlPullParserException, IOException {
17615 synchronized (mPackages) {
17616 mSettings.readDefaultAppsLPw(parser, userId);
17620 } catch (Exception e) {
17621 if (DEBUG_BACKUP) {
17622 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17628 public byte[] getIntentFilterVerificationBackup(int userId) {
17629 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17630 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17633 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17635 final XmlSerializer serializer = new FastXmlSerializer();
17636 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17637 serializer.startDocument(null, true);
17638 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17640 synchronized (mPackages) {
17641 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17644 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17645 serializer.endDocument();
17646 serializer.flush();
17647 } catch (Exception e) {
17648 if (DEBUG_BACKUP) {
17649 Slog.e(TAG, "Unable to write default apps for backup", e);
17654 return dataStream.toByteArray();
17658 public void restoreIntentFilterVerification(byte[] backup, int userId) {
17659 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17660 throw new SecurityException("Only the system may call restorePreferredActivities()");
17664 final XmlPullParser parser = Xml.newPullParser();
17665 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17666 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17667 new BlobXmlRestorer() {
17669 public void apply(XmlPullParser parser, int userId)
17670 throws XmlPullParserException, IOException {
17671 synchronized (mPackages) {
17672 mSettings.readAllDomainVerificationsLPr(parser, userId);
17673 mSettings.writeLPr();
17677 } catch (Exception e) {
17678 if (DEBUG_BACKUP) {
17679 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17685 public byte[] getPermissionGrantBackup(int userId) {
17686 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17687 throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17690 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17692 final XmlSerializer serializer = new FastXmlSerializer();
17693 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17694 serializer.startDocument(null, true);
17695 serializer.startTag(null, TAG_PERMISSION_BACKUP);
17697 synchronized (mPackages) {
17698 serializeRuntimePermissionGrantsLPr(serializer, userId);
17701 serializer.endTag(null, TAG_PERMISSION_BACKUP);
17702 serializer.endDocument();
17703 serializer.flush();
17704 } catch (Exception e) {
17705 if (DEBUG_BACKUP) {
17706 Slog.e(TAG, "Unable to write default apps for backup", e);
17711 return dataStream.toByteArray();
17715 public void restorePermissionGrants(byte[] backup, int userId) {
17716 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17717 throw new SecurityException("Only the system may call restorePermissionGrants()");
17721 final XmlPullParser parser = Xml.newPullParser();
17722 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17723 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17724 new BlobXmlRestorer() {
17726 public void apply(XmlPullParser parser, int userId)
17727 throws XmlPullParserException, IOException {
17728 synchronized (mPackages) {
17729 processRestoredPermissionGrantsLPr(parser, userId);
17733 } catch (Exception e) {
17734 if (DEBUG_BACKUP) {
17735 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17740 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17741 throws IOException {
17742 serializer.startTag(null, TAG_ALL_GRANTS);
17744 final int N = mSettings.mPackages.size();
17745 for (int i = 0; i < N; i++) {
17746 final PackageSetting ps = mSettings.mPackages.valueAt(i);
17747 boolean pkgGrantsKnown = false;
17749 PermissionsState packagePerms = ps.getPermissionsState();
17751 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17752 final int grantFlags = state.getFlags();
17753 // only look at grants that are not system/policy fixed
17754 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17755 final boolean isGranted = state.isGranted();
17756 // And only back up the user-twiddled state bits
17757 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17758 final String packageName = mSettings.mPackages.keyAt(i);
17759 if (!pkgGrantsKnown) {
17760 serializer.startTag(null, TAG_GRANT);
17761 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17762 pkgGrantsKnown = true;
17765 final boolean userSet =
17766 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17767 final boolean userFixed =
17768 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17769 final boolean revoke =
17770 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17772 serializer.startTag(null, TAG_PERMISSION);
17773 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17775 serializer.attribute(null, ATTR_IS_GRANTED, "true");
17778 serializer.attribute(null, ATTR_USER_SET, "true");
17781 serializer.attribute(null, ATTR_USER_FIXED, "true");
17784 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17786 serializer.endTag(null, TAG_PERMISSION);
17791 if (pkgGrantsKnown) {
17792 serializer.endTag(null, TAG_GRANT);
17796 serializer.endTag(null, TAG_ALL_GRANTS);
17799 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17800 throws XmlPullParserException, IOException {
17801 String pkgName = null;
17802 int outerDepth = parser.getDepth();
17804 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17805 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17806 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17810 final String tagName = parser.getName();
17811 if (tagName.equals(TAG_GRANT)) {
17812 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17813 if (DEBUG_BACKUP) {
17814 Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17816 } else if (tagName.equals(TAG_PERMISSION)) {
17818 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17819 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17821 int newFlagSet = 0;
17822 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17823 newFlagSet |= FLAG_PERMISSION_USER_SET;
17825 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17826 newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17828 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17829 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17831 if (DEBUG_BACKUP) {
17832 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName
17833 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17835 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17837 // Already installed so we apply the grant immediately
17838 if (DEBUG_BACKUP) {
17839 Slog.v(TAG, " + already installed; applying");
17841 PermissionsState perms = ps.getPermissionsState();
17842 BasePermission bp = mSettings.mPermissions.get(permName);
17845 perms.grantRuntimePermission(bp, userId);
17847 if (newFlagSet != 0) {
17848 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17852 // Need to wait for post-restore install to apply the grant
17853 if (DEBUG_BACKUP) {
17854 Slog.v(TAG, " - not yet installed; saving for later");
17856 mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17857 isGranted, newFlagSet, userId);
17860 PackageManagerService.reportSettingsProblem(Log.WARN,
17861 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17862 XmlUtils.skipCurrentTag(parser);
17866 scheduleWriteSettingsLocked();
17867 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17871 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17872 int sourceUserId, int targetUserId, int flags) {
17873 mContext.enforceCallingOrSelfPermission(
17874 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17875 int callingUid = Binder.getCallingUid();
17876 enforceOwnerRights(ownerPackage, callingUid);
17877 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17878 if (intentFilter.countActions() == 0) {
17879 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17882 synchronized (mPackages) {
17883 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17884 ownerPackage, targetUserId, flags);
17885 CrossProfileIntentResolver resolver =
17886 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17887 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17888 // We have all those whose filter is equal. Now checking if the rest is equal as well.
17889 if (existing != null) {
17890 int size = existing.size();
17891 for (int i = 0; i < size; i++) {
17892 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17897 resolver.addFilter(newFilter);
17898 scheduleWritePackageRestrictionsLocked(sourceUserId);
17903 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17904 mContext.enforceCallingOrSelfPermission(
17905 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17906 int callingUid = Binder.getCallingUid();
17907 enforceOwnerRights(ownerPackage, callingUid);
17908 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17909 synchronized (mPackages) {
17910 CrossProfileIntentResolver resolver =
17911 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17912 ArraySet<CrossProfileIntentFilter> set =
17913 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17914 for (CrossProfileIntentFilter filter : set) {
17915 if (filter.getOwnerPackage().equals(ownerPackage)) {
17916 resolver.removeFilter(filter);
17919 scheduleWritePackageRestrictionsLocked(sourceUserId);
17923 // Enforcing that callingUid is owning pkg on userId
17924 private void enforceOwnerRights(String pkg, int callingUid) {
17925 // The system owns everything.
17926 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17929 int callingUserId = UserHandle.getUserId(callingUid);
17930 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17932 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17935 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17936 throw new SecurityException("Calling uid " + callingUid
17937 + " does not own package " + pkg);
17942 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17943 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17946 private Intent getHomeIntent() {
17947 Intent intent = new Intent(Intent.ACTION_MAIN);
17948 intent.addCategory(Intent.CATEGORY_HOME);
17949 intent.addCategory(Intent.CATEGORY_DEFAULT);
17953 private IntentFilter getHomeFilter() {
17954 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17955 filter.addCategory(Intent.CATEGORY_HOME);
17956 filter.addCategory(Intent.CATEGORY_DEFAULT);
17960 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17962 Intent intent = getHomeIntent();
17963 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17964 PackageManager.GET_META_DATA, userId);
17965 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17966 true, false, false, userId);
17968 allHomeCandidates.clear();
17969 if (list != null) {
17970 for (ResolveInfo ri : list) {
17971 allHomeCandidates.add(ri);
17974 return (preferred == null || preferred.activityInfo == null)
17976 : new ComponentName(preferred.activityInfo.packageName,
17977 preferred.activityInfo.name);
17981 public void setHomeActivity(ComponentName comp, int userId) {
17982 ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17983 getHomeActivitiesAsUser(homeActivities, userId);
17985 boolean found = false;
17987 final int size = homeActivities.size();
17988 final ComponentName[] set = new ComponentName[size];
17989 for (int i = 0; i < size; i++) {
17990 final ResolveInfo candidate = homeActivities.get(i);
17991 final ActivityInfo info = candidate.activityInfo;
17992 final ComponentName activityName = new ComponentName(info.packageName, info.name);
17993 set[i] = activityName;
17994 if (!found && activityName.equals(comp)) {
17999 throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18002 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18003 set, comp, userId);
18006 private @Nullable String getSetupWizardPackageName() {
18007 final Intent intent = new Intent(Intent.ACTION_MAIN);
18008 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18010 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18011 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18012 | MATCH_DISABLED_COMPONENTS,
18013 UserHandle.myUserId());
18014 if (matches.size() == 1) {
18015 return matches.get(0).getComponentInfo().packageName;
18017 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18018 + ": matches=" + matches);
18023 private @Nullable String getStorageManagerPackageName() {
18024 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18026 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18027 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18028 | MATCH_DISABLED_COMPONENTS,
18029 UserHandle.myUserId());
18030 if (matches.size() == 1) {
18031 return matches.get(0).getComponentInfo().packageName;
18033 Slog.e(TAG, "There should probably be exactly one storage manager; found "
18034 + matches.size() + ": matches=" + matches);
18040 public void setApplicationEnabledSetting(String appPackageName,
18041 int newState, int flags, int userId, String callingPackage) {
18042 if (!sUserManager.exists(userId)) return;
18043 if (callingPackage == null) {
18044 callingPackage = Integer.toString(Binder.getCallingUid());
18046 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18050 public void setComponentEnabledSetting(ComponentName componentName,
18051 int newState, int flags, int userId) {
18052 if (!sUserManager.exists(userId)) return;
18053 setEnabledSetting(componentName.getPackageName(),
18054 componentName.getClassName(), newState, flags, userId, null);
18057 private void setEnabledSetting(final String packageName, String className, int newState,
18058 final int flags, int userId, String callingPackage) {
18059 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18060 || newState == COMPONENT_ENABLED_STATE_ENABLED
18061 || newState == COMPONENT_ENABLED_STATE_DISABLED
18062 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18063 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18064 throw new IllegalArgumentException("Invalid new component state: "
18067 PackageSetting pkgSetting;
18068 final int uid = Binder.getCallingUid();
18069 final int permission;
18070 if (uid == Process.SYSTEM_UID) {
18071 permission = PackageManager.PERMISSION_GRANTED;
18073 permission = mContext.checkCallingOrSelfPermission(
18074 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18076 enforceCrossUserPermission(uid, userId,
18077 false /* requireFullPermission */, true /* checkShell */, "set enabled");
18078 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18079 boolean sendNow = false;
18080 boolean isApp = (className == null);
18081 String componentName = isApp ? packageName : className;
18082 int packageUid = -1;
18083 ArrayList<String> components;
18086 synchronized (mPackages) {
18087 pkgSetting = mSettings.mPackages.get(packageName);
18088 if (pkgSetting == null) {
18089 if (className == null) {
18090 throw new IllegalArgumentException("Unknown package: " + packageName);
18092 throw new IllegalArgumentException(
18093 "Unknown component: " + packageName + "/" + className);
18097 // Limit who can change which apps
18098 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18099 // Don't allow apps that don't have permission to modify other apps
18100 if (!allowedByPermission) {
18101 throw new SecurityException(
18102 "Permission Denial: attempt to change component state from pid="
18103 + Binder.getCallingPid()
18104 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18106 // Don't allow changing protected packages.
18107 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18108 throw new SecurityException("Cannot disable a protected package: " + packageName);
18112 synchronized (mPackages) {
18113 if (uid == Process.SHELL_UID) {
18114 // Shell can only change whole packages between ENABLED and DISABLED_USER states
18115 int oldState = pkgSetting.getEnabled(userId);
18116 if (className == null
18118 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18119 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18120 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18122 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18123 || newState == COMPONENT_ENABLED_STATE_DEFAULT
18124 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18127 throw new SecurityException(
18128 "Shell cannot change component state for " + packageName + "/"
18129 + className + " to " + newState);
18132 if (className == null) {
18133 // We're dealing with an application/package level state change
18134 if (pkgSetting.getEnabled(userId) == newState) {
18138 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18139 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18140 // Don't care about who enables an app.
18141 callingPackage = null;
18143 pkgSetting.setEnabled(newState, userId, callingPackage);
18144 // pkgSetting.pkg.mSetEnabled = newState;
18146 // We're dealing with a component level state change
18147 // First, verify that this is a valid class name.
18148 PackageParser.Package pkg = pkgSetting.pkg;
18149 if (pkg == null || !pkg.hasComponentClassName(className)) {
18151 pkg.applicationInfo.targetSdkVersion >=
18152 Build.VERSION_CODES.JELLY_BEAN) {
18153 throw new IllegalArgumentException("Component class " + className
18154 + " does not exist in " + packageName);
18156 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18157 + className + " does not exist in " + packageName);
18160 switch (newState) {
18161 case COMPONENT_ENABLED_STATE_ENABLED:
18162 if (!pkgSetting.enableComponentLPw(className, userId)) {
18166 case COMPONENT_ENABLED_STATE_DISABLED:
18167 if (!pkgSetting.disableComponentLPw(className, userId)) {
18171 case COMPONENT_ENABLED_STATE_DEFAULT:
18172 if (!pkgSetting.restoreComponentLPw(className, userId)) {
18177 Slog.e(TAG, "Invalid new component state: " + newState);
18181 scheduleWritePackageRestrictionsLocked(userId);
18182 components = mPendingBroadcasts.get(userId, packageName);
18183 final boolean newPackage = components == null;
18185 components = new ArrayList<String>();
18187 if (!components.contains(componentName)) {
18188 components.add(componentName);
18190 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18192 // Purge entry from pending broadcast list if another one exists already
18193 // since we are sending one right away.
18194 mPendingBroadcasts.remove(userId, packageName);
18197 mPendingBroadcasts.put(userId, packageName, components);
18199 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18200 // Schedule a message
18201 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18206 long callingId = Binder.clearCallingIdentity();
18209 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18210 sendPackageChangedBroadcast(packageName,
18211 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18214 Binder.restoreCallingIdentity(callingId);
18219 public void flushPackageRestrictionsAsUser(int userId) {
18220 if (!sUserManager.exists(userId)) {
18223 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18224 false /* checkShell */, "flushPackageRestrictions");
18225 synchronized (mPackages) {
18226 mSettings.writePackageRestrictionsLPr(userId);
18227 mDirtyUsers.remove(userId);
18228 if (mDirtyUsers.isEmpty()) {
18229 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18234 private void sendPackageChangedBroadcast(String packageName,
18235 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18237 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18239 Bundle extras = new Bundle(4);
18240 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18241 String nameList[] = new String[componentNames.size()];
18242 componentNames.toArray(nameList);
18243 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18244 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18245 extras.putInt(Intent.EXTRA_UID, packageUid);
18246 // If this is not reporting a change of the overall package, then only send it
18247 // to registered receivers. We don't want to launch a swath of apps for every
18248 // little component state change.
18249 final int flags = !componentNames.contains(packageName)
18250 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18251 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null,
18252 new int[] {UserHandle.getUserId(packageUid)});
18256 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18257 if (!sUserManager.exists(userId)) return;
18258 final int uid = Binder.getCallingUid();
18259 final int permission = mContext.checkCallingOrSelfPermission(
18260 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18261 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18262 enforceCrossUserPermission(uid, userId,
18263 true /* requireFullPermission */, true /* checkShell */, "stop package");
18265 synchronized (mPackages) {
18266 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18267 allowedByPermission, uid, userId)) {
18268 scheduleWritePackageRestrictionsLocked(userId);
18274 public String getInstallerPackageName(String packageName) {
18276 synchronized (mPackages) {
18277 return mSettings.getInstallerPackageNameLPr(packageName);
18281 public boolean isOrphaned(String packageName) {
18283 synchronized (mPackages) {
18284 return mSettings.isOrphaned(packageName);
18289 public int getApplicationEnabledSetting(String packageName, int userId) {
18290 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18291 int uid = Binder.getCallingUid();
18292 enforceCrossUserPermission(uid, userId,
18293 false /* requireFullPermission */, false /* checkShell */, "get enabled");
18295 synchronized (mPackages) {
18296 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18301 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18302 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18303 int uid = Binder.getCallingUid();
18304 enforceCrossUserPermission(uid, userId,
18305 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18307 synchronized (mPackages) {
18308 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18313 public void enterSafeMode() {
18314 enforceSystemOrRoot("Only the system can request entering safe mode");
18316 if (!mSystemReady) {
18322 public void systemReady() {
18323 mSystemReady = true;
18325 // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18326 // disabled after already being started.
18327 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18328 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18330 // Read the compatibilty setting when the system is ready.
18331 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18332 mContext.getContentResolver(),
18333 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18334 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18335 if (DEBUG_SETTINGS) {
18336 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18339 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18341 synchronized (mPackages) {
18342 // Verify that all of the preferred activity components actually
18343 // exist. It is possible for applications to be updated and at
18344 // that point remove a previously declared activity component that
18345 // had been set as a preferred activity. We try to clean this up
18346 // the next time we encounter that preferred activity, but it is
18347 // possible for the user flow to never be able to return to that
18348 // situation so here we do a sanity check to make sure we haven't
18349 // left any junk around.
18350 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18351 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18352 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18354 for (PreferredActivity pa : pir.filterSet()) {
18355 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18359 if (removed.size() > 0) {
18360 for (int r=0; r<removed.size(); r++) {
18361 PreferredActivity pa = removed.get(r);
18362 Slog.w(TAG, "Removing dangling preferred activity: "
18363 + pa.mPref.mComponent);
18364 pir.removeFilter(pa);
18366 mSettings.writePackageRestrictionsLPr(
18367 mSettings.mPreferredActivities.keyAt(i));
18371 for (int userId : UserManagerService.getInstance().getUserIds()) {
18372 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18373 grantPermissionsUserIds = ArrayUtils.appendInt(
18374 grantPermissionsUserIds, userId);
18378 sUserManager.systemReady();
18380 // If we upgraded grant all default permissions before kicking off.
18381 for (int userId : grantPermissionsUserIds) {
18382 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18385 // If we did not grant default permissions, we preload from this the
18386 // default permission exceptions lazily to ensure we don't hit the
18387 // disk on a new user creation.
18388 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18389 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18392 // Kick off any messages waiting for system ready
18393 if (mPostSystemReadyMessages != null) {
18394 for (Message msg : mPostSystemReadyMessages) {
18395 msg.sendToTarget();
18397 mPostSystemReadyMessages = null;
18400 // Watch for external volumes that come and go over time
18401 final StorageManager storage = mContext.getSystemService(StorageManager.class);
18402 storage.registerListener(mStorageListener);
18404 mInstallerService.systemReady();
18405 mPackageDexOptimizer.systemReady();
18407 MountServiceInternal mountServiceInternal = LocalServices.getService(
18408 MountServiceInternal.class);
18409 mountServiceInternal.addExternalStoragePolicy(
18410 new MountServiceInternal.ExternalStorageMountPolicy() {
18412 public int getMountMode(int uid, String packageName) {
18413 if (Process.isIsolated(uid)) {
18414 return Zygote.MOUNT_EXTERNAL_NONE;
18416 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18417 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18419 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18420 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18422 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18423 return Zygote.MOUNT_EXTERNAL_READ;
18425 return Zygote.MOUNT_EXTERNAL_WRITE;
18429 public boolean hasExternalStorage(int uid, String packageName) {
18434 // Now that we're mostly running, clean up stale users and apps
18435 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18436 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18440 public boolean isSafeMode() {
18445 public boolean hasSystemUidErrors() {
18446 return mHasSystemUidErrors;
18449 static String arrayToString(int[] array) {
18450 StringBuffer buf = new StringBuffer(128);
18452 if (array != null) {
18453 for (int i=0; i<array.length; i++) {
18454 if (i > 0) buf.append(", ");
18455 buf.append(array[i]);
18459 return buf.toString();
18462 static class DumpState {
18463 public static final int DUMP_LIBS = 1 << 0;
18464 public static final int DUMP_FEATURES = 1 << 1;
18465 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18466 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18467 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18468 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18469 public static final int DUMP_PERMISSIONS = 1 << 6;
18470 public static final int DUMP_PACKAGES = 1 << 7;
18471 public static final int DUMP_SHARED_USERS = 1 << 8;
18472 public static final int DUMP_MESSAGES = 1 << 9;
18473 public static final int DUMP_PROVIDERS = 1 << 10;
18474 public static final int DUMP_VERIFIERS = 1 << 11;
18475 public static final int DUMP_PREFERRED = 1 << 12;
18476 public static final int DUMP_PREFERRED_XML = 1 << 13;
18477 public static final int DUMP_KEYSETS = 1 << 14;
18478 public static final int DUMP_VERSION = 1 << 15;
18479 public static final int DUMP_INSTALLS = 1 << 16;
18480 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18481 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18482 public static final int DUMP_FROZEN = 1 << 19;
18483 public static final int DUMP_DEXOPT = 1 << 20;
18484 public static final int DUMP_COMPILER_STATS = 1 << 21;
18486 public static final int OPTION_SHOW_FILTERS = 1 << 0;
18488 private int mTypes;
18490 private int mOptions;
18492 private boolean mTitlePrinted;
18494 private SharedUserSetting mSharedUser;
18496 public boolean isDumping(int type) {
18497 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18501 return (mTypes & type) != 0;
18504 public void setDump(int type) {
18508 public boolean isOptionEnabled(int option) {
18509 return (mOptions & option) != 0;
18512 public void setOptionEnabled(int option) {
18513 mOptions |= option;
18516 public boolean onTitlePrinted() {
18517 final boolean printed = mTitlePrinted;
18518 mTitlePrinted = true;
18522 public boolean getTitlePrinted() {
18523 return mTitlePrinted;
18526 public void setTitlePrinted(boolean enabled) {
18527 mTitlePrinted = enabled;
18530 public SharedUserSetting getSharedUser() {
18531 return mSharedUser;
18534 public void setSharedUser(SharedUserSetting user) {
18535 mSharedUser = user;
18540 public void onShellCommand(FileDescriptor in, FileDescriptor out,
18541 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18542 (new PackageManagerShellCommand(this)).exec(
18543 this, in, out, err, args, resultReceiver);
18547 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18548 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18549 != PackageManager.PERMISSION_GRANTED) {
18550 pw.println("Permission Denial: can't dump ActivityManager from from pid="
18551 + Binder.getCallingPid()
18552 + ", uid=" + Binder.getCallingUid()
18553 + " without permission "
18554 + android.Manifest.permission.DUMP);
18558 DumpState dumpState = new DumpState();
18559 boolean fullPreferred = false;
18560 boolean checkin = false;
18562 String packageName = null;
18563 ArraySet<String> permissionNames = null;
18566 while (opti < args.length) {
18567 String opt = args[opti];
18568 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18573 if ("-a".equals(opt)) {
18574 // Right now we only know how to print all.
18575 } else if ("-h".equals(opt)) {
18576 pw.println("Package manager dump options:");
18577 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
18578 pw.println(" --checkin: dump for a checkin");
18579 pw.println(" -f: print details of intent filters");
18580 pw.println(" -h: print this help");
18581 pw.println(" cmd may be one of:");
18582 pw.println(" l[ibraries]: list known shared libraries");
18583 pw.println(" f[eatures]: list device features");
18584 pw.println(" k[eysets]: print known keysets");
18585 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18586 pw.println(" perm[issions]: dump permissions");
18587 pw.println(" permission [name ...]: dump declaration and use of given permission");
18588 pw.println(" pref[erred]: print preferred package settings");
18589 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
18590 pw.println(" prov[iders]: dump content providers");
18591 pw.println(" p[ackages]: dump installed packages");
18592 pw.println(" s[hared-users]: dump shared user IDs");
18593 pw.println(" m[essages]: print collected runtime messages");
18594 pw.println(" v[erifiers]: print package verifier info");
18595 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
18596 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18597 pw.println(" version: print database version info");
18598 pw.println(" write: write current settings now");
18599 pw.println(" installs: details about install sessions");
18600 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
18601 pw.println(" dexopt: dump dexopt state");
18602 pw.println(" compiler-stats: dump compiler statistics");
18603 pw.println(" <package.name>: info about given package");
18605 } else if ("--checkin".equals(opt)) {
18607 } else if ("-f".equals(opt)) {
18608 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18610 pw.println("Unknown argument: " + opt + "; use -h for help");
18614 // Is the caller requesting to dump a particular piece of data?
18615 if (opti < args.length) {
18616 String cmd = args[opti];
18618 // Is this a package name?
18619 if ("android".equals(cmd) || cmd.contains(".")) {
18621 // When dumping a single package, we always dump all of its
18622 // filter information since the amount of data will be reasonable.
18623 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18624 } else if ("check-permission".equals(cmd)) {
18625 if (opti >= args.length) {
18626 pw.println("Error: check-permission missing permission argument");
18629 String perm = args[opti];
18631 if (opti >= args.length) {
18632 pw.println("Error: check-permission missing package argument");
18635 String pkg = args[opti];
18637 int user = UserHandle.getUserId(Binder.getCallingUid());
18638 if (opti < args.length) {
18640 user = Integer.parseInt(args[opti]);
18641 } catch (NumberFormatException e) {
18642 pw.println("Error: check-permission user argument is not a number: "
18647 pw.println(checkPermission(perm, pkg, user));
18649 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18650 dumpState.setDump(DumpState.DUMP_LIBS);
18651 } else if ("f".equals(cmd) || "features".equals(cmd)) {
18652 dumpState.setDump(DumpState.DUMP_FEATURES);
18653 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18654 if (opti >= args.length) {
18655 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18656 | DumpState.DUMP_SERVICE_RESOLVERS
18657 | DumpState.DUMP_RECEIVER_RESOLVERS
18658 | DumpState.DUMP_CONTENT_RESOLVERS);
18660 while (opti < args.length) {
18661 String name = args[opti];
18662 if ("a".equals(name) || "activity".equals(name)) {
18663 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18664 } else if ("s".equals(name) || "service".equals(name)) {
18665 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18666 } else if ("r".equals(name) || "receiver".equals(name)) {
18667 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18668 } else if ("c".equals(name) || "content".equals(name)) {
18669 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18671 pw.println("Error: unknown resolver table type: " + name);
18677 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18678 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18679 } else if ("permission".equals(cmd)) {
18680 if (opti >= args.length) {
18681 pw.println("Error: permission requires permission name");
18684 permissionNames = new ArraySet<>();
18685 while (opti < args.length) {
18686 permissionNames.add(args[opti]);
18689 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18690 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18691 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18692 dumpState.setDump(DumpState.DUMP_PREFERRED);
18693 } else if ("preferred-xml".equals(cmd)) {
18694 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18695 if (opti < args.length && "--full".equals(args[opti])) {
18696 fullPreferred = true;
18699 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18700 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18701 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18702 dumpState.setDump(DumpState.DUMP_PACKAGES);
18703 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18704 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18705 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18706 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18707 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18708 dumpState.setDump(DumpState.DUMP_MESSAGES);
18709 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18710 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18711 } else if ("i".equals(cmd) || "ifv".equals(cmd)
18712 || "intent-filter-verifiers".equals(cmd)) {
18713 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18714 } else if ("version".equals(cmd)) {
18715 dumpState.setDump(DumpState.DUMP_VERSION);
18716 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18717 dumpState.setDump(DumpState.DUMP_KEYSETS);
18718 } else if ("installs".equals(cmd)) {
18719 dumpState.setDump(DumpState.DUMP_INSTALLS);
18720 } else if ("frozen".equals(cmd)) {
18721 dumpState.setDump(DumpState.DUMP_FROZEN);
18722 } else if ("dexopt".equals(cmd)) {
18723 dumpState.setDump(DumpState.DUMP_DEXOPT);
18724 } else if ("compiler-stats".equals(cmd)) {
18725 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18726 } else if ("write".equals(cmd)) {
18727 synchronized (mPackages) {
18728 mSettings.writeLPr();
18729 pw.println("Settings written.");
18736 pw.println("vers,1");
18740 synchronized (mPackages) {
18741 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18743 if (dumpState.onTitlePrinted())
18745 pw.println("Database versions:");
18746 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
18750 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18752 if (dumpState.onTitlePrinted())
18754 pw.println("Verifiers:");
18755 pw.print(" Required: ");
18756 pw.print(mRequiredVerifierPackage);
18757 pw.print(" (uid=");
18758 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18759 UserHandle.USER_SYSTEM));
18761 } else if (mRequiredVerifierPackage != null) {
18762 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18764 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18765 UserHandle.USER_SYSTEM));
18769 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18770 packageName == null) {
18771 if (mIntentFilterVerifierComponent != null) {
18772 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18774 if (dumpState.onTitlePrinted())
18776 pw.println("Intent Filter Verifier:");
18777 pw.print(" Using: ");
18778 pw.print(verifierPackageName);
18779 pw.print(" (uid=");
18780 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18781 UserHandle.USER_SYSTEM));
18783 } else if (verifierPackageName != null) {
18784 pw.print("ifv,"); pw.print(verifierPackageName);
18786 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18787 UserHandle.USER_SYSTEM));
18791 pw.println("No Intent Filter Verifier available!");
18795 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18796 boolean printedHeader = false;
18797 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18798 while (it.hasNext()) {
18799 String name = it.next();
18800 SharedLibraryEntry ent = mSharedLibraries.get(name);
18802 if (!printedHeader) {
18803 if (dumpState.onTitlePrinted())
18805 pw.println("Libraries:");
18806 printedHeader = true;
18816 if (ent.path != null) {
18818 pw.print("(jar) ");
18819 pw.print(ent.path);
18822 pw.print(ent.path);
18826 pw.print("(apk) ");
18837 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18838 if (dumpState.onTitlePrinted())
18841 pw.println("Features:");
18844 for (FeatureInfo feat : mAvailableFeatures.values()) {
18847 pw.print(feat.name);
18849 pw.println(feat.version);
18852 pw.print(feat.name);
18853 if (feat.version > 0) {
18854 pw.print(" version=");
18855 pw.print(feat.version);
18862 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18863 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18864 : "Activity Resolver Table:", " ", packageName,
18865 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18866 dumpState.setTitlePrinted(true);
18869 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18870 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18871 : "Receiver Resolver Table:", " ", packageName,
18872 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18873 dumpState.setTitlePrinted(true);
18876 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18877 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18878 : "Service Resolver Table:", " ", packageName,
18879 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18880 dumpState.setTitlePrinted(true);
18883 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18884 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18885 : "Provider Resolver Table:", " ", packageName,
18886 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18887 dumpState.setTitlePrinted(true);
18891 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18892 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18893 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18894 int user = mSettings.mPreferredActivities.keyAt(i);
18896 dumpState.getTitlePrinted()
18897 ? "\nPreferred Activities User " + user + ":"
18898 : "Preferred Activities User " + user + ":", " ",
18899 packageName, true, false)) {
18900 dumpState.setTitlePrinted(true);
18905 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18907 FileOutputStream fout = new FileOutputStream(fd);
18908 BufferedOutputStream str = new BufferedOutputStream(fout);
18909 XmlSerializer serializer = new FastXmlSerializer();
18911 serializer.setOutput(str, StandardCharsets.UTF_8.name());
18912 serializer.startDocument(null, true);
18913 serializer.setFeature(
18914 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18915 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18916 serializer.endDocument();
18917 serializer.flush();
18918 } catch (IllegalArgumentException e) {
18919 pw.println("Failed writing: " + e);
18920 } catch (IllegalStateException e) {
18921 pw.println("Failed writing: " + e);
18922 } catch (IOException e) {
18923 pw.println("Failed writing: " + e);
18928 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18929 && packageName == null) {
18931 int count = mSettings.mPackages.size();
18933 pw.println("No applications!");
18936 final String prefix = " ";
18937 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18938 if (allPackageSettings.size() == 0) {
18939 pw.println("No domain preferred apps!");
18942 pw.println("App verification status:");
18945 for (PackageSetting ps : allPackageSettings) {
18946 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18947 if (ivi == null || ivi.getPackageName() == null) continue;
18948 pw.println(prefix + "Package: " + ivi.getPackageName());
18949 pw.println(prefix + "Domains: " + ivi.getDomainsString());
18950 pw.println(prefix + "Status: " + ivi.getStatusString());
18955 pw.println(prefix + "No app verification established.");
18958 for (int userId : sUserManager.getUserIds()) {
18959 pw.println("App linkages for user " + userId + ":");
18962 for (PackageSetting ps : allPackageSettings) {
18963 final long status = ps.getDomainVerificationStatusForUser(userId);
18964 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18967 pw.println(prefix + "Package: " + ps.name);
18968 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18969 String statusStr = IntentFilterVerificationInfo.
18970 getStatusStringFromValue(status);
18971 pw.println(prefix + "Status: " + statusStr);
18976 pw.println(prefix + "No configured app linkages.");
18984 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18985 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18986 if (packageName == null && permissionNames == null) {
18987 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18989 if (dumpState.onTitlePrinted())
18991 pw.println("AppOp Permissions:");
18993 pw.print(" AppOp Permission ");
18994 pw.print(mAppOpPermissionPackages.keyAt(iperm));
18996 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18997 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18998 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
19004 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19005 boolean printedSomething = false;
19006 for (PackageParser.Provider p : mProviders.mProviders.values()) {
19007 if (packageName != null && !packageName.equals(p.info.packageName)) {
19010 if (!printedSomething) {
19011 if (dumpState.onTitlePrinted())
19013 pw.println("Registered ContentProviders:");
19014 printedSomething = true;
19016 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
19017 pw.print(" "); pw.println(p.toString());
19019 printedSomething = false;
19020 for (Map.Entry<String, PackageParser.Provider> entry :
19021 mProvidersByAuthority.entrySet()) {
19022 PackageParser.Provider p = entry.getValue();
19023 if (packageName != null && !packageName.equals(p.info.packageName)) {
19026 if (!printedSomething) {
19027 if (dumpState.onTitlePrinted())
19029 pw.println("ContentProvider Authorities:");
19030 printedSomething = true;
19032 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
19033 pw.print(" "); pw.println(p.toString());
19034 if (p.info != null && p.info.applicationInfo != null) {
19035 final String appInfo = p.info.applicationInfo.toString();
19036 pw.print(" applicationInfo="); pw.println(appInfo);
19041 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19042 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19045 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19046 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19049 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19050 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19053 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19054 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19057 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19058 // XXX should handle packageName != null by dumping only install data that
19059 // the given package is involved with.
19060 if (dumpState.onTitlePrinted()) pw.println();
19061 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
19064 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19065 // XXX should handle packageName != null by dumping only install data that
19066 // the given package is involved with.
19067 if (dumpState.onTitlePrinted()) pw.println();
19069 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19071 ipw.println("Frozen packages:");
19072 ipw.increaseIndent();
19073 if (mFrozenPackages.size() == 0) {
19074 ipw.println("(none)");
19076 for (int i = 0; i < mFrozenPackages.size(); i++) {
19077 ipw.println(mFrozenPackages.valueAt(i));
19080 ipw.decreaseIndent();
19083 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19084 if (dumpState.onTitlePrinted()) pw.println();
19085 dumpDexoptStateLPr(pw, packageName);
19088 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19089 if (dumpState.onTitlePrinted()) pw.println();
19090 dumpCompilerStatsLPr(pw, packageName);
19093 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19094 if (dumpState.onTitlePrinted()) pw.println();
19095 mSettings.dumpReadMessagesLPr(pw, dumpState);
19098 pw.println("Package warning messages:");
19099 BufferedReader in = null;
19100 String line = null;
19102 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19103 while ((line = in.readLine()) != null) {
19104 if (line.contains("ignored: updated version")) continue;
19107 } catch (IOException ignored) {
19109 IoUtils.closeQuietly(in);
19113 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19114 BufferedReader in = null;
19115 String line = null;
19117 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19118 while ((line = in.readLine()) != null) {
19119 if (line.contains("ignored: updated version")) continue;
19123 } catch (IOException ignored) {
19125 IoUtils.closeQuietly(in);
19131 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19132 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19134 ipw.println("Dexopt state:");
19135 ipw.increaseIndent();
19136 Collection<PackageParser.Package> packages = null;
19137 if (packageName != null) {
19138 PackageParser.Package targetPackage = mPackages.get(packageName);
19139 if (targetPackage != null) {
19140 packages = Collections.singletonList(targetPackage);
19142 ipw.println("Unable to find package: " + packageName);
19146 packages = mPackages.values();
19149 for (PackageParser.Package pkg : packages) {
19150 ipw.println("[" + pkg.packageName + "]");
19151 ipw.increaseIndent();
19152 mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19153 ipw.decreaseIndent();
19157 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19158 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19160 ipw.println("Compiler stats:");
19161 ipw.increaseIndent();
19162 Collection<PackageParser.Package> packages = null;
19163 if (packageName != null) {
19164 PackageParser.Package targetPackage = mPackages.get(packageName);
19165 if (targetPackage != null) {
19166 packages = Collections.singletonList(targetPackage);
19168 ipw.println("Unable to find package: " + packageName);
19172 packages = mPackages.values();
19175 for (PackageParser.Package pkg : packages) {
19176 ipw.println("[" + pkg.packageName + "]");
19177 ipw.increaseIndent();
19179 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19180 if (stats == null) {
19181 ipw.println("(No recorded stats)");
19185 ipw.decreaseIndent();
19189 private String dumpDomainString(String packageName) {
19190 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19192 List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19194 ArraySet<String> result = new ArraySet<>();
19195 if (iviList.size() > 0) {
19196 for (IntentFilterVerificationInfo ivi : iviList) {
19197 for (String host : ivi.getDomains()) {
19202 if (filters != null && filters.size() > 0) {
19203 for (IntentFilter filter : filters) {
19204 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19205 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19206 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19207 result.addAll(filter.getHostsList());
19212 StringBuilder sb = new StringBuilder(result.size() * 16);
19213 for (String domain : result) {
19214 if (sb.length() > 0) sb.append(" ");
19217 return sb.toString();
19220 // ------- apps on sdcard specific code -------
19221 static final boolean DEBUG_SD_INSTALL = false;
19223 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19225 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19227 private boolean mMediaMounted = false;
19229 static String getEncryptKey() {
19231 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19232 SD_ENCRYPTION_KEYSTORE_NAME);
19233 if (sdEncKey == null) {
19234 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19235 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19236 if (sdEncKey == null) {
19237 Slog.e(TAG, "Failed to create encryption keys");
19242 } catch (NoSuchAlgorithmException nsae) {
19243 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19245 } catch (IOException ioe) {
19246 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19252 * Update media status on PackageManager.
19255 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19256 int callingUid = Binder.getCallingUid();
19257 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19258 throw new SecurityException("Media status can only be updated by the system");
19260 // reader; this apparently protects mMediaMounted, but should probably
19261 // be a different lock in that case.
19262 synchronized (mPackages) {
19263 Log.i(TAG, "Updating external media status from "
19264 + (mMediaMounted ? "mounted" : "unmounted") + " to "
19265 + (mediaStatus ? "mounted" : "unmounted"));
19266 if (DEBUG_SD_INSTALL)
19267 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19268 + ", mMediaMounted=" + mMediaMounted);
19269 if (mediaStatus == mMediaMounted) {
19270 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19272 mHandler.sendMessage(msg);
19275 mMediaMounted = mediaStatus;
19277 // Queue up an async operation since the package installation may take a
19279 mHandler.post(new Runnable() {
19280 public void run() {
19281 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19287 * Called by MountService when the initial ASECs to scan are available.
19288 * Should block until all the ASEC containers are finished being scanned.
19290 public void scanAvailableAsecs() {
19291 updateExternalMediaStatusInner(true, false, false);
19295 * Collect information of applications on external media, map them against
19296 * existing containers and update information based on current mount status.
19297 * Please note that we always have to report status if reportStatus has been
19298 * set to true especially when unloading packages.
19300 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19301 boolean externalStorage) {
19302 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19303 int[] uidArr = EmptyArray.INT;
19305 final String[] list = PackageHelper.getSecureContainerList();
19306 if (ArrayUtils.isEmpty(list)) {
19307 Log.i(TAG, "No secure containers found");
19309 // Process list of secure containers and categorize them
19310 // as active or stale based on their package internal state.
19313 synchronized (mPackages) {
19314 for (String cid : list) {
19315 // Leave stages untouched for now; installer service owns them
19316 if (PackageInstallerService.isStageName(cid)) continue;
19318 if (DEBUG_SD_INSTALL)
19319 Log.i(TAG, "Processing container " + cid);
19320 String pkgName = getAsecPackageName(cid);
19321 if (pkgName == null) {
19322 Slog.i(TAG, "Found stale container " + cid + " with no package name");
19325 if (DEBUG_SD_INSTALL)
19326 Log.i(TAG, "Looking for pkg : " + pkgName);
19328 final PackageSetting ps = mSettings.mPackages.get(pkgName);
19330 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19335 * Skip packages that are not external if we're unmounting
19336 * external storage.
19338 if (externalStorage && !isMounted && !isExternal(ps)) {
19342 final AsecInstallArgs args = new AsecInstallArgs(cid,
19343 getAppDexInstructionSets(ps), ps.isForwardLocked());
19344 // The package status is changed only if the code path
19345 // matches between settings and the container id.
19346 if (ps.codePathString != null
19347 && ps.codePathString.startsWith(args.getCodePath())) {
19348 if (DEBUG_SD_INSTALL) {
19349 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19350 + " at code path: " + ps.codePathString);
19353 // We do have a valid package installed on sdcard
19354 processCids.put(args, ps.codePathString);
19355 final int uid = ps.appId;
19357 uidArr = ArrayUtils.appendInt(uidArr, uid);
19360 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19361 + ps.codePathString);
19366 Arrays.sort(uidArr);
19369 // Process packages with valid entries.
19371 if (DEBUG_SD_INSTALL)
19372 Log.i(TAG, "Loading packages");
19373 loadMediaPackages(processCids, uidArr, externalStorage);
19374 startCleaningPackages();
19375 mInstallerService.onSecureContainersAvailable();
19377 if (DEBUG_SD_INSTALL)
19378 Log.i(TAG, "Unloading packages");
19379 unloadMediaPackages(processCids, uidArr, reportStatus);
19383 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19384 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19385 final int size = infos.size();
19386 final String[] packageNames = new String[size];
19387 final int[] packageUids = new int[size];
19388 for (int i = 0; i < size; i++) {
19389 final ApplicationInfo info = infos.get(i);
19390 packageNames[i] = info.packageName;
19391 packageUids[i] = info.uid;
19393 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19397 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19398 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19399 sendResourcesChangedBroadcast(mediaStatus, replacing,
19400 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19403 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19404 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19405 int size = pkgList.length;
19407 // Send broadcasts here
19408 Bundle extras = new Bundle();
19409 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19410 if (uidArr != null) {
19411 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19414 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19416 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19417 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19418 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19423 * Look at potentially valid container ids from processCids If package
19424 * information doesn't match the one on record or package scanning fails,
19425 * the cid is added to list of removeCids. We currently don't delete stale
19428 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19429 boolean externalStorage) {
19430 ArrayList<String> pkgList = new ArrayList<String>();
19431 Set<AsecInstallArgs> keys = processCids.keySet();
19433 for (AsecInstallArgs args : keys) {
19434 String codePath = processCids.get(args);
19435 if (DEBUG_SD_INSTALL)
19436 Log.i(TAG, "Loading container : " + args.cid);
19437 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19439 // Make sure there are no container errors first.
19440 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19441 Slog.e(TAG, "Failed to mount cid : " + args.cid
19442 + " when installing from sdcard");
19445 // Check code path here.
19446 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19447 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19448 + " does not match one in settings " + codePath);
19452 int parseFlags = mDefParseFlags;
19453 if (args.isExternalAsec()) {
19454 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19456 if (args.isFwdLocked()) {
19457 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19460 synchronized (mInstallLock) {
19461 PackageParser.Package pkg = null;
19463 // Sadly we don't know the package name yet to freeze it
19464 pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19465 SCAN_IGNORE_FROZEN, 0, null);
19466 } catch (PackageManagerException e) {
19467 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19469 // Scan the package
19472 * TODO why is the lock being held? doPostInstall is
19473 * called in other places without the lock. This needs
19474 * to be straightened out.
19477 synchronized (mPackages) {
19478 retCode = PackageManager.INSTALL_SUCCEEDED;
19479 pkgList.add(pkg.packageName);
19480 // Post process args
19481 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19482 pkg.applicationInfo.uid);
19485 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
19490 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19491 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19496 synchronized (mPackages) {
19497 // If the platform SDK has changed since the last time we booted,
19498 // we need to re-grant app permission to catch any new ones that
19499 // appear. This is really a hack, and means that apps can in some
19500 // cases get permissions that the user didn't initially explicitly
19501 // allow... it would be nice to have some better way to handle
19503 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19504 : mSettings.getInternalVersion();
19505 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19506 : StorageManager.UUID_PRIVATE_INTERNAL;
19508 int updateFlags = UPDATE_PERMISSIONS_ALL;
19509 if (ver.sdkVersion != mSdkVersion) {
19510 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19511 + mSdkVersion + "; regranting permissions for external");
19512 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19514 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19516 // Yay, everything is now upgraded
19517 ver.forceCurrent();
19519 // can downgrade to reader
19520 // Persist settings
19521 mSettings.writeLPr();
19523 // Send a broadcast to let everyone know we are done processing
19524 if (pkgList.size() > 0) {
19525 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19530 * Utility method to unload a list of specified containers
19532 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19533 // Just unmount all valid containers.
19534 for (AsecInstallArgs arg : cidArgs) {
19535 synchronized (mInstallLock) {
19536 arg.doPostDeleteLI(false);
19542 * Unload packages mounted on external media. This involves deleting package
19543 * data from internal structures, sending broadcasts about disabled packages,
19544 * gc'ing to free up references, unmounting all secure containers
19545 * corresponding to packages on external media, and posting a
19546 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19547 * that we always have to post this message if status has been requested no
19550 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19551 final boolean reportStatus) {
19552 if (DEBUG_SD_INSTALL)
19553 Log.i(TAG, "unloading media packages");
19554 ArrayList<String> pkgList = new ArrayList<String>();
19555 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19556 final Set<AsecInstallArgs> keys = processCids.keySet();
19557 for (AsecInstallArgs args : keys) {
19558 String pkgName = args.getPackageName();
19559 if (DEBUG_SD_INSTALL)
19560 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19561 // Delete package internally
19562 PackageRemovedInfo outInfo = new PackageRemovedInfo();
19563 synchronized (mInstallLock) {
19564 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19566 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19567 "unloadMediaPackages")) {
19568 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19572 pkgList.add(pkgName);
19574 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19575 failedList.add(args);
19581 synchronized (mPackages) {
19582 // We didn't update the settings after removing each package;
19583 // write them now for all packages.
19584 mSettings.writeLPr();
19587 // We have to absolutely send UPDATED_MEDIA_STATUS only
19588 // after confirming that all the receivers processed the ordered
19589 // broadcast when packages get disabled, force a gc to clean things up.
19590 // and unload all the containers.
19591 if (pkgList.size() > 0) {
19592 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19593 new IIntentReceiver.Stub() {
19594 public void performReceive(Intent intent, int resultCode, String data,
19595 Bundle extras, boolean ordered, boolean sticky,
19596 int sendingUser) throws RemoteException {
19597 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19598 reportStatus ? 1 : 0, 1, keys);
19599 mHandler.sendMessage(msg);
19603 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19605 mHandler.sendMessage(msg);
19609 private void loadPrivatePackages(final VolumeInfo vol) {
19610 mHandler.post(new Runnable() {
19612 public void run() {
19613 loadPrivatePackagesInner(vol);
19618 private void loadPrivatePackagesInner(VolumeInfo vol) {
19619 final String volumeUuid = vol.fsUuid;
19620 if (TextUtils.isEmpty(volumeUuid)) {
19621 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19625 final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19626 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19627 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19629 final VersionInfo ver;
19630 final List<PackageSetting> packages;
19631 synchronized (mPackages) {
19632 ver = mSettings.findOrCreateVersion(volumeUuid);
19633 packages = mSettings.getVolumePackagesLPr(volumeUuid);
19636 for (PackageSetting ps : packages) {
19637 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19638 synchronized (mInstallLock) {
19639 final PackageParser.Package pkg;
19641 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19642 loaded.add(pkg.applicationInfo);
19644 } catch (PackageManagerException e) {
19645 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19648 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19649 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19650 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19651 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19656 // Reconcile app data for all started/unlocked users
19657 final StorageManager sm = mContext.getSystemService(StorageManager.class);
19658 final UserManager um = mContext.getSystemService(UserManager.class);
19659 UserManagerInternal umInternal = getUserManagerInternal();
19660 for (UserInfo user : um.getUsers()) {
19662 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19663 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19664 } else if (umInternal.isUserRunning(user.id)) {
19665 flags = StorageManager.FLAG_STORAGE_DE;
19671 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19672 synchronized (mInstallLock) {
19673 reconcileAppsDataLI(volumeUuid, user.id, flags);
19675 } catch (IllegalStateException e) {
19676 // Device was probably ejected, and we'll process that event momentarily
19677 Slog.w(TAG, "Failed to prepare storage: " + e);
19681 synchronized (mPackages) {
19682 int updateFlags = UPDATE_PERMISSIONS_ALL;
19683 if (ver.sdkVersion != mSdkVersion) {
19684 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19685 + mSdkVersion + "; regranting permissions for " + volumeUuid);
19686 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19688 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19690 // Yay, everything is now upgraded
19691 ver.forceCurrent();
19693 mSettings.writeLPr();
19696 for (PackageFreezer freezer : freezers) {
19700 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19701 sendResourcesChangedBroadcast(true, false, loaded, null);
19704 private void unloadPrivatePackages(final VolumeInfo vol) {
19705 mHandler.post(new Runnable() {
19707 public void run() {
19708 unloadPrivatePackagesInner(vol);
19713 private void unloadPrivatePackagesInner(VolumeInfo vol) {
19714 final String volumeUuid = vol.fsUuid;
19715 if (TextUtils.isEmpty(volumeUuid)) {
19716 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19720 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19721 synchronized (mInstallLock) {
19722 synchronized (mPackages) {
19723 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19724 for (PackageSetting ps : packages) {
19725 if (ps.pkg == null) continue;
19727 final ApplicationInfo info = ps.pkg.applicationInfo;
19728 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19729 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19731 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19732 "unloadPrivatePackagesInner")) {
19733 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19735 unloaded.add(info);
19737 Slog.w(TAG, "Failed to unload " + ps.codePath);
19741 // Try very hard to release any references to this package
19742 // so we don't risk the system server being killed due to
19744 AttributeCache.instance().removePackage(ps.name);
19747 mSettings.writeLPr();
19751 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19752 sendResourcesChangedBroadcast(false, false, unloaded, null);
19754 // Try very hard to release any references to this path so we don't risk
19755 // the system server being killed due to open FDs
19756 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19758 for (int i = 0; i < 3; i++) {
19760 System.runFinalization();
19765 * Prepare storage areas for given user on all mounted devices.
19767 void prepareUserData(int userId, int userSerial, int flags) {
19768 synchronized (mInstallLock) {
19769 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19770 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19771 final String volumeUuid = vol.getFsUuid();
19772 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19777 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19778 boolean allowRecover) {
19779 // Prepare storage and verify that serial numbers are consistent; if
19780 // there's a mismatch we need to destroy to avoid leaking data
19781 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19783 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19785 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19786 UserManagerService.enforceSerialNumber(
19787 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19788 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19789 UserManagerService.enforceSerialNumber(
19790 Environment.getDataSystemDeDirectory(userId), userSerial);
19793 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19794 UserManagerService.enforceSerialNumber(
19795 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19796 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19797 UserManagerService.enforceSerialNumber(
19798 Environment.getDataSystemCeDirectory(userId), userSerial);
19802 synchronized (mInstallLock) {
19803 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19805 } catch (Exception e) {
19806 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19807 + " because we failed to prepare: " + e);
19808 destroyUserDataLI(volumeUuid, userId,
19809 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19811 if (allowRecover) {
19812 // Try one last time; if we fail again we're really in trouble
19813 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19819 * Destroy storage areas for given user on all mounted devices.
19821 void destroyUserData(int userId, int flags) {
19822 synchronized (mInstallLock) {
19823 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19824 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19825 final String volumeUuid = vol.getFsUuid();
19826 destroyUserDataLI(volumeUuid, userId, flags);
19831 private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19832 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19834 // Clean up app data, profile data, and media data
19835 mInstaller.destroyUserData(volumeUuid, userId, flags);
19837 // Clean up system data
19838 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19839 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19840 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19841 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19843 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19844 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19848 // Data with special labels is now gone, so finish the job
19849 storage.destroyUserStorage(volumeUuid, userId, flags);
19851 } catch (Exception e) {
19852 logCriticalInfo(Log.WARN,
19853 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19858 * Examine all users present on given mounted volume, and destroy data
19859 * belonging to users that are no longer valid, or whose user ID has been
19862 private void reconcileUsers(String volumeUuid) {
19863 final List<File> files = new ArrayList<>();
19864 Collections.addAll(files, FileUtils
19865 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19866 Collections.addAll(files, FileUtils
19867 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19868 Collections.addAll(files, FileUtils
19869 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19870 Collections.addAll(files, FileUtils
19871 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19872 for (File file : files) {
19873 if (!file.isDirectory()) continue;
19876 final UserInfo info;
19878 userId = Integer.parseInt(file.getName());
19879 info = sUserManager.getUserInfo(userId);
19880 } catch (NumberFormatException e) {
19881 Slog.w(TAG, "Invalid user directory " + file);
19885 boolean destroyUser = false;
19886 if (info == null) {
19887 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19888 + " because no matching user was found");
19889 destroyUser = true;
19890 } else if (!mOnlyCore) {
19892 UserManagerService.enforceSerialNumber(file, info.serialNumber);
19893 } catch (IOException e) {
19894 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19895 + " because we failed to enforce serial number: " + e);
19896 destroyUser = true;
19901 synchronized (mInstallLock) {
19902 destroyUserDataLI(volumeUuid, userId,
19903 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19909 private void assertPackageKnown(String volumeUuid, String packageName)
19910 throws PackageManagerException {
19911 synchronized (mPackages) {
19912 // Normalize package name to handle renamed packages
19913 packageName = normalizePackageNameLPr(packageName);
19915 final PackageSetting ps = mSettings.mPackages.get(packageName);
19917 throw new PackageManagerException("Package " + packageName + " is unknown");
19918 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19919 throw new PackageManagerException(
19920 "Package " + packageName + " found on unknown volume " + volumeUuid
19921 + "; expected volume " + ps.volumeUuid);
19926 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19927 throws PackageManagerException {
19928 synchronized (mPackages) {
19929 // Normalize package name to handle renamed packages
19930 packageName = normalizePackageNameLPr(packageName);
19932 final PackageSetting ps = mSettings.mPackages.get(packageName);
19934 throw new PackageManagerException("Package " + packageName + " is unknown");
19935 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19936 throw new PackageManagerException(
19937 "Package " + packageName + " found on unknown volume " + volumeUuid
19938 + "; expected volume " + ps.volumeUuid);
19939 } else if (!ps.getInstalled(userId)) {
19940 throw new PackageManagerException(
19941 "Package " + packageName + " not installed for user " + userId);
19947 * Examine all apps present on given mounted volume, and destroy apps that
19948 * aren't expected, either due to uninstallation or reinstallation on
19951 private void reconcileApps(String volumeUuid) {
19952 final File[] files = FileUtils
19953 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19954 for (File file : files) {
19955 final boolean isPackage = (isApkFile(file) || file.isDirectory())
19956 && !PackageInstallerService.isStageName(file.getName());
19958 // Ignore entries which are not packages
19963 final PackageLite pkg = PackageParser.parsePackageLite(file,
19964 PackageParser.PARSE_MUST_BE_APK);
19965 assertPackageKnown(volumeUuid, pkg.packageName);
19967 } catch (PackageParserException | PackageManagerException e) {
19968 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19969 synchronized (mInstallLock) {
19970 removeCodePathLI(file);
19977 * Reconcile all app data for the given user.
19979 * Verifies that directories exist and that ownership and labeling is
19980 * correct for all installed apps on all mounted volumes.
19982 void reconcileAppsData(int userId, int flags) {
19983 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19984 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19985 final String volumeUuid = vol.getFsUuid();
19986 synchronized (mInstallLock) {
19987 reconcileAppsDataLI(volumeUuid, userId, flags);
19993 * Reconcile all app data on given mounted volume.
19995 * Destroys app data that isn't expected, either due to uninstallation or
19996 * reinstallation on another volume.
19998 * Verifies that directories exist and that ownership and labeling is
19999 * correct for all installed apps.
20001 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
20002 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20003 + Integer.toHexString(flags));
20005 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20006 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20008 // First look for stale data that doesn't belong, and check if things
20009 // have changed since we did our last restorecon
20010 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20011 if (StorageManager.isFileEncryptedNativeOrEmulated()
20012 && !StorageManager.isUserKeyUnlocked(userId)) {
20013 throw new RuntimeException(
20014 "Yikes, someone asked us to reconcile CE storage while " + userId
20015 + " was still locked; this would have caused massive data loss!");
20018 final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20019 for (File file : files) {
20020 final String packageName = file.getName();
20022 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20023 } catch (PackageManagerException e) {
20024 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20026 mInstaller.destroyAppData(volumeUuid, packageName, userId,
20027 StorageManager.FLAG_STORAGE_CE, 0);
20028 } catch (InstallerException e2) {
20029 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20034 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20035 final File[] files = FileUtils.listFilesOrEmpty(deDir);
20036 for (File file : files) {
20037 final String packageName = file.getName();
20039 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20040 } catch (PackageManagerException e) {
20041 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20043 mInstaller.destroyAppData(volumeUuid, packageName, userId,
20044 StorageManager.FLAG_STORAGE_DE, 0);
20045 } catch (InstallerException e2) {
20046 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20052 // Ensure that data directories are ready to roll for all packages
20053 // installed for this volume and user
20054 final List<PackageSetting> packages;
20055 synchronized (mPackages) {
20056 packages = mSettings.getVolumePackagesLPr(volumeUuid);
20058 int preparedCount = 0;
20059 for (PackageSetting ps : packages) {
20060 final String packageName = ps.name;
20061 if (ps.pkg == null) {
20062 Slog.w(TAG, "Odd, missing scanned package " + packageName);
20063 // TODO: might be due to legacy ASEC apps; we should circle back
20064 // and reconcile again once they're scanned
20068 if (ps.getInstalled(userId)) {
20069 prepareAppDataLIF(ps.pkg, userId, flags);
20071 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
20072 // We may have just shuffled around app data directories, so
20073 // prepare them one more time
20074 prepareAppDataLIF(ps.pkg, userId, flags);
20081 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20085 * Prepare app data for the given app just after it was installed or
20086 * upgraded. This method carefully only touches users that it's installed
20087 * for, and it forces a restorecon to handle any seinfo changes.
20089 * Verifies that directories exist and that ownership and labeling is
20090 * correct for all installed apps. If there is an ownership mismatch, it
20091 * will try recovering system apps by wiping data; third-party app data is
20094 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20096 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20097 final PackageSetting ps;
20098 synchronized (mPackages) {
20099 ps = mSettings.mPackages.get(pkg.packageName);
20100 mSettings.writeKernelMappingLPr(ps);
20103 final UserManager um = mContext.getSystemService(UserManager.class);
20104 UserManagerInternal umInternal = getUserManagerInternal();
20105 for (UserInfo user : um.getUsers()) {
20107 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20108 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20109 } else if (umInternal.isUserRunning(user.id)) {
20110 flags = StorageManager.FLAG_STORAGE_DE;
20115 if (ps.getInstalled(user.id)) {
20116 // TODO: when user data is locked, mark that we're still dirty
20117 prepareAppDataLIF(pkg, user.id, flags);
20123 * Prepare app data for the given app.
20125 * Verifies that directories exist and that ownership and labeling is
20126 * correct for all installed apps. If there is an ownership mismatch, this
20127 * will try recovering system apps by wiping data; third-party app data is
20130 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20132 Slog.wtf(TAG, "Package was null!", new Throwable());
20135 prepareAppDataLeafLIF(pkg, userId, flags);
20136 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20137 for (int i = 0; i < childCount; i++) {
20138 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20142 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20143 if (DEBUG_APP_DATA) {
20144 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20145 + Integer.toHexString(flags));
20148 final String volumeUuid = pkg.volumeUuid;
20149 final String packageName = pkg.packageName;
20150 final ApplicationInfo app = pkg.applicationInfo;
20151 final int appId = UserHandle.getAppId(app.uid);
20153 Preconditions.checkNotNull(app.seinfo);
20156 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20157 appId, app.seinfo, app.targetSdkVersion);
20158 } catch (InstallerException e) {
20159 if (app.isSystemApp()) {
20160 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20161 + ", but trying to recover: " + e);
20162 destroyAppDataLeafLIF(pkg, userId, flags);
20164 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20165 appId, app.seinfo, app.targetSdkVersion);
20166 logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20167 } catch (InstallerException e2) {
20168 logCriticalInfo(Log.DEBUG, "Recovery failed!");
20171 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20175 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20177 // CE storage is unlocked right now, so read out the inode and
20178 // remember for use later when it's locked
20179 // TODO: mark this structure as dirty so we persist it!
20180 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20181 StorageManager.FLAG_STORAGE_CE);
20182 synchronized (mPackages) {
20183 final PackageSetting ps = mSettings.mPackages.get(packageName);
20185 ps.setCeDataInode(ceDataInode, userId);
20188 } catch (InstallerException e) {
20189 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20193 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20196 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20198 Slog.wtf(TAG, "Package was null!", new Throwable());
20201 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20202 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20203 for (int i = 0; i < childCount; i++) {
20204 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20208 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20209 final String volumeUuid = pkg.volumeUuid;
20210 final String packageName = pkg.packageName;
20211 final ApplicationInfo app = pkg.applicationInfo;
20213 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20214 // Create a native library symlink only if we have native libraries
20215 // and if the native libraries are 32 bit libraries. We do not provide
20216 // this symlink for 64 bit libraries.
20217 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20218 final String nativeLibPath = app.nativeLibraryDir;
20220 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20221 nativeLibPath, userId);
20222 } catch (InstallerException e) {
20223 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20230 * For system apps on non-FBE devices, this method migrates any existing
20231 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20232 * requested by the app.
20234 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20235 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20236 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20237 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20238 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20240 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20242 } catch (InstallerException e) {
20243 logCriticalInfo(Log.WARN,
20244 "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20252 public PackageFreezer freezePackage(String packageName, String killReason) {
20253 return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20256 public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20257 return new PackageFreezer(packageName, userId, killReason);
20260 public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20261 String killReason) {
20262 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20265 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20266 String killReason) {
20267 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20268 return new PackageFreezer();
20270 return freezePackage(packageName, userId, killReason);
20274 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20275 String killReason) {
20276 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20279 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20280 String killReason) {
20281 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20282 return new PackageFreezer();
20284 return freezePackage(packageName, userId, killReason);
20289 * Class that freezes and kills the given package upon creation, and
20290 * unfreezes it upon closing. This is typically used when doing surgery on
20291 * app code/data to prevent the app from running while you're working.
20293 private class PackageFreezer implements AutoCloseable {
20294 private final String mPackageName;
20295 private final PackageFreezer[] mChildren;
20297 private final boolean mWeFroze;
20299 private final AtomicBoolean mClosed = new AtomicBoolean();
20300 private final CloseGuard mCloseGuard = CloseGuard.get();
20303 * Create and return a stub freezer that doesn't actually do anything,
20304 * typically used when someone requested
20305 * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20306 * {@link PackageManager#DELETE_DONT_KILL_APP}.
20308 public PackageFreezer() {
20309 mPackageName = null;
20312 mCloseGuard.open("close");
20315 public PackageFreezer(String packageName, int userId, String killReason) {
20316 synchronized (mPackages) {
20317 mPackageName = packageName;
20318 mWeFroze = mFrozenPackages.add(mPackageName);
20320 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20322 killApplication(ps.name, ps.appId, userId, killReason);
20325 final PackageParser.Package p = mPackages.get(packageName);
20326 if (p != null && p.childPackages != null) {
20327 final int N = p.childPackages.size();
20328 mChildren = new PackageFreezer[N];
20329 for (int i = 0; i < N; i++) {
20330 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20331 userId, killReason);
20337 mCloseGuard.open("close");
20341 protected void finalize() throws Throwable {
20343 mCloseGuard.warnIfOpen();
20351 public void close() {
20352 mCloseGuard.close();
20353 if (mClosed.compareAndSet(false, true)) {
20354 synchronized (mPackages) {
20356 mFrozenPackages.remove(mPackageName);
20359 if (mChildren != null) {
20360 for (PackageFreezer freezer : mChildren) {
20370 * Verify that given package is currently frozen.
20372 private void checkPackageFrozen(String packageName) {
20373 synchronized (mPackages) {
20374 if (!mFrozenPackages.contains(packageName)) {
20375 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20381 public int movePackage(final String packageName, final String volumeUuid) {
20382 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20384 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20385 final int moveId = mNextMoveId.getAndIncrement();
20386 mHandler.post(new Runnable() {
20388 public void run() {
20390 movePackageInternal(packageName, volumeUuid, moveId, user);
20391 } catch (PackageManagerException e) {
20392 Slog.w(TAG, "Failed to move " + packageName, e);
20393 mMoveCallbacks.notifyStatusChanged(moveId,
20394 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20401 private void movePackageInternal(final String packageName, final String volumeUuid,
20402 final int moveId, UserHandle user) throws PackageManagerException {
20403 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20404 final PackageManager pm = mContext.getPackageManager();
20406 final boolean currentAsec;
20407 final String currentVolumeUuid;
20408 final File codeFile;
20409 final String installerPackageName;
20410 final String packageAbiOverride;
20412 final String seinfo;
20413 final String label;
20414 final int targetSdkVersion;
20415 final PackageFreezer freezer;
20416 final int[] installedUserIds;
20419 synchronized (mPackages) {
20420 final PackageParser.Package pkg = mPackages.get(packageName);
20421 final PackageSetting ps = mSettings.mPackages.get(packageName);
20422 if (pkg == null || ps == null) {
20423 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20426 if (pkg.applicationInfo.isSystemApp()) {
20427 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20428 "Cannot move system application");
20431 if (pkg.applicationInfo.isExternalAsec()) {
20432 currentAsec = true;
20433 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20434 } else if (pkg.applicationInfo.isForwardLocked()) {
20435 currentAsec = true;
20436 currentVolumeUuid = "forward_locked";
20438 currentAsec = false;
20439 currentVolumeUuid = ps.volumeUuid;
20441 final File probe = new File(pkg.codePath);
20442 final File probeOat = new File(probe, "oat");
20443 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20444 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20445 "Move only supported for modern cluster style installs");
20449 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20450 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20451 "Package already moved to " + volumeUuid);
20453 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20454 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20455 "Device admin cannot be moved");
20458 if (mFrozenPackages.contains(packageName)) {
20459 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20460 "Failed to move already frozen package");
20463 codeFile = new File(pkg.codePath);
20464 installerPackageName = ps.installerPackageName;
20465 packageAbiOverride = ps.cpuAbiOverrideString;
20466 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20467 seinfo = pkg.applicationInfo.seinfo;
20468 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20469 targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20470 freezer = freezePackage(packageName, "movePackageInternal");
20471 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20474 final Bundle extras = new Bundle();
20475 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20476 extras.putString(Intent.EXTRA_TITLE, label);
20477 mMoveCallbacks.notifyCreated(moveId, extras);
20480 final boolean moveCompleteApp;
20481 final File measurePath;
20483 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20484 installFlags = INSTALL_INTERNAL;
20485 moveCompleteApp = !currentAsec;
20486 measurePath = Environment.getDataAppDirectory(volumeUuid);
20487 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20488 installFlags = INSTALL_EXTERNAL;
20489 moveCompleteApp = false;
20490 measurePath = storage.getPrimaryPhysicalVolume().getPath();
20492 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20493 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20494 || !volume.isMountedWritable()) {
20496 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20497 "Move location not mounted private volume");
20500 Preconditions.checkState(!currentAsec);
20502 installFlags = INSTALL_INTERNAL;
20503 moveCompleteApp = true;
20504 measurePath = Environment.getDataAppDirectory(volumeUuid);
20507 final PackageStats stats = new PackageStats(null, -1);
20508 synchronized (mInstaller) {
20509 for (int userId : installedUserIds) {
20510 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20512 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20513 "Failed to measure package size");
20518 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20521 final long startFreeBytes = measurePath.getFreeSpace();
20522 final long sizeBytes;
20523 if (moveCompleteApp) {
20524 sizeBytes = stats.codeSize + stats.dataSize;
20526 sizeBytes = stats.codeSize;
20529 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20531 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20532 "Not enough free space to move");
20535 mMoveCallbacks.notifyStatusChanged(moveId, 10);
20537 final CountDownLatch installedLatch = new CountDownLatch(1);
20538 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20540 public void onUserActionRequired(Intent intent) throws RemoteException {
20541 throw new IllegalStateException();
20545 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20546 Bundle extras) throws RemoteException {
20547 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20548 + PackageManager.installStatusToString(returnCode, msg));
20550 installedLatch.countDown();
20553 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20555 case PackageInstaller.STATUS_SUCCESS:
20556 mMoveCallbacks.notifyStatusChanged(moveId,
20557 PackageManager.MOVE_SUCCEEDED);
20559 case PackageInstaller.STATUS_FAILURE_STORAGE:
20560 mMoveCallbacks.notifyStatusChanged(moveId,
20561 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20564 mMoveCallbacks.notifyStatusChanged(moveId,
20565 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20571 final MoveInfo move;
20572 if (moveCompleteApp) {
20573 // Kick off a thread to report progress estimates
20576 public void run() {
20579 if (installedLatch.await(1, TimeUnit.SECONDS)) {
20582 } catch (InterruptedException ignored) {
20585 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20586 final int progress = 10 + (int) MathUtils.constrain(
20587 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20588 mMoveCallbacks.notifyStatusChanged(moveId, progress);
20593 final String dataAppName = codeFile.getName();
20594 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20595 dataAppName, appId, seinfo, targetSdkVersion);
20600 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20602 final Message msg = mHandler.obtainMessage(INIT_COPY);
20603 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20604 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20605 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20606 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20607 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20610 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20611 System.identityHashCode(msg.obj));
20612 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20613 System.identityHashCode(msg.obj));
20615 mHandler.sendMessage(msg);
20619 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20622 final int realMoveId = mNextMoveId.getAndIncrement();
20623 final Bundle extras = new Bundle();
20624 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20625 mMoveCallbacks.notifyCreated(realMoveId, extras);
20627 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20629 public void onCreated(int moveId, Bundle extras) {
20634 public void onStatusChanged(int moveId, int status, long estMillis) {
20635 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20639 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20640 storage.setPrimaryStorageUuid(volumeUuid, callback);
20645 public int getMoveStatus(int moveId) {
20646 mContext.enforceCallingOrSelfPermission(
20647 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20648 return mMoveCallbacks.mLastStatus.get(moveId);
20652 public void registerMoveCallback(IPackageMoveObserver callback) {
20653 mContext.enforceCallingOrSelfPermission(
20654 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20655 mMoveCallbacks.register(callback);
20659 public void unregisterMoveCallback(IPackageMoveObserver callback) {
20660 mContext.enforceCallingOrSelfPermission(
20661 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20662 mMoveCallbacks.unregister(callback);
20666 public boolean setInstallLocation(int loc) {
20667 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20669 if (getInstallLocation() == loc) {
20672 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20673 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20674 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20675 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20682 public int getInstallLocation() {
20683 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20684 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20685 PackageHelper.APP_INSTALL_AUTO);
20688 /** Called by UserManagerService */
20689 void cleanUpUser(UserManagerService userManager, int userHandle) {
20690 synchronized (mPackages) {
20691 mDirtyUsers.remove(userHandle);
20692 mUserNeedsBadging.delete(userHandle);
20693 mSettings.removeUserLPw(userHandle);
20694 mPendingBroadcasts.remove(userHandle);
20695 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20696 removeUnusedPackagesLPw(userManager, userHandle);
20701 * We're removing userHandle and would like to remove any downloaded packages
20702 * that are no longer in use by any other user.
20703 * @param userHandle the user being removed
20705 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20706 final boolean DEBUG_CLEAN_APKS = false;
20707 int [] users = userManager.getUserIds();
20708 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20709 while (psit.hasNext()) {
20710 PackageSetting ps = psit.next();
20711 if (ps.pkg == null) {
20714 final String packageName = ps.pkg.packageName;
20715 // Skip over if system app
20716 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20719 if (DEBUG_CLEAN_APKS) {
20720 Slog.i(TAG, "Checking package " + packageName);
20722 boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20724 if (DEBUG_CLEAN_APKS) {
20725 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO");
20728 for (int i = 0; i < users.length; i++) {
20729 if (users[i] != userHandle && ps.getInstalled(users[i])) {
20731 if (DEBUG_CLEAN_APKS) {
20732 Slog.i(TAG, " Keeping package " + packageName + " for user "
20740 if (DEBUG_CLEAN_APKS) {
20741 Slog.i(TAG, " Removing package " + packageName);
20743 mHandler.post(new Runnable() {
20744 public void run() {
20745 deletePackageX(packageName, userHandle, 0);
20752 /** Called by UserManagerService */
20753 void createNewUser(int userId) {
20754 synchronized (mInstallLock) {
20755 mSettings.createNewUserLI(this, mInstaller, userId);
20757 synchronized (mPackages) {
20758 scheduleWritePackageRestrictionsLocked(userId);
20759 scheduleWritePackageListLocked(userId);
20760 applyFactoryDefaultBrowserLPw(userId);
20761 primeDomainVerificationsLPw(userId);
20765 void onNewUserCreated(final int userId) {
20766 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20767 // If permission review for legacy apps is required, we represent
20768 // dagerous permissions for such apps as always granted runtime
20769 // permissions to keep per user flag state whether review is needed.
20770 // Hence, if a new user is added we have to propagate dangerous
20771 // permission grants for these legacy apps.
20772 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20773 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20774 | UPDATE_PERMISSIONS_REPLACE_ALL);
20779 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20780 mContext.enforceCallingOrSelfPermission(
20781 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20782 "Only package verification agents can read the verifier device identity");
20784 synchronized (mPackages) {
20785 return mSettings.getVerifierDeviceIdentityLPw();
20790 public void setPermissionEnforced(String permission, boolean enforced) {
20791 // TODO: Now that we no longer change GID for storage, this should to away.
20792 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20793 "setPermissionEnforced");
20794 if (READ_EXTERNAL_STORAGE.equals(permission)) {
20795 synchronized (mPackages) {
20796 if (mSettings.mReadExternalStorageEnforced == null
20797 || mSettings.mReadExternalStorageEnforced != enforced) {
20798 mSettings.mReadExternalStorageEnforced = enforced;
20799 mSettings.writeLPr();
20802 // kill any non-foreground processes so we restart them and
20803 // grant/revoke the GID.
20804 final IActivityManager am = ActivityManagerNative.getDefault();
20806 final long token = Binder.clearCallingIdentity();
20808 am.killProcessesBelowForeground("setPermissionEnforcement");
20809 } catch (RemoteException e) {
20811 Binder.restoreCallingIdentity(token);
20815 throw new IllegalArgumentException("No selective enforcement for " + permission);
20821 public boolean isPermissionEnforced(String permission) {
20826 public boolean isStorageLow() {
20827 final long token = Binder.clearCallingIdentity();
20829 final DeviceStorageMonitorInternal
20830 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20832 return dsm.isMemoryLow();
20837 Binder.restoreCallingIdentity(token);
20842 public IPackageInstaller getPackageInstaller() {
20843 return mInstallerService;
20846 private boolean userNeedsBadging(int userId) {
20847 int index = mUserNeedsBadging.indexOfKey(userId);
20849 final UserInfo userInfo;
20850 final long token = Binder.clearCallingIdentity();
20852 userInfo = sUserManager.getUserInfo(userId);
20854 Binder.restoreCallingIdentity(token);
20857 if (userInfo != null && userInfo.isManagedProfile()) {
20862 mUserNeedsBadging.put(userId, b);
20865 return mUserNeedsBadging.valueAt(index);
20869 public KeySet getKeySetByAlias(String packageName, String alias) {
20870 if (packageName == null || alias == null) {
20873 synchronized(mPackages) {
20874 final PackageParser.Package pkg = mPackages.get(packageName);
20876 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20877 throw new IllegalArgumentException("Unknown package: " + packageName);
20879 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20880 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20885 public KeySet getSigningKeySet(String packageName) {
20886 if (packageName == null) {
20889 synchronized(mPackages) {
20890 final PackageParser.Package pkg = mPackages.get(packageName);
20892 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20893 throw new IllegalArgumentException("Unknown package: " + packageName);
20895 if (pkg.applicationInfo.uid != Binder.getCallingUid()
20896 && Process.SYSTEM_UID != Binder.getCallingUid()) {
20897 throw new SecurityException("May not access signing KeySet of other apps.");
20899 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20900 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20905 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20906 if (packageName == null || ks == null) {
20909 synchronized(mPackages) {
20910 final PackageParser.Package pkg = mPackages.get(packageName);
20912 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20913 throw new IllegalArgumentException("Unknown package: " + packageName);
20915 IBinder ksh = ks.getToken();
20916 if (ksh instanceof KeySetHandle) {
20917 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20918 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20925 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20926 if (packageName == null || ks == null) {
20929 synchronized(mPackages) {
20930 final PackageParser.Package pkg = mPackages.get(packageName);
20932 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20933 throw new IllegalArgumentException("Unknown package: " + packageName);
20935 IBinder ksh = ks.getToken();
20936 if (ksh instanceof KeySetHandle) {
20937 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20938 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20944 private void deletePackageIfUnusedLPr(final String packageName) {
20945 PackageSetting ps = mSettings.mPackages.get(packageName);
20949 if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20950 // TODO Implement atomic delete if package is unused
20951 // It is currently possible that the package will be deleted even if it is installed
20952 // after this method returns.
20953 mHandler.post(new Runnable() {
20954 public void run() {
20955 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20962 * Check and throw if the given before/after packages would be considered a
20965 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20966 throws PackageManagerException {
20967 if (after.versionCode < before.mVersionCode) {
20968 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20969 "Update version code " + after.versionCode + " is older than current "
20970 + before.mVersionCode);
20971 } else if (after.versionCode == before.mVersionCode) {
20972 if (after.baseRevisionCode < before.baseRevisionCode) {
20973 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20974 "Update base revision code " + after.baseRevisionCode
20975 + " is older than current " + before.baseRevisionCode);
20978 if (!ArrayUtils.isEmpty(after.splitNames)) {
20979 for (int i = 0; i < after.splitNames.length; i++) {
20980 final String splitName = after.splitNames[i];
20981 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20983 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20984 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20985 "Update split " + splitName + " revision code "
20986 + after.splitRevisionCodes[i] + " is older than current "
20987 + before.splitRevisionCodes[j]);
20995 private static class MoveCallbacks extends Handler {
20996 private static final int MSG_CREATED = 1;
20997 private static final int MSG_STATUS_CHANGED = 2;
20999 private final RemoteCallbackList<IPackageMoveObserver>
21000 mCallbacks = new RemoteCallbackList<>();
21002 private final SparseIntArray mLastStatus = new SparseIntArray();
21004 public MoveCallbacks(Looper looper) {
21008 public void register(IPackageMoveObserver callback) {
21009 mCallbacks.register(callback);
21012 public void unregister(IPackageMoveObserver callback) {
21013 mCallbacks.unregister(callback);
21017 public void handleMessage(Message msg) {
21018 final SomeArgs args = (SomeArgs) msg.obj;
21019 final int n = mCallbacks.beginBroadcast();
21020 for (int i = 0; i < n; i++) {
21021 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21023 invokeCallback(callback, msg.what, args);
21024 } catch (RemoteException ignored) {
21027 mCallbacks.finishBroadcast();
21031 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21032 throws RemoteException {
21034 case MSG_CREATED: {
21035 callback.onCreated(args.argi1, (Bundle) args.arg2);
21038 case MSG_STATUS_CHANGED: {
21039 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21045 private void notifyCreated(int moveId, Bundle extras) {
21046 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21048 final SomeArgs args = SomeArgs.obtain();
21049 args.argi1 = moveId;
21050 args.arg2 = extras;
21051 obtainMessage(MSG_CREATED, args).sendToTarget();
21054 private void notifyStatusChanged(int moveId, int status) {
21055 notifyStatusChanged(moveId, status, -1);
21058 private void notifyStatusChanged(int moveId, int status, long estMillis) {
21059 Slog.v(TAG, "Move " + moveId + " status " + status);
21061 final SomeArgs args = SomeArgs.obtain();
21062 args.argi1 = moveId;
21063 args.argi2 = status;
21064 args.arg3 = estMillis;
21065 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21067 synchronized (mLastStatus) {
21068 mLastStatus.put(moveId, status);
21073 private final static class OnPermissionChangeListeners extends Handler {
21074 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21076 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21077 new RemoteCallbackList<>();
21079 public OnPermissionChangeListeners(Looper looper) {
21084 public void handleMessage(Message msg) {
21085 switch (msg.what) {
21086 case MSG_ON_PERMISSIONS_CHANGED: {
21087 final int uid = msg.arg1;
21088 handleOnPermissionsChanged(uid);
21093 public void addListenerLocked(IOnPermissionsChangeListener listener) {
21094 mPermissionListeners.register(listener);
21098 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21099 mPermissionListeners.unregister(listener);
21102 public void onPermissionsChanged(int uid) {
21103 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21104 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21108 private void handleOnPermissionsChanged(int uid) {
21109 final int count = mPermissionListeners.beginBroadcast();
21111 for (int i = 0; i < count; i++) {
21112 IOnPermissionsChangeListener callback = mPermissionListeners
21113 .getBroadcastItem(i);
21115 callback.onPermissionsChanged(uid);
21116 } catch (RemoteException e) {
21117 Log.e(TAG, "Permission listener is dead", e);
21121 mPermissionListeners.finishBroadcast();
21126 private class PackageManagerInternalImpl extends PackageManagerInternal {
21128 public void setLocationPackagesProvider(PackagesProvider provider) {
21129 synchronized (mPackages) {
21130 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21135 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21136 synchronized (mPackages) {
21137 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21142 public void setSmsAppPackagesProvider(PackagesProvider provider) {
21143 synchronized (mPackages) {
21144 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21149 public void setDialerAppPackagesProvider(PackagesProvider provider) {
21150 synchronized (mPackages) {
21151 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21156 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21157 synchronized (mPackages) {
21158 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21163 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21164 synchronized (mPackages) {
21165 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21170 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21171 synchronized (mPackages) {
21172 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21173 packageName, userId);
21178 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21179 synchronized (mPackages) {
21180 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21181 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21182 packageName, userId);
21187 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21188 synchronized (mPackages) {
21189 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21190 packageName, userId);
21195 public void setKeepUninstalledPackages(final List<String> packageList) {
21196 Preconditions.checkNotNull(packageList);
21197 List<String> removedFromList = null;
21198 synchronized (mPackages) {
21199 if (mKeepUninstalledPackages != null) {
21200 final int packagesCount = mKeepUninstalledPackages.size();
21201 for (int i = 0; i < packagesCount; i++) {
21202 String oldPackage = mKeepUninstalledPackages.get(i);
21203 if (packageList != null && packageList.contains(oldPackage)) {
21206 if (removedFromList == null) {
21207 removedFromList = new ArrayList<>();
21209 removedFromList.add(oldPackage);
21212 mKeepUninstalledPackages = new ArrayList<>(packageList);
21213 if (removedFromList != null) {
21214 final int removedCount = removedFromList.size();
21215 for (int i = 0; i < removedCount; i++) {
21216 deletePackageIfUnusedLPr(removedFromList.get(i));
21223 public boolean isPermissionsReviewRequired(String packageName, int userId) {
21224 synchronized (mPackages) {
21225 // If we do not support permission review, done.
21226 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21230 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21231 if (packageSetting == null) {
21235 // Permission review applies only to apps not supporting the new permission model.
21236 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21240 // Legacy apps have the permission and get user consent on launch.
21241 PermissionsState permissionsState = packageSetting.getPermissionsState();
21242 return permissionsState.isPermissionReviewRequired(userId);
21247 public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21248 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21252 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21254 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21258 public void setDeviceAndProfileOwnerPackages(
21259 int deviceOwnerUserId, String deviceOwnerPackage,
21260 SparseArray<String> profileOwnerPackages) {
21261 mProtectedPackages.setDeviceAndProfileOwnerPackages(
21262 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21266 public boolean isPackageDataProtected(int userId, String packageName) {
21267 return mProtectedPackages.isPackageDataProtected(userId, packageName);
21271 public boolean wasPackageEverLaunched(String packageName, int userId) {
21272 synchronized (mPackages) {
21273 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21278 public String getNameForUid(int uid) {
21279 return PackageManagerService.this.getNameForUid(uid);
21284 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21285 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21286 synchronized (mPackages) {
21287 final long identity = Binder.clearCallingIdentity();
21289 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21290 packageNames, userId);
21292 Binder.restoreCallingIdentity(identity);
21297 private static void enforceSystemOrPhoneCaller(String tag) {
21298 int callingUid = Binder.getCallingUid();
21299 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21300 throw new SecurityException(
21301 "Cannot call " + tag + " from UID " + callingUid);
21305 boolean isHistoricalPackageUsageAvailable() {
21306 return mPackageUsage.isHistoricalPackageUsageAvailable();
21310 * Return a <b>copy</b> of the collection of packages known to the package manager.
21311 * @return A copy of the values of mPackages.
21313 Collection<PackageParser.Package> getPackages() {
21314 synchronized (mPackages) {
21315 return new ArrayList<>(mPackages.values());
21320 * Logs process start information (including base APK hash) to the security log.
21323 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21324 String apkFile, int pid) {
21325 if (!SecurityLog.isLoggingEnabled()) {
21328 Bundle data = new Bundle();
21329 data.putLong("startTimestamp", System.currentTimeMillis());
21330 data.putString("processName", processName);
21331 data.putInt("uid", uid);
21332 data.putString("seinfo", seinfo);
21333 data.putString("apkFile", apkFile);
21334 data.putInt("pid", pid);
21335 Message msg = mProcessLoggingHandler.obtainMessage(
21336 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21338 mProcessLoggingHandler.sendMessage(msg);
21341 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21342 return mCompilerStats.getPackageStats(pkgName);
21345 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21346 return getOrCreateCompilerPackageStats(pkg.packageName);
21349 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21350 return mCompilerStats.getOrCreatePackageStats(pkgName);
21353 public void deleteCompilerPackageStats(String pkgName) {
21354 mCompilerStats.deletePackageStats(pkgName);