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 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
469 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
471 /** Permission grant: not grant the permission. */
472 private static final int GRANT_DENIED = 1;
474 /** Permission grant: grant the permission as an install permission. */
475 private static final int GRANT_INSTALL = 2;
477 /** Permission grant: grant the permission as a runtime one. */
478 private static final int GRANT_RUNTIME = 3;
480 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
481 private static final int GRANT_UPGRADE = 4;
483 /** Canonical intent used to identify what counts as a "web browser" app */
484 private static final Intent sBrowserIntent;
486 sBrowserIntent = new Intent();
487 sBrowserIntent.setAction(Intent.ACTION_VIEW);
488 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
489 sBrowserIntent.setData(Uri.parse("http:"));
493 * The set of all protected actions [i.e. those actions for which a high priority
494 * intent filter is disallowed].
496 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
498 PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
499 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
500 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
501 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
504 // Compilation reasons.
505 public static final int REASON_FIRST_BOOT = 0;
506 public static final int REASON_BOOT = 1;
507 public static final int REASON_INSTALL = 2;
508 public static final int REASON_BACKGROUND_DEXOPT = 3;
509 public static final int REASON_AB_OTA = 4;
510 public static final int REASON_NON_SYSTEM_LIBRARY = 5;
511 public static final int REASON_SHARED_APK = 6;
512 public static final int REASON_FORCED_DEXOPT = 7;
513 public static final int REASON_CORE_APP = 8;
515 public static final int REASON_LAST = REASON_CORE_APP;
517 /** Special library name that skips shared libraries check during compilation. */
518 private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
520 final ServiceThread mHandlerThread;
522 final PackageHandler mHandler;
524 private final ProcessLoggingHandler mProcessLoggingHandler;
527 * Messages for {@link #mHandler} that need to wait for system ready before
530 private ArrayList<Message> mPostSystemReadyMessages;
532 final int mSdkVersion = Build.VERSION.SDK_INT;
534 final Context mContext;
535 final boolean mFactoryTest;
536 final boolean mOnlyCore;
537 final DisplayMetrics mMetrics;
538 final int mDefParseFlags;
539 final String[] mSeparateProcesses;
540 final boolean mIsUpgrade;
541 final boolean mIsPreNUpgrade;
542 final boolean mIsPreNMR1Upgrade;
544 @GuardedBy("mPackages")
545 private boolean mDexOptDialogShown;
547 /** The location for ASEC container files on internal storage. */
548 final String mAsecInternalPath;
550 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
551 // LOCK HELD. Can be called with mInstallLock held.
552 @GuardedBy("mInstallLock")
553 final Installer mInstaller;
555 /** Directory where installed third-party apps stored */
556 final File mAppInstallDir;
557 final File mEphemeralInstallDir;
560 * Directory to which applications installed internally have their
561 * 32 bit native libraries copied.
563 private File mAppLib32InstallDir;
565 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
567 final File mDrmAppPrivateInstallDir;
569 // ----------------------------------------------------------------
571 // Lock for state used when installing and doing other long running
572 // operations. Methods that must be called with this lock held have
574 final Object mInstallLock = new Object();
576 // ----------------------------------------------------------------
578 // Keys are String (package name), values are Package. This also serves
579 // as the lock for the global state. Methods that must be called with
580 // this lock held have the prefix "LP".
581 @GuardedBy("mPackages")
582 final ArrayMap<String, PackageParser.Package> mPackages =
583 new ArrayMap<String, PackageParser.Package>();
585 final ArrayMap<String, Set<String>> mKnownCodebase =
586 new ArrayMap<String, Set<String>>();
588 // Tracks available target package names -> overlay package paths.
589 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
590 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
593 * Tracks new system packages [received in an OTA] that we expect to
594 * find updated user-installed versions. Keys are package name, values
595 * are package location.
597 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
599 * Tracks high priority intent filters for protected actions. During boot, certain
600 * filter actions are protected and should never be allowed to have a high priority
601 * intent filter for them. However, there is one, and only one exception -- the
602 * setup wizard. It must be able to define a high priority intent filter for these
603 * actions to ensure there are no escapes from the wizard. We need to delay processing
604 * of these during boot as we need to look at all of the system packages in order
605 * to know which component is the setup wizard.
607 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
609 * Whether or not processing protected filters should be deferred.
611 private boolean mDeferProtectedFilters = true;
614 * Tracks existing system packages prior to receiving an OTA. Keys are package name.
616 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
618 * Whether or not system app permissions should be promoted from install to runtime.
620 boolean mPromoteSystemApps;
622 @GuardedBy("mPackages")
623 final Settings mSettings;
626 * Set of package names that are currently "frozen", which means active
627 * surgery is being done on the code/data for that package. The platform
628 * will refuse to launch frozen packages to avoid race conditions.
630 * @see PackageFreezer
632 @GuardedBy("mPackages")
633 final ArraySet<String> mFrozenPackages = new ArraySet<>();
635 final ProtectedPackages mProtectedPackages;
639 // System configuration read by SystemConfig.
640 final int[] mGlobalGids;
641 final SparseArray<ArraySet<String>> mSystemPermissions;
642 final ArrayMap<String, FeatureInfo> mAvailableFeatures;
644 // If mac_permissions.xml was found for seinfo labeling.
645 boolean mFoundPolicyFile;
647 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
649 public static final class SharedLibraryEntry {
650 public final String path;
651 public final String apk;
653 SharedLibraryEntry(String _path, String _apk) {
659 // Currently known shared libraries.
660 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
661 new ArrayMap<String, SharedLibraryEntry>();
663 // All available activities, for your resolving pleasure.
664 final ActivityIntentResolver mActivities =
665 new ActivityIntentResolver();
667 // All available receivers, for your resolving pleasure.
668 final ActivityIntentResolver mReceivers =
669 new ActivityIntentResolver();
671 // All available services, for your resolving pleasure.
672 final ServiceIntentResolver mServices = new ServiceIntentResolver();
674 // All available providers, for your resolving pleasure.
675 final ProviderIntentResolver mProviders = new ProviderIntentResolver();
677 // Mapping from provider base names (first directory in content URI codePath)
678 // to the provider information.
679 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
680 new ArrayMap<String, PackageParser.Provider>();
682 // Mapping from instrumentation class names to info about them.
683 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
684 new ArrayMap<ComponentName, PackageParser.Instrumentation>();
686 // Mapping from permission names to info about them.
687 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
688 new ArrayMap<String, PackageParser.PermissionGroup>();
690 // Packages whose data we have transfered into another package, thus
691 // should no longer exist.
692 final ArraySet<String> mTransferedPackages = new ArraySet<String>();
694 // Broadcast actions that are only available to the system.
695 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
697 /** List of packages waiting for verification. */
698 final SparseArray<PackageVerificationState> mPendingVerification
699 = new SparseArray<PackageVerificationState>();
701 /** Set of packages associated with each app op permission. */
702 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
704 final PackageInstallerService mInstallerService;
706 private final PackageDexOptimizer mPackageDexOptimizer;
708 private AtomicInteger mNextMoveId = new AtomicInteger();
709 private final MoveCallbacks mMoveCallbacks;
711 private final OnPermissionChangeListeners mOnPermissionChangeListeners;
713 // Cache of users who need badging.
714 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
716 /** Token for keys in mPendingVerification. */
717 private int mPendingVerificationToken = 0;
719 volatile boolean mSystemReady;
720 volatile boolean mSafeMode;
721 volatile boolean mHasSystemUidErrors;
723 ApplicationInfo mAndroidApplication;
724 final ActivityInfo mResolveActivity = new ActivityInfo();
725 final ResolveInfo mResolveInfo = new ResolveInfo();
726 ComponentName mResolveComponentName;
727 PackageParser.Package mPlatformPackage;
728 ComponentName mCustomResolverComponentName;
730 boolean mResolverReplaced = false;
732 private final @Nullable ComponentName mIntentFilterVerifierComponent;
733 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
735 private int mIntentFilterVerificationToken = 0;
737 /** Component that knows whether or not an ephemeral application exists */
738 final ComponentName mEphemeralResolverComponent;
739 /** The service connection to the ephemeral resolver */
740 final EphemeralResolverConnection mEphemeralResolverConnection;
742 /** Component used to install ephemeral applications */
743 final ComponentName mEphemeralInstallerComponent;
744 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
745 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
747 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
748 = new SparseArray<IntentFilterVerificationState>();
750 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
752 // List of packages names to keep cached, even if they are uninstalled for all users
753 private List<String> mKeepUninstalledPackages;
755 private UserManagerInternal mUserManagerInternal;
757 private static class IFVerificationParams {
758 PackageParser.Package pkg;
763 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
764 int _userId, int _verifierUid) {
766 replacing = _replacing;
768 replacing = _replacing;
769 verifierUid = _verifierUid;
773 private interface IntentFilterVerifier<T extends IntentFilter> {
774 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
775 T filter, String packageName);
776 void startVerifications(int userId);
777 void receiveVerificationResponse(int verificationId);
780 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
781 private Context mContext;
782 private ComponentName mIntentFilterVerifierComponent;
783 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
785 public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
787 mIntentFilterVerifierComponent = verifierComponent;
790 private String getDefaultScheme() {
791 return IntentFilter.SCHEME_HTTPS;
795 public void startVerifications(int userId) {
796 // Launch verifications requests
797 int count = mCurrentIntentFilterVerifications.size();
798 for (int n=0; n<count; n++) {
799 int verificationId = mCurrentIntentFilterVerifications.get(n);
800 final IntentFilterVerificationState ivs =
801 mIntentFilterVerificationStates.get(verificationId);
803 String packageName = ivs.getPackageName();
805 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
806 final int filterCount = filters.size();
807 ArraySet<String> domainsSet = new ArraySet<>();
808 for (int m=0; m<filterCount; m++) {
809 PackageParser.ActivityIntentInfo filter = filters.get(m);
810 domainsSet.addAll(filter.getHostsList());
812 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
813 synchronized (mPackages) {
814 if (mSettings.createIntentFilterVerificationIfNeededLPw(
815 packageName, domainsList) != null) {
816 scheduleWriteSettingsLocked();
819 sendVerificationRequest(userId, verificationId, ivs);
821 mCurrentIntentFilterVerifications.clear();
824 private void sendVerificationRequest(int userId, int verificationId,
825 IntentFilterVerificationState ivs) {
827 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
828 verificationIntent.putExtra(
829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
831 verificationIntent.putExtra(
832 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
834 verificationIntent.putExtra(
835 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
836 ivs.getHostsString());
837 verificationIntent.putExtra(
838 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
839 ivs.getPackageName());
840 verificationIntent.setComponent(mIntentFilterVerifierComponent);
841 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
843 UserHandle user = new UserHandle(userId);
844 mContext.sendBroadcastAsUser(verificationIntent, user);
845 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
846 "Sending IntentFilter verification broadcast");
849 public void receiveVerificationResponse(int verificationId) {
850 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
852 final boolean verified = ivs.isVerified();
854 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
855 final int count = filters.size();
856 if (DEBUG_DOMAIN_VERIFICATION) {
857 Slog.i(TAG, "Received verification response " + verificationId
858 + " for " + count + " filters, verified=" + verified);
860 for (int n=0; n<count; n++) {
861 PackageParser.ActivityIntentInfo filter = filters.get(n);
862 filter.setVerified(verified);
864 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
865 + " verified with result:" + verified + " and hosts:"
866 + ivs.getHostsString());
869 mIntentFilterVerificationStates.remove(verificationId);
871 final String packageName = ivs.getPackageName();
872 IntentFilterVerificationInfo ivi = null;
874 synchronized (mPackages) {
875 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
878 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
879 + verificationId + " packageName:" + packageName);
882 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
883 "Updating IntentFilterVerificationInfo for package " + packageName
884 +" verificationId:" + verificationId);
886 synchronized (mPackages) {
888 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
890 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
892 scheduleWriteSettingsLocked();
894 final int userId = ivs.getUserId();
895 if (userId != UserHandle.USER_ALL) {
896 final int userStatus =
897 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
899 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
900 boolean needUpdate = false;
902 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
903 // already been set by the User thru the Disambiguation dialog
904 switch (userStatus) {
905 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
907 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
909 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
914 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
916 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
926 mSettings.updateIntentFilterVerificationStatusLPw(
927 packageName, updatedStatus, userId);
928 scheduleWritePackageRestrictionsLocked(userId);
935 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
936 ActivityIntentInfo filter, String packageName) {
937 if (!hasValidDomains(filter)) {
940 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
942 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
945 if (DEBUG_DOMAIN_VERIFICATION) {
946 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
948 ivs.addFilter(filter);
952 private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
953 int userId, int verificationId, String packageName) {
954 IntentFilterVerificationState ivs = new IntentFilterVerificationState(
955 verifierUid, userId, packageName);
956 ivs.setPendingState();
957 synchronized (mPackages) {
958 mIntentFilterVerificationStates.append(verificationId, ivs);
959 mCurrentIntentFilterVerifications.add(verificationId);
965 private static boolean hasValidDomains(ActivityIntentInfo filter) {
966 return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
967 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
968 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
971 // Set of pending broadcasts for aggregating enable/disable of components.
972 static class PendingPackageBroadcasts {
973 // for each user id, a map of <package name -> components within that package>
974 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
976 public PendingPackageBroadcasts() {
977 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
980 public ArrayList<String> get(int userId, String packageName) {
981 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
982 return packages.get(packageName);
985 public void put(int userId, String packageName, ArrayList<String> components) {
986 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
987 packages.put(packageName, components);
990 public void remove(int userId, String packageName) {
991 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
992 if (packages != null) {
993 packages.remove(packageName);
997 public void remove(int userId) {
998 mUidMap.remove(userId);
1001 public int userIdCount() {
1002 return mUidMap.size();
1005 public int userIdAt(int n) {
1006 return mUidMap.keyAt(n);
1009 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1010 return mUidMap.get(userId);
1014 // total number of pending broadcast entries across all userIds
1016 for (int i = 0; i< mUidMap.size(); i++) {
1017 num += mUidMap.valueAt(i).size();
1022 public void clear() {
1026 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1027 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1029 map = new ArrayMap<String, ArrayList<String>>();
1030 mUidMap.put(userId, map);
1035 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1037 // Service Connection to remote media container service to copy
1038 // package uri's from external media onto secure containers
1039 // or internal storage.
1040 private IMediaContainerService mContainerService = null;
1042 static final int SEND_PENDING_BROADCAST = 1;
1043 static final int MCS_BOUND = 3;
1044 static final int END_COPY = 4;
1045 static final int INIT_COPY = 5;
1046 static final int MCS_UNBIND = 6;
1047 static final int START_CLEANING_PACKAGE = 7;
1048 static final int FIND_INSTALL_LOC = 8;
1049 static final int POST_INSTALL = 9;
1050 static final int MCS_RECONNECT = 10;
1051 static final int MCS_GIVE_UP = 11;
1052 static final int UPDATED_MEDIA_STATUS = 12;
1053 static final int WRITE_SETTINGS = 13;
1054 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1055 static final int PACKAGE_VERIFIED = 15;
1056 static final int CHECK_PENDING_VERIFICATION = 16;
1057 static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1058 static final int INTENT_FILTER_VERIFIED = 18;
1059 static final int WRITE_PACKAGE_LIST = 19;
1061 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
1063 // Delay time in millisecs
1064 static final int BROADCAST_DELAY = 10 * 1000;
1066 static UserManagerService sUserManager;
1068 // Stores a list of users whose package restrictions file needs to be updated
1069 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1071 final private DefaultContainerConnection mDefContainerConn =
1072 new DefaultContainerConnection();
1073 class DefaultContainerConnection implements ServiceConnection {
1074 public void onServiceConnected(ComponentName name, IBinder service) {
1075 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1076 IMediaContainerService imcs =
1077 IMediaContainerService.Stub.asInterface(service);
1078 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1081 public void onServiceDisconnected(ComponentName name) {
1082 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1086 // Recordkeeping of restore-after-install operations that are currently in flight
1087 // between the Package Manager and the Backup Manager
1088 static class PostInstallData {
1089 public InstallArgs args;
1090 public PackageInstalledInfo res;
1092 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1098 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1099 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
1101 // XML tags for backup/restore of various bits of state
1102 private static final String TAG_PREFERRED_BACKUP = "pa";
1103 private static final String TAG_DEFAULT_APPS = "da";
1104 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1106 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1107 private static final String TAG_ALL_GRANTS = "rt-grants";
1108 private static final String TAG_GRANT = "grant";
1109 private static final String ATTR_PACKAGE_NAME = "pkg";
1111 private static final String TAG_PERMISSION = "perm";
1112 private static final String ATTR_PERMISSION_NAME = "name";
1113 private static final String ATTR_IS_GRANTED = "g";
1114 private static final String ATTR_USER_SET = "set";
1115 private static final String ATTR_USER_FIXED = "fixed";
1116 private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1118 // System/policy permission grants are not backed up
1119 private static final int SYSTEM_RUNTIME_GRANT_MASK =
1120 FLAG_PERMISSION_POLICY_FIXED
1121 | FLAG_PERMISSION_SYSTEM_FIXED
1122 | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1124 // And we back up these user-adjusted states
1125 private static final int USER_RUNTIME_GRANT_MASK =
1126 FLAG_PERMISSION_USER_SET
1127 | FLAG_PERMISSION_USER_FIXED
1128 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1130 final @Nullable String mRequiredVerifierPackage;
1131 final @NonNull String mRequiredInstallerPackage;
1132 final @NonNull String mRequiredUninstallerPackage;
1133 final @Nullable String mSetupWizardPackage;
1134 final @Nullable String mStorageManagerPackage;
1135 final @NonNull String mServicesSystemSharedLibraryPackageName;
1136 final @NonNull String mSharedSystemSharedLibraryPackageName;
1138 private final PackageUsage mPackageUsage = new PackageUsage();
1139 private final CompilerStats mCompilerStats = new CompilerStats();
1141 class PackageHandler extends Handler {
1142 private boolean mBound = false;
1143 final ArrayList<HandlerParams> mPendingInstalls =
1144 new ArrayList<HandlerParams>();
1146 private boolean connectToService() {
1147 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1148 " DefaultContainerService");
1149 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1150 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1151 if (mContext.bindServiceAsUser(service, mDefContainerConn,
1152 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1153 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1157 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1161 private void disconnectService() {
1162 mContainerService = null;
1164 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1165 mContext.unbindService(mDefContainerConn);
1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1169 PackageHandler(Looper looper) {
1173 public void handleMessage(Message msg) {
1175 doHandleMessage(msg);
1177 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1181 void doHandleMessage(Message msg) {
1184 HandlerParams params = (HandlerParams) msg.obj;
1185 int idx = mPendingInstalls.size();
1186 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1187 // If a bind was already initiated we dont really
1188 // need to do anything. The pending install
1189 // will be processed later on.
1191 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1192 System.identityHashCode(mHandler));
1193 // If this is the only one pending we might
1194 // have to bind to the service again.
1195 if (!connectToService()) {
1196 Slog.e(TAG, "Failed to bind to media container service");
1197 params.serviceError();
1198 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1199 System.identityHashCode(mHandler));
1200 if (params.traceMethod != null) {
1201 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1202 params.traceCookie);
1206 // Once we bind to the service, the first
1207 // pending request will be processed.
1208 mPendingInstalls.add(idx, params);
1211 mPendingInstalls.add(idx, params);
1212 // Already bound to the service. Just make
1213 // sure we trigger off processing the first request.
1215 mHandler.sendEmptyMessage(MCS_BOUND);
1221 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1222 if (msg.obj != null) {
1223 mContainerService = (IMediaContainerService) msg.obj;
1224 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1225 System.identityHashCode(mHandler));
1227 if (mContainerService == null) {
1229 // Something seriously wrong since we are not bound and we are not
1230 // waiting for connection. Bail out.
1231 Slog.e(TAG, "Cannot bind to media container service");
1232 for (HandlerParams params : mPendingInstalls) {
1233 // Indicate service bind error
1234 params.serviceError();
1235 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1236 System.identityHashCode(params));
1237 if (params.traceMethod != null) {
1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1239 params.traceMethod, params.traceCookie);
1243 mPendingInstalls.clear();
1245 Slog.w(TAG, "Waiting to connect to media container service");
1247 } else if (mPendingInstalls.size() > 0) {
1248 HandlerParams params = mPendingInstalls.get(0);
1249 if (params != null) {
1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1251 System.identityHashCode(params));
1252 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1253 if (params.startCopy()) {
1254 // We are done... look for more work or to
1256 if (DEBUG_SD_INSTALL) Log.i(TAG,
1257 "Checking for more work or unbind...");
1258 // Delete pending install
1259 if (mPendingInstalls.size() > 0) {
1260 mPendingInstalls.remove(0);
1262 if (mPendingInstalls.size() == 0) {
1264 if (DEBUG_SD_INSTALL) Log.i(TAG,
1265 "Posting delayed MCS_UNBIND");
1266 removeMessages(MCS_UNBIND);
1267 Message ubmsg = obtainMessage(MCS_UNBIND);
1268 // Unbind after a little delay, to avoid
1269 // continual thrashing.
1270 sendMessageDelayed(ubmsg, 10000);
1273 // There are more pending requests in queue.
1274 // Just post MCS_BOUND message to trigger processing
1275 // of next pending install.
1276 if (DEBUG_SD_INSTALL) Log.i(TAG,
1277 "Posting MCS_BOUND for next work");
1278 mHandler.sendEmptyMessage(MCS_BOUND);
1281 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1284 // Should never happen ideally.
1285 Slog.w(TAG, "Empty queue");
1289 case MCS_RECONNECT: {
1290 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1291 if (mPendingInstalls.size() > 0) {
1293 disconnectService();
1295 if (!connectToService()) {
1296 Slog.e(TAG, "Failed to bind to media container service");
1297 for (HandlerParams params : mPendingInstalls) {
1298 // Indicate service bind error
1299 params.serviceError();
1300 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1301 System.identityHashCode(params));
1303 mPendingInstalls.clear();
1309 // If there is no actual work left, then time to unbind.
1310 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1312 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1314 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1316 disconnectService();
1318 } else if (mPendingInstalls.size() > 0) {
1319 // There are more pending requests in queue.
1320 // Just post MCS_BOUND message to trigger processing
1321 // of next pending install.
1322 mHandler.sendEmptyMessage(MCS_BOUND);
1328 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1329 HandlerParams params = mPendingInstalls.remove(0);
1330 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1331 System.identityHashCode(params));
1334 case SEND_PENDING_BROADCAST: {
1336 ArrayList<String> components[];
1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1340 synchronized (mPackages) {
1341 if (mPendingBroadcasts == null) {
1344 size = mPendingBroadcasts.size();
1346 // Nothing to be done. Just return
1349 packages = new String[size];
1350 components = new ArrayList[size];
1351 uids = new int[size];
1352 int i = 0; // filling out the above arrays
1354 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1355 int packageUserId = mPendingBroadcasts.userIdAt(n);
1356 Iterator<Map.Entry<String, ArrayList<String>>> it
1357 = mPendingBroadcasts.packagesForUserId(packageUserId)
1358 .entrySet().iterator();
1359 while (it.hasNext() && i < size) {
1360 Map.Entry<String, ArrayList<String>> ent = it.next();
1361 packages[i] = ent.getKey();
1362 components[i] = ent.getValue();
1363 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1364 uids[i] = (ps != null)
1365 ? UserHandle.getUid(packageUserId, ps.appId)
1371 mPendingBroadcasts.clear();
1374 for (int i = 0; i < size; i++) {
1375 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1377 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1380 case START_CLEANING_PACKAGE: {
1381 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1382 final String packageName = (String)msg.obj;
1383 final int userId = msg.arg1;
1384 final boolean andCode = msg.arg2 != 0;
1385 synchronized (mPackages) {
1386 if (userId == UserHandle.USER_ALL) {
1387 int[] users = sUserManager.getUserIds();
1388 for (int user : users) {
1389 mSettings.addPackageToCleanLPw(
1390 new PackageCleanItem(user, packageName, andCode));
1393 mSettings.addPackageToCleanLPw(
1394 new PackageCleanItem(userId, packageName, andCode));
1397 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1398 startCleaningPackages();
1400 case POST_INSTALL: {
1401 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1403 PostInstallData data = mRunningInstalls.get(msg.arg1);
1404 final boolean didRestore = (msg.arg2 != 0);
1405 mRunningInstalls.delete(msg.arg1);
1408 InstallArgs args = data.args;
1409 PackageInstalledInfo parentRes = data.res;
1411 final boolean grantPermissions = (args.installFlags
1412 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1413 final boolean killApp = (args.installFlags
1414 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1415 final String[] grantedPermissions = args.installGrantPermissions;
1417 // Handle the parent package
1418 handlePackagePostInstall(parentRes, grantPermissions, killApp,
1419 grantedPermissions, didRestore, args.installerPackageName,
1422 // Handle the child packages
1423 final int childCount = (parentRes.addedChildPackages != null)
1424 ? parentRes.addedChildPackages.size() : 0;
1425 for (int i = 0; i < childCount; i++) {
1426 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1427 handlePackagePostInstall(childRes, grantPermissions, killApp,
1428 grantedPermissions, false, args.installerPackageName,
1432 // Log tracing if needed
1433 if (args.traceMethod != null) {
1434 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1438 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1443 case UPDATED_MEDIA_STATUS: {
1444 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1445 boolean reportStatus = msg.arg1 == 1;
1446 boolean doGc = msg.arg2 == 1;
1447 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1449 // Force a gc to clear up stale containers.
1450 Runtime.getRuntime().gc();
1452 if (msg.obj != null) {
1453 @SuppressWarnings("unchecked")
1454 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1455 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1456 // Unload containers
1457 unloadAllContainers(args);
1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1462 PackageHelper.getMountService().finishMediaUpdate();
1463 } catch (RemoteException e) {
1464 Log.e(TAG, "MountService not running?");
1468 case WRITE_SETTINGS: {
1469 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470 synchronized (mPackages) {
1471 removeMessages(WRITE_SETTINGS);
1472 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1473 mSettings.writeLPr();
1474 mDirtyUsers.clear();
1476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478 case WRITE_PACKAGE_RESTRICTIONS: {
1479 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1480 synchronized (mPackages) {
1481 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1482 for (int userId : mDirtyUsers) {
1483 mSettings.writePackageRestrictionsLPr(userId);
1485 mDirtyUsers.clear();
1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489 case WRITE_PACKAGE_LIST: {
1490 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1491 synchronized (mPackages) {
1492 removeMessages(WRITE_PACKAGE_LIST);
1493 mSettings.writePackageListLPr(msg.arg1);
1495 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1497 case CHECK_PENDING_VERIFICATION: {
1498 final int verificationId = msg.arg1;
1499 final PackageVerificationState state = mPendingVerification.get(verificationId);
1501 if ((state != null) && !state.timeoutExtended()) {
1502 final InstallArgs args = state.getInstallArgs();
1503 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1505 Slog.i(TAG, "Verification timed out for " + originUri);
1506 mPendingVerification.remove(verificationId);
1508 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1510 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1511 Slog.i(TAG, "Continuing with installation of " + originUri);
1512 state.setVerifierResponse(Binder.getCallingUid(),
1513 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1514 broadcastPackageVerified(verificationId, originUri,
1515 PackageManager.VERIFICATION_ALLOW,
1516 state.getInstallArgs().getUser());
1518 ret = args.copyApk(mContainerService, true);
1519 } catch (RemoteException e) {
1520 Slog.e(TAG, "Could not contact the ContainerService");
1523 broadcastPackageVerified(verificationId, originUri,
1524 PackageManager.VERIFICATION_REJECT,
1525 state.getInstallArgs().getUser());
1528 Trace.asyncTraceEnd(
1529 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1531 processPendingInstall(args, ret);
1532 mHandler.sendEmptyMessage(MCS_UNBIND);
1536 case PACKAGE_VERIFIED: {
1537 final int verificationId = msg.arg1;
1539 final PackageVerificationState state = mPendingVerification.get(verificationId);
1540 if (state == null) {
1541 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1545 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1547 state.setVerifierResponse(response.callerUid, response.code);
1549 if (state.isVerificationComplete()) {
1550 mPendingVerification.remove(verificationId);
1552 final InstallArgs args = state.getInstallArgs();
1553 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1556 if (state.isInstallAllowed()) {
1557 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1558 broadcastPackageVerified(verificationId, originUri,
1559 response.code, state.getInstallArgs().getUser());
1561 ret = args.copyApk(mContainerService, true);
1562 } catch (RemoteException e) {
1563 Slog.e(TAG, "Could not contact the ContainerService");
1566 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1569 Trace.asyncTraceEnd(
1570 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1572 processPendingInstall(args, ret);
1573 mHandler.sendEmptyMessage(MCS_UNBIND);
1578 case START_INTENT_FILTER_VERIFICATIONS: {
1579 IFVerificationParams params = (IFVerificationParams) msg.obj;
1580 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1581 params.replacing, params.pkg);
1584 case INTENT_FILTER_VERIFIED: {
1585 final int verificationId = msg.arg1;
1587 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1589 if (state == null) {
1590 Slog.w(TAG, "Invalid IntentFilter verification token "
1591 + verificationId + " received");
1595 final int userId = state.getUserId();
1597 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598 "Processing IntentFilter verification with token:"
1599 + verificationId + " and userId:" + userId);
1601 final IntentFilterVerificationResponse response =
1602 (IntentFilterVerificationResponse) msg.obj;
1604 state.setVerifierResponse(response.callerUid, response.code);
1606 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1607 "IntentFilter verification with token:" + verificationId
1608 + " and userId:" + userId
1609 + " is settings verifier response with response code:"
1612 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1613 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1614 + response.getFailedDomainsString());
1617 if (state.isVerificationComplete()) {
1618 mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1621 "IntentFilter verification with token:" + verificationId
1622 + " was not said to be complete");
1631 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1632 boolean killApp, String[] grantedPermissions,
1633 boolean launchedForRestore, String installerPackage,
1634 IPackageInstallObserver2 installObserver) {
1635 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1636 // Send the removed broadcasts
1637 if (res.removedInfo != null) {
1638 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1641 // Now that we successfully installed the package, grant runtime
1642 // permissions if requested before broadcasting the install.
1643 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1644 >= Build.VERSION_CODES.M) {
1645 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1648 final boolean update = res.removedInfo != null
1649 && res.removedInfo.removedPackage != null;
1651 // If this is the first time we have child packages for a disabled privileged
1652 // app that had no children, we grant requested runtime permissions to the new
1653 // children if the parent on the system image had them already granted.
1654 if (res.pkg.parentPackage != null) {
1655 synchronized (mPackages) {
1656 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1660 synchronized (mPackages) {
1661 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1664 final String packageName = res.pkg.applicationInfo.packageName;
1665 Bundle extras = new Bundle(1);
1666 extras.putInt(Intent.EXTRA_UID, res.uid);
1668 // Determine the set of users who are adding this package for
1669 // the first time vs. those who are seeing an update.
1670 int[] firstUsers = EMPTY_INT_ARRAY;
1671 int[] updateUsers = EMPTY_INT_ARRAY;
1672 if (res.origUsers == null || res.origUsers.length == 0) {
1673 firstUsers = res.newUsers;
1675 for (int newUser : res.newUsers) {
1676 boolean isNew = true;
1677 for (int origUser : res.origUsers) {
1678 if (origUser == newUser) {
1684 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1686 updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1691 // Send installed broadcasts if the install/update is not ephemeral
1692 if (!isEphemeral(res.pkg)) {
1693 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1695 // Send added for users that see the package for the first time
1696 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1697 extras, 0 /*flags*/, null /*targetPackage*/,
1698 null /*finishedReceiver*/, firstUsers);
1700 // Send added for users that don't see the package for the first time
1702 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1704 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705 extras, 0 /*flags*/, null /*targetPackage*/,
1706 null /*finishedReceiver*/, updateUsers);
1708 // Send replaced for users that don't see the package for the first time
1710 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1711 packageName, extras, 0 /*flags*/,
1712 null /*targetPackage*/, null /*finishedReceiver*/,
1714 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1715 null /*package*/, null /*extras*/, 0 /*flags*/,
1716 packageName /*targetPackage*/,
1717 null /*finishedReceiver*/, updateUsers);
1718 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1719 // First-install and we did a restore, so we're responsible for the
1720 // first-launch broadcast.
1722 Slog.i(TAG, "Post-restore of " + packageName
1723 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1725 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1728 // Send broadcast package appeared if forward locked/external for all users
1729 // treat asec-hosted packages like removable media on upgrade
1730 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1731 if (DEBUG_INSTALL) {
1732 Slog.i(TAG, "upgrading pkg " + res.pkg
1733 + " is ASEC-hosted -> AVAILABLE");
1735 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1736 ArrayList<String> pkgList = new ArrayList<>(1);
1737 pkgList.add(packageName);
1738 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1742 // Work that needs to happen on first install within each user
1743 if (firstUsers != null && firstUsers.length > 0) {
1744 synchronized (mPackages) {
1745 for (int userId : firstUsers) {
1746 // If this app is a browser and it's newly-installed for some
1747 // users, clear any default-browser state in those users. The
1748 // app's nature doesn't depend on the user, so we can just check
1749 // its browser nature in any user and generalize.
1750 if (packageIsBrowser(packageName, userId)) {
1751 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1754 // We may also need to apply pending (restored) runtime
1755 // permission grants within these users.
1756 mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1761 // Log current value of "unknown sources" setting
1762 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1763 getUnknownSourcesSettings());
1765 // Force a gc to clear up things
1766 Runtime.getRuntime().gc();
1768 // Remove the replaced package's older resources safely now
1769 // We delete after a gc for applications on sdcard.
1770 if (res.removedInfo != null && res.removedInfo.args != null) {
1771 synchronized (mInstallLock) {
1772 res.removedInfo.args.doPostDeleteLI(true);
1777 // If someone is watching installs - notify them
1778 if (installObserver != null) {
1780 Bundle extras = extrasForInstallResult(res);
1781 installObserver.onPackageInstalled(res.name, res.returnCode,
1782 res.returnMsg, extras);
1783 } catch (RemoteException e) {
1784 Slog.i(TAG, "Observer no longer exists.");
1789 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1790 PackageParser.Package pkg) {
1791 if (pkg.parentPackage == null) {
1794 if (pkg.requestedPermissions == null) {
1797 final PackageSetting disabledSysParentPs = mSettings
1798 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1799 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1800 || !disabledSysParentPs.isPrivileged()
1801 || (disabledSysParentPs.childPackageNames != null
1802 && !disabledSysParentPs.childPackageNames.isEmpty())) {
1805 final int[] allUserIds = sUserManager.getUserIds();
1806 final int permCount = pkg.requestedPermissions.size();
1807 for (int i = 0; i < permCount; i++) {
1808 String permission = pkg.requestedPermissions.get(i);
1809 BasePermission bp = mSettings.mPermissions.get(permission);
1810 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1813 for (int userId : allUserIds) {
1814 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1815 permission, userId)) {
1816 grantRuntimePermission(pkg.packageName, permission, userId);
1822 private StorageEventListener mStorageListener = new StorageEventListener() {
1824 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1825 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1826 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1827 final String volumeUuid = vol.getFsUuid();
1829 // Clean up any users or apps that were removed or recreated
1830 // while this volume was missing
1831 reconcileUsers(volumeUuid);
1832 reconcileApps(volumeUuid);
1834 // Clean up any install sessions that expired or were
1835 // cancelled while this volume was missing
1836 mInstallerService.onPrivateVolumeMounted(volumeUuid);
1838 loadPrivatePackages(vol);
1840 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1841 unloadPrivatePackages(vol);
1845 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1846 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1847 updateExternalMediaStatus(true, false);
1848 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1849 updateExternalMediaStatus(false, false);
1855 public void onVolumeForgotten(String fsUuid) {
1856 if (TextUtils.isEmpty(fsUuid)) {
1857 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1861 // Remove any apps installed on the forgotten volume
1862 synchronized (mPackages) {
1863 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1864 for (PackageSetting ps : packages) {
1865 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1866 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1867 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1870 mSettings.onVolumeForgotten(fsUuid);
1871 mSettings.writeLPr();
1876 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1877 String[] grantedPermissions) {
1878 for (int userId : userIds) {
1879 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1882 // We could have touched GID membership, so flush out packages.list
1883 synchronized (mPackages) {
1884 mSettings.writePackageListLPr();
1888 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1889 String[] grantedPermissions) {
1890 SettingBase sb = (SettingBase) pkg.mExtras;
1895 PermissionsState permissionsState = sb.getPermissionsState();
1897 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1898 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1900 for (String permission : pkg.requestedPermissions) {
1901 final BasePermission bp;
1902 synchronized (mPackages) {
1903 bp = mSettings.mPermissions.get(permission);
1905 if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1906 && (grantedPermissions == null
1907 || ArrayUtils.contains(grantedPermissions, permission))) {
1908 final int flags = permissionsState.getPermissionFlags(permission, userId);
1909 // Installer cannot change immutable permissions.
1910 if ((flags & immutableFlags) == 0) {
1911 grantRuntimePermission(pkg.packageName, permission, userId);
1917 Bundle extrasForInstallResult(PackageInstalledInfo res) {
1918 Bundle extras = null;
1919 switch (res.returnCode) {
1920 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1921 extras = new Bundle();
1922 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1923 res.origPermission);
1924 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1928 case PackageManager.INSTALL_SUCCEEDED: {
1929 extras = new Bundle();
1930 extras.putBoolean(Intent.EXTRA_REPLACING,
1931 res.removedInfo != null && res.removedInfo.removedPackage != null);
1938 void scheduleWriteSettingsLocked() {
1939 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1940 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1944 void scheduleWritePackageListLocked(int userId) {
1945 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1946 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1948 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1952 void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1953 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1954 scheduleWritePackageRestrictionsLocked(userId);
1957 void scheduleWritePackageRestrictionsLocked(int userId) {
1958 final int[] userIds = (userId == UserHandle.USER_ALL)
1959 ? sUserManager.getUserIds() : new int[]{userId};
1960 for (int nextUserId : userIds) {
1961 if (!sUserManager.exists(nextUserId)) return;
1962 mDirtyUsers.add(nextUserId);
1963 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1964 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1969 public static PackageManagerService main(Context context, Installer installer,
1970 boolean factoryTest, boolean onlyCore) {
1971 // Self-check for initial settings.
1972 PackageManagerServiceCompilerMapping.checkProperties();
1974 PackageManagerService m = new PackageManagerService(context, installer,
1975 factoryTest, onlyCore);
1976 m.enableSystemUserPackages();
1977 ServiceManager.addService("package", m);
1981 private void enableSystemUserPackages() {
1982 if (!UserManager.isSplitSystemUser()) {
1985 // For system user, enable apps based on the following conditions:
1986 // - app is whitelisted or belong to one of these groups:
1987 // -- system app which has no launcher icons
1988 // -- system app which has INTERACT_ACROSS_USERS permission
1989 // -- system IME app
1990 // - app is not in the blacklist
1991 AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1992 Set<String> enableApps = new ArraySet<>();
1993 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1994 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1995 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1996 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1997 enableApps.addAll(wlApps);
1998 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1999 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2000 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2001 enableApps.removeAll(blApps);
2002 Log.i(TAG, "Applications installed for system user: " + enableApps);
2003 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2005 final int allAppsSize = allAps.size();
2006 synchronized (mPackages) {
2007 for (int i = 0; i < allAppsSize; i++) {
2008 String pName = allAps.get(i);
2009 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2010 // Should not happen, but we shouldn't be failing if it does
2011 if (pkgSetting == null) {
2014 boolean install = enableApps.contains(pName);
2015 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2016 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2017 + " for system user");
2018 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2024 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2025 DisplayManager displayManager = (DisplayManager) context.getSystemService(
2026 Context.DISPLAY_SERVICE);
2027 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2031 * Requests that files preopted on a secondary system partition be copied to the data partition
2032 * if possible. Note that the actual copying of the files is accomplished by init for security
2033 * reasons. This simply requests that the copy takes place and awaits confirmation of its
2034 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2036 private static void requestCopyPreoptedFiles() {
2037 final int WAIT_TIME_MS = 100;
2038 final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2039 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2040 SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2041 // We will wait for up to 100 seconds.
2042 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2043 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2045 Thread.sleep(WAIT_TIME_MS);
2046 } catch (InterruptedException e) {
2049 if (SystemClock.uptimeMillis() > timeEnd) {
2050 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2051 Slog.wtf(TAG, "cppreopt did not finish!");
2058 public PackageManagerService(Context context, Installer installer,
2059 boolean factoryTest, boolean onlyCore) {
2060 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2061 SystemClock.uptimeMillis());
2063 if (mSdkVersion <= 0) {
2064 Slog.w(TAG, "**** ro.build.version.sdk not set!");
2068 mFactoryTest = factoryTest;
2069 mOnlyCore = onlyCore;
2070 mMetrics = new DisplayMetrics();
2071 mSettings = new Settings(mPackages);
2072 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2073 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2074 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2075 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2076 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2077 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2078 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2079 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2080 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2081 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2082 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2083 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2085 String separateProcesses = SystemProperties.get("debug.separate_processes");
2086 if (separateProcesses != null && separateProcesses.length() > 0) {
2087 if ("*".equals(separateProcesses)) {
2088 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2089 mSeparateProcesses = null;
2090 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2093 mSeparateProcesses = separateProcesses.split(",");
2094 Slog.w(TAG, "Running with debug.separate_processes: "
2095 + separateProcesses);
2099 mSeparateProcesses = null;
2102 mInstaller = installer;
2103 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2105 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2107 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2108 FgThread.get().getLooper());
2110 getDefaultDisplayMetrics(context, mMetrics);
2112 SystemConfig systemConfig = SystemConfig.getInstance();
2113 mGlobalGids = systemConfig.getGlobalGids();
2114 mSystemPermissions = systemConfig.getSystemPermissions();
2115 mAvailableFeatures = systemConfig.getAvailableFeatures();
2117 mProtectedPackages = new ProtectedPackages(mContext);
2119 synchronized (mInstallLock) {
2121 synchronized (mPackages) {
2122 mHandlerThread = new ServiceThread(TAG,
2123 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2124 mHandlerThread.start();
2125 mHandler = new PackageHandler(mHandlerThread.getLooper());
2126 mProcessLoggingHandler = new ProcessLoggingHandler();
2127 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2129 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2131 File dataDir = Environment.getDataDirectory();
2132 mAppInstallDir = new File(dataDir, "app");
2133 mAppLib32InstallDir = new File(dataDir, "app-lib");
2134 mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2135 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2136 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2138 sUserManager = new UserManagerService(context, this, mPackages);
2140 // Propagate permission configuration in to package manager.
2141 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2142 = systemConfig.getPermissions();
2143 for (int i=0; i<permConfig.size(); i++) {
2144 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2145 BasePermission bp = mSettings.mPermissions.get(perm.name);
2147 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2148 mSettings.mPermissions.put(perm.name, bp);
2150 if (perm.gids != null) {
2151 bp.setGids(perm.gids, perm.perUser);
2155 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2156 for (int i=0; i<libConfig.size(); i++) {
2157 mSharedLibraries.put(libConfig.keyAt(i),
2158 new SharedLibraryEntry(libConfig.valueAt(i), null));
2161 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2163 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2165 // Clean up orphaned packages for which the code path doesn't exist
2166 // and they are an update to a system app - caused by bug/32321269
2167 final int packageSettingCount = mSettings.mPackages.size();
2168 for (int i = packageSettingCount - 1; i >= 0; i--) {
2169 PackageSetting ps = mSettings.mPackages.valueAt(i);
2170 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2171 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2172 mSettings.mPackages.removeAt(i);
2173 mSettings.enableSystemPackageLPw(ps.name);
2178 requestCopyPreoptedFiles();
2181 String customResolverActivity = Resources.getSystem().getString(
2182 R.string.config_customResolverActivity);
2183 if (TextUtils.isEmpty(customResolverActivity)) {
2184 customResolverActivity = null;
2186 mCustomResolverComponentName = ComponentName.unflattenFromString(
2187 customResolverActivity);
2190 long startTime = SystemClock.uptimeMillis();
2192 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2195 // Set flag to monitor and not change apk file paths when
2196 // scanning install directories.
2197 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2199 final String bootClassPath = System.getenv("BOOTCLASSPATH");
2200 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2202 if (bootClassPath == null) {
2203 Slog.w(TAG, "No BOOTCLASSPATH found!");
2206 if (systemServerClassPath == null) {
2207 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2210 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2211 final String[] dexCodeInstructionSets =
2212 getDexCodeInstructionSets(
2213 allInstructionSets.toArray(new String[allInstructionSets.size()]));
2216 * Ensure all external libraries have had dexopt run on them.
2218 if (mSharedLibraries.size() > 0) {
2219 // NOTE: For now, we're compiling these system "shared libraries"
2220 // (and framework jars) into all available architectures. It's possible
2221 // to compile them only when we come across an app that uses them (there's
2222 // already logic for that in scanPackageLI) but that adds some complexity.
2223 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2224 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2225 final String lib = libEntry.path;
2231 // Shared libraries do not have profiles so we perform a full
2232 // AOT compilation (if needed).
2233 int dexoptNeeded = DexFile.getDexOptNeeded(
2234 lib, dexCodeInstructionSet,
2235 getCompilerFilterForReason(REASON_SHARED_APK),
2236 false /* newProfile */);
2237 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2238 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2239 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2240 getCompilerFilterForReason(REASON_SHARED_APK),
2241 StorageManager.UUID_PRIVATE_INTERNAL,
2242 SKIP_SHARED_LIBRARY_CHECK);
2244 } catch (FileNotFoundException e) {
2245 Slog.w(TAG, "Library not found: " + lib);
2246 } catch (IOException | InstallerException e) {
2247 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2254 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2256 final VersionInfo ver = mSettings.getInternalVersion();
2257 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2259 // when upgrading from pre-M, promote system app permissions from install to runtime
2260 mPromoteSystemApps =
2261 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2263 // When upgrading from pre-N, we need to handle package extraction like first boot,
2264 // as there is no profiling data available.
2265 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2267 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2269 // save off the names of pre-existing system packages prior to scanning; we don't
2270 // want to automatically grant runtime permissions for new system apps
2271 if (mPromoteSystemApps) {
2272 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2273 while (pkgSettingIter.hasNext()) {
2274 PackageSetting ps = pkgSettingIter.next();
2275 if (isSystemApp(ps)) {
2276 mExistingSystemPackages.add(ps.name);
2281 // Collect vendor overlay packages.
2282 // (Do this before scanning any apps.)
2283 // For security and version matching reason, only consider
2284 // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2285 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2286 scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2287 | PackageParser.PARSE_IS_SYSTEM
2288 | PackageParser.PARSE_IS_SYSTEM_DIR
2289 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2291 // Find base frameworks (resource packages without code).
2292 scanDirTracedLI(frameworkDir, mDefParseFlags
2293 | PackageParser.PARSE_IS_SYSTEM
2294 | PackageParser.PARSE_IS_SYSTEM_DIR
2295 | PackageParser.PARSE_IS_PRIVILEGED,
2296 scanFlags | SCAN_NO_DEX, 0);
2298 // Collected privileged system packages.
2299 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2300 scanDirTracedLI(privilegedAppDir, mDefParseFlags
2301 | PackageParser.PARSE_IS_SYSTEM
2302 | PackageParser.PARSE_IS_SYSTEM_DIR
2303 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2305 // Collect ordinary system packages.
2306 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2307 scanDirTracedLI(systemAppDir, mDefParseFlags
2308 | PackageParser.PARSE_IS_SYSTEM
2309 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2311 // Collect all vendor packages.
2312 File vendorAppDir = new File("/vendor/app");
2314 vendorAppDir = vendorAppDir.getCanonicalFile();
2315 } catch (IOException e) {
2316 // failed to look up canonical path, continue with original one
2318 scanDirTracedLI(vendorAppDir, mDefParseFlags
2319 | PackageParser.PARSE_IS_SYSTEM
2320 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2322 // Collect all OEM packages.
2323 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2324 scanDirTracedLI(oemAppDir, mDefParseFlags
2325 | PackageParser.PARSE_IS_SYSTEM
2326 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2328 // Prune any system packages that no longer exist.
2329 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2331 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2332 while (psit.hasNext()) {
2333 PackageSetting ps = psit.next();
2336 * If this is not a system app, it can't be a
2337 * disable system app.
2339 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2344 * If the package is scanned, it's not erased.
2346 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2347 if (scannedPkg != null) {
2349 * If the system app is both scanned and in the
2350 * disabled packages list, then it must have been
2351 * added via OTA. Remove it from the currently
2352 * scanned package so the previously user-installed
2353 * application can be scanned.
2355 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2356 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2357 + ps.name + "; removing system app. Last known codePath="
2358 + ps.codePathString + ", installStatus=" + ps.installStatus
2359 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2360 + scannedPkg.mVersionCode);
2361 removePackageLI(scannedPkg, true);
2362 mExpectingBetter.put(ps.name, ps.codePath);
2368 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2370 logCriticalInfo(Log.WARN, "System package " + ps.name
2371 + " no longer exists; it's data will be wiped");
2372 // Actual deletion of code and data will be handled by later
2373 // reconciliation step
2375 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2376 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2377 possiblyDeletedUpdatedSystemApps.add(ps.name);
2383 //look for any incomplete package installations
2384 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2385 for (int i = 0; i < deletePkgsList.size(); i++) {
2386 // Actual deletion of code and data will be handled by later
2387 // reconciliation step
2388 final String packageName = deletePkgsList.get(i).name;
2389 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2390 synchronized (mPackages) {
2391 mSettings.removePackageLPw(packageName);
2396 deleteTempPackageFiles();
2398 // Remove any shared userIDs that have no associated packages
2399 mSettings.pruneSharedUsersLPw();
2402 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2403 SystemClock.uptimeMillis());
2404 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2406 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2407 | PackageParser.PARSE_FORWARD_LOCK,
2408 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2410 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2411 | PackageParser.PARSE_IS_EPHEMERAL,
2412 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2415 * Remove disable package settings for any updated system
2416 * apps that were removed via an OTA. If they're not a
2417 * previously-updated app, remove them completely.
2418 * Otherwise, just revoke their system-level permissions.
2420 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2421 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2422 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2425 if (deletedPkg == null) {
2426 msg = "Updated system package " + deletedAppName
2427 + " no longer exists; it's data will be wiped";
2428 // Actual deletion of code and data will be handled by later
2429 // reconciliation step
2431 msg = "Updated system app + " + deletedAppName
2432 + " no longer present; removing system privileges for "
2435 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2437 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2438 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2440 logCriticalInfo(Log.WARN, msg);
2444 * Make sure all system apps that we expected to appear on
2445 * the userdata partition actually showed up. If they never
2446 * appeared, crawl back and revive the system version.
2448 for (int i = 0; i < mExpectingBetter.size(); i++) {
2449 final String packageName = mExpectingBetter.keyAt(i);
2450 if (!mPackages.containsKey(packageName)) {
2451 final File scanFile = mExpectingBetter.valueAt(i);
2453 logCriticalInfo(Log.WARN, "Expected better " + packageName
2454 + " but never showed up; reverting to system");
2456 int reparseFlags = mDefParseFlags;
2457 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2458 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2459 | PackageParser.PARSE_IS_SYSTEM_DIR
2460 | PackageParser.PARSE_IS_PRIVILEGED;
2461 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2462 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2463 | PackageParser.PARSE_IS_SYSTEM_DIR;
2464 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2465 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2466 | PackageParser.PARSE_IS_SYSTEM_DIR;
2467 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2468 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2469 | PackageParser.PARSE_IS_SYSTEM_DIR;
2471 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2475 mSettings.enableSystemPackageLPw(packageName);
2478 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2479 } catch (PackageManagerException e) {
2480 Slog.e(TAG, "Failed to parse original system package: "
2486 mExpectingBetter.clear();
2488 // Resolve the storage manager.
2489 mStorageManagerPackage = getStorageManagerPackageName();
2491 // Resolve protected action filters. Only the setup wizard is allowed to
2492 // have a high priority filter for these actions.
2493 mSetupWizardPackage = getSetupWizardPackageName();
2494 if (mProtectedFilters.size() > 0) {
2495 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2496 Slog.i(TAG, "No setup wizard;"
2497 + " All protected intents capped to priority 0");
2499 for (ActivityIntentInfo filter : mProtectedFilters) {
2500 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2501 if (DEBUG_FILTERS) {
2502 Slog.i(TAG, "Found setup wizard;"
2503 + " allow priority " + filter.getPriority() + ";"
2504 + " package: " + filter.activity.info.packageName
2505 + " activity: " + filter.activity.className
2506 + " priority: " + filter.getPriority());
2508 // skip setup wizard; allow it to keep the high priority filter
2511 Slog.w(TAG, "Protected action; cap priority to 0;"
2512 + " package: " + filter.activity.info.packageName
2513 + " activity: " + filter.activity.className
2514 + " origPrio: " + filter.getPriority());
2515 filter.setPriority(0);
2518 mDeferProtectedFilters = false;
2519 mProtectedFilters.clear();
2521 // Now that we know all of the shared libraries, update all clients to have
2522 // the correct library paths.
2523 updateAllSharedLibrariesLPw();
2525 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2526 // NOTE: We ignore potential failures here during a system scan (like
2527 // the rest of the commands above) because there's precious little we
2528 // can do about it. A settings error is reported, though.
2529 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2530 false /* boot complete */);
2533 // Now that we know all the packages we are keeping,
2534 // read and update their last usage times.
2535 mPackageUsage.read(mPackages);
2536 mCompilerStats.read();
2538 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2539 SystemClock.uptimeMillis());
2540 Slog.i(TAG, "Time to scan packages: "
2541 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2544 // If the platform SDK has changed since the last time we booted,
2545 // we need to re-grant app permission to catch any new ones that
2546 // appear. This is really a hack, and means that apps can in some
2547 // cases get permissions that the user didn't initially explicitly
2548 // allow... it would be nice to have some better way to handle
2550 int updateFlags = UPDATE_PERMISSIONS_ALL;
2551 if (ver.sdkVersion != mSdkVersion) {
2552 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2553 + mSdkVersion + "; regranting permissions for internal storage");
2554 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2556 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2557 ver.sdkVersion = mSdkVersion;
2559 // If this is the first boot or an update from pre-M, and it is a normal
2560 // boot, then we need to initialize the default preferred apps across
2561 // all defined users.
2562 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2563 for (UserInfo user : sUserManager.getUsers(true)) {
2564 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2565 applyFactoryDefaultBrowserLPw(user.id);
2566 primeDomainVerificationsLPw(user.id);
2570 // Prepare storage for system user really early during boot,
2571 // since core system apps like SettingsProvider and SystemUI
2572 // can't wait for user to start
2573 final int storageFlags;
2574 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2575 storageFlags = StorageManager.FLAG_STORAGE_DE;
2577 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2579 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2582 // If this is first boot after an OTA, and a normal boot, then
2583 // we need to clear code cache directories.
2584 // Note that we do *not* clear the application profiles. These remain valid
2585 // across OTAs and are used to drive profile verification (post OTA) and
2586 // profile compilation (without waiting to collect a fresh set of profiles).
2587 if (mIsUpgrade && !onlyCore) {
2588 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2589 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2590 final PackageSetting ps = mSettings.mPackages.valueAt(i);
2591 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2592 // No apps are running this early, so no need to freeze
2593 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2594 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2595 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2598 ver.fingerprint = Build.FINGERPRINT;
2601 checkDefaultBrowser();
2603 // clear only after permissions and other defaults have been updated
2604 mExistingSystemPackages.clear();
2605 mPromoteSystemApps = false;
2607 // All the changes are done during package scanning.
2608 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2610 // can downgrade to reader
2611 mSettings.writeLPr();
2613 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2614 // early on (before the package manager declares itself as early) because other
2615 // components in the system server might ask for package contexts for these apps.
2617 // Note that "onlyCore" in this context means the system is encrypted or encrypting
2618 // (i.e, that the data partition is unavailable).
2619 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2620 long start = System.nanoTime();
2621 List<PackageParser.Package> coreApps = new ArrayList<>();
2622 for (PackageParser.Package pkg : mPackages.values()) {
2628 int[] stats = performDexOptUpgrade(coreApps, false,
2629 getCompilerFilterForReason(REASON_CORE_APP));
2631 final int elapsedTimeSeconds =
2632 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2633 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2636 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2637 stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2641 // TODO: Should we log these stats to tron too ?
2642 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2643 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2644 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2645 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2648 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2649 SystemClock.uptimeMillis());
2652 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2653 mRequiredInstallerPackage = getRequiredInstallerLPr();
2654 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2655 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2656 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2657 mIntentFilterVerifierComponent);
2658 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2659 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2660 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2661 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2663 mRequiredVerifierPackage = null;
2664 mRequiredInstallerPackage = null;
2665 mRequiredUninstallerPackage = null;
2666 mIntentFilterVerifierComponent = null;
2667 mIntentFilterVerifier = null;
2668 mServicesSystemSharedLibraryPackageName = null;
2669 mSharedSystemSharedLibraryPackageName = null;
2672 mInstallerService = new PackageInstallerService(context, this);
2674 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2675 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2676 // both the installer and resolver must be present to enable ephemeral
2677 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2678 if (DEBUG_EPHEMERAL) {
2679 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2680 + " installer:" + ephemeralInstallerComponent);
2682 mEphemeralResolverComponent = ephemeralResolverComponent;
2683 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2684 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2685 mEphemeralResolverConnection =
2686 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2688 if (DEBUG_EPHEMERAL) {
2689 final String missingComponent =
2690 (ephemeralResolverComponent == null)
2691 ? (ephemeralInstallerComponent == null)
2692 ? "resolver and installer"
2695 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2697 mEphemeralResolverComponent = null;
2698 mEphemeralInstallerComponent = null;
2699 mEphemeralResolverConnection = null;
2702 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2703 } // synchronized (mPackages)
2704 } // synchronized (mInstallLock)
2706 // Now after opening every single application zip, make sure they
2707 // are all flushed. Not really needed, but keeps things nice and
2709 Runtime.getRuntime().gc();
2711 // The initial scanning above does many calls into installd while
2712 // holding the mPackages lock, but we're mostly interested in yelling
2713 // once we have a booted system.
2714 mInstaller.setWarnIfHeld(mPackages);
2716 // Expose private service for system components to use.
2717 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2721 public boolean isFirstBoot() {
2726 public boolean isOnlyCoreApps() {
2731 public boolean isUpgrade() {
2735 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2736 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2738 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2739 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2740 UserHandle.USER_SYSTEM);
2741 if (matches.size() == 1) {
2742 return matches.get(0).getComponentInfo().packageName;
2743 } else if (matches.size() == 0) {
2744 Log.e(TAG, "There should probably be a verifier, but, none were found");
2747 throw new RuntimeException("There must be exactly one verifier; found " + matches);
2750 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2751 synchronized (mPackages) {
2752 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2753 if (libraryEntry == null) {
2754 throw new IllegalStateException("Missing required shared library:" + libraryName);
2756 return libraryEntry.apk;
2760 private @NonNull String getRequiredInstallerLPr() {
2761 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2762 intent.addCategory(Intent.CATEGORY_DEFAULT);
2763 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2765 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2766 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2767 UserHandle.USER_SYSTEM);
2768 if (matches.size() == 1) {
2769 ResolveInfo resolveInfo = matches.get(0);
2770 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2771 throw new RuntimeException("The installer must be a privileged app");
2773 return matches.get(0).getComponentInfo().packageName;
2775 throw new RuntimeException("There must be exactly one installer; found " + matches);
2779 private @NonNull String getRequiredUninstallerLPr() {
2780 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2781 intent.addCategory(Intent.CATEGORY_DEFAULT);
2782 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2784 final ResolveInfo resolveInfo = resolveIntent(intent, null,
2785 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2786 UserHandle.USER_SYSTEM);
2787 if (resolveInfo == null ||
2788 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2789 throw new RuntimeException("There must be exactly one uninstaller; found "
2792 return resolveInfo.getComponentInfo().packageName;
2795 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2796 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2798 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2799 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2800 UserHandle.USER_SYSTEM);
2801 ResolveInfo best = null;
2802 final int N = matches.size();
2803 for (int i = 0; i < N; i++) {
2804 final ResolveInfo cur = matches.get(i);
2805 final String packageName = cur.getComponentInfo().packageName;
2806 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2807 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2811 if (best == null || cur.priority > best.priority) {
2817 return best.getComponentInfo().getComponentName();
2819 throw new RuntimeException("There must be at least one intent filter verifier");
2823 private @Nullable ComponentName getEphemeralResolverLPr() {
2824 final String[] packageArray =
2825 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2826 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2827 if (DEBUG_EPHEMERAL) {
2828 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2833 final int resolveFlags =
2834 MATCH_DIRECT_BOOT_AWARE
2835 | MATCH_DIRECT_BOOT_UNAWARE
2836 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2837 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2838 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2839 resolveFlags, UserHandle.USER_SYSTEM);
2841 final int N = resolvers.size();
2843 if (DEBUG_EPHEMERAL) {
2844 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2849 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2850 for (int i = 0; i < N; i++) {
2851 final ResolveInfo info = resolvers.get(i);
2853 if (info.serviceInfo == null) {
2857 final String packageName = info.serviceInfo.packageName;
2858 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2859 if (DEBUG_EPHEMERAL) {
2860 Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2861 + " pkg: " + packageName + ", info:" + info);
2866 if (DEBUG_EPHEMERAL) {
2867 Slog.v(TAG, "Ephemeral resolver found;"
2868 + " pkg: " + packageName + ", info:" + info);
2870 return new ComponentName(packageName, info.serviceInfo.name);
2872 if (DEBUG_EPHEMERAL) {
2873 Slog.v(TAG, "Ephemeral resolver NOT found");
2878 private @Nullable ComponentName getEphemeralInstallerLPr() {
2879 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2880 intent.addCategory(Intent.CATEGORY_DEFAULT);
2881 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2883 final int resolveFlags =
2884 MATCH_DIRECT_BOOT_AWARE
2885 | MATCH_DIRECT_BOOT_UNAWARE
2886 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2887 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2888 resolveFlags, UserHandle.USER_SYSTEM);
2889 if (matches.size() == 0) {
2891 } else if (matches.size() == 1) {
2892 return matches.get(0).getComponentInfo().getComponentName();
2894 throw new RuntimeException(
2895 "There must be at most one ephemeral installer; found " + matches);
2899 private void primeDomainVerificationsLPw(int userId) {
2900 if (DEBUG_DOMAIN_VERIFICATION) {
2901 Slog.d(TAG, "Priming domain verifications in user " + userId);
2904 SystemConfig systemConfig = SystemConfig.getInstance();
2905 ArraySet<String> packages = systemConfig.getLinkedApps();
2906 ArraySet<String> domains = new ArraySet<String>();
2908 for (String packageName : packages) {
2909 PackageParser.Package pkg = mPackages.get(packageName);
2911 if (!pkg.isSystemApp()) {
2912 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2917 for (PackageParser.Activity a : pkg.activities) {
2918 for (ActivityIntentInfo filter : a.intents) {
2919 if (hasValidDomains(filter)) {
2920 domains.addAll(filter.getHostsList());
2925 if (domains.size() > 0) {
2926 if (DEBUG_DOMAIN_VERIFICATION) {
2927 Slog.v(TAG, " + " + packageName);
2929 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2930 // state w.r.t. the formal app-linkage "no verification attempted" state;
2931 // and then 'always' in the per-user state actually used for intent resolution.
2932 final IntentFilterVerificationInfo ivi;
2933 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2934 new ArrayList<String>(domains));
2935 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2936 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2937 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2939 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2940 + "' does not handle web links");
2943 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2947 scheduleWritePackageRestrictionsLocked(userId);
2948 scheduleWriteSettingsLocked();
2951 private void applyFactoryDefaultBrowserLPw(int userId) {
2952 // The default browser app's package name is stored in a string resource,
2953 // with a product-specific overlay used for vendor customization.
2954 String browserPkg = mContext.getResources().getString(
2955 com.android.internal.R.string.default_browser);
2956 if (!TextUtils.isEmpty(browserPkg)) {
2957 // non-empty string => required to be a known package
2958 PackageSetting ps = mSettings.mPackages.get(browserPkg);
2960 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2963 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2967 // Nothing valid explicitly set? Make the factory-installed browser the explicit
2968 // default. If there's more than one, just leave everything alone.
2969 if (browserPkg == null) {
2970 calculateDefaultBrowserLPw(userId);
2974 private void calculateDefaultBrowserLPw(int userId) {
2975 List<String> allBrowsers = resolveAllBrowserApps(userId);
2976 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2977 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2980 private List<String> resolveAllBrowserApps(int userId) {
2981 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2982 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2983 PackageManager.MATCH_ALL, userId);
2985 final int count = list.size();
2986 List<String> result = new ArrayList<String>(count);
2987 for (int i=0; i<count; i++) {
2988 ResolveInfo info = list.get(i);
2989 if (info.activityInfo == null
2990 || !info.handleAllWebDataURI
2991 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2992 || result.contains(info.activityInfo.packageName)) {
2995 result.add(info.activityInfo.packageName);
3001 private boolean packageIsBrowser(String packageName, int userId) {
3002 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3003 PackageManager.MATCH_ALL, userId);
3004 final int N = list.size();
3005 for (int i = 0; i < N; i++) {
3006 ResolveInfo info = list.get(i);
3007 if (packageName.equals(info.activityInfo.packageName)) {
3014 private void checkDefaultBrowser() {
3015 final int myUserId = UserHandle.myUserId();
3016 final String packageName = getDefaultBrowserPackageName(myUserId);
3017 if (packageName != null) {
3018 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3020 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3021 synchronized (mPackages) {
3022 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
3029 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3030 throws RemoteException {
3032 return super.onTransact(code, data, reply, flags);
3033 } catch (RuntimeException e) {
3034 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3035 Slog.wtf(TAG, "Package Manager Crash", e);
3041 static int[] appendInts(int[] cur, int[] add) {
3042 if (add == null) return cur;
3043 if (cur == null) return add;
3044 final int N = add.length;
3045 for (int i=0; i<N; i++) {
3046 cur = appendInt(cur, add[i]);
3051 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3052 if (!sUserManager.exists(userId)) return null;
3056 final PackageParser.Package p = ps.pkg;
3061 final PermissionsState permissionsState = ps.getPermissionsState();
3063 // Compute GIDs only if requested
3064 final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3065 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3066 // Compute granted permissions only if package has requested permissions
3067 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3068 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3069 final PackageUserState state = ps.readUserState(userId);
3071 return PackageParser.generatePackageInfo(p, gids, flags,
3072 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3076 public void checkPackageStartable(String packageName, int userId) {
3077 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3079 synchronized (mPackages) {
3080 final PackageSetting ps = mSettings.mPackages.get(packageName);
3082 throw new SecurityException("Package " + packageName + " was not found!");
3085 if (!ps.getInstalled(userId)) {
3086 throw new SecurityException(
3087 "Package " + packageName + " was not installed for user " + userId + "!");
3090 if (mSafeMode && !ps.isSystem()) {
3091 throw new SecurityException("Package " + packageName + " not a system app!");
3094 if (mFrozenPackages.contains(packageName)) {
3095 throw new SecurityException("Package " + packageName + " is currently frozen!");
3098 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3099 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3100 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3106 public boolean isPackageAvailable(String packageName, int userId) {
3107 if (!sUserManager.exists(userId)) return false;
3108 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3109 false /* requireFullPermission */, false /* checkShell */, "is package available");
3110 synchronized (mPackages) {
3111 PackageParser.Package p = mPackages.get(packageName);
3113 final PackageSetting ps = (PackageSetting) p.mExtras;
3115 final PackageUserState state = ps.readUserState(userId);
3116 if (state != null) {
3117 return PackageParser.isAvailable(state);
3126 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3127 if (!sUserManager.exists(userId)) return null;
3128 flags = updateFlagsForPackage(flags, userId, packageName);
3129 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3130 false /* requireFullPermission */, false /* checkShell */, "get package info");
3133 synchronized (mPackages) {
3134 // Normalize package name to hanlde renamed packages
3135 packageName = normalizePackageNameLPr(packageName);
3137 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3138 PackageParser.Package p = null;
3139 if (matchFactoryOnly) {
3140 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3142 return generatePackageInfo(ps, flags, userId);
3146 p = mPackages.get(packageName);
3147 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3151 if (DEBUG_PACKAGE_INFO)
3152 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3154 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3156 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3157 final PackageSetting ps = mSettings.mPackages.get(packageName);
3158 return generatePackageInfo(ps, flags, userId);
3165 public String[] currentToCanonicalPackageNames(String[] names) {
3166 String[] out = new String[names.length];
3168 synchronized (mPackages) {
3169 for (int i=names.length-1; i>=0; i--) {
3170 PackageSetting ps = mSettings.mPackages.get(names[i]);
3171 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3178 public String[] canonicalToCurrentPackageNames(String[] names) {
3179 String[] out = new String[names.length];
3181 synchronized (mPackages) {
3182 for (int i=names.length-1; i>=0; i--) {
3183 String cur = mSettings.mRenamedPackages.get(names[i]);
3184 out[i] = cur != null ? cur : names[i];
3191 public int getPackageUid(String packageName, int flags, int userId) {
3192 if (!sUserManager.exists(userId)) return -1;
3193 flags = updateFlagsForPackage(flags, userId, packageName);
3194 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3195 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3198 synchronized (mPackages) {
3199 final PackageParser.Package p = mPackages.get(packageName);
3200 if (p != null && p.isMatch(flags)) {
3201 return UserHandle.getUid(userId, p.applicationInfo.uid);
3203 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3204 final PackageSetting ps = mSettings.mPackages.get(packageName);
3205 if (ps != null && ps.isMatch(flags)) {
3206 return UserHandle.getUid(userId, ps.appId);
3215 public int[] getPackageGids(String packageName, int flags, int userId) {
3216 if (!sUserManager.exists(userId)) return null;
3217 flags = updateFlagsForPackage(flags, userId, packageName);
3218 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3219 false /* requireFullPermission */, false /* checkShell */,
3223 synchronized (mPackages) {
3224 final PackageParser.Package p = mPackages.get(packageName);
3225 if (p != null && p.isMatch(flags)) {
3226 PackageSetting ps = (PackageSetting) p.mExtras;
3227 return ps.getPermissionsState().computeGids(userId);
3229 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3230 final PackageSetting ps = mSettings.mPackages.get(packageName);
3231 if (ps != null && ps.isMatch(flags)) {
3232 return ps.getPermissionsState().computeGids(userId);
3240 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3241 if (bp.perm != null) {
3242 return PackageParser.generatePermissionInfo(bp.perm, flags);
3244 PermissionInfo pi = new PermissionInfo();
3246 pi.packageName = bp.sourcePackage;
3247 pi.nonLocalizedLabel = bp.name;
3248 pi.protectionLevel = bp.protectionLevel;
3253 public PermissionInfo getPermissionInfo(String name, int flags) {
3255 synchronized (mPackages) {
3256 final BasePermission p = mSettings.mPermissions.get(name);
3258 return generatePermissionInfo(p, flags);
3265 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3268 synchronized (mPackages) {
3269 if (group != null && !mPermissionGroups.containsKey(group)) {
3270 // This is thrown as NameNotFoundException
3274 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3275 for (BasePermission p : mSettings.mPermissions.values()) {
3276 if (group == null) {
3277 if (p.perm == null || p.perm.info.group == null) {
3278 out.add(generatePermissionInfo(p, flags));
3281 if (p.perm != null && group.equals(p.perm.info.group)) {
3282 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3286 return new ParceledListSlice<>(out);
3291 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3293 synchronized (mPackages) {
3294 return PackageParser.generatePermissionGroupInfo(
3295 mPermissionGroups.get(name), flags);
3300 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3302 synchronized (mPackages) {
3303 final int N = mPermissionGroups.size();
3304 ArrayList<PermissionGroupInfo> out
3305 = new ArrayList<PermissionGroupInfo>(N);
3306 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3307 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3309 return new ParceledListSlice<>(out);
3313 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3315 if (!sUserManager.exists(userId)) return null;
3316 PackageSetting ps = mSettings.mPackages.get(packageName);
3318 if (ps.pkg == null) {
3319 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3320 if (pInfo != null) {
3321 return pInfo.applicationInfo;
3325 return PackageParser.generateApplicationInfo(ps.pkg, flags,
3326 ps.readUserState(userId), userId);
3332 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3333 if (!sUserManager.exists(userId)) return null;
3334 flags = updateFlagsForApplication(flags, userId, packageName);
3335 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3336 false /* requireFullPermission */, false /* checkShell */, "get application info");
3339 synchronized (mPackages) {
3340 // Normalize package name to hanlde renamed packages
3341 packageName = normalizePackageNameLPr(packageName);
3343 PackageParser.Package p = mPackages.get(packageName);
3344 if (DEBUG_PACKAGE_INFO) Log.v(
3345 TAG, "getApplicationInfo " + packageName
3348 PackageSetting ps = mSettings.mPackages.get(packageName);
3349 if (ps == null) return null;
3350 // Note: isEnabledLP() does not apply here - always return info
3351 return PackageParser.generateApplicationInfo(
3352 p, flags, ps.readUserState(userId), userId);
3354 if ("android".equals(packageName)||"system".equals(packageName)) {
3355 return mAndroidApplication;
3357 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3358 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3364 private String normalizePackageNameLPr(String packageName) {
3365 String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3366 return normalizedPackageName != null ? normalizedPackageName : packageName;
3370 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3371 final IPackageDataObserver observer) {
3372 mContext.enforceCallingOrSelfPermission(
3373 android.Manifest.permission.CLEAR_APP_CACHE, null);
3374 // Queue up an async operation since clearing cache may take a little while.
3375 mHandler.post(new Runnable() {
3377 mHandler.removeCallbacks(this);
3378 boolean success = true;
3379 synchronized (mInstallLock) {
3381 mInstaller.freeCache(volumeUuid, freeStorageSize);
3382 } catch (InstallerException e) {
3383 Slog.w(TAG, "Couldn't clear application caches: " + e);
3387 if (observer != null) {
3389 observer.onRemoveCompleted(null, success);
3390 } catch (RemoteException e) {
3391 Slog.w(TAG, "RemoveException when invoking call back");
3399 public void freeStorage(final String volumeUuid, final long freeStorageSize,
3400 final IntentSender pi) {
3401 mContext.enforceCallingOrSelfPermission(
3402 android.Manifest.permission.CLEAR_APP_CACHE, null);
3403 // Queue up an async operation since clearing cache may take a little while.
3404 mHandler.post(new Runnable() {
3406 mHandler.removeCallbacks(this);
3407 boolean success = true;
3408 synchronized (mInstallLock) {
3410 mInstaller.freeCache(volumeUuid, freeStorageSize);
3411 } catch (InstallerException e) {
3412 Slog.w(TAG, "Couldn't clear application caches: " + e);
3418 // Callback via pending intent
3419 int code = success ? 1 : 0;
3420 pi.sendIntent(null, code, null,
3422 } catch (SendIntentException e1) {
3423 Slog.i(TAG, "Failed to send pending intent");
3430 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3431 synchronized (mInstallLock) {
3433 mInstaller.freeCache(volumeUuid, freeStorageSize);
3434 } catch (InstallerException e) {
3435 throw new IOException("Failed to free enough space", e);
3441 * Update given flags based on encryption status of current user.
3443 private int updateFlags(int flags, int userId) {
3444 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3445 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3446 // Caller expressed an explicit opinion about what encryption
3447 // aware/unaware components they want to see, so fall through and
3448 // give them what they want
3450 // Caller expressed no opinion, so match based on user state
3451 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3452 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3454 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3460 private UserManagerInternal getUserManagerInternal() {
3461 if (mUserManagerInternal == null) {
3462 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3464 return mUserManagerInternal;
3468 * Update given flags when being used to request {@link PackageInfo}.
3470 private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3471 boolean triaged = true;
3472 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3473 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3474 // Caller is asking for component details, so they'd better be
3475 // asking for specific encryption matching behavior, or be triaged
3476 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3477 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3478 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3482 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3483 | PackageManager.MATCH_SYSTEM_ONLY
3484 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3487 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3488 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3489 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3491 return updateFlags(flags, userId);
3495 * Update given flags when being used to request {@link ApplicationInfo}.
3497 private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3498 return updateFlagsForPackage(flags, userId, cookie);
3502 * Update given flags when being used to request {@link ComponentInfo}.
3504 private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3505 if (cookie instanceof Intent) {
3506 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3507 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3511 boolean triaged = true;
3512 // Caller is asking for component details, so they'd better be
3513 // asking for specific encryption matching behavior, or be triaged
3514 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3515 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3516 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3519 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3520 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3521 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3524 return updateFlags(flags, userId);
3528 * Update given flags when being used to request {@link ResolveInfo}.
3530 int updateFlagsForResolve(int flags, int userId, Object cookie) {
3531 // Safe mode means we shouldn't match any third-party components
3533 flags |= PackageManager.MATCH_SYSTEM_ONLY;
3536 return updateFlagsForComponent(flags, userId, cookie);
3540 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3541 if (!sUserManager.exists(userId)) return null;
3542 flags = updateFlagsForComponent(flags, userId, component);
3543 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3544 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3545 synchronized (mPackages) {
3546 PackageParser.Activity a = mActivities.mActivities.get(component);
3548 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3549 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3550 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3551 if (ps == null) return null;
3552 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3555 if (mResolveComponentName.equals(component)) {
3556 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3557 new PackageUserState(), userId);
3564 public boolean activitySupportsIntent(ComponentName component, Intent intent,
3565 String resolvedType) {
3566 synchronized (mPackages) {
3567 if (component.equals(mResolveComponentName)) {
3568 // The resolver supports EVERYTHING!
3571 PackageParser.Activity a = mActivities.mActivities.get(component);
3575 for (int i=0; i<a.intents.size(); i++) {
3576 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3577 intent.getData(), intent.getCategories(), TAG) >= 0) {
3586 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3587 if (!sUserManager.exists(userId)) return null;
3588 flags = updateFlagsForComponent(flags, userId, component);
3589 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3590 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3591 synchronized (mPackages) {
3592 PackageParser.Activity a = mReceivers.mActivities.get(component);
3593 if (DEBUG_PACKAGE_INFO) Log.v(
3594 TAG, "getReceiverInfo " + component + ": " + a);
3595 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3596 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3597 if (ps == null) return null;
3598 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3606 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3607 if (!sUserManager.exists(userId)) return null;
3608 flags = updateFlagsForComponent(flags, userId, component);
3609 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3610 false /* requireFullPermission */, false /* checkShell */, "get service info");
3611 synchronized (mPackages) {
3612 PackageParser.Service s = mServices.mServices.get(component);
3613 if (DEBUG_PACKAGE_INFO) Log.v(
3614 TAG, "getServiceInfo " + component + ": " + s);
3615 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3616 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3617 if (ps == null) return null;
3618 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3626 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3627 if (!sUserManager.exists(userId)) return null;
3628 flags = updateFlagsForComponent(flags, userId, component);
3629 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3630 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3631 synchronized (mPackages) {
3632 PackageParser.Provider p = mProviders.mProviders.get(component);
3633 if (DEBUG_PACKAGE_INFO) Log.v(
3634 TAG, "getProviderInfo " + component + ": " + p);
3635 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3636 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3637 if (ps == null) return null;
3638 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3646 public String[] getSystemSharedLibraryNames() {
3648 synchronized (mPackages) {
3649 libSet = mSharedLibraries.keySet();
3650 int size = libSet.size();
3652 String[] libs = new String[size];
3653 libSet.toArray(libs);
3661 public @NonNull String getServicesSystemSharedLibraryPackageName() {
3662 synchronized (mPackages) {
3663 return mServicesSystemSharedLibraryPackageName;
3668 public @NonNull String getSharedSystemSharedLibraryPackageName() {
3669 synchronized (mPackages) {
3670 return mSharedSystemSharedLibraryPackageName;
3675 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3676 synchronized (mPackages) {
3677 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3679 final FeatureInfo fi = new FeatureInfo();
3680 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3681 FeatureInfo.GL_ES_VERSION_UNDEFINED);
3684 return new ParceledListSlice<>(res);
3689 public boolean hasSystemFeature(String name, int version) {
3690 synchronized (mPackages) {
3691 final FeatureInfo feat = mAvailableFeatures.get(name);
3695 return feat.version >= version;
3701 public int checkPermission(String permName, String pkgName, int userId) {
3702 if (!sUserManager.exists(userId)) {
3703 return PackageManager.PERMISSION_DENIED;
3706 synchronized (mPackages) {
3707 final PackageParser.Package p = mPackages.get(pkgName);
3708 if (p != null && p.mExtras != null) {
3709 final PackageSetting ps = (PackageSetting) p.mExtras;
3710 final PermissionsState permissionsState = ps.getPermissionsState();
3711 if (permissionsState.hasPermission(permName, userId)) {
3712 return PackageManager.PERMISSION_GRANTED;
3714 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3715 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3716 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3717 return PackageManager.PERMISSION_GRANTED;
3722 return PackageManager.PERMISSION_DENIED;
3726 public int checkUidPermission(String permName, int uid) {
3727 final int userId = UserHandle.getUserId(uid);
3729 if (!sUserManager.exists(userId)) {
3730 return PackageManager.PERMISSION_DENIED;
3733 synchronized (mPackages) {
3734 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3736 final SettingBase ps = (SettingBase) obj;
3737 final PermissionsState permissionsState = ps.getPermissionsState();
3738 if (permissionsState.hasPermission(permName, userId)) {
3739 return PackageManager.PERMISSION_GRANTED;
3741 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3742 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3743 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3744 return PackageManager.PERMISSION_GRANTED;
3747 ArraySet<String> perms = mSystemPermissions.get(uid);
3748 if (perms != null) {
3749 if (perms.contains(permName)) {
3750 return PackageManager.PERMISSION_GRANTED;
3752 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3753 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3754 return PackageManager.PERMISSION_GRANTED;
3760 return PackageManager.PERMISSION_DENIED;
3764 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3765 if (UserHandle.getCallingUserId() != userId) {
3766 mContext.enforceCallingPermission(
3767 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3768 "isPermissionRevokedByPolicy for user " + userId);
3771 if (checkPermission(permission, packageName, userId)
3772 == PackageManager.PERMISSION_GRANTED) {
3776 final long identity = Binder.clearCallingIdentity();
3778 final int flags = getPermissionFlags(permission, packageName, userId);
3779 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3781 Binder.restoreCallingIdentity(identity);
3786 public String getPermissionControllerPackageName() {
3787 synchronized (mPackages) {
3788 return mRequiredInstallerPackage;
3793 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3794 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3795 * @param checkShell whether to prevent shell from access if there's a debugging restriction
3796 * @param message the message to log on security exception
3798 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3799 boolean checkShell, String message) {
3800 enforceCrossUserPermission(
3803 requireFullPermission,
3809 private void enforceCrossUserPermission(int callingUid, int userId,
3810 boolean requireFullPermission, boolean checkShell,
3811 boolean requirePermissionWhenSameUser, String message) {
3813 throw new IllegalArgumentException("Invalid userId " + userId);
3816 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3818 if (!requirePermissionWhenSameUser && userId == UserHandle.getUserId(callingUid)) return;
3819 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3820 if (requireFullPermission) {
3821 mContext.enforceCallingOrSelfPermission(
3822 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3825 mContext.enforceCallingOrSelfPermission(
3826 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3827 } catch (SecurityException se) {
3828 mContext.enforceCallingOrSelfPermission(
3829 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3835 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3836 if (callingUid == Process.SHELL_UID) {
3838 && sUserManager.hasUserRestriction(restriction, userHandle)) {
3839 throw new SecurityException("Shell does not have permission to access user "
3841 } else if (userHandle < 0) {
3842 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3843 + Debug.getCallers(3));
3848 private BasePermission findPermissionTreeLP(String permName) {
3849 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3850 if (permName.startsWith(bp.name) &&
3851 permName.length() > bp.name.length() &&
3852 permName.charAt(bp.name.length()) == '.') {
3859 private BasePermission checkPermissionTreeLP(String permName) {
3860 if (permName != null) {
3861 BasePermission bp = findPermissionTreeLP(permName);
3863 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3866 throw new SecurityException("Calling uid "
3867 + Binder.getCallingUid()
3868 + " is not allowed to add to permission tree "
3869 + bp.name + " owned by uid " + bp.uid);
3872 throw new SecurityException("No permission tree found for " + permName);
3875 static boolean compareStrings(CharSequence s1, CharSequence s2) {
3882 if (s1.getClass() != s2.getClass()) {
3885 return s1.equals(s2);
3888 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3889 if (pi1.icon != pi2.icon) return false;
3890 if (pi1.logo != pi2.logo) return false;
3891 if (pi1.protectionLevel != pi2.protectionLevel) return false;
3892 if (!compareStrings(pi1.name, pi2.name)) return false;
3893 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3894 // We'll take care of setting this one.
3895 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3896 // These are not currently stored in settings.
3897 //if (!compareStrings(pi1.group, pi2.group)) return false;
3898 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3899 //if (pi1.labelRes != pi2.labelRes) return false;
3900 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3904 int permissionInfoFootprint(PermissionInfo info) {
3905 int size = info.name.length();
3906 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3907 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3911 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3913 for (BasePermission perm : mSettings.mPermissions.values()) {
3914 if (perm.uid == tree.uid) {
3915 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3921 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3922 // We calculate the max size of permissions defined by this uid and throw
3923 // if that plus the size of 'info' would exceed our stated maximum.
3924 if (tree.uid != Process.SYSTEM_UID) {
3925 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3926 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3927 throw new SecurityException("Permission tree size cap exceeded");
3932 boolean addPermissionLocked(PermissionInfo info, boolean async) {
3933 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3934 throw new SecurityException("Label must be specified in permission");
3936 BasePermission tree = checkPermissionTreeLP(info.name);
3937 BasePermission bp = mSettings.mPermissions.get(info.name);
3938 boolean added = bp == null;
3939 boolean changed = true;
3940 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3942 enforcePermissionCapLocked(info, tree);
3943 bp = new BasePermission(info.name, tree.sourcePackage,
3944 BasePermission.TYPE_DYNAMIC);
3945 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3946 throw new SecurityException(
3947 "Not allowed to modify non-dynamic permission "
3950 if (bp.protectionLevel == fixedLevel
3951 && bp.perm.owner.equals(tree.perm.owner)
3952 && bp.uid == tree.uid
3953 && comparePermissionInfos(bp.perm.info, info)) {
3957 bp.protectionLevel = fixedLevel;
3958 info = new PermissionInfo(info);
3959 info.protectionLevel = fixedLevel;
3960 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3961 bp.perm.info.packageName = tree.perm.info.packageName;
3964 mSettings.mPermissions.put(info.name, bp);
3968 mSettings.writeLPr();
3970 scheduleWriteSettingsLocked();
3977 public boolean addPermission(PermissionInfo info) {
3978 synchronized (mPackages) {
3979 return addPermissionLocked(info, false);
3984 public boolean addPermissionAsync(PermissionInfo info) {
3985 synchronized (mPackages) {
3986 return addPermissionLocked(info, true);
3991 public void removePermission(String name) {
3992 synchronized (mPackages) {
3993 checkPermissionTreeLP(name);
3994 BasePermission bp = mSettings.mPermissions.get(name);
3996 if (bp.type != BasePermission.TYPE_DYNAMIC) {
3997 throw new SecurityException(
3998 "Not allowed to modify non-dynamic permission "
4001 mSettings.mPermissions.remove(name);
4002 mSettings.writeLPr();
4007 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4008 BasePermission bp) {
4009 int index = pkg.requestedPermissions.indexOf(bp.name);
4011 throw new SecurityException("Package " + pkg.packageName
4012 + " has not requested permission " + bp.name);
4014 if (!bp.isRuntime() && !bp.isDevelopment()) {
4015 throw new SecurityException("Permission " + bp.name
4016 + " is not a changeable permission type");
4021 public void grantRuntimePermission(String packageName, String name, final int userId) {
4022 if (!sUserManager.exists(userId)) {
4023 Log.e(TAG, "No such user:" + userId);
4027 mContext.enforceCallingOrSelfPermission(
4028 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4029 "grantRuntimePermission");
4031 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4032 true /* requireFullPermission */, true /* checkShell */,
4033 "grantRuntimePermission");
4036 final SettingBase sb;
4038 synchronized (mPackages) {
4039 final PackageParser.Package pkg = mPackages.get(packageName);
4041 throw new IllegalArgumentException("Unknown package: " + packageName);
4044 final BasePermission bp = mSettings.mPermissions.get(name);
4046 throw new IllegalArgumentException("Unknown permission: " + name);
4049 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4051 // If a permission review is required for legacy apps we represent
4052 // their permissions as always granted runtime ones since we need
4053 // to keep the review required permission flag per user while an
4054 // install permission's state is shared across all users.
4055 if (Build.PERMISSIONS_REVIEW_REQUIRED
4056 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4057 && bp.isRuntime()) {
4061 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4062 sb = (SettingBase) pkg.mExtras;
4064 throw new IllegalArgumentException("Unknown package: " + packageName);
4067 final PermissionsState permissionsState = sb.getPermissionsState();
4069 final int flags = permissionsState.getPermissionFlags(name, userId);
4070 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4071 throw new SecurityException("Cannot grant system fixed permission "
4072 + name + " for package " + packageName);
4075 if (bp.isDevelopment()) {
4076 // Development permissions must be handled specially, since they are not
4077 // normal runtime permissions. For now they apply to all users.
4078 if (permissionsState.grantInstallPermission(bp) !=
4079 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4080 scheduleWriteSettingsLocked();
4085 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4086 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4090 final int result = permissionsState.grantRuntimePermission(bp, userId);
4092 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4096 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4097 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4098 mHandler.post(new Runnable() {
4101 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4108 mOnPermissionChangeListeners.onPermissionsChanged(uid);
4110 // Not critical if that is lost - app has to request again.
4111 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4114 // Only need to do this if user is initialized. Otherwise it's a new user
4115 // and there are no processes running as the user yet and there's no need
4116 // to make an expensive call to remount processes for the changed permissions.
4117 if (READ_EXTERNAL_STORAGE.equals(name)
4118 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4119 final long token = Binder.clearCallingIdentity();
4121 if (sUserManager.isInitialized(userId)) {
4122 MountServiceInternal mountServiceInternal = LocalServices.getService(
4123 MountServiceInternal.class);
4124 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4127 Binder.restoreCallingIdentity(token);
4133 public void revokeRuntimePermission(String packageName, String name, int userId) {
4134 if (!sUserManager.exists(userId)) {
4135 Log.e(TAG, "No such user:" + userId);
4139 mContext.enforceCallingOrSelfPermission(
4140 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4141 "revokeRuntimePermission");
4143 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4144 true /* requireFullPermission */, true /* checkShell */,
4145 "revokeRuntimePermission");
4149 synchronized (mPackages) {
4150 final PackageParser.Package pkg = mPackages.get(packageName);
4152 throw new IllegalArgumentException("Unknown package: " + packageName);
4155 final BasePermission bp = mSettings.mPermissions.get(name);
4157 throw new IllegalArgumentException("Unknown permission: " + name);
4160 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4162 // If a permission review is required for legacy apps we represent
4163 // their permissions as always granted runtime ones since we need
4164 // to keep the review required permission flag per user while an
4165 // install permission's state is shared across all users.
4166 if (Build.PERMISSIONS_REVIEW_REQUIRED
4167 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4168 && bp.isRuntime()) {
4172 SettingBase sb = (SettingBase) pkg.mExtras;
4174 throw new IllegalArgumentException("Unknown package: " + packageName);
4177 final PermissionsState permissionsState = sb.getPermissionsState();
4179 final int flags = permissionsState.getPermissionFlags(name, userId);
4180 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4181 throw new SecurityException("Cannot revoke system fixed permission "
4182 + name + " for package " + packageName);
4185 if (bp.isDevelopment()) {
4186 // Development permissions must be handled specially, since they are not
4187 // normal runtime permissions. For now they apply to all users.
4188 if (permissionsState.revokeInstallPermission(bp) !=
4189 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4190 scheduleWriteSettingsLocked();
4195 if (permissionsState.revokeRuntimePermission(bp, userId) ==
4196 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4200 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4202 // Critical, after this call app should never have the permission.
4203 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4205 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4208 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4212 * We might auto-grant permissions if any permission of the group is already granted. Hence if
4213 * the group of a granted permission changes we need to revoke it to avoid having permissions of
4214 * the new group auto-granted.
4216 * @param newPackage The new package that was installed
4217 * @param oldPackage The old package that was updated
4218 * @param allPackageNames All package names
4220 private void revokeRuntimePermissionsIfGroupChanged(
4221 PackageParser.Package newPackage,
4222 PackageParser.Package oldPackage,
4223 ArrayList<String> allPackageNames) {
4224 final int numOldPackagePermissions = oldPackage.permissions.size();
4225 final ArrayMap<String, String> oldPermissionNameToGroupName
4226 = new ArrayMap<>(numOldPackagePermissions);
4228 for (int i = 0; i < numOldPackagePermissions; i++) {
4229 final PackageParser.Permission permission = oldPackage.permissions.get(i);
4231 if (permission.group != null) {
4232 oldPermissionNameToGroupName.put(permission.info.name,
4233 permission.group.info.name);
4237 final int numNewPackagePermissions = newPackage.permissions.size();
4238 for (int newPermissionNum = 0; newPermissionNum < numNewPackagePermissions;
4239 newPermissionNum++) {
4240 final PackageParser.Permission newPermission =
4241 newPackage.permissions.get(newPermissionNum);
4242 final int newProtection = newPermission.info.protectionLevel;
4244 if ((newProtection & PermissionInfo.PROTECTION_DANGEROUS) != 0) {
4245 final String permissionName = newPermission.info.name;
4246 final String newPermissionGroupName =
4247 newPermission.group == null ? null : newPermission.group.info.name;
4248 final String oldPermissionGroupName = oldPermissionNameToGroupName.get(
4251 if (newPermissionGroupName != null
4252 && !newPermissionGroupName.equals(oldPermissionGroupName)) {
4253 final List<UserInfo> users = mContext.getSystemService(UserManager.class)
4256 final int numUsers = users.size();
4257 for (int userNum = 0; userNum < numUsers; userNum++) {
4258 final int userId = users.get(userNum).id;
4259 final int numPackages = allPackageNames.size();
4260 for (int packageNum = 0; packageNum < numPackages; packageNum++) {
4261 final String packageName = allPackageNames.get(packageNum);
4263 if (checkPermission(permissionName, packageName, userId)
4264 == PackageManager.PERMISSION_GRANTED) {
4265 EventLog.writeEvent(0x534e4554, "72710897",
4266 newPackage.applicationInfo.uid,
4267 "Revoking permission", permissionName, "from package",
4268 packageName, "as the group changed from",
4269 oldPermissionGroupName, "to", newPermissionGroupName);
4272 revokeRuntimePermission(packageName, permissionName, userId);
4273 } catch (IllegalArgumentException e) {
4274 Slog.e(TAG, "Could not revoke " + permissionName + " from "
4287 public void resetRuntimePermissions() {
4288 mContext.enforceCallingOrSelfPermission(
4289 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4290 "revokeRuntimePermission");
4292 int callingUid = Binder.getCallingUid();
4293 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4294 mContext.enforceCallingOrSelfPermission(
4295 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4296 "resetRuntimePermissions");
4299 synchronized (mPackages) {
4300 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4301 for (int userId : UserManagerService.getInstance().getUserIds()) {
4302 final int packageCount = mPackages.size();
4303 for (int i = 0; i < packageCount; i++) {
4304 PackageParser.Package pkg = mPackages.valueAt(i);
4305 if (!(pkg.mExtras instanceof PackageSetting)) {
4308 PackageSetting ps = (PackageSetting) pkg.mExtras;
4309 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4316 public int getPermissionFlags(String name, String packageName, int userId) {
4317 if (!sUserManager.exists(userId)) {
4321 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4323 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4324 true /* requireFullPermission */, false /* checkShell */,
4325 "getPermissionFlags");
4327 synchronized (mPackages) {
4328 final PackageParser.Package pkg = mPackages.get(packageName);
4333 final BasePermission bp = mSettings.mPermissions.get(name);
4338 SettingBase sb = (SettingBase) pkg.mExtras;
4343 PermissionsState permissionsState = sb.getPermissionsState();
4344 return permissionsState.getPermissionFlags(name, userId);
4349 public void updatePermissionFlags(String name, String packageName, int flagMask,
4350 int flagValues, int userId) {
4351 if (!sUserManager.exists(userId)) {
4355 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4357 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4358 true /* requireFullPermission */, true /* checkShell */,
4359 "updatePermissionFlags");
4361 // Only the system can change these flags and nothing else.
4362 if (getCallingUid() != Process.SYSTEM_UID) {
4363 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4364 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4365 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4366 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4367 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4370 synchronized (mPackages) {
4371 final PackageParser.Package pkg = mPackages.get(packageName);
4373 throw new IllegalArgumentException("Unknown package: " + packageName);
4376 final BasePermission bp = mSettings.mPermissions.get(name);
4378 throw new IllegalArgumentException("Unknown permission: " + name);
4381 SettingBase sb = (SettingBase) pkg.mExtras;
4383 throw new IllegalArgumentException("Unknown package: " + packageName);
4386 PermissionsState permissionsState = sb.getPermissionsState();
4388 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4390 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4391 // Install and runtime permissions are stored in different places,
4392 // so figure out what permission changed and persist the change.
4393 if (permissionsState.getInstallPermissionState(name) != null) {
4394 scheduleWriteSettingsLocked();
4395 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4397 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4404 * Update the permission flags for all packages and runtime permissions of a user in order
4405 * to allow device or profile owner to remove POLICY_FIXED.
4408 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4409 if (!sUserManager.exists(userId)) {
4413 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4415 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4416 true /* requireFullPermission */, true /* checkShell */,
4417 "updatePermissionFlagsForAllApps");
4419 // Only the system can change system fixed flags.
4420 if (getCallingUid() != Process.SYSTEM_UID) {
4421 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4422 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4425 synchronized (mPackages) {
4426 boolean changed = false;
4427 final int packageCount = mPackages.size();
4428 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4429 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4430 SettingBase sb = (SettingBase) pkg.mExtras;
4434 PermissionsState permissionsState = sb.getPermissionsState();
4435 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4436 userId, flagMask, flagValues);
4439 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4444 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4445 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4446 != PackageManager.PERMISSION_GRANTED
4447 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4448 != PackageManager.PERMISSION_GRANTED) {
4449 throw new SecurityException(message + " requires "
4450 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4451 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4456 public boolean shouldShowRequestPermissionRationale(String permissionName,
4457 String packageName, int userId) {
4458 if (UserHandle.getCallingUserId() != userId) {
4459 mContext.enforceCallingPermission(
4460 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4461 "canShowRequestPermissionRationale for user " + userId);
4464 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4465 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4469 if (checkPermission(permissionName, packageName, userId)
4470 == PackageManager.PERMISSION_GRANTED) {
4476 final long identity = Binder.clearCallingIdentity();
4478 flags = getPermissionFlags(permissionName,
4479 packageName, userId);
4481 Binder.restoreCallingIdentity(identity);
4484 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4485 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4486 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4488 if ((flags & fixedFlags) != 0) {
4492 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4496 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4497 mContext.enforceCallingOrSelfPermission(
4498 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4499 "addOnPermissionsChangeListener");
4501 synchronized (mPackages) {
4502 mOnPermissionChangeListeners.addListenerLocked(listener);
4507 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4508 synchronized (mPackages) {
4509 mOnPermissionChangeListeners.removeListenerLocked(listener);
4514 public boolean isProtectedBroadcast(String actionName) {
4515 synchronized (mPackages) {
4516 if (mProtectedBroadcasts.contains(actionName)) {
4518 } else if (actionName != null) {
4519 // TODO: remove these terrible hacks
4520 if (actionName.startsWith("android.net.netmon.lingerExpired")
4521 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4522 || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4523 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4532 public int checkSignatures(String pkg1, String pkg2) {
4533 synchronized (mPackages) {
4534 final PackageParser.Package p1 = mPackages.get(pkg1);
4535 final PackageParser.Package p2 = mPackages.get(pkg2);
4536 if (p1 == null || p1.mExtras == null
4537 || p2 == null || p2.mExtras == null) {
4538 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4540 return compareSignatures(p1.mSignatures, p2.mSignatures);
4545 public int checkUidSignatures(int uid1, int uid2) {
4546 // Map to base uids.
4547 uid1 = UserHandle.getAppId(uid1);
4548 uid2 = UserHandle.getAppId(uid2);
4550 synchronized (mPackages) {
4553 Object obj = mSettings.getUserIdLPr(uid1);
4555 if (obj instanceof SharedUserSetting) {
4556 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4557 } else if (obj instanceof PackageSetting) {
4558 s1 = ((PackageSetting)obj).signatures.mSignatures;
4560 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4563 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4565 obj = mSettings.getUserIdLPr(uid2);
4567 if (obj instanceof SharedUserSetting) {
4568 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4569 } else if (obj instanceof PackageSetting) {
4570 s2 = ((PackageSetting)obj).signatures.mSignatures;
4572 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4575 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4577 return compareSignatures(s1, s2);
4582 * This method should typically only be used when granting or revoking
4583 * permissions, since the app may immediately restart after this call.
4585 * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4586 * guard your work against the app being relaunched.
4588 private void killUid(int appId, int userId, String reason) {
4589 final long identity = Binder.clearCallingIdentity();
4591 IActivityManager am = ActivityManagerNative.getDefault();
4594 am.killUid(appId, userId, reason);
4595 } catch (RemoteException e) {
4596 /* ignore - same process */
4600 Binder.restoreCallingIdentity(identity);
4605 * Compares two sets of signatures. Returns:
4607 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4609 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4611 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4613 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4615 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4617 static int compareSignatures(Signature[] s1, Signature[] s2) {
4620 ? PackageManager.SIGNATURE_NEITHER_SIGNED
4621 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4625 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4628 if (s1.length != s2.length) {
4629 return PackageManager.SIGNATURE_NO_MATCH;
4632 // Since both signature sets are of size 1, we can compare without HashSets.
4633 if (s1.length == 1) {
4634 return s1[0].equals(s2[0]) ?
4635 PackageManager.SIGNATURE_MATCH :
4636 PackageManager.SIGNATURE_NO_MATCH;
4639 ArraySet<Signature> set1 = new ArraySet<Signature>();
4640 for (Signature sig : s1) {
4643 ArraySet<Signature> set2 = new ArraySet<Signature>();
4644 for (Signature sig : s2) {
4647 // Make sure s2 contains all signatures in s1.
4648 if (set1.equals(set2)) {
4649 return PackageManager.SIGNATURE_MATCH;
4651 return PackageManager.SIGNATURE_NO_MATCH;
4655 * If the database version for this type of package (internal storage or
4656 * external storage) is less than the version where package signatures
4657 * were updated, return true.
4659 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4660 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4661 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4665 * Used for backward compatibility to make sure any packages with
4666 * certificate chains get upgraded to the new style. {@code existingSigs}
4667 * will be in the old format (since they were stored on disk from before the
4668 * system upgrade) and {@code scannedSigs} will be in the newer format.
4670 private int compareSignaturesCompat(PackageSignatures existingSigs,
4671 PackageParser.Package scannedPkg) {
4672 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4673 return PackageManager.SIGNATURE_NO_MATCH;
4676 ArraySet<Signature> existingSet = new ArraySet<Signature>();
4677 for (Signature sig : existingSigs.mSignatures) {
4678 existingSet.add(sig);
4680 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4681 for (Signature sig : scannedPkg.mSignatures) {
4683 Signature[] chainSignatures = sig.getChainSignatures();
4684 for (Signature chainSig : chainSignatures) {
4685 scannedCompatSet.add(chainSig);
4687 } catch (CertificateEncodingException e) {
4688 scannedCompatSet.add(sig);
4692 * Make sure the expanded scanned set contains all signatures in the
4695 if (scannedCompatSet.equals(existingSet)) {
4696 // Migrate the old signatures to the new scheme.
4697 existingSigs.assignSignatures(scannedPkg.mSignatures);
4698 // The new KeySets will be re-added later in the scanning process.
4699 synchronized (mPackages) {
4700 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4702 return PackageManager.SIGNATURE_MATCH;
4704 return PackageManager.SIGNATURE_NO_MATCH;
4707 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4708 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4709 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4712 private int compareSignaturesRecover(PackageSignatures existingSigs,
4713 PackageParser.Package scannedPkg) {
4714 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4715 return PackageManager.SIGNATURE_NO_MATCH;
4720 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4721 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4722 + scannedPkg.packageName);
4723 return PackageManager.SIGNATURE_MATCH;
4725 } catch (CertificateException e) {
4726 msg = e.getMessage();
4729 logCriticalInfo(Log.INFO,
4730 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4731 return PackageManager.SIGNATURE_NO_MATCH;
4735 public List<String> getAllPackages() {
4736 synchronized (mPackages) {
4737 return new ArrayList<String>(mPackages.keySet());
4742 public String[] getPackagesForUid(int uid) {
4743 uid = UserHandle.getAppId(uid);
4745 synchronized (mPackages) {
4746 Object obj = mSettings.getUserIdLPr(uid);
4747 if (obj instanceof SharedUserSetting) {
4748 final SharedUserSetting sus = (SharedUserSetting) obj;
4749 final int N = sus.packages.size();
4750 final String[] res = new String[N];
4751 for (int i = 0; i < N; i++) {
4752 res[i] = sus.packages.valueAt(i).name;
4755 } else if (obj instanceof PackageSetting) {
4756 final PackageSetting ps = (PackageSetting) obj;
4757 return new String[] { ps.name };
4764 public String getNameForUid(int uid) {
4766 synchronized (mPackages) {
4767 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4768 if (obj instanceof SharedUserSetting) {
4769 final SharedUserSetting sus = (SharedUserSetting) obj;
4770 return sus.name + ":" + sus.userId;
4771 } else if (obj instanceof PackageSetting) {
4772 final PackageSetting ps = (PackageSetting) obj;
4780 public int getUidForSharedUser(String sharedUserName) {
4781 if(sharedUserName == null) {
4785 synchronized (mPackages) {
4786 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4795 public int getFlagsForUid(int uid) {
4796 synchronized (mPackages) {
4797 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4798 if (obj instanceof SharedUserSetting) {
4799 final SharedUserSetting sus = (SharedUserSetting) obj;
4800 return sus.pkgFlags;
4801 } else if (obj instanceof PackageSetting) {
4802 final PackageSetting ps = (PackageSetting) obj;
4810 public int getPrivateFlagsForUid(int uid) {
4811 synchronized (mPackages) {
4812 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4813 if (obj instanceof SharedUserSetting) {
4814 final SharedUserSetting sus = (SharedUserSetting) obj;
4815 return sus.pkgPrivateFlags;
4816 } else if (obj instanceof PackageSetting) {
4817 final PackageSetting ps = (PackageSetting) obj;
4818 return ps.pkgPrivateFlags;
4825 public boolean isUidPrivileged(int uid) {
4826 uid = UserHandle.getAppId(uid);
4828 synchronized (mPackages) {
4829 Object obj = mSettings.getUserIdLPr(uid);
4830 if (obj instanceof SharedUserSetting) {
4831 final SharedUserSetting sus = (SharedUserSetting) obj;
4832 final Iterator<PackageSetting> it = sus.packages.iterator();
4833 while (it.hasNext()) {
4834 if (it.next().isPrivileged()) {
4838 } else if (obj instanceof PackageSetting) {
4839 final PackageSetting ps = (PackageSetting) obj;
4840 return ps.isPrivileged();
4847 public String[] getAppOpPermissionPackages(String permissionName) {
4848 synchronized (mPackages) {
4849 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4853 return pkgs.toArray(new String[pkgs.size()]);
4858 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4859 int flags, int userId) {
4861 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4863 if (!sUserManager.exists(userId)) return null;
4864 flags = updateFlagsForResolve(flags, userId, intent);
4865 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4866 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4868 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4869 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4871 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4873 final ResolveInfo bestChoice =
4874 chooseBestActivity(intent, resolvedType, flags, query, userId);
4877 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4882 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4883 IntentFilter filter, int match, ComponentName activity) {
4884 final int userId = UserHandle.getCallingUserId();
4885 if (DEBUG_PREFERRED) {
4886 Log.v(TAG, "setLastChosenActivity intent=" + intent
4887 + " resolvedType=" + resolvedType
4889 + " filter=" + filter
4891 + " activity=" + activity);
4892 filter.dump(new PrintStreamPrinter(System.out), " ");
4894 intent.setComponent(null);
4895 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4897 // Find any earlier preferred or last chosen entries and nuke them
4898 findPreferredActivity(intent, resolvedType,
4899 flags, query, 0, false, true, false, userId);
4900 // Add the new activity as the last chosen for this filter
4901 addPreferredActivityInternal(filter, match, null, activity, false, userId,
4902 "Setting last chosen");
4906 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4907 final int userId = UserHandle.getCallingUserId();
4908 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4909 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4911 return findPreferredActivity(intent, resolvedType, flags, query, 0,
4912 false, false, false, userId);
4915 private boolean isEphemeralDisabled() {
4916 // ephemeral apps have been disabled across the board
4917 if (DISABLE_EPHEMERAL_APPS) {
4920 // system isn't up yet; can't read settings, so, assume no ephemeral apps
4921 if (!mSystemReady) {
4924 // we can't get a content resolver until the system is ready; these checks must happen last
4925 final ContentResolver resolver = mContext.getContentResolver();
4926 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4929 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4932 private boolean isEphemeralAllowed(
4933 Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4934 boolean skipPackageCheck) {
4935 // Short circuit and return early if possible.
4936 if (isEphemeralDisabled()) {
4939 final int callingUser = UserHandle.getCallingUserId();
4940 if (callingUser != UserHandle.USER_SYSTEM) {
4943 if (mEphemeralResolverConnection == null) {
4946 if (intent.getComponent() != null) {
4949 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4952 if (!skipPackageCheck && intent.getPackage() != null) {
4955 final boolean isWebUri = hasWebURI(intent);
4956 if (!isWebUri || intent.getData().getHost() == null) {
4959 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4960 synchronized (mPackages) {
4961 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4962 for (int n = 0; n < count; n++) {
4963 ResolveInfo info = resolvedActivities.get(n);
4964 String packageName = info.activityInfo.packageName;
4965 PackageSetting ps = mSettings.mPackages.get(packageName);
4967 // Try to get the status from User settings first
4968 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4969 int status = (int) (packedStatus >> 32);
4970 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4971 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4972 if (DEBUG_EPHEMERAL) {
4973 Slog.v(TAG, "DENY ephemeral apps;"
4974 + " pkg: " + packageName + ", status: " + status);
4981 // We've exhausted all ways to deny ephemeral application; let the system look for them.
4985 private static EphemeralResolveInfo getEphemeralResolveInfo(
4986 Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4987 String resolvedType, int userId, String packageName) {
4988 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4989 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4990 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4991 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4992 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4993 ephemeralPrefixCount);
4994 final int[] shaPrefix = digest.getDigestPrefix();
4995 final byte[][] digestBytes = digest.getDigestBytes();
4996 final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4997 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4998 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4999 // No hash prefix match; there are no ephemeral apps for this domain.
5003 // Go in reverse order so we match the narrowest scope first.
5004 for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5005 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5006 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5009 final List<IntentFilter> filters = ephemeralApplication.getFilters();
5010 // No filters; this should never happen.
5011 if (filters.isEmpty()) {
5014 if (packageName != null
5015 && !packageName.equals(ephemeralApplication.getPackageName())) {
5018 // We have a domain match; resolve the filters to see if anything matches.
5019 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5020 for (int j = filters.size() - 1; j >= 0; --j) {
5021 final EphemeralResolveIntentInfo intentInfo =
5022 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5023 ephemeralResolver.addFilter(intentInfo);
5025 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5026 intent, resolvedType, false /*defaultOnly*/, userId);
5027 if (!matchedResolveInfoList.isEmpty()) {
5028 return matchedResolveInfoList.get(0);
5032 // Hash or filter mis-match; no ephemeral apps for this domain.
5036 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5037 int flags, List<ResolveInfo> query, int userId) {
5038 if (query != null) {
5039 final int N = query.size();
5041 return query.get(0);
5043 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5044 // If there is more than one activity with the same priority,
5045 // then let the user decide between them.
5046 ResolveInfo r0 = query.get(0);
5047 ResolveInfo r1 = query.get(1);
5048 if (DEBUG_INTENT_MATCHING || debug) {
5049 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5050 + r1.activityInfo.name + "=" + r1.priority);
5052 // If the first activity has a higher priority, or a different
5053 // default, then it is always desirable to pick it.
5054 if (r0.priority != r1.priority
5055 || r0.preferredOrder != r1.preferredOrder
5056 || r0.isDefault != r1.isDefault) {
5057 return query.get(0);
5059 // If we have saved a preference for a preferred activity for
5060 // this Intent, use that.
5061 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5062 flags, query, r0.priority, true, false, debug, userId);
5066 ri = new ResolveInfo(mResolveInfo);
5067 ri.activityInfo = new ActivityInfo(ri.activityInfo);
5068 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5069 // If all of the options come from the same package, show the application's
5070 // label and icon instead of the generic resolver's.
5071 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5072 // and then throw away the ResolveInfo itself, meaning that the caller loses
5073 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5074 // a fallback for this case; we only set the target package's resources on
5075 // the ResolveInfo, not the ActivityInfo.
5076 final String intentPackage = intent.getPackage();
5077 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5078 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5079 ri.resolvePackageName = intentPackage;
5080 if (userNeedsBadging(userId)) {
5081 ri.noResourceId = true;
5083 ri.icon = appi.icon;
5085 ri.iconResourceId = appi.icon;
5086 ri.labelRes = appi.labelRes;
5088 ri.activityInfo.applicationInfo = new ApplicationInfo(
5089 ri.activityInfo.applicationInfo);
5091 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5092 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5094 // Make sure that the resolver is displayable in car mode
5095 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5096 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5104 * Return true if the given list is not empty and all of its contents have
5105 * an activityInfo with the given package name.
5107 private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5108 if (ArrayUtils.isEmpty(list)) {
5111 for (int i = 0, N = list.size(); i < N; i++) {
5112 final ResolveInfo ri = list.get(i);
5113 final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5114 if (ai == null || !packageName.equals(ai.packageName)) {
5121 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5122 int flags, List<ResolveInfo> query, boolean debug, int userId) {
5123 final int N = query.size();
5124 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5126 // Get the list of persistent preferred activities that handle the intent
5127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5128 List<PersistentPreferredActivity> pprefs = ppir != null
5129 ? ppir.queryIntent(intent, resolvedType,
5130 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5132 if (pprefs != null && pprefs.size() > 0) {
5133 final int M = pprefs.size();
5134 for (int i=0; i<M; i++) {
5135 final PersistentPreferredActivity ppa = pprefs.get(i);
5136 if (DEBUG_PREFERRED || debug) {
5137 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5138 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5139 + "\n component=" + ppa.mComponent);
5140 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5142 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5143 flags | MATCH_DISABLED_COMPONENTS, userId);
5144 if (DEBUG_PREFERRED || debug) {
5145 Slog.v(TAG, "Found persistent preferred activity:");
5147 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5149 Slog.v(TAG, " null");
5153 // This previously registered persistent preferred activity
5154 // component is no longer known. Ignore it and do NOT remove it.
5157 for (int j=0; j<N; j++) {
5158 final ResolveInfo ri = query.get(j);
5159 if (!ri.activityInfo.applicationInfo.packageName
5160 .equals(ai.applicationInfo.packageName)) {
5163 if (!ri.activityInfo.name.equals(ai.name)) {
5166 // Found a persistent preference that can handle the intent.
5167 if (DEBUG_PREFERRED || debug) {
5168 Slog.v(TAG, "Returning persistent preferred activity: " +
5169 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5178 // TODO: handle preferred activities missing while user has amnesia
5179 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5180 List<ResolveInfo> query, int priority, boolean always,
5181 boolean removeMatches, boolean debug, int userId) {
5182 if (!sUserManager.exists(userId)) return null;
5183 flags = updateFlagsForResolve(flags, userId, intent);
5185 synchronized (mPackages) {
5186 if (intent.getSelector() != null) {
5187 intent = intent.getSelector();
5189 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5191 // Try to find a matching persistent preferred activity.
5192 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5195 // If a persistent preferred activity matched, use it.
5200 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5201 // Get the list of preferred activities that handle the intent
5202 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5203 List<PreferredActivity> prefs = pir != null
5204 ? pir.queryIntent(intent, resolvedType,
5205 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5207 if (prefs != null && prefs.size() > 0) {
5208 boolean changed = false;
5210 // First figure out how good the original match set is.
5211 // We will only allow preferred activities that came
5212 // from the same match quality.
5215 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5217 final int N = query.size();
5218 for (int j=0; j<N; j++) {
5219 final ResolveInfo ri = query.get(j);
5220 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5221 + ": 0x" + Integer.toHexString(match));
5222 if (ri.match > match) {
5227 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5228 + Integer.toHexString(match));
5230 match &= IntentFilter.MATCH_CATEGORY_MASK;
5231 final int M = prefs.size();
5232 for (int i=0; i<M; i++) {
5233 final PreferredActivity pa = prefs.get(i);
5234 if (DEBUG_PREFERRED || debug) {
5235 Slog.v(TAG, "Checking PreferredActivity ds="
5236 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5237 + "\n component=" + pa.mPref.mComponent);
5238 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5240 if (pa.mPref.mMatch != match) {
5241 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5242 + Integer.toHexString(pa.mPref.mMatch));
5245 // If it's not an "always" type preferred activity and that's what we're
5246 // looking for, skip it.
5247 if (always && !pa.mPref.mAlways) {
5248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5251 final ActivityInfo ai = getActivityInfo(
5252 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5253 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5255 if (DEBUG_PREFERRED || debug) {
5256 Slog.v(TAG, "Found preferred activity:");
5258 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5260 Slog.v(TAG, " null");
5264 // This previously registered preferred activity
5265 // component is no longer known. Most likely an update
5266 // to the app was installed and in the new version this
5267 // component no longer exists. Clean it up by removing
5268 // it from the preferred activities list, and skip it.
5269 Slog.w(TAG, "Removing dangling preferred activity: "
5270 + pa.mPref.mComponent);
5271 pir.removeFilter(pa);
5275 for (int j=0; j<N; j++) {
5276 final ResolveInfo ri = query.get(j);
5277 if (!ri.activityInfo.applicationInfo.packageName
5278 .equals(ai.applicationInfo.packageName)) {
5281 if (!ri.activityInfo.name.equals(ai.name)) {
5285 if (removeMatches) {
5286 pir.removeFilter(pa);
5288 if (DEBUG_PREFERRED) {
5289 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5294 // Okay we found a previously set preferred or last chosen app.
5295 // If the result set is different from when this
5296 // was created, we need to clear it and re-ask the
5297 // user their preference, if we're looking for an "always" type entry.
5298 if (always && !pa.mPref.sameSet(query)) {
5299 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5300 + intent + " type " + resolvedType);
5301 if (DEBUG_PREFERRED) {
5302 Slog.v(TAG, "Removing preferred activity since set changed "
5303 + pa.mPref.mComponent);
5305 pir.removeFilter(pa);
5306 // Re-add the filter as a "last chosen" entry (!always)
5307 PreferredActivity lastChosen = new PreferredActivity(
5308 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5309 pir.addFilter(lastChosen);
5314 // Yay! Either the set matched or we're looking for the last chosen
5315 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5316 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5322 if (DEBUG_PREFERRED) {
5323 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5325 scheduleWritePackageRestrictionsLocked(userId);
5330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5335 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5338 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5340 mContext.enforceCallingOrSelfPermission(
5341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5342 List<CrossProfileIntentFilter> matches =
5343 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5344 if (matches != null) {
5345 int size = matches.size();
5346 for (int i = 0; i < size; i++) {
5347 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5350 if (hasWebURI(intent)) {
5351 // cross-profile app linking works only towards the parent.
5352 final UserInfo parent = getProfileParent(sourceUserId);
5353 synchronized(mPackages) {
5354 int flags = updateFlagsForResolve(0, parent.id, intent);
5355 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5356 intent, resolvedType, flags, sourceUserId, parent.id);
5357 return xpDomainInfo != null;
5363 private UserInfo getProfileParent(int userId) {
5364 final long identity = Binder.clearCallingIdentity();
5366 return sUserManager.getProfileParent(userId);
5368 Binder.restoreCallingIdentity(identity);
5372 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5373 String resolvedType, int userId) {
5374 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5375 if (resolver != null) {
5376 return resolver.queryIntent(intent, resolvedType, false, userId);
5382 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5383 String resolvedType, int flags, int userId) {
5385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5387 return new ParceledListSlice<>(
5388 queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5394 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5395 String resolvedType, int flags, int userId) {
5396 if (!sUserManager.exists(userId)) return Collections.emptyList();
5397 flags = updateFlagsForResolve(flags, userId, intent);
5398 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5399 false /* requireFullPermission */, false /* checkShell */,
5400 "query intent activities");
5401 ComponentName comp = intent.getComponent();
5403 if (intent.getSelector() != null) {
5404 intent = intent.getSelector();
5405 comp = intent.getComponent();
5410 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5411 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5413 final ResolveInfo ri = new ResolveInfo();
5414 ri.activityInfo = ai;
5421 boolean sortResult = false;
5422 boolean addEphemeral = false;
5423 boolean matchEphemeralPackage = false;
5424 List<ResolveInfo> result;
5425 final String pkgName = intent.getPackage();
5426 synchronized (mPackages) {
5427 if (pkgName == null) {
5428 List<CrossProfileIntentFilter> matchingFilters =
5429 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5430 // Check for results that need to skip the current profile.
5431 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
5432 resolvedType, flags, userId);
5433 if (xpResolveInfo != null) {
5434 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5435 xpResult.add(xpResolveInfo);
5436 return filterIfNotSystemUser(xpResult, userId);
5439 // Check for results in the current profile.
5440 result = filterIfNotSystemUser(mActivities.queryIntent(
5441 intent, resolvedType, flags, userId), userId);
5443 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5445 // Check for cross profile results.
5446 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5447 xpResolveInfo = queryCrossProfileIntents(
5448 matchingFilters, intent, resolvedType, flags, userId,
5449 hasNonNegativePriorityResult);
5450 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5451 boolean isVisibleToUser = filterIfNotSystemUser(
5452 Collections.singletonList(xpResolveInfo), userId).size() > 0;
5453 if (isVisibleToUser) {
5454 result.add(xpResolveInfo);
5458 if (hasWebURI(intent)) {
5459 CrossProfileDomainInfo xpDomainInfo = null;
5460 final UserInfo parent = getProfileParent(userId);
5461 if (parent != null) {
5462 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5463 flags, userId, parent.id);
5465 if (xpDomainInfo != null) {
5466 if (xpResolveInfo != null) {
5467 // If we didn't remove it, the cross-profile ResolveInfo would be twice
5469 result.remove(xpResolveInfo);
5471 if (result.size() == 0 && !addEphemeral) {
5472 result.add(xpDomainInfo.resolveInfo);
5476 if (result.size() > 1 || addEphemeral) {
5477 result = filterCandidatesWithDomainPreferredActivitiesLPr(
5478 intent, flags, result, xpDomainInfo, userId);
5483 final PackageParser.Package pkg = mPackages.get(pkgName);
5485 result = filterIfNotSystemUser(
5486 mActivities.queryIntentForPackage(
5487 intent, resolvedType, flags, pkg.activities, userId),
5490 // the caller wants to resolve for a particular package; however, there
5491 // were no installed results, so, try to find an ephemeral result
5492 addEphemeral = isEphemeralAllowed(
5493 intent, null /*result*/, userId, true /*skipPackageCheck*/);
5494 matchEphemeralPackage = true;
5495 result = new ArrayList<ResolveInfo>();
5500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5501 final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5502 mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5503 matchEphemeralPackage ? pkgName : null);
5505 if (DEBUG_EPHEMERAL) {
5506 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5508 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5509 ephemeralInstaller.ephemeralResolveInfo = ai;
5510 // make sure this resolver is the default
5511 ephemeralInstaller.isDefault = true;
5512 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5513 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5514 // add a non-generic filter
5515 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5516 ephemeralInstaller.filter.addDataPath(
5517 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5518 result.add(ephemeralInstaller);
5520 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5523 Collections.sort(result, mResolvePrioritySorter);
5528 private static class CrossProfileDomainInfo {
5529 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5530 ResolveInfo resolveInfo;
5531 /* Best domain verification status of the activities found in the other profile */
5532 int bestDomainVerificationStatus;
5535 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5536 String resolvedType, int flags, int sourceUserId, int parentUserId) {
5537 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5541 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5542 resolvedType, flags, parentUserId);
5544 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5547 CrossProfileDomainInfo result = null;
5548 int size = resultTargetUser.size();
5549 for (int i = 0; i < size; i++) {
5550 ResolveInfo riTargetUser = resultTargetUser.get(i);
5551 // Intent filter verification is only for filters that specify a host. So don't return
5552 // those that handle all web uris.
5553 if (riTargetUser.handleAllWebDataURI) {
5556 String packageName = riTargetUser.activityInfo.packageName;
5557 PackageSetting ps = mSettings.mPackages.get(packageName);
5561 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5562 int status = (int)(verificationState >> 32);
5563 if (result == null) {
5564 result = new CrossProfileDomainInfo();
5565 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5566 sourceUserId, parentUserId);
5567 result.bestDomainVerificationStatus = status;
5569 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5570 result.bestDomainVerificationStatus);
5573 // Don't consider matches with status NEVER across profiles.
5574 if (result != null && result.bestDomainVerificationStatus
5575 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5582 * Verification statuses are ordered from the worse to the best, except for
5583 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5585 private int bestDomainVerificationStatus(int status1, int status2) {
5586 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5589 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5592 return (int) MathUtils.max(status1, status2);
5595 private boolean isUserEnabled(int userId) {
5596 long callingId = Binder.clearCallingIdentity();
5598 UserInfo userInfo = sUserManager.getUserInfo(userId);
5599 return userInfo != null && userInfo.isEnabled();
5601 Binder.restoreCallingIdentity(callingId);
5606 * Filter out activities with systemUserOnly flag set, when current user is not System.
5608 * @return filtered list
5610 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5611 if (userId == UserHandle.USER_SYSTEM) {
5612 return resolveInfos;
5614 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5615 ResolveInfo info = resolveInfos.get(i);
5616 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5617 resolveInfos.remove(i);
5620 return resolveInfos;
5624 * @param resolveInfos list of resolve infos in descending priority order
5625 * @return if the list contains a resolve info with non-negative priority
5627 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5628 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5631 private static boolean hasWebURI(Intent intent) {
5632 if (intent.getData() == null) {
5635 final String scheme = intent.getScheme();
5636 if (TextUtils.isEmpty(scheme)) {
5639 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5642 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5643 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5645 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5647 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5648 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5652 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5653 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5654 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5655 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5656 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5657 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5659 synchronized (mPackages) {
5660 final int count = candidates.size();
5661 // First, try to use linked apps. Partition the candidates into four lists:
5662 // one for the final results, one for the "do not use ever", one for "undefined status"
5663 // and finally one for "browser app type".
5664 for (int n=0; n<count; n++) {
5665 ResolveInfo info = candidates.get(n);
5666 String packageName = info.activityInfo.packageName;
5667 PackageSetting ps = mSettings.mPackages.get(packageName);
5669 // Add to the special match all list (Browser use case)
5670 if (info.handleAllWebDataURI) {
5671 matchAllList.add(info);
5674 // Try to get the status from User settings first
5675 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5676 int status = (int)(packedStatus >> 32);
5677 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5678 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5679 if (DEBUG_DOMAIN_VERIFICATION) {
5680 Slog.i(TAG, " + always: " + info.activityInfo.packageName
5681 + " : linkgen=" + linkGeneration);
5683 // Use link-enabled generation as preferredOrder, i.e.
5684 // prefer newly-enabled over earlier-enabled.
5685 info.preferredOrder = linkGeneration;
5686 alwaysList.add(info);
5687 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5688 if (DEBUG_DOMAIN_VERIFICATION) {
5689 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
5691 neverList.add(info);
5692 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5693 if (DEBUG_DOMAIN_VERIFICATION) {
5694 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
5696 alwaysAskList.add(info);
5697 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5698 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5699 if (DEBUG_DOMAIN_VERIFICATION) {
5700 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
5702 undefinedList.add(info);
5707 // We'll want to include browser possibilities in a few cases
5708 boolean includeBrowser = false;
5710 // First try to add the "always" resolution(s) for the current user, if any
5711 if (alwaysList.size() > 0) {
5712 result.addAll(alwaysList);
5714 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5715 result.addAll(undefinedList);
5716 // Maybe add one for the other profile.
5717 if (xpDomainInfo != null && (
5718 xpDomainInfo.bestDomainVerificationStatus
5719 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5720 result.add(xpDomainInfo.resolveInfo);
5722 includeBrowser = true;
5725 // The presence of any 'always ask' alternatives means we'll also offer browsers.
5726 // If there were 'always' entries their preferred order has been set, so we also
5727 // back that off to make the alternatives equivalent
5728 if (alwaysAskList.size() > 0) {
5729 for (ResolveInfo i : result) {
5730 i.preferredOrder = 0;
5732 result.addAll(alwaysAskList);
5733 includeBrowser = true;
5736 if (includeBrowser) {
5737 // Also add browsers (all of them or only the default one)
5738 if (DEBUG_DOMAIN_VERIFICATION) {
5739 Slog.v(TAG, " ...including browsers in candidate set");
5741 if ((matchFlags & MATCH_ALL) != 0) {
5742 result.addAll(matchAllList);
5744 // Browser/generic handling case. If there's a default browser, go straight
5745 // to that (but only if there is no other higher-priority match).
5746 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5747 int maxMatchPrio = 0;
5748 ResolveInfo defaultBrowserMatch = null;
5749 final int numCandidates = matchAllList.size();
5750 for (int n = 0; n < numCandidates; n++) {
5751 ResolveInfo info = matchAllList.get(n);
5752 // track the highest overall match priority...
5753 if (info.priority > maxMatchPrio) {
5754 maxMatchPrio = info.priority;
5756 // ...and the highest-priority default browser match
5757 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5758 if (defaultBrowserMatch == null
5759 || (defaultBrowserMatch.priority < info.priority)) {
5761 Slog.v(TAG, "Considering default browser match " + info);
5763 defaultBrowserMatch = info;
5767 if (defaultBrowserMatch != null
5768 && defaultBrowserMatch.priority >= maxMatchPrio
5769 && !TextUtils.isEmpty(defaultBrowserPackageName))
5772 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5774 result.add(defaultBrowserMatch);
5776 result.addAll(matchAllList);
5780 // If there is nothing selected, add all candidates and remove the ones that the user
5781 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5782 if (result.size() == 0) {
5783 result.addAll(candidates);
5784 result.removeAll(neverList);
5788 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5789 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5791 for (ResolveInfo info : result) {
5792 Slog.v(TAG, " + " + info.activityInfo);
5798 // Returns a packed value as a long:
5800 // high 'int'-sized word: link status: undefined/ask/never/always.
5801 // low 'int'-sized word: relative priority among 'always' results.
5802 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5803 long result = ps.getDomainVerificationStatusForUser(userId);
5804 // if none available, get the master status
5805 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5806 if (ps.getIntentFilterVerificationInfo() != null) {
5807 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5813 private ResolveInfo querySkipCurrentProfileIntents(
5814 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5815 int flags, int sourceUserId) {
5816 if (matchingFilters != null) {
5817 int size = matchingFilters.size();
5818 for (int i = 0; i < size; i ++) {
5819 CrossProfileIntentFilter filter = matchingFilters.get(i);
5820 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5821 // Checking if there are activities in the target user that can handle the
5823 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5824 resolvedType, flags, sourceUserId);
5825 if (resolveInfo != null) {
5834 // Return matching ResolveInfo in target user if any.
5835 private ResolveInfo queryCrossProfileIntents(
5836 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5837 int flags, int sourceUserId, boolean matchInCurrentProfile) {
5838 if (matchingFilters != null) {
5839 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5840 // match the same intent. For performance reasons, it is better not to
5841 // run queryIntent twice for the same userId
5842 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5843 int size = matchingFilters.size();
5844 for (int i = 0; i < size; i++) {
5845 CrossProfileIntentFilter filter = matchingFilters.get(i);
5846 int targetUserId = filter.getTargetUserId();
5847 boolean skipCurrentProfile =
5848 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5849 boolean skipCurrentProfileIfNoMatchFound =
5850 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5851 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5852 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5853 // Checking if there are activities in the target user that can handle the
5855 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5856 resolvedType, flags, sourceUserId);
5857 if (resolveInfo != null) return resolveInfo;
5858 alreadyTriedUserIds.put(targetUserId, true);
5866 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5867 * will forward the intent to the filter's target user.
5868 * Otherwise, returns null.
5870 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5871 String resolvedType, int flags, int sourceUserId) {
5872 int targetUserId = filter.getTargetUserId();
5873 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5874 resolvedType, flags, targetUserId);
5875 if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5876 // If all the matches in the target profile are suspended, return null.
5877 for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5878 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5879 & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5880 return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5888 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5889 int sourceUserId, int targetUserId) {
5890 ResolveInfo forwardingResolveInfo = new ResolveInfo();
5891 long ident = Binder.clearCallingIdentity();
5892 boolean targetIsProfile;
5894 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5896 Binder.restoreCallingIdentity(ident);
5899 if (targetIsProfile) {
5900 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5902 className = FORWARD_INTENT_TO_PARENT;
5904 ComponentName forwardingActivityComponentName = new ComponentName(
5905 mAndroidApplication.packageName, className);
5906 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5908 if (!targetIsProfile) {
5909 forwardingActivityInfo.showUserIcon = targetUserId;
5910 forwardingResolveInfo.noResourceId = true;
5912 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5913 forwardingResolveInfo.priority = 0;
5914 forwardingResolveInfo.preferredOrder = 0;
5915 forwardingResolveInfo.match = 0;
5916 forwardingResolveInfo.isDefault = true;
5917 forwardingResolveInfo.filter = filter;
5918 forwardingResolveInfo.targetUserId = targetUserId;
5919 return forwardingResolveInfo;
5923 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5924 Intent[] specifics, String[] specificTypes, Intent intent,
5925 String resolvedType, int flags, int userId) {
5926 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5927 specificTypes, intent, resolvedType, flags, userId));
5930 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5931 Intent[] specifics, String[] specificTypes, Intent intent,
5932 String resolvedType, int flags, int userId) {
5933 if (!sUserManager.exists(userId)) return Collections.emptyList();
5934 flags = updateFlagsForResolve(flags, userId, intent);
5935 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5936 false /* requireFullPermission */, false /* checkShell */,
5937 "query intent activity options");
5938 final String resultsAction = intent.getAction();
5940 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5941 | PackageManager.GET_RESOLVED_FILTER, userId);
5943 if (DEBUG_INTENT_MATCHING) {
5944 Log.v(TAG, "Query " + intent + ": " + results);
5947 int specificsPos = 0;
5950 // todo: note that the algorithm used here is O(N^2). This
5951 // isn't a problem in our current environment, but if we start running
5952 // into situations where we have more than 5 or 10 matches then this
5953 // should probably be changed to something smarter...
5955 // First we go through and resolve each of the specific items
5956 // that were supplied, taking care of removing any corresponding
5957 // duplicate items in the generic resolve list.
5958 if (specifics != null) {
5959 for (int i=0; i<specifics.length; i++) {
5960 final Intent sintent = specifics[i];
5961 if (sintent == null) {
5965 if (DEBUG_INTENT_MATCHING) {
5966 Log.v(TAG, "Specific #" + i + ": " + sintent);
5969 String action = sintent.getAction();
5970 if (resultsAction != null && resultsAction.equals(action)) {
5971 // If this action was explicitly requested, then don't
5972 // remove things that have it.
5976 ResolveInfo ri = null;
5977 ActivityInfo ai = null;
5979 ComponentName comp = sintent.getComponent();
5983 specificTypes != null ? specificTypes[i] : null,
5988 if (ri == mResolveInfo) {
5989 // ACK! Must do something better with this.
5991 ai = ri.activityInfo;
5992 comp = new ComponentName(ai.applicationInfo.packageName,
5995 ai = getActivityInfo(comp, flags, userId);
6001 // Look for any generic query activities that are duplicates
6002 // of this specific one, and remove them from the results.
6003 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6006 for (j=specificsPos; j<N; j++) {
6007 ResolveInfo sri = results.get(j);
6008 if ((sri.activityInfo.name.equals(comp.getClassName())
6009 && sri.activityInfo.applicationInfo.packageName.equals(
6010 comp.getPackageName()))
6011 || (action != null && sri.filter.matchAction(action))) {
6013 if (DEBUG_INTENT_MATCHING) Log.v(
6014 TAG, "Removing duplicate item from " + j
6015 + " due to specific " + specificsPos);
6024 // Add this specific item to its proper place.
6026 ri = new ResolveInfo();
6027 ri.activityInfo = ai;
6029 results.add(specificsPos, ri);
6030 ri.specificIndex = i;
6035 // Now we go through the remaining generic results and remove any
6036 // duplicate actions that are found here.
6038 for (int i=specificsPos; i<N-1; i++) {
6039 final ResolveInfo rii = results.get(i);
6040 if (rii.filter == null) {
6044 // Iterate over all of the actions of this result's intent
6045 // filter... typically this should be just one.
6046 final Iterator<String> it = rii.filter.actionsIterator();
6050 while (it.hasNext()) {
6051 final String action = it.next();
6052 if (resultsAction != null && resultsAction.equals(action)) {
6053 // If this action was explicitly requested, then don't
6054 // remove things that have it.
6057 for (int j=i+1; j<N; j++) {
6058 final ResolveInfo rij = results.get(j);
6059 if (rij.filter != null && rij.filter.hasAction(action)) {
6061 if (DEBUG_INTENT_MATCHING) Log.v(
6062 TAG, "Removing duplicate item from " + j
6063 + " due to action " + action + " at " + i);
6070 // If the caller didn't request filter information, drop it now
6071 // so we don't have to marshall/unmarshall it.
6072 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6077 // Filter out the caller activity if so requested.
6078 if (caller != null) {
6080 for (int i=0; i<N; i++) {
6081 ActivityInfo ainfo = results.get(i).activityInfo;
6082 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6083 && caller.getClassName().equals(ainfo.name)) {
6090 // If the caller didn't request filter information,
6091 // drop them now so we don't have to
6092 // marshall/unmarshall it.
6093 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6095 for (int i=0; i<N; i++) {
6096 results.get(i).filter = null;
6100 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6105 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6106 String resolvedType, int flags, int userId) {
6107 return new ParceledListSlice<>(
6108 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6111 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6112 String resolvedType, int flags, int userId) {
6113 if (!sUserManager.exists(userId)) return Collections.emptyList();
6114 flags = updateFlagsForResolve(flags, userId, intent);
6115 ComponentName comp = intent.getComponent();
6117 if (intent.getSelector() != null) {
6118 intent = intent.getSelector();
6119 comp = intent.getComponent();
6123 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6124 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6126 ResolveInfo ri = new ResolveInfo();
6127 ri.activityInfo = ai;
6134 synchronized (mPackages) {
6135 String pkgName = intent.getPackage();
6136 if (pkgName == null) {
6137 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6139 final PackageParser.Package pkg = mPackages.get(pkgName);
6141 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6144 return Collections.emptyList();
6149 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6150 if (!sUserManager.exists(userId)) return null;
6151 flags = updateFlagsForResolve(flags, userId, intent);
6152 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6153 if (query != null) {
6154 if (query.size() >= 1) {
6155 // If there is more than one service with the same priority,
6156 // just arbitrarily pick the first one.
6157 return query.get(0);
6164 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6165 String resolvedType, int flags, int userId) {
6166 return new ParceledListSlice<>(
6167 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6170 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6171 String resolvedType, int flags, int userId) {
6172 if (!sUserManager.exists(userId)) return Collections.emptyList();
6173 flags = updateFlagsForResolve(flags, userId, intent);
6174 ComponentName comp = intent.getComponent();
6176 if (intent.getSelector() != null) {
6177 intent = intent.getSelector();
6178 comp = intent.getComponent();
6182 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6183 final ServiceInfo si = getServiceInfo(comp, flags, userId);
6185 final ResolveInfo ri = new ResolveInfo();
6186 ri.serviceInfo = si;
6193 synchronized (mPackages) {
6194 String pkgName = intent.getPackage();
6195 if (pkgName == null) {
6196 return mServices.queryIntent(intent, resolvedType, flags, userId);
6198 final PackageParser.Package pkg = mPackages.get(pkgName);
6200 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6203 return Collections.emptyList();
6208 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6209 String resolvedType, int flags, int userId) {
6210 return new ParceledListSlice<>(
6211 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6214 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6215 Intent intent, String resolvedType, int flags, int userId) {
6216 if (!sUserManager.exists(userId)) return Collections.emptyList();
6217 flags = updateFlagsForResolve(flags, userId, intent);
6218 ComponentName comp = intent.getComponent();
6220 if (intent.getSelector() != null) {
6221 intent = intent.getSelector();
6222 comp = intent.getComponent();
6226 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6227 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6229 final ResolveInfo ri = new ResolveInfo();
6230 ri.providerInfo = pi;
6237 synchronized (mPackages) {
6238 String pkgName = intent.getPackage();
6239 if (pkgName == null) {
6240 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6242 final PackageParser.Package pkg = mPackages.get(pkgName);
6244 return mProviders.queryIntentForPackage(
6245 intent, resolvedType, flags, pkg.providers, userId);
6247 return Collections.emptyList();
6252 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6253 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6254 flags = updateFlagsForPackage(flags, userId, null);
6255 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6256 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6257 false /* requireFullPermission */, false /* checkShell */,
6258 "get installed packages");
6261 synchronized (mPackages) {
6262 ArrayList<PackageInfo> list;
6263 if (listUninstalled) {
6264 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6265 for (PackageSetting ps : mSettings.mPackages.values()) {
6266 final PackageInfo pi;
6267 if (ps.pkg != null) {
6268 pi = generatePackageInfo(ps, flags, userId);
6270 pi = generatePackageInfo(ps, flags, userId);
6277 list = new ArrayList<PackageInfo>(mPackages.size());
6278 for (PackageParser.Package p : mPackages.values()) {
6279 final PackageInfo pi =
6280 generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6287 return new ParceledListSlice<PackageInfo>(list);
6291 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6292 String[] permissions, boolean[] tmp, int flags, int userId) {
6294 final PermissionsState permissionsState = ps.getPermissionsState();
6295 for (int i=0; i<permissions.length; i++) {
6296 final String permission = permissions[i];
6297 if (permissionsState.hasPermission(permission, userId)) {
6304 if (numMatch == 0) {
6307 final PackageInfo pi;
6308 if (ps.pkg != null) {
6309 pi = generatePackageInfo(ps, flags, userId);
6311 pi = generatePackageInfo(ps, flags, userId);
6313 // The above might return null in cases of uninstalled apps or install-state
6314 // skew across users/profiles.
6316 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6317 if (numMatch == permissions.length) {
6318 pi.requestedPermissions = permissions;
6320 pi.requestedPermissions = new String[numMatch];
6322 for (int i=0; i<permissions.length; i++) {
6324 pi.requestedPermissions[numMatch] = permissions[i];
6335 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6336 String[] permissions, int flags, int userId) {
6337 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6338 flags = updateFlagsForPackage(flags, userId, permissions);
6339 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6342 synchronized (mPackages) {
6343 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6344 boolean[] tmpBools = new boolean[permissions.length];
6345 if (listUninstalled) {
6346 for (PackageSetting ps : mSettings.mPackages.values()) {
6347 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6350 for (PackageParser.Package pkg : mPackages.values()) {
6351 PackageSetting ps = (PackageSetting)pkg.mExtras;
6353 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6359 return new ParceledListSlice<PackageInfo>(list);
6364 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6365 final int callingUid = Binder.getCallingUid();
6366 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6367 flags = updateFlagsForApplication(flags, userId, null);
6368 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6370 enforceCrossUserPermission(
6373 false /* requireFullPermission */,
6374 false /* checkShell */,
6375 "get installed application info");
6378 synchronized (mPackages) {
6379 ArrayList<ApplicationInfo> list;
6380 if (listUninstalled) {
6381 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6382 for (PackageSetting ps : mSettings.mPackages.values()) {
6384 if (ps.pkg != null) {
6385 ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6386 ps.readUserState(userId), userId);
6388 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6395 list = new ArrayList<ApplicationInfo>(mPackages.size());
6396 for (PackageParser.Package p : mPackages.values()) {
6397 if (p.mExtras != null) {
6398 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6399 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6407 return new ParceledListSlice<ApplicationInfo>(list);
6412 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6413 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6417 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6418 "getEphemeralApplications");
6419 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6420 true /* requireFullPermission */, false /* checkShell */,
6421 "getEphemeralApplications");
6422 synchronized (mPackages) {
6423 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6424 .getEphemeralApplicationsLPw(userId);
6425 if (ephemeralApps != null) {
6426 return new ParceledListSlice<>(ephemeralApps);
6433 public boolean isEphemeralApplication(String packageName, int userId) {
6434 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6435 true /* requireFullPermission */, false /* checkShell */,
6437 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6441 if (!isCallerSameApp(packageName)) {
6444 synchronized (mPackages) {
6445 PackageParser.Package pkg = mPackages.get(packageName);
6447 return pkg.applicationInfo.isEphemeralApp();
6454 public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6455 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6459 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6460 true /* requireFullPermission */, false /* checkShell */,
6462 if (!isCallerSameApp(packageName)) {
6465 synchronized (mPackages) {
6466 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6467 packageName, userId);
6472 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6473 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6477 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6478 true /* requireFullPermission */, true /* checkShell */,
6480 if (!isCallerSameApp(packageName)) {
6483 synchronized (mPackages) {
6484 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6485 packageName, cookie, userId);
6490 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6491 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6495 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6496 "getEphemeralApplicationIcon");
6497 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6498 true /* requireFullPermission */, false /* checkShell */,
6499 "getEphemeralApplicationIcon");
6500 synchronized (mPackages) {
6501 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6502 packageName, userId);
6506 private boolean isCallerSameApp(String packageName) {
6507 PackageParser.Package pkg = mPackages.get(packageName);
6509 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6513 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6514 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6517 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6518 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6521 synchronized (mPackages) {
6522 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6523 final int userId = UserHandle.getCallingUserId();
6524 while (i.hasNext()) {
6525 final PackageParser.Package p = i.next();
6526 if (p.applicationInfo == null) continue;
6528 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6529 && !p.applicationInfo.isDirectBootAware();
6530 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6531 && p.applicationInfo.isDirectBootAware();
6533 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6534 && (!mSafeMode || isSystemApp(p))
6535 && (matchesUnaware || matchesAware)) {
6536 PackageSetting ps = mSettings.mPackages.get(p.packageName);
6538 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6539 ps.readUserState(userId), userId);
6552 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6553 if (!sUserManager.exists(userId)) return null;
6554 flags = updateFlagsForComponent(flags, userId, name);
6556 synchronized (mPackages) {
6557 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6558 PackageSetting ps = provider != null
6559 ? mSettings.mPackages.get(provider.owner.packageName)
6562 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6563 ? PackageParser.generateProviderInfo(provider, flags,
6564 ps.readUserState(userId), userId)
6573 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6575 synchronized (mPackages) {
6576 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6577 .entrySet().iterator();
6578 final int userId = UserHandle.getCallingUserId();
6579 while (i.hasNext()) {
6580 Map.Entry<String, PackageParser.Provider> entry = i.next();
6581 PackageParser.Provider p = entry.getValue();
6582 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6584 if (ps != null && p.syncable
6585 && (!mSafeMode || (p.info.applicationInfo.flags
6586 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6587 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6588 ps.readUserState(userId), userId);
6590 outNames.add(entry.getKey());
6599 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6600 int uid, int flags) {
6601 final int userId = processName != null ? UserHandle.getUserId(uid)
6602 : UserHandle.getCallingUserId();
6603 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6604 flags = updateFlagsForComponent(flags, userId, processName);
6606 ArrayList<ProviderInfo> finalList = null;
6608 synchronized (mPackages) {
6609 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6610 while (i.hasNext()) {
6611 final PackageParser.Provider p = i.next();
6612 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6613 if (ps != null && p.info.authority != null
6614 && (processName == null
6615 || (p.info.processName.equals(processName)
6616 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6617 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6618 if (finalList == null) {
6619 finalList = new ArrayList<ProviderInfo>(3);
6621 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6622 ps.readUserState(userId), userId);
6624 finalList.add(info);
6630 if (finalList != null) {
6631 Collections.sort(finalList, mProviderInitOrderSorter);
6632 return new ParceledListSlice<ProviderInfo>(finalList);
6635 return ParceledListSlice.emptyList();
6639 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6641 synchronized (mPackages) {
6642 final PackageParser.Instrumentation i = mInstrumentation.get(name);
6643 return PackageParser.generateInstrumentationInfo(i, flags);
6648 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6649 String targetPackage, int flags) {
6650 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6653 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6655 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6658 synchronized (mPackages) {
6659 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6660 while (i.hasNext()) {
6661 final PackageParser.Instrumentation p = i.next();
6662 if (targetPackage == null
6663 || targetPackage.equals(p.info.targetPackage)) {
6664 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6676 private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6677 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6678 if (overlays == null) {
6679 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6682 for (PackageParser.Package opkg : overlays.values()) {
6683 // Not much to do if idmap fails: we already logged the error
6684 // and we certainly don't want to abort installation of pkg simply
6685 // because an overlay didn't fit properly. For these reasons,
6686 // ignore the return value of createIdmapForPackagePairLI.
6687 createIdmapForPackagePairLI(pkg, opkg);
6691 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6692 PackageParser.Package opkg) {
6693 if (!opkg.mTrustedOverlay) {
6694 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6695 opkg.baseCodePath + ": overlay not trusted");
6698 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6699 if (overlaySet == null) {
6700 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6701 opkg.baseCodePath + " but target package has no known overlays");
6704 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6705 // TODO: generate idmap for split APKs
6707 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6708 } catch (InstallerException e) {
6709 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6710 + opkg.baseCodePath);
6713 PackageParser.Package[] overlayArray =
6714 overlaySet.values().toArray(new PackageParser.Package[0]);
6715 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6716 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6717 return p1.mOverlayPriority - p2.mOverlayPriority;
6720 Arrays.sort(overlayArray, cmp);
6722 pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6724 for (PackageParser.Package p : overlayArray) {
6725 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6730 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6733 scanDirLI(dir, parseFlags, scanFlags, currentTime);
6735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6739 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6740 final File[] files = dir.listFiles();
6741 if (ArrayUtils.isEmpty(files)) {
6742 Log.d(TAG, "No files in app dir " + dir);
6746 if (DEBUG_PACKAGE_SCANNING) {
6747 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6748 + " flags=0x" + Integer.toHexString(parseFlags));
6751 for (File file : files) {
6752 final boolean isPackage = (isApkFile(file) || file.isDirectory())
6753 && !PackageInstallerService.isStageName(file.getName());
6755 // Ignore entries which are not packages
6759 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6760 scanFlags, currentTime, null);
6761 } catch (PackageManagerException e) {
6762 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6764 // Delete invalid userdata apps
6765 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6766 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6767 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6768 removeCodePathLI(file);
6774 private static File getSettingsProblemFile() {
6775 File dataDir = Environment.getDataDirectory();
6776 File systemDir = new File(dataDir, "system");
6777 File fname = new File(systemDir, "uiderrors.txt");
6781 static void reportSettingsProblem(int priority, String msg) {
6782 logCriticalInfo(priority, msg);
6785 static void logCriticalInfo(int priority, String msg) {
6786 Slog.println(priority, TAG, msg);
6787 EventLogTags.writePmCriticalInfo(msg);
6789 File fname = getSettingsProblemFile();
6790 FileOutputStream out = new FileOutputStream(fname, true);
6791 PrintWriter pw = new FastPrintWriter(out);
6792 SimpleDateFormat formatter = new SimpleDateFormat();
6793 String dateString = formatter.format(new Date(System.currentTimeMillis()));
6794 pw.println(dateString + ": " + msg);
6796 FileUtils.setPermissions(
6798 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6800 } catch (java.io.IOException e) {
6804 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6805 if (srcFile.isDirectory()) {
6806 final File baseFile = new File(pkg.baseCodePath);
6807 long maxModifiedTime = baseFile.lastModified();
6808 if (pkg.splitCodePaths != null) {
6809 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6810 final File splitFile = new File(pkg.splitCodePaths[i]);
6811 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6814 return maxModifiedTime;
6816 return srcFile.lastModified();
6819 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6820 final int policyFlags) throws PackageManagerException {
6821 // When upgrading from pre-N MR1, verify the package time stamp using the package
6822 // directory and not the APK file.
6823 final long lastModifiedTime = mIsPreNMR1Upgrade
6824 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6826 && ps.codePath.equals(srcFile)
6827 && ps.timeStamp == lastModifiedTime
6828 && !isCompatSignatureUpdateNeeded(pkg)
6829 && !isRecoverSignatureUpdateNeeded(pkg)) {
6830 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6831 KeySetManagerService ksms = mSettings.mKeySetManagerService;
6832 ArraySet<PublicKey> signingKs;
6833 synchronized (mPackages) {
6834 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6836 if (ps.signatures.mSignatures != null
6837 && ps.signatures.mSignatures.length != 0
6838 && signingKs != null) {
6839 // Optimization: reuse the existing cached certificates
6840 // if the package appears to be unchanged.
6841 pkg.mSignatures = ps.signatures.mSignatures;
6842 pkg.mSigningKeys = signingKs;
6846 Slog.w(TAG, "PackageSetting for " + ps.name
6847 + " is missing signatures. Collecting certs again to recover them.");
6849 Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6853 PackageParser.collectCertificates(pkg, policyFlags);
6854 } catch (PackageParserException e) {
6855 throw PackageManagerException.from(e);
6860 * Traces a package scan.
6861 * @see #scanPackageLI(File, int, int, long, UserHandle)
6863 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6864 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6865 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6867 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6869 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6874 * Scans a package and returns the newly parsed package.
6875 * Returns {@code null} in case of errors and the error code is stored in mLastScanError
6877 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6878 long currentTime, UserHandle user) throws PackageManagerException {
6879 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6880 PackageParser pp = new PackageParser();
6881 pp.setSeparateProcesses(mSeparateProcesses);
6882 pp.setOnlyCoreApps(mOnlyCore);
6883 pp.setDisplayMetrics(mMetrics);
6885 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6886 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6889 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6890 final PackageParser.Package pkg;
6892 pkg = pp.parsePackage(scanFile, parseFlags);
6893 } catch (PackageParserException e) {
6894 throw PackageManagerException.from(e);
6896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6899 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6903 * Scans a package and returns the newly parsed package.
6904 * @throws PackageManagerException on a parse error.
6906 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6907 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6908 throws PackageManagerException {
6909 // If the package has children and this is the first dive in the function
6910 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6911 // packages (parent and children) would be successfully scanned before the
6912 // actual scan since scanning mutates internal state and we want to atomically
6913 // install the package and its children.
6914 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6915 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6916 scanFlags |= SCAN_CHECK_ONLY;
6919 scanFlags &= ~SCAN_CHECK_ONLY;
6923 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6924 scanFlags, currentTime, user);
6926 // Scan the children
6927 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6928 for (int i = 0; i < childCount; i++) {
6929 PackageParser.Package childPackage = pkg.childPackages.get(i);
6930 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6935 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6936 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6943 * Scans a package and returns the newly parsed package.
6944 * @throws PackageManagerException on a parse error.
6946 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6947 int policyFlags, int scanFlags, long currentTime, UserHandle user)
6948 throws PackageManagerException {
6949 PackageSetting ps = null;
6950 PackageSetting updatedPkg;
6952 synchronized (mPackages) {
6953 // Look to see if we already know about this package.
6954 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6955 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6956 // This package has been renamed to its original name. Let's
6958 ps = mSettings.peekPackageLPr(oldName);
6960 // If there was no original package, see one for the real package name.
6962 ps = mSettings.peekPackageLPr(pkg.packageName);
6964 // Check to see if this package could be hiding/updating a system
6965 // package. Must look for it either under the original or real
6966 // package name depending on our state.
6967 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6968 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6970 // If this is a package we don't know about on the system partition, we
6971 // may need to remove disabled child packages on the system partition
6972 // or may need to not add child packages if the parent apk is updated
6973 // on the data partition and no longer defines this child package.
6974 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6975 // If this is a parent package for an updated system app and this system
6976 // app got an OTA update which no longer defines some of the child packages
6977 // we have to prune them from the disabled system packages.
6978 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6979 if (disabledPs != null) {
6980 final int scannedChildCount = (pkg.childPackages != null)
6981 ? pkg.childPackages.size() : 0;
6982 final int disabledChildCount = disabledPs.childPackageNames != null
6983 ? disabledPs.childPackageNames.size() : 0;
6984 for (int i = 0; i < disabledChildCount; i++) {
6985 String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6986 boolean disabledPackageAvailable = false;
6987 for (int j = 0; j < scannedChildCount; j++) {
6988 PackageParser.Package childPkg = pkg.childPackages.get(j);
6989 if (childPkg.packageName.equals(disabledChildPackageName)) {
6990 disabledPackageAvailable = true;
6994 if (!disabledPackageAvailable) {
6995 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7002 boolean updatedPkgBetter = false;
7003 // First check if this is a system package that may involve an update
7004 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7005 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7006 // it needs to drop FLAG_PRIVILEGED.
7007 if (locationIsPrivileged(scanFile)) {
7008 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7010 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7013 if (ps != null && !ps.codePath.equals(scanFile)) {
7014 // The path has changed from what was last scanned... check the
7015 // version of the new path against what we have stored to determine
7017 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7018 if (pkg.mVersionCode <= ps.versionCode) {
7019 // The system package has been updated and the code path does not match
7020 // Ignore entry. Skip it.
7021 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7022 + " ignored: updated version " + ps.versionCode
7023 + " better than this " + pkg.mVersionCode);
7024 if (!updatedPkg.codePath.equals(scanFile)) {
7025 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7026 + ps.name + " changing from " + updatedPkg.codePathString
7027 + " to " + scanFile);
7028 updatedPkg.codePath = scanFile;
7029 updatedPkg.codePathString = scanFile.toString();
7030 updatedPkg.resourcePath = scanFile;
7031 updatedPkg.resourcePathString = scanFile.toString();
7033 updatedPkg.pkg = pkg;
7034 updatedPkg.versionCode = pkg.mVersionCode;
7036 // Update the disabled system child packages to point to the package too.
7037 final int childCount = updatedPkg.childPackageNames != null
7038 ? updatedPkg.childPackageNames.size() : 0;
7039 for (int i = 0; i < childCount; i++) {
7040 String childPackageName = updatedPkg.childPackageNames.get(i);
7041 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7043 if (updatedChildPkg != null) {
7044 updatedChildPkg.pkg = pkg;
7045 updatedChildPkg.versionCode = pkg.mVersionCode;
7049 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7050 + scanFile + " ignored: updated version " + ps.versionCode
7051 + " better than this " + pkg.mVersionCode);
7053 // The current app on the system partition is better than
7054 // what we have updated to on the data partition; switch
7055 // back to the system partition version.
7056 // At this point, its safely assumed that package installation for
7057 // apps in system partition will go through. If not there won't be a working
7058 // version of the app
7060 synchronized (mPackages) {
7061 // Just remove the loaded entries from package lists.
7062 mPackages.remove(ps.name);
7065 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7066 + " reverting from " + ps.codePathString
7067 + ": new version " + pkg.mVersionCode
7068 + " better than installed " + ps.versionCode);
7070 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7071 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7072 synchronized (mInstallLock) {
7073 args.cleanUpResourcesLI();
7075 synchronized (mPackages) {
7076 mSettings.enableSystemPackageLPw(ps.name);
7078 updatedPkgBetter = true;
7083 if (updatedPkg != null) {
7084 // An updated system app will not have the PARSE_IS_SYSTEM flag set
7086 policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7088 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7089 // flag set initially
7090 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7091 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7095 // Verify certificates against what was last scanned
7096 collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7099 * A new system app appeared, but we already had a non-system one of the
7100 * same name installed earlier.
7102 boolean shouldHideSystemApp = false;
7103 if (updatedPkg == null && ps != null
7104 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7106 * Check to make sure the signatures match first. If they don't,
7107 * wipe the installed application and its data.
7109 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7110 != PackageManager.SIGNATURE_MATCH) {
7111 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7112 + " signatures don't match existing userdata copy; removing");
7113 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7114 "scanPackageInternalLI")) {
7115 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7120 * If the newly-added system app is an older version than the
7121 * already installed version, hide it. It will be scanned later
7122 * and re-added like an update.
7124 if (pkg.mVersionCode <= ps.versionCode) {
7125 shouldHideSystemApp = true;
7126 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7127 + " but new version " + pkg.mVersionCode + " better than installed "
7128 + ps.versionCode + "; hiding system");
7131 * The newly found system app is a newer version that the
7132 * one previously installed. Simply remove the
7133 * already-installed application and replace it with our own
7134 * while keeping the application data.
7136 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7137 + " reverting from " + ps.codePathString + ": new version "
7138 + pkg.mVersionCode + " better than installed " + ps.versionCode);
7139 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7140 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7141 synchronized (mInstallLock) {
7142 args.cleanUpResourcesLI();
7148 // The apk is forward locked (not public) if its code and resources
7149 // are kept in different files. (except for app in either system or
7151 // TODO grab this value from PackageSettings
7152 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7153 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7154 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7158 // TODO: extend to support forward-locked splits
7159 String resourcePath = null;
7160 String baseResourcePath = null;
7161 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7162 if (ps != null && ps.resourcePathString != null) {
7163 resourcePath = ps.resourcePathString;
7164 baseResourcePath = ps.resourcePathString;
7166 // Should not happen at all. Just log an error.
7167 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7170 resourcePath = pkg.codePath;
7171 baseResourcePath = pkg.baseCodePath;
7174 // Set application objects path explicitly.
7175 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7176 pkg.setApplicationInfoCodePath(pkg.codePath);
7177 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7178 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7179 pkg.setApplicationInfoResourcePath(resourcePath);
7180 pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7181 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7183 // Note that we invoke the following method only if we are about to unpack an application
7184 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7185 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7188 * If the system app should be overridden by a previously installed
7189 * data, hide the system app now and let the /data/app scan pick it up
7192 if (shouldHideSystemApp) {
7193 synchronized (mPackages) {
7194 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7201 private static String fixProcessName(String defProcessName,
7202 String processName, int uid) {
7203 if (processName == null) {
7204 return defProcessName;
7209 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7210 throws PackageManagerException {
7211 if (pkgSetting.signatures.mSignatures != null) {
7212 // Already existing package. Make sure signatures match
7213 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7214 == PackageManager.SIGNATURE_MATCH;
7216 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7217 == PackageManager.SIGNATURE_MATCH;
7220 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7221 == PackageManager.SIGNATURE_MATCH;
7224 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7225 + pkg.packageName + " signatures do not match the "
7226 + "previously installed version; ignoring!");
7230 // Check for shared user signatures
7231 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7232 // Already existing package. Make sure signatures match
7233 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7234 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7236 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7237 == PackageManager.SIGNATURE_MATCH;
7240 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7241 == PackageManager.SIGNATURE_MATCH;
7244 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7245 "Package " + pkg.packageName
7246 + " has no signatures that match those in shared user "
7247 + pkgSetting.sharedUser.name + "; ignoring!");
7253 * Enforces that only the system UID or root's UID can call a method exposed
7256 * @param message used as message if SecurityException is thrown
7257 * @throws SecurityException if the caller is not system or root
7259 private static final void enforceSystemOrRoot(String message) {
7260 final int uid = Binder.getCallingUid();
7261 if (uid != Process.SYSTEM_UID && uid != 0) {
7262 throw new SecurityException(message);
7267 public void performFstrimIfNeeded() {
7268 enforceSystemOrRoot("Only the system can request fstrim");
7270 // Before everything else, see whether we need to fstrim.
7272 IMountService ms = PackageHelper.getMountService();
7274 boolean doTrim = false;
7275 final long interval = android.provider.Settings.Global.getLong(
7276 mContext.getContentResolver(),
7277 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7278 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7280 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7281 if (timeSinceLast > interval) {
7283 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7284 + "; running immediately");
7288 final boolean dexOptDialogShown;
7289 synchronized (mPackages) {
7290 dexOptDialogShown = mDexOptDialogShown;
7292 if (!isFirstBoot() && dexOptDialogShown) {
7294 ActivityManagerNative.getDefault().showBootMessage(
7295 mContext.getResources().getString(
7296 R.string.android_upgrading_fstrim), true);
7297 } catch (RemoteException e) {
7300 ms.runMaintenance();
7303 Slog.e(TAG, "Mount service unavailable!");
7305 } catch (RemoteException e) {
7306 // Can't happen; MountService is local
7311 public void updatePackagesIfNeeded() {
7312 enforceSystemOrRoot("Only the system can request package update");
7314 // We need to re-extract after an OTA.
7315 boolean causeUpgrade = isUpgrade();
7317 // First boot or factory reset.
7318 // Note: we also handle devices that are upgrading to N right now as if it is their
7319 // first boot, as they do not have profile data.
7320 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7322 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7323 boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7325 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7329 List<PackageParser.Package> pkgs;
7330 synchronized (mPackages) {
7331 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7334 final long startTime = System.nanoTime();
7335 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7336 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7338 final int elapsedTimeSeconds =
7339 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7341 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7342 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7343 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7344 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7345 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7349 * Performs dexopt on the set of packages in {@code packages} and returns an int array
7350 * containing statistics about the invocation. The array consists of three elements,
7351 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7352 * and {@code numberOfPackagesFailed}.
7354 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7355 String compilerFilter) {
7357 int numberOfPackagesVisited = 0;
7358 int numberOfPackagesOptimized = 0;
7359 int numberOfPackagesSkipped = 0;
7360 int numberOfPackagesFailed = 0;
7361 final int numberOfPackagesToDexopt = pkgs.size();
7363 for (PackageParser.Package pkg : pkgs) {
7364 numberOfPackagesVisited++;
7366 if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7368 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7370 numberOfPackagesSkipped++;
7375 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7376 numberOfPackagesToDexopt + ": " + pkg.packageName);
7381 ActivityManagerNative.getDefault().showBootMessage(
7382 mContext.getResources().getString(R.string.android_upgrading_apk,
7383 numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7384 } catch (RemoteException e) {
7386 synchronized (mPackages) {
7387 mDexOptDialogShown = true;
7391 // If the OTA updates a system app which was previously preopted to a non-preopted state
7392 // the app might end up being verified at runtime. That's because by default the apps
7393 // are verify-profile but for preopted apps there's no profile.
7394 // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7395 // that before the OTA the app was preopted) the app gets compiled with a non-profile
7396 // filter (by default interpret-only).
7397 // Note that at this stage unused apps are already filtered.
7398 if (isSystemApp(pkg) &&
7399 DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7400 !Environment.getReferenceProfile(pkg.packageName).exists()) {
7401 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7404 // checkProfiles is false to avoid merging profiles during boot which
7405 // might interfere with background compilation (b/28612421).
7406 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7407 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7408 // trade-off worth doing to save boot time work.
7409 int dexOptStatus = performDexOptTraced(pkg.packageName,
7410 false /* checkProfiles */,
7413 switch (dexOptStatus) {
7414 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7415 numberOfPackagesOptimized++;
7417 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7418 numberOfPackagesSkipped++;
7420 case PackageDexOptimizer.DEX_OPT_FAILED:
7421 numberOfPackagesFailed++;
7424 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7429 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7430 numberOfPackagesFailed };
7434 public void notifyPackageUse(String packageName, int reason) {
7435 synchronized (mPackages) {
7436 PackageParser.Package p = mPackages.get(packageName);
7440 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7444 // TODO: this is not used nor needed. Delete it.
7446 public boolean performDexOptIfNeeded(String packageName) {
7447 int dexOptStatus = performDexOptTraced(packageName,
7448 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7449 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7453 public boolean performDexOpt(String packageName,
7454 boolean checkProfiles, int compileReason, boolean force) {
7455 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7456 getCompilerFilterForReason(compileReason), force);
7457 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7461 public boolean performDexOptMode(String packageName,
7462 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7463 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7464 targetCompilerFilter, force);
7465 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7468 private int performDexOptTraced(String packageName,
7469 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7470 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7472 return performDexOptInternal(packageName, checkProfiles,
7473 targetCompilerFilter, force);
7475 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7479 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7480 // if the package can now be considered up to date for the given filter.
7481 private int performDexOptInternal(String packageName,
7482 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7483 PackageParser.Package p;
7484 synchronized (mPackages) {
7485 p = mPackages.get(packageName);
7487 // Package could not be found. Report failure.
7488 return PackageDexOptimizer.DEX_OPT_FAILED;
7490 mPackageUsage.maybeWriteAsync(mPackages);
7491 mCompilerStats.maybeWriteAsync();
7493 long callingId = Binder.clearCallingIdentity();
7495 synchronized (mInstallLock) {
7496 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7497 targetCompilerFilter, force);
7500 Binder.restoreCallingIdentity(callingId);
7504 public ArraySet<String> getOptimizablePackages() {
7505 ArraySet<String> pkgs = new ArraySet<String>();
7506 synchronized (mPackages) {
7507 for (PackageParser.Package p : mPackages.values()) {
7508 if (PackageDexOptimizer.canOptimizePackage(p)) {
7509 pkgs.add(p.packageName);
7516 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7517 boolean checkProfiles, String targetCompilerFilter,
7519 // Select the dex optimizer based on the force parameter.
7520 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7521 // allocate an object here.
7522 PackageDexOptimizer pdo = force
7523 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7524 : mPackageDexOptimizer;
7526 // Optimize all dependencies first. Note: we ignore the return value and march on
7528 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7529 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7530 if (!deps.isEmpty()) {
7531 for (PackageParser.Package depPackage : deps) {
7532 // TODO: Analyze and investigate if we (should) profile libraries.
7533 // Currently this will do a full compilation of the library by default.
7534 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7535 false /* checkProfiles */,
7536 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7537 getOrCreateCompilerPackageStats(depPackage));
7540 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7541 targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7544 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7545 if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7546 ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7547 Set<String> collectedNames = new HashSet<>();
7548 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7554 return Collections.emptyList();
7558 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7559 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7560 if (!collectedNames.contains(p.packageName)) {
7561 collectedNames.add(p.packageName);
7564 if (p.usesLibraries != null) {
7565 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7567 if (p.usesOptionalLibraries != null) {
7568 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7574 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7575 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7576 for (String libName : libs) {
7577 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7578 if (libPkg != null) {
7579 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7584 private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7585 synchronized (mPackages) {
7586 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7587 if (lib != null && lib.apk != null) {
7588 return mPackages.get(lib.apk);
7594 public void shutdown() {
7595 mPackageUsage.writeNow(mPackages);
7596 mCompilerStats.writeNow();
7600 public void dumpProfiles(String packageName) {
7601 PackageParser.Package pkg;
7602 synchronized (mPackages) {
7603 pkg = mPackages.get(packageName);
7605 throw new IllegalArgumentException("Unknown package: " + packageName);
7608 /* Only the shell, root, or the app user should be able to dump profiles. */
7609 int callingUid = Binder.getCallingUid();
7610 if (callingUid != Process.SHELL_UID &&
7611 callingUid != Process.ROOT_UID &&
7612 callingUid != pkg.applicationInfo.uid) {
7613 throw new SecurityException("dumpProfiles");
7616 synchronized (mInstallLock) {
7617 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7618 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7620 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7621 String gid = Integer.toString(sharedGid);
7622 String codePaths = TextUtils.join(";", allCodePaths);
7623 mInstaller.dumpProfiles(gid, packageName, codePaths);
7624 } catch (InstallerException e) {
7625 Slog.w(TAG, "Failed to dump profiles", e);
7627 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7632 public void forceDexOpt(String packageName) {
7633 enforceSystemOrRoot("forceDexOpt");
7635 PackageParser.Package pkg;
7636 synchronized (mPackages) {
7637 pkg = mPackages.get(packageName);
7639 throw new IllegalArgumentException("Unknown package: " + packageName);
7643 synchronized (mInstallLock) {
7644 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7646 // Whoever is calling forceDexOpt wants a fully compiled package.
7647 // Don't use profiles since that may cause compilation to be skipped.
7648 final int res = performDexOptInternalWithDependenciesLI(pkg,
7649 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7652 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7653 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7654 throw new IllegalStateException("Failed to dexopt: " + res);
7659 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7660 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7661 Slog.w(TAG, "Unable to update from " + oldPkg.name
7662 + " to " + newPkg.packageName
7663 + ": old package not in system partition");
7665 } else if (mPackages.get(oldPkg.name) != null) {
7666 Slog.w(TAG, "Unable to update from " + oldPkg.name
7667 + " to " + newPkg.packageName
7668 + ": old package still exists");
7674 void removeCodePathLI(File codePath) {
7675 if (codePath.isDirectory()) {
7677 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7678 } catch (InstallerException e) {
7679 Slog.w(TAG, "Failed to remove code path", e);
7686 private int[] resolveUserIds(int userId) {
7687 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7690 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7692 Slog.wtf(TAG, "Package was null!", new Throwable());
7695 clearAppDataLeafLIF(pkg, userId, flags);
7696 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7697 for (int i = 0; i < childCount; i++) {
7698 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7702 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7703 final PackageSetting ps;
7704 synchronized (mPackages) {
7705 ps = mSettings.mPackages.get(pkg.packageName);
7707 for (int realUserId : resolveUserIds(userId)) {
7708 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7710 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7712 } catch (InstallerException e) {
7713 Slog.w(TAG, String.valueOf(e));
7718 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7720 Slog.wtf(TAG, "Package was null!", new Throwable());
7723 destroyAppDataLeafLIF(pkg, userId, flags);
7724 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7725 for (int i = 0; i < childCount; i++) {
7726 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7730 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7731 final PackageSetting ps;
7732 synchronized (mPackages) {
7733 ps = mSettings.mPackages.get(pkg.packageName);
7735 for (int realUserId : resolveUserIds(userId)) {
7736 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7738 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7740 } catch (InstallerException e) {
7741 Slog.w(TAG, String.valueOf(e));
7746 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7748 Slog.wtf(TAG, "Package was null!", new Throwable());
7751 destroyAppProfilesLeafLIF(pkg);
7752 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7753 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7754 for (int i = 0; i < childCount; i++) {
7755 destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7756 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7757 true /* removeBaseMarker */);
7761 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7762 boolean removeBaseMarker) {
7763 if (pkg.isForwardLocked()) {
7767 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7769 path = PackageManagerServiceUtils.realpath(new File(path));
7770 } catch (IOException e) {
7771 // TODO: Should we return early here ?
7772 Slog.w(TAG, "Failed to get canonical path", e);
7776 final String useMarker = path.replace('/', '@');
7777 for (int realUserId : resolveUserIds(userId)) {
7778 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7779 if (removeBaseMarker) {
7780 File foreignUseMark = new File(profileDir, useMarker);
7781 if (foreignUseMark.exists()) {
7782 if (!foreignUseMark.delete()) {
7783 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7789 File[] markers = profileDir.listFiles();
7790 if (markers != null) {
7791 final String searchString = "@" + pkg.packageName + "@";
7792 // We also delete all markers that contain the package name we're
7793 // uninstalling. These are associated with secondary dex-files belonging
7794 // to the package. Reconstructing the path of these dex files is messy
7796 for (File marker : markers) {
7797 if (marker.getName().indexOf(searchString) > 0) {
7798 if (!marker.delete()) {
7799 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7809 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7811 mInstaller.destroyAppProfiles(pkg.packageName);
7812 } catch (InstallerException e) {
7813 Slog.w(TAG, String.valueOf(e));
7817 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7819 Slog.wtf(TAG, "Package was null!", new Throwable());
7822 clearAppProfilesLeafLIF(pkg);
7823 // We don't remove the base foreign use marker when clearing profiles because
7824 // we will rename it when the app is updated. Unlike the actual profile contents,
7825 // the foreign use marker is good across installs.
7826 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7827 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7828 for (int i = 0; i < childCount; i++) {
7829 clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7833 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7835 mInstaller.clearAppProfiles(pkg.packageName);
7836 } catch (InstallerException e) {
7837 Slog.w(TAG, String.valueOf(e));
7841 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7842 long lastUpdateTime) {
7843 // Set parent install/update time
7844 PackageSetting ps = (PackageSetting) pkg.mExtras;
7846 ps.firstInstallTime = firstInstallTime;
7847 ps.lastUpdateTime = lastUpdateTime;
7849 // Set children install/update time
7850 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7851 for (int i = 0; i < childCount; i++) {
7852 PackageParser.Package childPkg = pkg.childPackages.get(i);
7853 ps = (PackageSetting) childPkg.mExtras;
7855 ps.firstInstallTime = firstInstallTime;
7856 ps.lastUpdateTime = lastUpdateTime;
7861 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7862 PackageParser.Package changingLib) {
7863 if (file.path != null) {
7864 usesLibraryFiles.add(file.path);
7867 PackageParser.Package p = mPackages.get(file.apk);
7868 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7869 // If we are doing this while in the middle of updating a library apk,
7870 // then we need to make sure to use that new apk for determining the
7871 // dependencies here. (We haven't yet finished committing the new apk
7872 // to the package manager state.)
7873 if (p == null || p.packageName.equals(changingLib.packageName)) {
7878 usesLibraryFiles.addAll(p.getAllCodePaths());
7882 private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7883 PackageParser.Package changingLib) throws PackageManagerException {
7884 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7885 final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7886 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7887 for (int i=0; i<N; i++) {
7888 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7890 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7891 "Package " + pkg.packageName + " requires unavailable shared library "
7892 + pkg.usesLibraries.get(i) + "; failing!");
7894 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7896 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7897 for (int i=0; i<N; i++) {
7898 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7900 Slog.w(TAG, "Package " + pkg.packageName
7901 + " desires unavailable shared library "
7902 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7904 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7907 N = usesLibraryFiles.size();
7909 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7911 pkg.usesLibraryFiles = null;
7916 private static boolean hasString(List<String> list, List<String> which) {
7920 for (int i=list.size()-1; i>=0; i--) {
7921 for (int j=which.size()-1; j>=0; j--) {
7922 if (which.get(j).equals(list.get(i))) {
7930 private void updateAllSharedLibrariesLPw() {
7931 for (PackageParser.Package pkg : mPackages.values()) {
7933 updateSharedLibrariesLPw(pkg, null);
7934 } catch (PackageManagerException e) {
7935 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7940 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7941 PackageParser.Package changingPkg) {
7942 ArrayList<PackageParser.Package> res = null;
7943 for (PackageParser.Package pkg : mPackages.values()) {
7944 if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7945 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7947 res = new ArrayList<PackageParser.Package>();
7951 updateSharedLibrariesLPw(pkg, changingPkg);
7952 } catch (PackageManagerException e) {
7953 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7961 * Derive the value of the {@code cpuAbiOverride} based on the provided
7962 * value and an optional stored value from the package settings.
7964 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7965 String cpuAbiOverride = null;
7967 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7968 cpuAbiOverride = null;
7969 } else if (abiOverride != null) {
7970 cpuAbiOverride = abiOverride;
7971 } else if (settings != null) {
7972 cpuAbiOverride = settings.cpuAbiOverrideString;
7975 return cpuAbiOverride;
7978 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7979 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7980 throws PackageManagerException {
7981 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7982 // If the package has children and this is the first dive in the function
7983 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7984 // whether all packages (parent and children) would be successfully scanned
7985 // before the actual scan since scanning mutates internal state and we want
7986 // to atomically install the package and its children.
7987 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7988 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7989 scanFlags |= SCAN_CHECK_ONLY;
7992 scanFlags &= ~SCAN_CHECK_ONLY;
7995 final PackageParser.Package scannedPkg;
7998 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7999 // Scan the children
8000 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8001 for (int i = 0; i < childCount; i++) {
8002 PackageParser.Package childPkg = pkg.childPackages.get(i);
8003 scanPackageLI(childPkg, policyFlags,
8004 scanFlags, currentTime, user);
8007 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8010 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8011 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8017 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8018 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8019 boolean success = false;
8021 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8026 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8027 // DELETE_DATA_ON_FAILURES is only used by frozen paths
8028 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8029 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8030 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8036 * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8038 private static boolean apkHasCode(String fileName) {
8039 StrictJarFile jarFile = null;
8041 jarFile = new StrictJarFile(fileName,
8042 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8043 return jarFile.findEntry("classes.dex") != null;
8044 } catch (IOException ignore) {
8047 if (jarFile != null) {
8050 } catch (IOException ignore) {}
8056 * Enforces code policy for the package. This ensures that if an APK has
8057 * declared hasCode="true" in its manifest that the APK actually contains
8060 * @throws PackageManagerException If bytecode could not be found when it should exist
8062 private static void enforceCodePolicy(PackageParser.Package pkg)
8063 throws PackageManagerException {
8064 final boolean shouldHaveCode =
8065 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8066 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8067 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8068 "Package " + pkg.baseCodePath + " code is missing");
8071 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8072 for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8073 final boolean splitShouldHaveCode =
8074 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8075 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8076 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8077 "Package " + pkg.splitCodePaths[i] + " code is missing");
8083 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8084 final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8085 throws PackageManagerException {
8086 final File scanFile = new File(pkg.codePath);
8087 if (pkg.applicationInfo.getCodePath() == null ||
8088 pkg.applicationInfo.getResourcePath() == null) {
8089 // Bail out. The resource and code paths haven't been set.
8090 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8091 "Code and resource paths haven't been set correctly");
8095 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8096 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8097 if (pkg.applicationInfo.isDirectBootAware()) {
8098 // we're direct boot aware; set for all components
8099 for (PackageParser.Service s : pkg.services) {
8100 s.info.encryptionAware = s.info.directBootAware = true;
8102 for (PackageParser.Provider p : pkg.providers) {
8103 p.info.encryptionAware = p.info.directBootAware = true;
8105 for (PackageParser.Activity a : pkg.activities) {
8106 a.info.encryptionAware = a.info.directBootAware = true;
8108 for (PackageParser.Activity r : pkg.receivers) {
8109 r.info.encryptionAware = r.info.directBootAware = true;
8113 // Only allow system apps to be flagged as core apps.
8114 pkg.coreApp = false;
8115 // clear flags not applicable to regular apps
8116 pkg.applicationInfo.privateFlags &=
8117 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8118 pkg.applicationInfo.privateFlags &=
8119 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8121 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8123 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8124 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8127 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8128 enforceCodePolicy(pkg);
8131 if (mCustomResolverComponentName != null &&
8132 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8133 setUpCustomResolverActivity(pkg);
8136 if (pkg.packageName.equals("android")) {
8137 synchronized (mPackages) {
8138 if (mAndroidApplication != null) {
8139 Slog.w(TAG, "*************************************************");
8140 Slog.w(TAG, "Core android package being redefined. Skipping.");
8141 Slog.w(TAG, " file=" + scanFile);
8142 Slog.w(TAG, "*************************************************");
8143 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8144 "Core android package being redefined. Skipping.");
8147 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8148 // Set up information for our fall-back user intent resolution activity.
8149 mPlatformPackage = pkg;
8150 pkg.mVersionCode = mSdkVersion;
8151 mAndroidApplication = pkg.applicationInfo;
8153 if (!mResolverReplaced) {
8154 mResolveActivity.applicationInfo = mAndroidApplication;
8155 mResolveActivity.name = ResolverActivity.class.getName();
8156 mResolveActivity.packageName = mAndroidApplication.packageName;
8157 mResolveActivity.processName = "system:ui";
8158 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8159 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8160 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8161 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8162 mResolveActivity.exported = true;
8163 mResolveActivity.enabled = true;
8164 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8165 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8166 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8167 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8168 | ActivityInfo.CONFIG_ORIENTATION
8169 | ActivityInfo.CONFIG_KEYBOARD
8170 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8171 mResolveInfo.activityInfo = mResolveActivity;
8172 mResolveInfo.priority = 0;
8173 mResolveInfo.preferredOrder = 0;
8174 mResolveInfo.match = 0;
8175 mResolveComponentName = new ComponentName(
8176 mAndroidApplication.packageName, mResolveActivity.name);
8182 if (DEBUG_PACKAGE_SCANNING) {
8183 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8184 Log.d(TAG, "Scanning package " + pkg.packageName);
8187 final PackageParser.Package oldPkg;
8189 synchronized (mPackages) {
8190 if (mPackages.containsKey(pkg.packageName)
8191 || mSharedLibraries.containsKey(pkg.packageName)) {
8192 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8193 "Application package " + pkg.packageName
8194 + " already installed. Skipping duplicate.");
8197 final PackageSetting oldPkgSetting = mSettings.peekPackageLPr(pkg.packageName);
8198 if (oldPkgSetting == null) {
8201 oldPkg = oldPkgSetting.pkg;
8204 // If we're only installing presumed-existing packages, require that the
8205 // scanned APK is both already known and at the path previously established
8206 // for it. Previously unknown packages we pick up normally, but if we have an
8207 // a priori expectation about this package's install presence, enforce it.
8208 // With a singular exception for new system packages. When an OTA contains
8209 // a new system package, we allow the codepath to change from a system location
8210 // to the user-installed location. If we don't allow this change, any newer,
8211 // user-installed version of the application will be ignored.
8212 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8213 if (mExpectingBetter.containsKey(pkg.packageName)) {
8214 logCriticalInfo(Log.WARN,
8215 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8217 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8218 if (known != null) {
8219 if (DEBUG_PACKAGE_SCANNING) {
8220 Log.d(TAG, "Examining " + pkg.codePath
8221 + " and requiring known paths " + known.codePathString
8222 + " & " + known.resourcePathString);
8224 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8225 || !pkg.applicationInfo.getResourcePath().equals(
8226 known.resourcePathString)) {
8227 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8228 "Application package " + pkg.packageName
8229 + " found at " + pkg.applicationInfo.getCodePath()
8230 + " but expected at " + known.codePathString
8238 // Initialize package source and resource directories
8239 File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8240 File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8242 SharedUserSetting suid = null;
8243 PackageSetting pkgSetting = null;
8245 if (!isSystemApp(pkg)) {
8246 // Only system apps can use these features.
8247 pkg.mOriginalPackages = null;
8248 pkg.mRealPackage = null;
8249 pkg.mAdoptPermissions = null;
8252 // Getting the package setting may have a side-effect, so if we
8253 // are only checking if scan would succeed, stash a copy of the
8254 // old setting to restore at the end.
8255 PackageSetting nonMutatedPs = null;
8258 synchronized (mPackages) {
8259 if (pkg.mSharedUserId != null) {
8260 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8262 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8263 "Creating application package " + pkg.packageName
8264 + " for shared user failed");
8266 if (DEBUG_PACKAGE_SCANNING) {
8267 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8268 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8269 + "): packages=" + suid.packages);
8273 // Check if we are renaming from an original package name.
8274 PackageSetting origPackage = null;
8275 String realName = null;
8276 if (pkg.mOriginalPackages != null) {
8277 // This package may need to be renamed to a previously
8278 // installed name. Let's check on that...
8279 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8280 if (pkg.mOriginalPackages.contains(renamed)) {
8281 // This package had originally been installed as the
8282 // original name, and we have already taken care of
8283 // transitioning to the new one. Just update the new
8284 // one to continue using the old name.
8285 realName = pkg.mRealPackage;
8286 if (!pkg.packageName.equals(renamed)) {
8287 // Callers into this function may have already taken
8288 // care of renaming the package; only do it here if
8289 // it is not already done.
8290 pkg.setPackageName(renamed);
8294 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8295 if ((origPackage = mSettings.peekPackageLPr(
8296 pkg.mOriginalPackages.get(i))) != null) {
8297 // We do have the package already installed under its
8298 // original name... should we use it?
8299 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8300 // New package is not compatible with original.
8303 } else if (origPackage.sharedUser != null) {
8304 // Make sure uid is compatible between packages.
8305 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8306 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8307 + " to " + pkg.packageName + ": old uid "
8308 + origPackage.sharedUser.name
8309 + " differs from " + pkg.mSharedUserId);
8313 // TODO: Add case when shared user id is added [b/28144775]
8315 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8316 + pkg.packageName + " to old name " + origPackage.name);
8324 if (mTransferedPackages.contains(pkg.packageName)) {
8325 Slog.w(TAG, "Package " + pkg.packageName
8326 + " was transferred to another, but its .apk remains");
8329 // See comments in nonMutatedPs declaration
8330 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8331 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8332 if (foundPs != null) {
8333 nonMutatedPs = new PackageSetting(foundPs);
8337 // Just create the setting, don't add it yet. For already existing packages
8338 // the PkgSetting exists already and doesn't have to be created.
8339 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8340 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8341 pkg.applicationInfo.primaryCpuAbi,
8342 pkg.applicationInfo.secondaryCpuAbi,
8343 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8345 if (pkgSetting == null) {
8346 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8347 "Creating application package " + pkg.packageName + " failed");
8350 if (pkgSetting.origPackage != null) {
8351 // If we are first transitioning from an original package,
8352 // fix up the new package's name now. We need to do this after
8353 // looking up the package under its new name, so getPackageLP
8354 // can take care of fiddling things correctly.
8355 pkg.setPackageName(origPackage.name);
8357 // File a report about this.
8358 String msg = "New package " + pkgSetting.realName
8359 + " renamed to replace old package " + pkgSetting.name;
8360 reportSettingsProblem(Log.WARN, msg);
8362 // Make a note of it.
8363 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8364 mTransferedPackages.add(origPackage.name);
8367 // No longer need to retain this.
8368 pkgSetting.origPackage = null;
8371 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8372 // Make a note of it.
8373 mTransferedPackages.add(pkg.packageName);
8376 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8377 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8380 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8381 // Check all shared libraries and map to their actual file path.
8382 // We only do this here for apps not on a system dir, because those
8383 // are the only ones that can fail an install due to this. We
8384 // will take care of the system apps by updating all of their
8385 // library paths after the scan is done.
8386 updateSharedLibrariesLPw(pkg, null);
8389 if (mFoundPolicyFile) {
8390 SELinuxMMAC.assignSeinfoValue(pkg);
8393 pkg.applicationInfo.uid = pkgSetting.appId;
8394 pkg.mExtras = pkgSetting;
8395 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8396 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8397 // We just determined the app is signed correctly, so bring
8398 // over the latest parsed certs.
8399 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8401 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8402 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8403 "Package " + pkg.packageName + " upgrade keys do not match the "
8404 + "previously installed version");
8406 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8407 String msg = "System package " + pkg.packageName
8408 + " signature changed; retaining data.";
8409 reportSettingsProblem(Log.WARN, msg);
8414 verifySignaturesLP(pkgSetting, pkg);
8415 // We just determined the app is signed correctly, so bring
8416 // over the latest parsed certs.
8417 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8418 } catch (PackageManagerException e) {
8419 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8422 // The signature has changed, but this package is in the system
8423 // image... let's recover!
8424 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8425 // However... if this package is part of a shared user, but it
8426 // doesn't match the signature of the shared user, let's fail.
8427 // What this means is that you can't change the signatures
8428 // associated with an overall shared user, which doesn't seem all
8429 // that unreasonable.
8430 if (pkgSetting.sharedUser != null) {
8431 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8432 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8433 throw new PackageManagerException(
8434 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8435 "Signature mismatch for shared user: "
8436 + pkgSetting.sharedUser);
8439 // File a report about this.
8440 String msg = "System package " + pkg.packageName
8441 + " signature changed; retaining data.";
8442 reportSettingsProblem(Log.WARN, msg);
8445 // Verify that this new package doesn't have any content providers
8446 // that conflict with existing packages. Only do this if the
8447 // package isn't already installed, since we don't want to break
8448 // things that are installed.
8449 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8450 final int N = pkg.providers.size();
8452 for (i=0; i<N; i++) {
8453 PackageParser.Provider p = pkg.providers.get(i);
8454 if (p.info.authority != null) {
8455 String names[] = p.info.authority.split(";");
8456 for (int j = 0; j < names.length; j++) {
8457 if (mProvidersByAuthority.containsKey(names[j])) {
8458 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8459 final String otherPackageName =
8460 ((other != null && other.getComponentName() != null) ?
8461 other.getComponentName().getPackageName() : "?");
8462 throw new PackageManagerException(
8463 INSTALL_FAILED_CONFLICTING_PROVIDER,
8464 "Can't install because provider name " + names[j]
8465 + " (in package " + pkg.applicationInfo.packageName
8466 + ") is already used by " + otherPackageName);
8473 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8474 // This package wants to adopt ownership of permissions from
8476 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8477 final String origName = pkg.mAdoptPermissions.get(i);
8478 final PackageSetting orig = mSettings.peekPackageLPr(origName);
8480 if (verifyPackageUpdateLPr(orig, pkg)) {
8481 Slog.i(TAG, "Adopting permissions from " + origName + " to "
8483 mSettings.transferPermissionsLPw(origName, pkg.packageName);
8490 final String pkgName = pkg.packageName;
8492 final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8493 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8494 pkg.applicationInfo.processName = fixProcessName(
8495 pkg.applicationInfo.packageName,
8496 pkg.applicationInfo.processName,
8497 pkg.applicationInfo.uid);
8499 if (pkg != mPlatformPackage) {
8500 // Get all of our default paths setup
8501 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8504 final String path = scanFile.getPath();
8505 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8507 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8508 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8510 // Some system apps still use directory structure for native libraries
8511 // in which case we might end up not detecting abi solely based on apk
8512 // structure. Try to detect abi based on directory structure.
8513 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8514 pkg.applicationInfo.primaryCpuAbi == null) {
8515 setBundledAppAbisAndRoots(pkg, pkgSetting);
8516 setNativeLibraryPaths(pkg);
8520 if ((scanFlags & SCAN_MOVE) != 0) {
8521 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8522 // but we already have this packages package info in the PackageSetting. We just
8523 // use that and derive the native library path based on the new codepath.
8524 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8525 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8528 // Set native library paths again. For moves, the path will be updated based on the
8529 // ABIs we've determined above. For non-moves, the path will be updated based on the
8530 // ABIs we determined during compilation, but the path will depend on the final
8531 // package path (after the rename away from the stage path).
8532 setNativeLibraryPaths(pkg);
8535 // This is a special case for the "system" package, where the ABI is
8536 // dictated by the zygote configuration (and init.rc). We should keep track
8537 // of this ABI so that we can deal with "normal" applications that run under
8538 // the same UID correctly.
8539 if (mPlatformPackage == pkg) {
8540 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8541 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8544 // If there's a mismatch between the abi-override in the package setting
8545 // and the abiOverride specified for the install. Warn about this because we
8546 // would've already compiled the app without taking the package setting into
8548 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8549 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8550 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8551 " for package " + pkg.packageName);
8555 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8556 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8557 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8559 // Copy the derived override back to the parsed package, so that we can
8560 // update the package settings accordingly.
8561 pkg.cpuAbiOverride = cpuAbiOverride;
8563 if (DEBUG_ABI_SELECTION) {
8564 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8565 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8566 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8569 // Push the derived path down into PackageSettings so we know what to
8570 // clean up at uninstall time.
8571 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8573 if (DEBUG_ABI_SELECTION) {
8574 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8575 " primary=" + pkg.applicationInfo.primaryCpuAbi +
8576 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8579 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8580 // We don't do this here during boot because we can do it all
8581 // at once after scanning all existing packages.
8583 // We also do this *before* we perform dexopt on this package, so that
8584 // we can avoid redundant dexopts, and also to make sure we've got the
8585 // code and package path correct.
8586 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8587 pkg, true /* boot complete */);
8590 if (mFactoryTest && pkg.requestedPermissions.contains(
8591 android.Manifest.permission.FACTORY_TEST)) {
8592 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8595 if (isSystemApp(pkg)) {
8596 pkgSetting.isOrphaned = true;
8599 ArrayList<PackageParser.Package> clientLibPkgs = null;
8601 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8602 if (nonMutatedPs != null) {
8603 synchronized (mPackages) {
8604 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8610 // Only privileged apps and updated privileged apps can add child packages.
8611 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8612 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8613 throw new PackageManagerException("Only privileged apps and updated "
8614 + "privileged apps can add child packages. Ignoring package "
8617 final int childCount = pkg.childPackages.size();
8618 for (int i = 0; i < childCount; i++) {
8619 PackageParser.Package childPkg = pkg.childPackages.get(i);
8620 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8621 childPkg.packageName)) {
8622 throw new PackageManagerException("Cannot override a child package of "
8623 + "another disabled system app. Ignoring package " + pkg.packageName);
8629 synchronized (mPackages) {
8630 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8631 // Only system apps can add new shared libraries.
8632 if (pkg.libraryNames != null) {
8633 for (int i=0; i<pkg.libraryNames.size(); i++) {
8634 String name = pkg.libraryNames.get(i);
8635 boolean allowed = false;
8636 if (pkg.isUpdatedSystemApp()) {
8637 // New library entries can only be added through the
8638 // system image. This is important to get rid of a lot
8639 // of nasty edge cases: for example if we allowed a non-
8640 // system update of the app to add a library, then uninstalling
8641 // the update would make the library go away, and assumptions
8642 // we made such as through app install filtering would now
8643 // have allowed apps on the device which aren't compatible
8644 // with it. Better to just have the restriction here, be
8645 // conservative, and create many fewer cases that can negatively
8646 // impact the user experience.
8647 final PackageSetting sysPs = mSettings
8648 .getDisabledSystemPkgLPr(pkg.packageName);
8649 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8650 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8651 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8661 if (!mSharedLibraries.containsKey(name)) {
8662 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8663 } else if (!name.equals(pkg.packageName)) {
8664 Slog.w(TAG, "Package " + pkg.packageName + " library "
8665 + name + " already exists; skipping");
8668 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8669 + name + " that is not declared on system image; skipping");
8672 if ((scanFlags & SCAN_BOOTING) == 0) {
8673 // If we are not booting, we need to update any applications
8674 // that are clients of our shared library. If we are booting,
8675 // this will all be done once the scan is complete.
8676 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8682 if ((scanFlags & SCAN_BOOTING) != 0) {
8683 // No apps can run during boot scan, so they don't need to be frozen
8684 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8685 // Caller asked to not kill app, so it's probably not frozen
8686 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8687 // Caller asked us to ignore frozen check for some reason; they
8688 // probably didn't know the package name
8690 // We're doing major surgery on this package, so it better be frozen
8691 // right now to keep it from launching
8692 checkPackageFrozen(pkgName);
8695 // Also need to kill any apps that are dependent on the library.
8696 if (clientLibPkgs != null) {
8697 for (int i=0; i<clientLibPkgs.size(); i++) {
8698 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8699 killApplication(clientPkg.applicationInfo.packageName,
8700 clientPkg.applicationInfo.uid, "update lib");
8704 // Make sure we're not adding any bogus keyset info
8705 KeySetManagerService ksms = mSettings.mKeySetManagerService;
8706 ksms.assertScannedPackageValid(pkg);
8709 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8711 boolean createIdmapFailed = false;
8712 synchronized (mPackages) {
8713 // We don't expect installation to fail beyond this point
8715 if (pkgSetting.pkg != null) {
8716 // Note that |user| might be null during the initial boot scan. If a codePath
8717 // for an app has changed during a boot scan, it's due to an app update that's
8718 // part of the system partition and marker changes must be applied to all users.
8719 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8720 (user != null) ? user : UserHandle.ALL);
8723 // Add the new setting to mSettings
8724 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8725 // Add the new setting to mPackages
8726 mPackages.put(pkg.applicationInfo.packageName, pkg);
8727 // Make sure we don't accidentally delete its data.
8728 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8729 while (iter.hasNext()) {
8730 PackageCleanItem item = iter.next();
8731 if (pkgName.equals(item.packageName)) {
8736 // Take care of first install / last update times.
8737 if (currentTime != 0) {
8738 if (pkgSetting.firstInstallTime == 0) {
8739 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8740 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8741 pkgSetting.lastUpdateTime = currentTime;
8743 } else if (pkgSetting.firstInstallTime == 0) {
8744 // We need *something*. Take time time stamp of the file.
8745 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8746 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8747 if (scanFileTime != pkgSetting.timeStamp) {
8748 // A package on the system image has changed; consider this
8750 pkgSetting.lastUpdateTime = scanFileTime;
8754 // Add the package's KeySets to the global KeySetManagerService
8755 ksms.addScannedPackageLPw(pkg);
8757 int N = pkg.providers.size();
8758 StringBuilder r = null;
8760 for (i=0; i<N; i++) {
8761 PackageParser.Provider p = pkg.providers.get(i);
8762 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8763 p.info.processName, pkg.applicationInfo.uid);
8764 mProviders.addProvider(p);
8765 p.syncable = p.info.isSyncable;
8766 if (p.info.authority != null) {
8767 String names[] = p.info.authority.split(";");
8768 p.info.authority = null;
8769 for (int j = 0; j < names.length; j++) {
8770 if (j == 1 && p.syncable) {
8771 // We only want the first authority for a provider to possibly be
8772 // syncable, so if we already added this provider using a different
8773 // authority clear the syncable flag. We copy the provider before
8774 // changing it because the mProviders object contains a reference
8775 // to a provider that we don't want to change.
8776 // Only do this for the second authority since the resulting provider
8777 // object can be the same for all future authorities for this provider.
8778 p = new PackageParser.Provider(p);
8781 if (!mProvidersByAuthority.containsKey(names[j])) {
8782 mProvidersByAuthority.put(names[j], p);
8783 if (p.info.authority == null) {
8784 p.info.authority = names[j];
8786 p.info.authority = p.info.authority + ";" + names[j];
8788 if (DEBUG_PACKAGE_SCANNING) {
8789 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8790 Log.d(TAG, "Registered content provider: " + names[j]
8791 + ", className = " + p.info.name + ", isSyncable = "
8792 + p.info.isSyncable);
8795 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8796 Slog.w(TAG, "Skipping provider name " + names[j] +
8797 " (in package " + pkg.applicationInfo.packageName +
8798 "): name already used by "
8799 + ((other != null && other.getComponentName() != null)
8800 ? other.getComponentName().getPackageName() : "?"));
8804 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8806 r = new StringBuilder(256);
8810 r.append(p.info.name);
8814 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
8817 N = pkg.services.size();
8819 for (i=0; i<N; i++) {
8820 PackageParser.Service s = pkg.services.get(i);
8821 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8822 s.info.processName, pkg.applicationInfo.uid);
8823 mServices.addService(s);
8824 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8826 r = new StringBuilder(256);
8830 r.append(s.info.name);
8834 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
8837 N = pkg.receivers.size();
8839 for (i=0; i<N; i++) {
8840 PackageParser.Activity a = pkg.receivers.get(i);
8841 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8842 a.info.processName, pkg.applicationInfo.uid);
8843 mReceivers.addActivity(a, "receiver");
8844 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8846 r = new StringBuilder(256);
8850 r.append(a.info.name);
8854 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
8857 N = pkg.activities.size();
8859 for (i=0; i<N; i++) {
8860 PackageParser.Activity a = pkg.activities.get(i);
8861 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8862 a.info.processName, pkg.applicationInfo.uid);
8863 mActivities.addActivity(a, "activity");
8864 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8866 r = new StringBuilder(256);
8870 r.append(a.info.name);
8874 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
8877 N = pkg.permissionGroups.size();
8879 for (i=0; i<N; i++) {
8880 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8881 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8882 final String curPackageName = cur == null ? null : cur.info.packageName;
8883 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8884 if (cur == null || isPackageUpdate) {
8885 mPermissionGroups.put(pg.info.name, pg);
8886 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8888 r = new StringBuilder(256);
8892 if (isPackageUpdate) {
8895 r.append(pg.info.name);
8898 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8899 + pg.info.packageName + " ignored: original from "
8900 + cur.info.packageName);
8901 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8903 r = new StringBuilder(256);
8908 r.append(pg.info.name);
8913 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
8916 N = pkg.permissions.size();
8918 for (i=0; i<N; i++) {
8919 PackageParser.Permission p = pkg.permissions.get(i);
8921 // Assume by default that we did not install this permission into the system.
8922 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8924 // Now that permission groups have a special meaning, we ignore permission
8925 // groups for legacy apps to prevent unexpected behavior. In particular,
8926 // permissions for one app being granted to someone just becase they happen
8927 // to be in a group defined by another app (before this had no implications).
8928 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8929 p.group = mPermissionGroups.get(p.info.group);
8930 // Warn for a permission in an unknown group.
8931 if (p.info.group != null && p.group == null) {
8932 Slog.w(TAG, "Permission " + p.info.name + " from package "
8933 + p.info.packageName + " in an unknown group " + p.info.group);
8937 ArrayMap<String, BasePermission> permissionMap =
8938 p.tree ? mSettings.mPermissionTrees
8939 : mSettings.mPermissions;
8940 BasePermission bp = permissionMap.get(p.info.name);
8942 // Allow system apps to redefine non-system permissions
8943 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8944 final boolean currentOwnerIsSystem = (bp.perm != null
8945 && isSystemApp(bp.perm.owner));
8946 if (isSystemApp(p.owner)) {
8947 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8948 // It's a built-in permission and no owner, take ownership now
8949 bp.packageSetting = pkgSetting;
8951 bp.uid = pkg.applicationInfo.uid;
8952 bp.sourcePackage = p.info.packageName;
8953 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8954 } else if (!currentOwnerIsSystem) {
8955 String msg = "New decl " + p.owner + " of permission "
8956 + p.info.name + " is system; overriding " + bp.sourcePackage;
8957 reportSettingsProblem(Log.WARN, msg);
8964 bp = new BasePermission(p.info.name, p.info.packageName,
8965 BasePermission.TYPE_NORMAL);
8966 permissionMap.put(p.info.name, bp);
8969 if (bp.perm == null) {
8970 if (bp.sourcePackage == null
8971 || bp.sourcePackage.equals(p.info.packageName)) {
8972 BasePermission tree = findPermissionTreeLP(p.info.name);
8974 || tree.sourcePackage.equals(p.info.packageName)) {
8975 bp.packageSetting = pkgSetting;
8977 bp.uid = pkg.applicationInfo.uid;
8978 bp.sourcePackage = p.info.packageName;
8979 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8980 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8982 r = new StringBuilder(256);
8986 r.append(p.info.name);
8989 Slog.w(TAG, "Permission " + p.info.name + " from package "
8990 + p.info.packageName + " ignored: base tree "
8991 + tree.name + " is from package "
8992 + tree.sourcePackage);
8995 Slog.w(TAG, "Permission " + p.info.name + " from package "
8996 + p.info.packageName + " ignored: original from "
8997 + bp.sourcePackage);
8999 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9001 r = new StringBuilder(256);
9006 r.append(p.info.name);
9009 bp.protectionLevel = p.info.protectionLevel;
9014 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
9017 N = pkg.instrumentation.size();
9019 for (i=0; i<N; i++) {
9020 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9021 a.info.packageName = pkg.applicationInfo.packageName;
9022 a.info.sourceDir = pkg.applicationInfo.sourceDir;
9023 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9024 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9025 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9026 a.info.dataDir = pkg.applicationInfo.dataDir;
9027 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9028 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9030 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9031 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9032 mInstrumentation.put(a.getComponentName(), a);
9033 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9035 r = new StringBuilder(256);
9039 r.append(a.info.name);
9043 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
9046 if (pkg.protectedBroadcasts != null) {
9047 N = pkg.protectedBroadcasts.size();
9048 for (i=0; i<N; i++) {
9049 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9053 pkgSetting.setTimeStamp(scanFileTime);
9055 // Create idmap files for pairs of (packages, overlay packages).
9056 // Note: "android", ie framework-res.apk, is handled by native layers.
9057 if (pkg.mOverlayTarget != null) {
9058 // This is an overlay package.
9059 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9060 if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9061 mOverlays.put(pkg.mOverlayTarget,
9062 new ArrayMap<String, PackageParser.Package>());
9064 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9065 map.put(pkg.packageName, pkg);
9066 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9067 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9068 createIdmapFailed = true;
9071 } else if (mOverlays.containsKey(pkg.packageName) &&
9072 !pkg.packageName.equals("android")) {
9073 // This is a regular package, with one or more known overlay packages.
9074 createIdmapsForPackageLI(pkg);
9077 if (oldPkg != null) {
9078 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
9079 // revokation from this method might need to kill apps which need the
9080 // mPackages lock on a different thread. This would dead lock.
9082 // Hence create a copy of all package names and pass it into
9083 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
9084 // revoked. If a new package is added before the async code runs the permission
9085 // won't be granted yet, hence new packages are no problem.
9086 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
9088 AsyncTask.execute(new Runnable() {
9090 revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg, allPackageNames);
9096 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9098 if (createIdmapFailed) {
9099 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9100 "scanPackageLI failed to createIdmap");
9105 private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9106 PackageParser.Package update, UserHandle user) {
9107 if (existing.applicationInfo == null || update.applicationInfo == null) {
9108 // This isn't due to an app installation.
9112 final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9113 final File newCodePath = new File(update.applicationInfo.getCodePath());
9115 // The codePath hasn't changed, so there's nothing for us to do.
9116 if (Objects.equals(oldCodePath, newCodePath)) {
9120 File canonicalNewCodePath;
9122 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9123 } catch (IOException e) {
9124 Slog.w(TAG, "Failed to get canonical path.", e);
9128 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9129 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9130 // that the last component of the path (i.e, the name) doesn't need canonicalization
9131 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9132 // but may change in the future. Hopefully this function won't exist at that point.
9133 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9134 oldCodePath.getName());
9136 // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9138 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9139 if (!oldMarkerPrefix.endsWith("@")) {
9140 oldMarkerPrefix += "@";
9142 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9143 if (!newMarkerPrefix.endsWith("@")) {
9144 newMarkerPrefix += "@";
9147 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9148 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9149 for (String updatedPath : updatedPaths) {
9150 String updatedPathName = new File(updatedPath).getName();
9151 markerSuffixes.add(updatedPathName.replace('/', '@'));
9154 for (int userId : resolveUserIds(user.getIdentifier())) {
9155 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9157 for (String markerSuffix : markerSuffixes) {
9158 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9159 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9160 if (oldForeignUseMark.exists()) {
9162 Os.rename(oldForeignUseMark.getAbsolutePath(),
9163 newForeignUseMark.getAbsolutePath());
9164 } catch (ErrnoException e) {
9165 Slog.w(TAG, "Failed to rename foreign use marker", e);
9166 oldForeignUseMark.delete();
9174 * Derive the ABI of a non-system package located at {@code scanFile}. This information
9175 * is derived purely on the basis of the contents of {@code scanFile} and
9176 * {@code cpuAbiOverride}.
9178 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9180 private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9181 String cpuAbiOverride, boolean extractLibs)
9182 throws PackageManagerException {
9183 // TODO: We can probably be smarter about this stuff. For installed apps,
9184 // we can calculate this information at install time once and for all. For
9185 // system apps, we can probably assume that this information doesn't change
9186 // after the first boot scan. As things stand, we do lots of unnecessary work.
9188 // Give ourselves some initial paths; we'll come back for another
9189 // pass once we've determined ABI below.
9190 setNativeLibraryPaths(pkg);
9192 // We would never need to extract libs for forward-locked and external packages,
9193 // since the container service will do it for us. We shouldn't attempt to
9194 // extract libs from system app when it was not updated.
9195 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9196 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9197 extractLibs = false;
9200 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9201 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9203 NativeLibraryHelper.Handle handle = null;
9205 handle = NativeLibraryHelper.Handle.create(pkg);
9206 // TODO(multiArch): This can be null for apps that didn't go through the
9207 // usual installation process. We can calculate it again, like we
9208 // do during install time.
9210 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9212 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9214 // Null out the abis so that they can be recalculated.
9215 pkg.applicationInfo.primaryCpuAbi = null;
9216 pkg.applicationInfo.secondaryCpuAbi = null;
9217 if (isMultiArch(pkg.applicationInfo)) {
9218 // Warn if we've set an abiOverride for multi-lib packages..
9219 // By definition, we need to copy both 32 and 64 bit libraries for
9221 if (pkg.cpuAbiOverride != null
9222 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9223 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9226 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9227 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9228 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9230 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9231 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9232 useIsaSpecificSubdirs);
9234 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9238 maybeThrowExceptionForMultiArchCopy(
9239 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9241 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9243 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9244 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9245 useIsaSpecificSubdirs);
9247 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9251 maybeThrowExceptionForMultiArchCopy(
9252 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9255 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9259 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9261 if (pkg.use32bitAbi) {
9262 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9263 pkg.applicationInfo.primaryCpuAbi = abi;
9265 pkg.applicationInfo.secondaryCpuAbi = abi;
9268 pkg.applicationInfo.primaryCpuAbi = abi;
9273 String[] abiList = (cpuAbiOverride != null) ?
9274 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9276 // Enable gross and lame hacks for apps that are built with old
9277 // SDK tools. We must scan their APKs for renderscript bitcode and
9278 // not launch them if it's present. Don't bother checking on devices
9279 // that don't have 64 bit support.
9280 boolean needsRenderScriptOverride = false;
9281 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9282 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9283 abiList = Build.SUPPORTED_32_BIT_ABIS;
9284 needsRenderScriptOverride = true;
9289 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9290 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9292 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9295 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9296 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9297 "Error unpackaging native libs for app, errorCode=" + copyRet);
9301 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9302 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9303 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9304 } else if (needsRenderScriptOverride) {
9305 pkg.applicationInfo.primaryCpuAbi = abiList[0];
9308 } catch (IOException ioe) {
9309 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9311 IoUtils.closeQuietly(handle);
9314 // Now that we've calculated the ABIs and determined if it's an internal app,
9315 // we will go ahead and populate the nativeLibraryPath.
9316 setNativeLibraryPaths(pkg);
9320 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9321 * i.e, so that all packages can be run inside a single process if required.
9323 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9324 * this function will either try and make the ABI for all packages in {@code packagesForUser}
9325 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9326 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9327 * updating a package that belongs to a shared user.
9329 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9330 * adds unnecessary complexity.
9332 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9333 PackageParser.Package scannedPackage, boolean bootComplete) {
9334 String requiredInstructionSet = null;
9335 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9336 requiredInstructionSet = VMRuntime.getInstructionSet(
9337 scannedPackage.applicationInfo.primaryCpuAbi);
9340 PackageSetting requirer = null;
9341 for (PackageSetting ps : packagesForUser) {
9342 // If packagesForUser contains scannedPackage, we skip it. This will happen
9343 // when scannedPackage is an update of an existing package. Without this check,
9344 // we will never be able to change the ABI of any package belonging to a shared
9345 // user, even if it's compatible with other packages.
9346 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9347 if (ps.primaryCpuAbiString == null) {
9351 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9352 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9353 // We have a mismatch between instruction sets (say arm vs arm64) warn about
9354 // this but there's not much we can do.
9355 String errorMessage = "Instruction set mismatch, "
9356 + ((requirer == null) ? "[caller]" : requirer)
9357 + " requires " + requiredInstructionSet + " whereas " + ps
9358 + " requires " + instructionSet;
9359 Slog.w(TAG, errorMessage);
9362 if (requiredInstructionSet == null) {
9363 requiredInstructionSet = instructionSet;
9369 if (requiredInstructionSet != null) {
9371 if (requirer != null) {
9372 // requirer != null implies that either scannedPackage was null or that scannedPackage
9373 // did not require an ABI, in which case we have to adjust scannedPackage to match
9374 // the ABI of the set (which is the same as requirer's ABI)
9375 adjustedAbi = requirer.primaryCpuAbiString;
9376 if (scannedPackage != null) {
9377 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9380 // requirer == null implies that we're updating all ABIs in the set to
9381 // match scannedPackage.
9382 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
9385 for (PackageSetting ps : packagesForUser) {
9386 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9387 if (ps.primaryCpuAbiString != null) {
9391 ps.primaryCpuAbiString = adjustedAbi;
9392 if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9393 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9394 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9395 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9397 + (requirer == null ? "null" : requirer.pkg.packageName)
9398 + ", scannedPackage="
9399 + (scannedPackage != null ? scannedPackage.packageName : "null")
9402 mInstaller.rmdex(ps.codePathString,
9403 getDexCodeInstructionSet(getPreferredInstructionSet()));
9404 } catch (InstallerException ignored) {
9412 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9413 synchronized (mPackages) {
9414 mResolverReplaced = true;
9415 // Set up information for custom user intent resolution activity.
9416 mResolveActivity.applicationInfo = pkg.applicationInfo;
9417 mResolveActivity.name = mCustomResolverComponentName.getClassName();
9418 mResolveActivity.packageName = pkg.applicationInfo.packageName;
9419 mResolveActivity.processName = pkg.applicationInfo.packageName;
9420 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9421 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9422 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9423 mResolveActivity.theme = 0;
9424 mResolveActivity.exported = true;
9425 mResolveActivity.enabled = true;
9426 mResolveInfo.activityInfo = mResolveActivity;
9427 mResolveInfo.priority = 0;
9428 mResolveInfo.preferredOrder = 0;
9429 mResolveInfo.match = 0;
9430 mResolveComponentName = mCustomResolverComponentName;
9431 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9432 mResolveComponentName);
9436 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9437 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9439 // Set up information for ephemeral installer activity
9440 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9441 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9442 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9443 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9444 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9445 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9446 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9447 mEphemeralInstallerActivity.theme = 0;
9448 mEphemeralInstallerActivity.exported = true;
9449 mEphemeralInstallerActivity.enabled = true;
9450 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9451 mEphemeralInstallerInfo.priority = 0;
9452 mEphemeralInstallerInfo.preferredOrder = 1;
9453 mEphemeralInstallerInfo.isDefault = true;
9454 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9455 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9457 if (DEBUG_EPHEMERAL) {
9458 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9462 private static String calculateBundledApkRoot(final String codePathString) {
9463 final File codePath = new File(codePathString);
9464 final File codeRoot;
9465 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9466 codeRoot = Environment.getRootDirectory();
9467 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9468 codeRoot = Environment.getOemDirectory();
9469 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9470 codeRoot = Environment.getVendorDirectory();
9472 // Unrecognized code path; take its top real segment as the apk root:
9473 // e.g. /something/app/blah.apk => /something
9475 File f = codePath.getCanonicalFile();
9476 File parent = f.getParentFile(); // non-null because codePath is a file
9478 while ((tmp = parent.getParentFile()) != null) {
9483 Slog.w(TAG, "Unrecognized code path "
9484 + codePath + " - using " + codeRoot);
9485 } catch (IOException e) {
9486 // Can't canonicalize the code path -- shenanigans?
9487 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9488 return Environment.getRootDirectory().getPath();
9491 return codeRoot.getPath();
9495 * Derive and set the location of native libraries for the given package,
9496 * which varies depending on where and how the package was installed.
9498 private void setNativeLibraryPaths(PackageParser.Package pkg) {
9499 final ApplicationInfo info = pkg.applicationInfo;
9500 final String codePath = pkg.codePath;
9501 final File codeFile = new File(codePath);
9502 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9503 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9505 info.nativeLibraryRootDir = null;
9506 info.nativeLibraryRootRequiresIsa = false;
9507 info.nativeLibraryDir = null;
9508 info.secondaryNativeLibraryDir = null;
9510 if (isApkFile(codeFile)) {
9511 // Monolithic install
9513 // If "/system/lib64/apkname" exists, assume that is the per-package
9514 // native library directory to use; otherwise use "/system/lib/apkname".
9515 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9516 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9517 getPrimaryInstructionSet(info));
9519 // This is a bundled system app so choose the path based on the ABI.
9520 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9521 // is just the default path.
9522 final String apkName = deriveCodePathName(codePath);
9523 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9524 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9525 apkName).getAbsolutePath();
9527 if (info.secondaryCpuAbi != null) {
9528 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9529 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9530 secondaryLibDir, apkName).getAbsolutePath();
9532 } else if (asecApp) {
9533 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9536 final String apkName = deriveCodePathName(codePath);
9537 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9541 info.nativeLibraryRootRequiresIsa = false;
9542 info.nativeLibraryDir = info.nativeLibraryRootDir;
9545 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9546 info.nativeLibraryRootRequiresIsa = true;
9548 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9549 getPrimaryInstructionSet(info)).getAbsolutePath();
9551 if (info.secondaryCpuAbi != null) {
9552 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9553 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9559 * Calculate the abis and roots for a bundled app. These can uniquely
9560 * be determined from the contents of the system partition, i.e whether
9561 * it contains 64 or 32 bit shared libraries etc. We do not validate any
9562 * of this information, and instead assume that the system was built
9565 private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9566 PackageSetting pkgSetting) {
9567 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9569 // If "/system/lib64/apkname" exists, assume that is the per-package
9570 // native library directory to use; otherwise use "/system/lib/apkname".
9571 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9572 setBundledAppAbi(pkg, apkRoot, apkName);
9573 // pkgSetting might be null during rescan following uninstall of updates
9574 // to a bundled app, so accommodate that possibility. The settings in
9575 // that case will be established later from the parsed package.
9577 // If the settings aren't null, sync them up with what we've just derived.
9578 // note that apkRoot isn't stored in the package settings.
9579 if (pkgSetting != null) {
9580 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9581 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9586 * Deduces the ABI of a bundled app and sets the relevant fields on the
9587 * parsed pkg object.
9589 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9590 * under which system libraries are installed.
9591 * @param apkName the name of the installed package.
9593 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9594 final File codeFile = new File(pkg.codePath);
9596 final boolean has64BitLibs;
9597 final boolean has32BitLibs;
9598 if (isApkFile(codeFile)) {
9599 // Monolithic install
9600 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9601 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9604 final File rootDir = new File(codeFile, LIB_DIR_NAME);
9605 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9606 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9607 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9608 has64BitLibs = (new File(rootDir, isa)).exists();
9610 has64BitLibs = false;
9612 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9613 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9614 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9615 has32BitLibs = (new File(rootDir, isa)).exists();
9617 has32BitLibs = false;
9621 if (has64BitLibs && !has32BitLibs) {
9622 // The package has 64 bit libs, but not 32 bit libs. Its primary
9623 // ABI should be 64 bit. We can safely assume here that the bundled
9624 // native libraries correspond to the most preferred ABI in the list.
9626 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9627 pkg.applicationInfo.secondaryCpuAbi = null;
9628 } else if (has32BitLibs && !has64BitLibs) {
9629 // The package has 32 bit libs but not 64 bit libs. Its primary
9630 // ABI should be 32 bit.
9632 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9633 pkg.applicationInfo.secondaryCpuAbi = null;
9634 } else if (has32BitLibs && has64BitLibs) {
9635 // The application has both 64 and 32 bit bundled libraries. We check
9636 // here that the app declares multiArch support, and warn if it doesn't.
9638 // We will be lenient here and record both ABIs. The primary will be the
9639 // ABI that's higher on the list, i.e, a device that's configured to prefer
9640 // 64 bit apps will see a 64 bit primary ABI,
9642 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9643 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9646 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9647 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9648 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9650 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9651 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9654 pkg.applicationInfo.primaryCpuAbi = null;
9655 pkg.applicationInfo.secondaryCpuAbi = null;
9659 private void killApplication(String pkgName, int appId, String reason) {
9660 killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9663 private void killApplication(String pkgName, int appId, int userId, String reason) {
9664 // Request the ActivityManager to kill the process(only for existing packages)
9665 // so that we do not end up in a confused state while the user is still using the older
9666 // version of the application while the new one gets installed.
9667 final long token = Binder.clearCallingIdentity();
9669 IActivityManager am = ActivityManagerNative.getDefault();
9672 am.killApplication(pkgName, appId, userId, reason);
9673 } catch (RemoteException e) {
9677 Binder.restoreCallingIdentity(token);
9681 private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9682 // Remove the parent package setting
9683 PackageSetting ps = (PackageSetting) pkg.mExtras;
9685 removePackageLI(ps, chatty);
9687 // Remove the child package setting
9688 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9689 for (int i = 0; i < childCount; i++) {
9690 PackageParser.Package childPkg = pkg.childPackages.get(i);
9691 ps = (PackageSetting) childPkg.mExtras;
9693 removePackageLI(ps, chatty);
9698 void removePackageLI(PackageSetting ps, boolean chatty) {
9699 if (DEBUG_INSTALL) {
9701 Log.d(TAG, "Removing package " + ps.name);
9705 synchronized (mPackages) {
9706 mPackages.remove(ps.name);
9707 final PackageParser.Package pkg = ps.pkg;
9709 cleanPackageDataStructuresLILPw(pkg, chatty);
9714 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9715 if (DEBUG_INSTALL) {
9717 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9721 synchronized (mPackages) {
9722 // Remove the parent package
9723 mPackages.remove(pkg.applicationInfo.packageName);
9724 cleanPackageDataStructuresLILPw(pkg, chatty);
9726 // Remove the child packages
9727 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9728 for (int i = 0; i < childCount; i++) {
9729 PackageParser.Package childPkg = pkg.childPackages.get(i);
9730 mPackages.remove(childPkg.applicationInfo.packageName);
9731 cleanPackageDataStructuresLILPw(childPkg, chatty);
9736 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9737 int N = pkg.providers.size();
9738 StringBuilder r = null;
9740 for (i=0; i<N; i++) {
9741 PackageParser.Provider p = pkg.providers.get(i);
9742 mProviders.removeProvider(p);
9743 if (p.info.authority == null) {
9745 /* There was another ContentProvider with this authority when
9746 * this app was installed so this authority is null,
9747 * Ignore it as we don't have to unregister the provider.
9751 String names[] = p.info.authority.split(";");
9752 for (int j = 0; j < names.length; j++) {
9753 if (mProvidersByAuthority.get(names[j]) == p) {
9754 mProvidersByAuthority.remove(names[j]);
9757 Log.d(TAG, "Unregistered content provider: " + names[j]
9758 + ", className = " + p.info.name + ", isSyncable = "
9759 + p.info.isSyncable);
9763 if (DEBUG_REMOVE && chatty) {
9765 r = new StringBuilder(256);
9769 r.append(p.info.name);
9773 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
9776 N = pkg.services.size();
9778 for (i=0; i<N; i++) {
9779 PackageParser.Service s = pkg.services.get(i);
9780 mServices.removeService(s);
9783 r = new StringBuilder(256);
9787 r.append(s.info.name);
9791 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
9794 N = pkg.receivers.size();
9796 for (i=0; i<N; i++) {
9797 PackageParser.Activity a = pkg.receivers.get(i);
9798 mReceivers.removeActivity(a, "receiver");
9799 if (DEBUG_REMOVE && chatty) {
9801 r = new StringBuilder(256);
9805 r.append(a.info.name);
9809 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
9812 N = pkg.activities.size();
9814 for (i=0; i<N; i++) {
9815 PackageParser.Activity a = pkg.activities.get(i);
9816 mActivities.removeActivity(a, "activity");
9817 if (DEBUG_REMOVE && chatty) {
9819 r = new StringBuilder(256);
9823 r.append(a.info.name);
9827 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
9830 N = pkg.permissions.size();
9832 for (i=0; i<N; i++) {
9833 PackageParser.Permission p = pkg.permissions.get(i);
9834 BasePermission bp = mSettings.mPermissions.get(p.info.name);
9836 bp = mSettings.mPermissionTrees.get(p.info.name);
9838 if (bp != null && bp.perm == p) {
9840 if (DEBUG_REMOVE && chatty) {
9842 r = new StringBuilder(256);
9846 r.append(p.info.name);
9849 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9850 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9851 if (appOpPkgs != null) {
9852 appOpPkgs.remove(pkg.packageName);
9857 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9860 N = pkg.requestedPermissions.size();
9862 for (i=0; i<N; i++) {
9863 String perm = pkg.requestedPermissions.get(i);
9864 BasePermission bp = mSettings.mPermissions.get(perm);
9865 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9866 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9867 if (appOpPkgs != null) {
9868 appOpPkgs.remove(pkg.packageName);
9869 if (appOpPkgs.isEmpty()) {
9870 mAppOpPermissionPackages.remove(perm);
9876 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9879 N = pkg.instrumentation.size();
9881 for (i=0; i<N; i++) {
9882 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9883 mInstrumentation.remove(a.getComponentName());
9884 if (DEBUG_REMOVE && chatty) {
9886 r = new StringBuilder(256);
9890 r.append(a.info.name);
9894 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
9898 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9899 // Only system apps can hold shared libraries.
9900 if (pkg.libraryNames != null) {
9901 for (i=0; i<pkg.libraryNames.size(); i++) {
9902 String name = pkg.libraryNames.get(i);
9903 SharedLibraryEntry cur = mSharedLibraries.get(name);
9904 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9905 mSharedLibraries.remove(name);
9906 if (DEBUG_REMOVE && chatty) {
9908 r = new StringBuilder(256);
9919 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
9923 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9924 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9925 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9932 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9933 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9934 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9936 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9937 // Update the parent permissions
9938 updatePermissionsLPw(pkg.packageName, pkg, flags);
9939 // Update the child permissions
9940 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9941 for (int i = 0; i < childCount; i++) {
9942 PackageParser.Package childPkg = pkg.childPackages.get(i);
9943 updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9947 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9949 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9950 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9953 private void updatePermissionsLPw(String changingPkg,
9954 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9955 // Make sure there are no dangling permission trees.
9956 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9957 while (it.hasNext()) {
9958 final BasePermission bp = it.next();
9959 if (bp.packageSetting == null) {
9960 // We may not yet have parsed the package, so just see if
9961 // we still know about its settings.
9962 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9964 if (bp.packageSetting == null) {
9965 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9966 + " from package " + bp.sourcePackage);
9968 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9969 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9970 Slog.i(TAG, "Removing old permission tree: " + bp.name
9971 + " from package " + bp.sourcePackage);
9972 flags |= UPDATE_PERMISSIONS_ALL;
9978 // Make sure all dynamic permissions have been assigned to a package,
9979 // and make sure there are no dangling permissions.
9980 it = mSettings.mPermissions.values().iterator();
9981 while (it.hasNext()) {
9982 final BasePermission bp = it.next();
9983 if (bp.type == BasePermission.TYPE_DYNAMIC) {
9984 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9985 + bp.name + " pkg=" + bp.sourcePackage
9986 + " info=" + bp.pendingInfo);
9987 if (bp.packageSetting == null && bp.pendingInfo != null) {
9988 final BasePermission tree = findPermissionTreeLP(bp.name);
9989 if (tree != null && tree.perm != null) {
9990 bp.packageSetting = tree.packageSetting;
9991 bp.perm = new PackageParser.Permission(tree.perm.owner,
9992 new PermissionInfo(bp.pendingInfo));
9993 bp.perm.info.packageName = tree.perm.info.packageName;
9994 bp.perm.info.name = bp.name;
9999 if (bp.packageSetting == null) {
10000 // We may not yet have parsed the package, so just see if
10001 // we still know about its settings.
10002 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10004 if (bp.packageSetting == null) {
10005 Slog.w(TAG, "Removing dangling permission: " + bp.name
10006 + " from package " + bp.sourcePackage);
10008 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10009 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10010 Slog.i(TAG, "Removing old permission: " + bp.name
10011 + " from package " + bp.sourcePackage);
10012 flags |= UPDATE_PERMISSIONS_ALL;
10018 // Now update the permissions for all packages, in particular
10019 // replace the granted permissions of the system packages.
10020 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10021 for (PackageParser.Package pkg : mPackages.values()) {
10022 if (pkg != pkgInfo) {
10023 // Only replace for packages on requested volume
10024 final String volumeUuid = getVolumeUuidForPackage(pkg);
10025 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10026 && Objects.equals(replaceVolumeUuid, volumeUuid);
10027 grantPermissionsLPw(pkg, replace, changingPkg);
10032 if (pkgInfo != null) {
10033 // Only replace for packages on requested volume
10034 final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10035 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10036 && Objects.equals(replaceVolumeUuid, volumeUuid);
10037 grantPermissionsLPw(pkgInfo, replace, changingPkg);
10041 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10042 String packageOfInterest) {
10043 // IMPORTANT: There are two types of permissions: install and runtime.
10044 // Install time permissions are granted when the app is installed to
10045 // all device users and users added in the future. Runtime permissions
10046 // are granted at runtime explicitly to specific users. Normal and signature
10047 // protected permissions are install time permissions. Dangerous permissions
10048 // are install permissions if the app's target SDK is Lollipop MR1 or older,
10049 // otherwise they are runtime permissions. This function does not manage
10050 // runtime permissions except for the case an app targeting Lollipop MR1
10051 // being upgraded to target a newer SDK, in which case dangerous permissions
10052 // are transformed from install time to runtime ones.
10054 final PackageSetting ps = (PackageSetting) pkg.mExtras;
10059 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10061 PermissionsState permissionsState = ps.getPermissionsState();
10062 PermissionsState origPermissions = permissionsState;
10064 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10066 boolean runtimePermissionsRevoked = false;
10067 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10069 boolean changedInstallPermission = false;
10072 ps.installPermissionsFixed = false;
10073 if (!ps.isSharedUser()) {
10074 origPermissions = new PermissionsState(permissionsState);
10075 permissionsState.reset();
10077 // We need to know only about runtime permission changes since the
10078 // calling code always writes the install permissions state but
10079 // the runtime ones are written only if changed. The only cases of
10080 // changed runtime permissions here are promotion of an install to
10081 // runtime and revocation of a runtime from a shared user.
10082 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10083 ps.sharedUser, UserManagerService.getInstance().getUserIds());
10084 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10085 runtimePermissionsRevoked = true;
10090 permissionsState.setGlobalGids(mGlobalGids);
10092 final int N = pkg.requestedPermissions.size();
10093 for (int i=0; i<N; i++) {
10094 final String name = pkg.requestedPermissions.get(i);
10095 final BasePermission bp = mSettings.mPermissions.get(name);
10097 if (DEBUG_INSTALL) {
10098 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10101 if (bp == null || bp.packageSetting == null) {
10102 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10103 Slog.w(TAG, "Unknown permission " + name
10104 + " in package " + pkg.packageName);
10109 final String perm = bp.name;
10110 boolean allowedSig = false;
10111 int grant = GRANT_DENIED;
10113 // Keep track of app op permissions.
10114 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10115 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10116 if (pkgs == null) {
10117 pkgs = new ArraySet<>();
10118 mAppOpPermissionPackages.put(bp.name, pkgs);
10120 pkgs.add(pkg.packageName);
10123 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10124 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10125 >= Build.VERSION_CODES.M;
10127 case PermissionInfo.PROTECTION_NORMAL: {
10128 // For all apps normal permissions are install time ones.
10129 grant = GRANT_INSTALL;
10132 case PermissionInfo.PROTECTION_DANGEROUS: {
10133 // If a permission review is required for legacy apps we represent
10134 // their permissions as always granted runtime ones since we need
10135 // to keep the review required permission flag per user while an
10136 // install permission's state is shared across all users.
10137 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10138 // For legacy apps dangerous permissions are install time ones.
10139 grant = GRANT_INSTALL;
10140 } else if (origPermissions.hasInstallPermission(bp.name)) {
10141 // For legacy apps that became modern, install becomes runtime.
10142 grant = GRANT_UPGRADE;
10143 } else if (mPromoteSystemApps
10145 && mExistingSystemPackages.contains(ps.name)) {
10146 // For legacy system apps, install becomes runtime.
10147 // We cannot check hasInstallPermission() for system apps since those
10148 // permissions were granted implicitly and not persisted pre-M.
10149 grant = GRANT_UPGRADE;
10151 // For modern apps keep runtime permissions unchanged.
10152 grant = GRANT_RUNTIME;
10156 case PermissionInfo.PROTECTION_SIGNATURE: {
10157 // For all apps signature permissions are install time ones.
10158 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10160 grant = GRANT_INSTALL;
10165 if (DEBUG_INSTALL) {
10166 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10169 if (grant != GRANT_DENIED) {
10170 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10171 // If this is an existing, non-system package, then
10172 // we can't add any new permissions to it.
10173 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10174 // Except... if this is a permission that was added
10175 // to the platform (note: need to only do this when
10176 // updating the platform).
10177 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10178 grant = GRANT_DENIED;
10184 case GRANT_INSTALL: {
10185 // Revoke this as runtime permission to handle the case of
10186 // a runtime permission being downgraded to an install one.
10187 // Also in permission review mode we keep dangerous permissions
10189 for (int userId : UserManagerService.getInstance().getUserIds()) {
10190 if (origPermissions.getRuntimePermissionState(
10191 bp.name, userId) != null) {
10192 // Revoke the runtime permission and clear the flags.
10193 origPermissions.revokeRuntimePermission(bp, userId);
10194 origPermissions.updatePermissionFlags(bp, userId,
10195 PackageManager.MASK_PERMISSION_FLAGS, 0);
10196 // If we revoked a permission permission, we have to write.
10197 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10198 changedRuntimePermissionUserIds, userId);
10201 // Grant an install permission.
10202 if (permissionsState.grantInstallPermission(bp) !=
10203 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10204 changedInstallPermission = true;
10208 case GRANT_RUNTIME: {
10209 // Grant previously granted runtime permissions.
10210 for (int userId : UserManagerService.getInstance().getUserIds()) {
10211 PermissionState permissionState = origPermissions
10212 .getRuntimePermissionState(bp.name, userId);
10213 int flags = permissionState != null
10214 ? permissionState.getFlags() : 0;
10215 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10216 if (permissionsState.grantRuntimePermission(bp, userId) ==
10217 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10218 // If we cannot put the permission as it was, we have to write.
10219 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10220 changedRuntimePermissionUserIds, userId);
10222 // If the app supports runtime permissions no need for a review.
10223 if (Build.PERMISSIONS_REVIEW_REQUIRED
10224 && appSupportsRuntimePermissions
10225 && (flags & PackageManager
10226 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10227 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10228 // Since we changed the flags, we have to write.
10229 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10230 changedRuntimePermissionUserIds, userId);
10232 } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10233 && !appSupportsRuntimePermissions) {
10234 // For legacy apps that need a permission review, every new
10235 // runtime permission is granted but it is pending a review.
10236 // We also need to review only platform defined runtime
10237 // permissions as these are the only ones the platform knows
10238 // how to disable the API to simulate revocation as legacy
10239 // apps don't expect to run with revoked permissions.
10240 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10241 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10242 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10243 // We changed the flags, hence have to write.
10244 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10245 changedRuntimePermissionUserIds, userId);
10248 if (permissionsState.grantRuntimePermission(bp, userId)
10249 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10250 // We changed the permission, hence have to write.
10251 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10252 changedRuntimePermissionUserIds, userId);
10255 // Propagate the permission flags.
10256 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10260 case GRANT_UPGRADE: {
10261 // Grant runtime permissions for a previously held install permission.
10262 PermissionState permissionState = origPermissions
10263 .getInstallPermissionState(bp.name);
10264 final int flags = permissionState != null ? permissionState.getFlags() : 0;
10266 if (origPermissions.revokeInstallPermission(bp)
10267 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10268 // We will be transferring the permission flags, so clear them.
10269 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10270 PackageManager.MASK_PERMISSION_FLAGS, 0);
10271 changedInstallPermission = true;
10274 // If the permission is not to be promoted to runtime we ignore it and
10275 // also its other flags as they are not applicable to install permissions.
10276 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10277 for (int userId : currentUserIds) {
10278 if (permissionsState.grantRuntimePermission(bp, userId) !=
10279 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10280 // Transfer the permission flags.
10281 permissionsState.updatePermissionFlags(bp, userId,
10283 // If we granted the permission, we have to write.
10284 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10285 changedRuntimePermissionUserIds, userId);
10292 if (packageOfInterest == null
10293 || packageOfInterest.equals(pkg.packageName)) {
10294 Slog.w(TAG, "Not granting permission " + perm
10295 + " to package " + pkg.packageName
10296 + " because it was previously installed without");
10301 if (permissionsState.revokeInstallPermission(bp) !=
10302 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10303 // Also drop the permission flags.
10304 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10305 PackageManager.MASK_PERMISSION_FLAGS, 0);
10306 changedInstallPermission = true;
10307 Slog.i(TAG, "Un-granting permission " + perm
10308 + " from package " + pkg.packageName
10309 + " (protectionLevel=" + bp.protectionLevel
10310 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10312 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10313 // Don't print warning for app op permissions, since it is fine for them
10314 // not to be granted, there is a UI for the user to decide.
10315 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10316 Slog.w(TAG, "Not granting permission " + perm
10317 + " to package " + pkg.packageName
10318 + " (protectionLevel=" + bp.protectionLevel
10319 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10326 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10327 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10328 // This is the first that we have heard about this package, so the
10329 // permissions we have now selected are fixed until explicitly
10331 ps.installPermissionsFixed = true;
10334 // Persist the runtime permissions state for users with changes. If permissions
10335 // were revoked because no app in the shared user declares them we have to
10336 // write synchronously to avoid losing runtime permissions state.
10337 for (int userId : changedRuntimePermissionUserIds) {
10338 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10341 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10344 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10345 boolean allowed = false;
10346 final int NP = PackageParser.NEW_PERMISSIONS.length;
10347 for (int ip=0; ip<NP; ip++) {
10348 final PackageParser.NewPermissionInfo npi
10349 = PackageParser.NEW_PERMISSIONS[ip];
10350 if (npi.name.equals(perm)
10351 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10353 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10354 + pkg.packageName);
10361 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10362 BasePermission bp, PermissionsState origPermissions) {
10364 allowed = (compareSignatures(
10365 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10366 == PackageManager.SIGNATURE_MATCH)
10367 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10368 == PackageManager.SIGNATURE_MATCH);
10369 if (!allowed && (bp.protectionLevel
10370 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10371 if (isSystemApp(pkg)) {
10372 // For updated system applications, a system permission
10373 // is granted only if it had been defined by the original application.
10374 if (pkg.isUpdatedSystemApp()) {
10375 final PackageSetting sysPs = mSettings
10376 .getDisabledSystemPkgLPr(pkg.packageName);
10377 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10378 // If the original was granted this permission, we take
10379 // that grant decision as read and propagate it to the
10381 if (sysPs.isPrivileged()) {
10385 // The system apk may have been updated with an older
10386 // version of the one on the data partition, but which
10387 // granted a new system permission that it didn't have
10388 // before. In this case we do want to allow the app to
10389 // now get the new permission if the ancestral apk is
10390 // privileged to get it.
10391 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10392 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10393 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10399 // Also if a privileged parent package on the system image or any of
10400 // its children requested a privileged permission, the updated child
10401 // packages can also get the permission.
10402 if (pkg.parentPackage != null) {
10403 final PackageSetting disabledSysParentPs = mSettings
10404 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10405 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10406 && disabledSysParentPs.isPrivileged()) {
10407 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10409 } else if (disabledSysParentPs.pkg.childPackages != null) {
10410 final int count = disabledSysParentPs.pkg.childPackages.size();
10411 for (int i = 0; i < count; i++) {
10412 PackageParser.Package disabledSysChildPkg =
10413 disabledSysParentPs.pkg.childPackages.get(i);
10414 if (isPackageRequestingPermission(disabledSysChildPkg,
10425 allowed = isPrivilegedApp(pkg);
10430 if (!allowed && (bp.protectionLevel
10431 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10432 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10433 // If this was a previously normal/dangerous permission that got moved
10434 // to a system permission as part of the runtime permission redesign, then
10435 // we still want to blindly grant it to old apps.
10438 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10439 && pkg.packageName.equals(mRequiredInstallerPackage)) {
10440 // If this permission is to be granted to the system installer and
10441 // this app is an installer, then it gets the permission.
10444 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10445 && pkg.packageName.equals(mRequiredVerifierPackage)) {
10446 // If this permission is to be granted to the system verifier and
10447 // this app is a verifier, then it gets the permission.
10450 if (!allowed && (bp.protectionLevel
10451 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10452 && isSystemApp(pkg)) {
10453 // Any pre-installed system app is allowed to get this permission.
10456 if (!allowed && (bp.protectionLevel
10457 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10458 // For development permissions, a development permission
10459 // is granted only if it was already granted.
10460 allowed = origPermissions.hasInstallPermission(perm);
10462 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10463 && pkg.packageName.equals(mSetupWizardPackage)) {
10464 // If this permission is to be granted to the system setup wizard and
10465 // this app is a setup wizard, then it gets the permission.
10472 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10473 final int permCount = pkg.requestedPermissions.size();
10474 for (int j = 0; j < permCount; j++) {
10475 String requestedPermission = pkg.requestedPermissions.get(j);
10476 if (permission.equals(requestedPermission)) {
10483 final class ActivityIntentResolver
10484 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10485 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10486 boolean defaultOnly, int userId) {
10487 if (!sUserManager.exists(userId)) return null;
10488 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10489 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10492 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10494 if (!sUserManager.exists(userId)) return null;
10496 return super.queryIntent(intent, resolvedType,
10497 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10500 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10501 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10502 if (!sUserManager.exists(userId)) return null;
10503 if (packageActivities == null) {
10507 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10508 final int N = packageActivities.size();
10509 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10510 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10512 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10513 for (int i = 0; i < N; ++i) {
10514 intentFilters = packageActivities.get(i).intents;
10515 if (intentFilters != null && intentFilters.size() > 0) {
10516 PackageParser.ActivityIntentInfo[] array =
10517 new PackageParser.ActivityIntentInfo[intentFilters.size()];
10518 intentFilters.toArray(array);
10519 listCut.add(array);
10522 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10526 * Finds a privileged activity that matches the specified activity names.
10528 private PackageParser.Activity findMatchingActivity(
10529 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10530 for (PackageParser.Activity sysActivity : activityList) {
10531 if (sysActivity.info.name.equals(activityInfo.name)) {
10532 return sysActivity;
10534 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10535 return sysActivity;
10537 if (sysActivity.info.targetActivity != null) {
10538 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10539 return sysActivity;
10541 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10542 return sysActivity;
10549 public class IterGenerator<E> {
10550 public Iterator<E> generate(ActivityIntentInfo info) {
10555 public class ActionIterGenerator extends IterGenerator<String> {
10557 public Iterator<String> generate(ActivityIntentInfo info) {
10558 return info.actionsIterator();
10562 public class CategoriesIterGenerator extends IterGenerator<String> {
10564 public Iterator<String> generate(ActivityIntentInfo info) {
10565 return info.categoriesIterator();
10569 public class SchemesIterGenerator extends IterGenerator<String> {
10571 public Iterator<String> generate(ActivityIntentInfo info) {
10572 return info.schemesIterator();
10576 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10578 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10579 return info.authoritiesIterator();
10584 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10585 * MODIFIED. Do not pass in a list that should not be changed.
10587 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10588 IterGenerator<T> generator, Iterator<T> searchIterator) {
10589 // loop through the set of actions; every one must be found in the intent filter
10590 while (searchIterator.hasNext()) {
10591 // we must have at least one filter in the list to consider a match
10592 if (intentList.size() == 0) {
10596 final T searchAction = searchIterator.next();
10598 // loop through the set of intent filters
10599 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10600 while (intentIter.hasNext()) {
10601 final ActivityIntentInfo intentInfo = intentIter.next();
10602 boolean selectionFound = false;
10604 // loop through the intent filter's selection criteria; at least one
10605 // of them must match the searched criteria
10606 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10607 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10608 final T intentSelection = intentSelectionIter.next();
10609 if (intentSelection != null && intentSelection.equals(searchAction)) {
10610 selectionFound = true;
10615 // the selection criteria wasn't found in this filter's set; this filter
10616 // is not a potential match
10617 if (!selectionFound) {
10618 intentIter.remove();
10624 private boolean isProtectedAction(ActivityIntentInfo filter) {
10625 final Iterator<String> actionsIter = filter.actionsIterator();
10626 while (actionsIter != null && actionsIter.hasNext()) {
10627 final String filterAction = actionsIter.next();
10628 if (PROTECTED_ACTIONS.contains(filterAction)) {
10636 * Adjusts the priority of the given intent filter according to policy.
10639 * <li>The priority for non privileged applications is capped to '0'</li>
10640 * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10641 * <li>The priority for unbundled updates to privileged applications is capped to the
10642 * priority defined on the system partition</li>
10645 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10646 * allowed to obtain any priority on any action.
10648 private void adjustPriority(
10649 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10650 // nothing to do; priority is fine as-is
10651 if (intent.getPriority() <= 0) {
10655 final ActivityInfo activityInfo = intent.activity.info;
10656 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10658 final boolean privilegedApp =
10659 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10660 if (!privilegedApp) {
10661 // non-privileged applications can never define a priority >0
10662 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10663 + " package: " + applicationInfo.packageName
10664 + " activity: " + intent.activity.className
10665 + " origPrio: " + intent.getPriority());
10666 intent.setPriority(0);
10670 if (systemActivities == null) {
10671 // the system package is not disabled; we're parsing the system partition
10672 if (isProtectedAction(intent)) {
10673 if (mDeferProtectedFilters) {
10674 // We can't deal with these just yet. No component should ever obtain a
10675 // >0 priority for a protected actions, with ONE exception -- the setup
10676 // wizard. The setup wizard, however, cannot be known until we're able to
10677 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10678 // until all intent filters have been processed. Chicken, meet egg.
10679 // Let the filter temporarily have a high priority and rectify the
10680 // priorities after all system packages have been scanned.
10681 mProtectedFilters.add(intent);
10682 if (DEBUG_FILTERS) {
10683 Slog.i(TAG, "Protected action; save for later;"
10684 + " package: " + applicationInfo.packageName
10685 + " activity: " + intent.activity.className
10686 + " origPrio: " + intent.getPriority());
10690 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10691 Slog.i(TAG, "No setup wizard;"
10692 + " All protected intents capped to priority 0");
10694 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10695 if (DEBUG_FILTERS) {
10696 Slog.i(TAG, "Found setup wizard;"
10697 + " allow priority " + intent.getPriority() + ";"
10698 + " package: " + intent.activity.info.packageName
10699 + " activity: " + intent.activity.className
10700 + " priority: " + intent.getPriority());
10702 // setup wizard gets whatever it wants
10705 Slog.w(TAG, "Protected action; cap priority to 0;"
10706 + " package: " + intent.activity.info.packageName
10707 + " activity: " + intent.activity.className
10708 + " origPrio: " + intent.getPriority());
10709 intent.setPriority(0);
10713 // privileged apps on the system image get whatever priority they request
10717 // privileged app unbundled update ... try to find the same activity
10718 final PackageParser.Activity foundActivity =
10719 findMatchingActivity(systemActivities, activityInfo);
10720 if (foundActivity == null) {
10721 // this is a new activity; it cannot obtain >0 priority
10722 if (DEBUG_FILTERS) {
10723 Slog.i(TAG, "New activity; cap priority to 0;"
10724 + " package: " + applicationInfo.packageName
10725 + " activity: " + intent.activity.className
10726 + " origPrio: " + intent.getPriority());
10728 intent.setPriority(0);
10732 // found activity, now check for filter equivalence
10734 // a shallow copy is enough; we modify the list, not its contents
10735 final List<ActivityIntentInfo> intentListCopy =
10736 new ArrayList<>(foundActivity.intents);
10737 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10739 // find matching action subsets
10740 final Iterator<String> actionsIterator = intent.actionsIterator();
10741 if (actionsIterator != null) {
10742 getIntentListSubset(
10743 intentListCopy, new ActionIterGenerator(), actionsIterator);
10744 if (intentListCopy.size() == 0) {
10745 // no more intents to match; we're not equivalent
10746 if (DEBUG_FILTERS) {
10747 Slog.i(TAG, "Mismatched action; cap priority to 0;"
10748 + " package: " + applicationInfo.packageName
10749 + " activity: " + intent.activity.className
10750 + " origPrio: " + intent.getPriority());
10752 intent.setPriority(0);
10757 // find matching category subsets
10758 final Iterator<String> categoriesIterator = intent.categoriesIterator();
10759 if (categoriesIterator != null) {
10760 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10761 categoriesIterator);
10762 if (intentListCopy.size() == 0) {
10763 // no more intents to match; we're not equivalent
10764 if (DEBUG_FILTERS) {
10765 Slog.i(TAG, "Mismatched category; cap priority to 0;"
10766 + " package: " + applicationInfo.packageName
10767 + " activity: " + intent.activity.className
10768 + " origPrio: " + intent.getPriority());
10770 intent.setPriority(0);
10775 // find matching schemes subsets
10776 final Iterator<String> schemesIterator = intent.schemesIterator();
10777 if (schemesIterator != null) {
10778 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10780 if (intentListCopy.size() == 0) {
10781 // no more intents to match; we're not equivalent
10782 if (DEBUG_FILTERS) {
10783 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10784 + " package: " + applicationInfo.packageName
10785 + " activity: " + intent.activity.className
10786 + " origPrio: " + intent.getPriority());
10788 intent.setPriority(0);
10793 // find matching authorities subsets
10794 final Iterator<IntentFilter.AuthorityEntry>
10795 authoritiesIterator = intent.authoritiesIterator();
10796 if (authoritiesIterator != null) {
10797 getIntentListSubset(intentListCopy,
10798 new AuthoritiesIterGenerator(),
10799 authoritiesIterator);
10800 if (intentListCopy.size() == 0) {
10801 // no more intents to match; we're not equivalent
10802 if (DEBUG_FILTERS) {
10803 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10804 + " package: " + applicationInfo.packageName
10805 + " activity: " + intent.activity.className
10806 + " origPrio: " + intent.getPriority());
10808 intent.setPriority(0);
10813 // we found matching filter(s); app gets the max priority of all intents
10814 int cappedPriority = 0;
10815 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10816 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10818 if (intent.getPriority() > cappedPriority) {
10819 if (DEBUG_FILTERS) {
10820 Slog.i(TAG, "Found matching filter(s);"
10821 + " cap priority to " + cappedPriority + ";"
10822 + " package: " + applicationInfo.packageName
10823 + " activity: " + intent.activity.className
10824 + " origPrio: " + intent.getPriority());
10826 intent.setPriority(cappedPriority);
10829 // all this for nothing; the requested priority was <= what was on the system
10832 public final void addActivity(PackageParser.Activity a, String type) {
10833 mActivities.put(a.getComponentName(), a);
10834 if (DEBUG_SHOW_INFO)
10836 TAG, " " + type + " " +
10837 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10838 if (DEBUG_SHOW_INFO)
10839 Log.v(TAG, " Class=" + a.info.name);
10840 final int NI = a.intents.size();
10841 for (int j=0; j<NI; j++) {
10842 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10843 if ("activity".equals(type)) {
10844 final PackageSetting ps =
10845 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10846 final List<PackageParser.Activity> systemActivities =
10847 ps != null && ps.pkg != null ? ps.pkg.activities : null;
10848 adjustPriority(systemActivities, intent);
10850 if (DEBUG_SHOW_INFO) {
10851 Log.v(TAG, " IntentFilter:");
10852 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10854 if (!intent.debugCheck()) {
10855 Log.w(TAG, "==> For Activity " + a.info.name);
10861 public final void removeActivity(PackageParser.Activity a, String type) {
10862 mActivities.remove(a.getComponentName());
10863 if (DEBUG_SHOW_INFO) {
10864 Log.v(TAG, " " + type + " "
10865 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10866 : a.info.name) + ":");
10867 Log.v(TAG, " Class=" + a.info.name);
10869 final int NI = a.intents.size();
10870 for (int j=0; j<NI; j++) {
10871 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10872 if (DEBUG_SHOW_INFO) {
10873 Log.v(TAG, " IntentFilter:");
10874 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10876 removeFilter(intent);
10881 protected boolean allowFilterResult(
10882 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10883 ActivityInfo filterAi = filter.activity.info;
10884 for (int i=dest.size()-1; i>=0; i--) {
10885 ActivityInfo destAi = dest.get(i).activityInfo;
10886 if (destAi.name == filterAi.name
10887 && destAi.packageName == filterAi.packageName) {
10895 protected ActivityIntentInfo[] newArray(int size) {
10896 return new ActivityIntentInfo[size];
10900 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10901 if (!sUserManager.exists(userId)) return true;
10902 PackageParser.Package p = filter.activity.owner;
10904 PackageSetting ps = (PackageSetting)p.mExtras;
10906 // System apps are never considered stopped for purposes of
10907 // filtering, because there may be no way for the user to
10908 // actually re-launch them.
10909 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10910 && ps.getStopped(userId);
10917 protected boolean isPackageForFilter(String packageName,
10918 PackageParser.ActivityIntentInfo info) {
10919 return packageName.equals(info.activity.owner.packageName);
10923 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10924 int match, int userId) {
10925 if (!sUserManager.exists(userId)) return null;
10926 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10929 final PackageParser.Activity activity = info.activity;
10930 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10934 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10935 ps.readUserState(userId), userId);
10939 final ResolveInfo res = new ResolveInfo();
10940 res.activityInfo = ai;
10941 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10944 if (info != null) {
10945 res.handleAllWebDataURI = info.handleAllWebDataURI();
10947 res.priority = info.getPriority();
10948 res.preferredOrder = activity.owner.mPreferredOrder;
10949 //System.out.println("Result: " + res.activityInfo.className +
10950 // " = " + res.priority);
10952 res.isDefault = info.hasDefault;
10953 res.labelRes = info.labelRes;
10954 res.nonLocalizedLabel = info.nonLocalizedLabel;
10955 if (userNeedsBadging(userId)) {
10956 res.noResourceId = true;
10958 res.icon = info.icon;
10960 res.iconResourceId = info.icon;
10961 res.system = res.activityInfo.applicationInfo.isSystemApp();
10966 protected void sortResults(List<ResolveInfo> results) {
10967 Collections.sort(results, mResolvePrioritySorter);
10971 protected void dumpFilter(PrintWriter out, String prefix,
10972 PackageParser.ActivityIntentInfo filter) {
10973 out.print(prefix); out.print(
10974 Integer.toHexString(System.identityHashCode(filter.activity)));
10976 filter.activity.printComponentShortName(out);
10977 out.print(" filter ");
10978 out.println(Integer.toHexString(System.identityHashCode(filter)));
10982 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10983 return filter.activity;
10986 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10987 PackageParser.Activity activity = (PackageParser.Activity)label;
10988 out.print(prefix); out.print(
10989 Integer.toHexString(System.identityHashCode(activity)));
10991 activity.printComponentShortName(out);
10993 out.print(" ("); out.print(count); out.print(" filters)");
10998 // Keys are String (activity class name), values are Activity.
10999 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11000 = new ArrayMap<ComponentName, PackageParser.Activity>();
11001 private int mFlags;
11004 private final class ServiceIntentResolver
11005 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11006 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11007 boolean defaultOnly, int userId) {
11008 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11009 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11012 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11014 if (!sUserManager.exists(userId)) return null;
11016 return super.queryIntent(intent, resolvedType,
11017 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11020 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11021 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11022 if (!sUserManager.exists(userId)) return null;
11023 if (packageServices == null) {
11027 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11028 final int N = packageServices.size();
11029 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11030 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11032 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11033 for (int i = 0; i < N; ++i) {
11034 intentFilters = packageServices.get(i).intents;
11035 if (intentFilters != null && intentFilters.size() > 0) {
11036 PackageParser.ServiceIntentInfo[] array =
11037 new PackageParser.ServiceIntentInfo[intentFilters.size()];
11038 intentFilters.toArray(array);
11039 listCut.add(array);
11042 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11045 public final void addService(PackageParser.Service s) {
11046 mServices.put(s.getComponentName(), s);
11047 if (DEBUG_SHOW_INFO) {
11049 + (s.info.nonLocalizedLabel != null
11050 ? s.info.nonLocalizedLabel : s.info.name) + ":");
11051 Log.v(TAG, " Class=" + s.info.name);
11053 final int NI = s.intents.size();
11055 for (j=0; j<NI; j++) {
11056 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11057 if (DEBUG_SHOW_INFO) {
11058 Log.v(TAG, " IntentFilter:");
11059 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11061 if (!intent.debugCheck()) {
11062 Log.w(TAG, "==> For Service " + s.info.name);
11068 public final void removeService(PackageParser.Service s) {
11069 mServices.remove(s.getComponentName());
11070 if (DEBUG_SHOW_INFO) {
11071 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
11072 ? s.info.nonLocalizedLabel : s.info.name) + ":");
11073 Log.v(TAG, " Class=" + s.info.name);
11075 final int NI = s.intents.size();
11077 for (j=0; j<NI; j++) {
11078 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11079 if (DEBUG_SHOW_INFO) {
11080 Log.v(TAG, " IntentFilter:");
11081 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11083 removeFilter(intent);
11088 protected boolean allowFilterResult(
11089 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11090 ServiceInfo filterSi = filter.service.info;
11091 for (int i=dest.size()-1; i>=0; i--) {
11092 ServiceInfo destAi = dest.get(i).serviceInfo;
11093 if (destAi.name == filterSi.name
11094 && destAi.packageName == filterSi.packageName) {
11102 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11103 return new PackageParser.ServiceIntentInfo[size];
11107 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11108 if (!sUserManager.exists(userId)) return true;
11109 PackageParser.Package p = filter.service.owner;
11111 PackageSetting ps = (PackageSetting)p.mExtras;
11113 // System apps are never considered stopped for purposes of
11114 // filtering, because there may be no way for the user to
11115 // actually re-launch them.
11116 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11117 && ps.getStopped(userId);
11124 protected boolean isPackageForFilter(String packageName,
11125 PackageParser.ServiceIntentInfo info) {
11126 return packageName.equals(info.service.owner.packageName);
11130 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11131 int match, int userId) {
11132 if (!sUserManager.exists(userId)) return null;
11133 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11134 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11137 final PackageParser.Service service = info.service;
11138 PackageSetting ps = (PackageSetting) service.owner.mExtras;
11142 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11143 ps.readUserState(userId), userId);
11147 final ResolveInfo res = new ResolveInfo();
11148 res.serviceInfo = si;
11149 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11150 res.filter = filter;
11152 res.priority = info.getPriority();
11153 res.preferredOrder = service.owner.mPreferredOrder;
11155 res.isDefault = info.hasDefault;
11156 res.labelRes = info.labelRes;
11157 res.nonLocalizedLabel = info.nonLocalizedLabel;
11158 res.icon = info.icon;
11159 res.system = res.serviceInfo.applicationInfo.isSystemApp();
11164 protected void sortResults(List<ResolveInfo> results) {
11165 Collections.sort(results, mResolvePrioritySorter);
11169 protected void dumpFilter(PrintWriter out, String prefix,
11170 PackageParser.ServiceIntentInfo filter) {
11171 out.print(prefix); out.print(
11172 Integer.toHexString(System.identityHashCode(filter.service)));
11174 filter.service.printComponentShortName(out);
11175 out.print(" filter ");
11176 out.println(Integer.toHexString(System.identityHashCode(filter)));
11180 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11181 return filter.service;
11184 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11185 PackageParser.Service service = (PackageParser.Service)label;
11186 out.print(prefix); out.print(
11187 Integer.toHexString(System.identityHashCode(service)));
11189 service.printComponentShortName(out);
11191 out.print(" ("); out.print(count); out.print(" filters)");
11196 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11197 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11198 // final List<ResolveInfo> retList = Lists.newArrayList();
11199 // while (i.hasNext()) {
11200 // final ResolveInfo resolveInfo = (ResolveInfo) i;
11201 // if (isEnabledLP(resolveInfo.serviceInfo)) {
11202 // retList.add(resolveInfo);
11208 // Keys are String (activity class name), values are Activity.
11209 private final ArrayMap<ComponentName, PackageParser.Service> mServices
11210 = new ArrayMap<ComponentName, PackageParser.Service>();
11211 private int mFlags;
11214 private final class ProviderIntentResolver
11215 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11216 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11217 boolean defaultOnly, int userId) {
11218 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11219 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11222 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11224 if (!sUserManager.exists(userId))
11227 return super.queryIntent(intent, resolvedType,
11228 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11231 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11232 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11233 if (!sUserManager.exists(userId))
11235 if (packageProviders == null) {
11239 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11240 final int N = packageProviders.size();
11241 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11242 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11244 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11245 for (int i = 0; i < N; ++i) {
11246 intentFilters = packageProviders.get(i).intents;
11247 if (intentFilters != null && intentFilters.size() > 0) {
11248 PackageParser.ProviderIntentInfo[] array =
11249 new PackageParser.ProviderIntentInfo[intentFilters.size()];
11250 intentFilters.toArray(array);
11251 listCut.add(array);
11254 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11257 public final void addProvider(PackageParser.Provider p) {
11258 if (mProviders.containsKey(p.getComponentName())) {
11259 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11263 mProviders.put(p.getComponentName(), p);
11264 if (DEBUG_SHOW_INFO) {
11266 + (p.info.nonLocalizedLabel != null
11267 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11268 Log.v(TAG, " Class=" + p.info.name);
11270 final int NI = p.intents.size();
11272 for (j = 0; j < NI; j++) {
11273 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11274 if (DEBUG_SHOW_INFO) {
11275 Log.v(TAG, " IntentFilter:");
11276 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11278 if (!intent.debugCheck()) {
11279 Log.w(TAG, "==> For Provider " + p.info.name);
11285 public final void removeProvider(PackageParser.Provider p) {
11286 mProviders.remove(p.getComponentName());
11287 if (DEBUG_SHOW_INFO) {
11288 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
11289 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11290 Log.v(TAG, " Class=" + p.info.name);
11292 final int NI = p.intents.size();
11294 for (j = 0; j < NI; j++) {
11295 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11296 if (DEBUG_SHOW_INFO) {
11297 Log.v(TAG, " IntentFilter:");
11298 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11300 removeFilter(intent);
11305 protected boolean allowFilterResult(
11306 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11307 ProviderInfo filterPi = filter.provider.info;
11308 for (int i = dest.size() - 1; i >= 0; i--) {
11309 ProviderInfo destPi = dest.get(i).providerInfo;
11310 if (destPi.name == filterPi.name
11311 && destPi.packageName == filterPi.packageName) {
11319 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11320 return new PackageParser.ProviderIntentInfo[size];
11324 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11325 if (!sUserManager.exists(userId))
11327 PackageParser.Package p = filter.provider.owner;
11329 PackageSetting ps = (PackageSetting) p.mExtras;
11331 // System apps are never considered stopped for purposes of
11332 // filtering, because there may be no way for the user to
11333 // actually re-launch them.
11334 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11335 && ps.getStopped(userId);
11342 protected boolean isPackageForFilter(String packageName,
11343 PackageParser.ProviderIntentInfo info) {
11344 return packageName.equals(info.provider.owner.packageName);
11348 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11349 int match, int userId) {
11350 if (!sUserManager.exists(userId))
11352 final PackageParser.ProviderIntentInfo info = filter;
11353 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11356 final PackageParser.Provider provider = info.provider;
11357 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11361 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11362 ps.readUserState(userId), userId);
11366 final ResolveInfo res = new ResolveInfo();
11367 res.providerInfo = pi;
11368 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11369 res.filter = filter;
11371 res.priority = info.getPriority();
11372 res.preferredOrder = provider.owner.mPreferredOrder;
11374 res.isDefault = info.hasDefault;
11375 res.labelRes = info.labelRes;
11376 res.nonLocalizedLabel = info.nonLocalizedLabel;
11377 res.icon = info.icon;
11378 res.system = res.providerInfo.applicationInfo.isSystemApp();
11383 protected void sortResults(List<ResolveInfo> results) {
11384 Collections.sort(results, mResolvePrioritySorter);
11388 protected void dumpFilter(PrintWriter out, String prefix,
11389 PackageParser.ProviderIntentInfo filter) {
11392 Integer.toHexString(System.identityHashCode(filter.provider)));
11394 filter.provider.printComponentShortName(out);
11395 out.print(" filter ");
11396 out.println(Integer.toHexString(System.identityHashCode(filter)));
11400 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11401 return filter.provider;
11404 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11405 PackageParser.Provider provider = (PackageParser.Provider)label;
11406 out.print(prefix); out.print(
11407 Integer.toHexString(System.identityHashCode(provider)));
11409 provider.printComponentShortName(out);
11411 out.print(" ("); out.print(count); out.print(" filters)");
11416 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11417 = new ArrayMap<ComponentName, PackageParser.Provider>();
11418 private int mFlags;
11421 private static final class EphemeralIntentResolver
11422 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11424 * The result that has the highest defined order. Ordering applies on a
11425 * per-package basis. Mapping is from package name to Pair of order and
11426 * EphemeralResolveInfo.
11428 * NOTE: This is implemented as a field variable for convenience and efficiency.
11429 * By having a field variable, we're able to track filter ordering as soon as
11430 * a non-zero order is defined. Otherwise, multiple loops across the result set
11431 * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11432 * this needs to be contained entirely within {@link #filterResults()}.
11434 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11437 protected EphemeralResolveIntentInfo[] newArray(int size) {
11438 return new EphemeralResolveIntentInfo[size];
11442 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11447 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11449 if (!sUserManager.exists(userId)) {
11452 final String packageName = info.getEphemeralResolveInfo().getPackageName();
11453 final Integer order = info.getOrder();
11454 final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11455 mOrderResult.get(packageName);
11456 // ordering is enabled and this item's order isn't high enough
11457 if (lastOrderResult != null && lastOrderResult.first >= order) {
11460 final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11462 // non-zero order, enable ordering
11463 mOrderResult.put(packageName, new Pair<>(order, res));
11469 protected void filterResults(List<EphemeralResolveInfo> results) {
11470 // only do work if ordering is enabled [most of the time it won't be]
11471 if (mOrderResult.size() == 0) {
11474 int resultSize = results.size();
11475 for (int i = 0; i < resultSize; i++) {
11476 final EphemeralResolveInfo info = results.get(i);
11477 final String packageName = info.getPackageName();
11478 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11479 if (savedInfo == null) {
11480 // package doesn't having ordering
11483 if (savedInfo.second == info) {
11484 // circled back to the highest ordered item; remove from order list
11485 mOrderResult.remove(savedInfo);
11486 if (mOrderResult.size() == 0) {
11487 // no more ordered items
11492 // item has a worse order, remove it from the result list
11500 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11501 new Comparator<ResolveInfo>() {
11502 public int compare(ResolveInfo r1, ResolveInfo r2) {
11503 int v1 = r1.priority;
11504 int v2 = r2.priority;
11505 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11507 return (v1 > v2) ? -1 : 1;
11509 v1 = r1.preferredOrder;
11510 v2 = r2.preferredOrder;
11512 return (v1 > v2) ? -1 : 1;
11514 if (r1.isDefault != r2.isDefault) {
11515 return r1.isDefault ? -1 : 1;
11519 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11521 return (v1 > v2) ? -1 : 1;
11523 if (r1.system != r2.system) {
11524 return r1.system ? -1 : 1;
11526 if (r1.activityInfo != null) {
11527 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11529 if (r1.serviceInfo != null) {
11530 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11532 if (r1.providerInfo != null) {
11533 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11539 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11540 new Comparator<ProviderInfo>() {
11541 public int compare(ProviderInfo p1, ProviderInfo p2) {
11542 final int v1 = p1.initOrder;
11543 final int v2 = p2.initOrder;
11544 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11548 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11549 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11550 final int[] userIds) {
11551 mHandler.post(new Runnable() {
11553 public void run() {
11555 final IActivityManager am = ActivityManagerNative.getDefault();
11556 if (am == null) return;
11557 final int[] resolvedUserIds;
11558 if (userIds == null) {
11559 resolvedUserIds = am.getRunningUserIds();
11561 resolvedUserIds = userIds;
11563 for (int id : resolvedUserIds) {
11564 final Intent intent = new Intent(action,
11565 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11566 if (extras != null) {
11567 intent.putExtras(extras);
11569 if (targetPkg != null) {
11570 intent.setPackage(targetPkg);
11572 // Modify the UID when posting to other users
11573 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11574 if (uid > 0 && UserHandle.getUserId(uid) != id) {
11575 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11576 intent.putExtra(Intent.EXTRA_UID, uid);
11578 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11579 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11580 if (DEBUG_BROADCASTS) {
11581 RuntimeException here = new RuntimeException("here");
11582 here.fillInStackTrace();
11583 Slog.d(TAG, "Sending to user " + id + ": "
11584 + intent.toShortString(false, true, false, false)
11585 + " " + intent.getExtras(), here);
11587 am.broadcastIntent(null, intent, null, finishedReceiver,
11588 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11589 null, finishedReceiver != null, false, id);
11591 } catch (RemoteException ex) {
11598 * Check if the external storage media is available. This is true if there
11599 * is a mounted external storage medium or if the external storage is
11602 private boolean isExternalMediaAvailable() {
11603 return mMediaMounted || Environment.isExternalStorageEmulated();
11607 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11609 synchronized (mPackages) {
11610 if (!isExternalMediaAvailable()) {
11611 // If the external storage is no longer mounted at this point,
11612 // the caller may not have been able to delete all of this
11613 // packages files and can not delete any more. Bail.
11616 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11617 if (lastPackage != null) {
11618 pkgs.remove(lastPackage);
11620 if (pkgs.size() > 0) {
11621 return pkgs.get(0);
11627 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11628 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11629 userId, andCode ? 1 : 0, packageName);
11630 if (mSystemReady) {
11631 msg.sendToTarget();
11633 if (mPostSystemReadyMessages == null) {
11634 mPostSystemReadyMessages = new ArrayList<>();
11636 mPostSystemReadyMessages.add(msg);
11640 void startCleaningPackages() {
11642 if (!isExternalMediaAvailable()) {
11645 synchronized (mPackages) {
11646 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11650 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11651 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11652 IActivityManager am = ActivityManagerNative.getDefault();
11655 am.startService(null, intent, null, mContext.getOpPackageName(),
11656 UserHandle.USER_SYSTEM);
11657 } catch (RemoteException e) {
11663 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11664 int installFlags, String installerPackageName, int userId) {
11665 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11667 final int callingUid = Binder.getCallingUid();
11668 enforceCrossUserPermission(callingUid, userId,
11669 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11671 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11673 if (observer != null) {
11674 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11676 } catch (RemoteException re) {
11681 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11682 installFlags |= PackageManager.INSTALL_FROM_ADB;
11685 // Caller holds INSTALL_PACKAGES permission, so we're less strict
11686 // about installerPackageName.
11688 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11689 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11693 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11694 user = UserHandle.ALL;
11696 user = new UserHandle(userId);
11699 // Only system components can circumvent runtime permissions when installing.
11700 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11701 && mContext.checkCallingOrSelfPermission(Manifest.permission
11702 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11703 throw new SecurityException("You need the "
11704 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11705 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11708 final File originFile = new File(originPath);
11709 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11711 final Message msg = mHandler.obtainMessage(INIT_COPY);
11712 final VerificationInfo verificationInfo = new VerificationInfo(
11713 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11714 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11715 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11716 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11717 null /*certificates*/);
11718 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11721 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11722 System.identityHashCode(msg.obj));
11723 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11724 System.identityHashCode(msg.obj));
11726 mHandler.sendMessage(msg);
11729 void installStage(String packageName, File stagedDir, String stagedCid,
11730 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11731 String installerPackageName, int installerUid, UserHandle user,
11732 Certificate[][] certificates) {
11733 if (DEBUG_EPHEMERAL) {
11734 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11735 Slog.d(TAG, "Ephemeral install of " + packageName);
11738 final VerificationInfo verificationInfo = new VerificationInfo(
11739 sessionParams.originatingUri, sessionParams.referrerUri,
11740 sessionParams.originatingUid, installerUid);
11742 final OriginInfo origin;
11743 if (stagedDir != null) {
11744 origin = OriginInfo.fromStagedFile(stagedDir);
11746 origin = OriginInfo.fromStagedContainer(stagedCid);
11749 final Message msg = mHandler.obtainMessage(INIT_COPY);
11750 final InstallParams params = new InstallParams(origin, null, observer,
11751 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11752 verificationInfo, user, sessionParams.abiOverride,
11753 sessionParams.grantedRuntimePermissions, certificates);
11754 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11757 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11758 System.identityHashCode(msg.obj));
11759 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11760 System.identityHashCode(msg.obj));
11762 mHandler.sendMessage(msg);
11765 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11767 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11768 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11771 private void sendPackageAddedForUser(String packageName, boolean isSystem,
11772 int appId, int userId) {
11773 Bundle extras = new Bundle(1);
11774 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11776 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11777 packageName, extras, 0, null, null, new int[] {userId});
11779 IActivityManager am = ActivityManagerNative.getDefault();
11780 if (isSystem && am.isUserRunning(userId, 0)) {
11781 // The just-installed/enabled app is bundled on the system, so presumed
11782 // to be able to run automatically without needing an explicit launch.
11783 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11784 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11785 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11786 .setPackage(packageName);
11787 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11788 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11790 } catch (RemoteException e) {
11791 // shouldn't happen
11792 Slog.w(TAG, "Unable to bootstrap installed package", e);
11797 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11799 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11800 PackageSetting pkgSetting;
11801 final int uid = Binder.getCallingUid();
11802 enforceCrossUserPermission(uid, userId,
11803 true /* requireFullPermission */, true /* checkShell */,
11804 "setApplicationHiddenSetting for user " + userId);
11806 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11807 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11811 long callingId = Binder.clearCallingIdentity();
11813 boolean sendAdded = false;
11814 boolean sendRemoved = false;
11816 synchronized (mPackages) {
11817 pkgSetting = mSettings.mPackages.get(packageName);
11818 if (pkgSetting == null) {
11821 // Do not allow "android" is being disabled
11822 if ("android".equals(packageName)) {
11823 Slog.w(TAG, "Cannot hide package: android");
11826 // Only allow protected packages to hide themselves.
11827 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11828 && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11829 Slog.w(TAG, "Not hiding protected package: " + packageName);
11833 if (pkgSetting.getHidden(userId) != hidden) {
11834 pkgSetting.setHidden(hidden, userId);
11835 mSettings.writePackageRestrictionsLPr(userId);
11837 sendRemoved = true;
11844 sendPackageAddedForUser(packageName, pkgSetting, userId);
11848 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11850 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11854 Binder.restoreCallingIdentity(callingId);
11859 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11861 final PackageRemovedInfo info = new PackageRemovedInfo();
11862 info.removedPackage = packageName;
11863 info.removedUsers = new int[] {userId};
11864 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11865 info.sendPackageRemovedBroadcasts(true /*killApp*/);
11868 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11869 if (pkgList.length > 0) {
11870 Bundle extras = new Bundle(1);
11871 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11873 sendPackageBroadcast(
11874 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11875 : Intent.ACTION_PACKAGES_UNSUSPENDED,
11876 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11877 new int[] {userId});
11882 * Returns true if application is not found or there was an error. Otherwise it returns
11883 * the hidden state of the package for the given user.
11886 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11887 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11888 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11889 true /* requireFullPermission */, false /* checkShell */,
11890 "getApplicationHidden for user " + userId);
11891 PackageSetting pkgSetting;
11892 long callingId = Binder.clearCallingIdentity();
11895 synchronized (mPackages) {
11896 pkgSetting = mSettings.mPackages.get(packageName);
11897 if (pkgSetting == null) {
11900 return pkgSetting.getHidden(userId);
11903 Binder.restoreCallingIdentity(callingId);
11911 public int installExistingPackageAsUser(String packageName, int userId) {
11912 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11914 PackageSetting pkgSetting;
11915 final int uid = Binder.getCallingUid();
11916 enforceCrossUserPermission(uid, userId,
11917 true /* requireFullPermission */, true /* checkShell */,
11918 "installExistingPackage for user " + userId);
11919 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11920 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11923 long callingId = Binder.clearCallingIdentity();
11925 boolean installed = false;
11928 synchronized (mPackages) {
11929 pkgSetting = mSettings.mPackages.get(packageName);
11930 if (pkgSetting == null) {
11931 return PackageManager.INSTALL_FAILED_INVALID_URI;
11933 if (!pkgSetting.getInstalled(userId)) {
11934 pkgSetting.setInstalled(true, userId);
11935 pkgSetting.setHidden(false, userId);
11936 mSettings.writePackageRestrictionsLPr(userId);
11942 if (pkgSetting.pkg != null) {
11943 synchronized (mInstallLock) {
11944 // We don't need to freeze for a brand new install
11945 prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11948 sendPackageAddedForUser(packageName, pkgSetting, userId);
11951 Binder.restoreCallingIdentity(callingId);
11954 return PackageManager.INSTALL_SUCCEEDED;
11957 boolean isUserRestricted(int userId, String restrictionKey) {
11958 Bundle restrictions = sUserManager.getUserRestrictions(userId);
11959 if (restrictions.getBoolean(restrictionKey, false)) {
11960 Log.w(TAG, "User is restricted: " + restrictionKey);
11967 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11969 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11970 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11971 true /* requireFullPermission */, true /* checkShell */,
11972 "setPackagesSuspended for user " + userId);
11974 if (ArrayUtils.isEmpty(packageNames)) {
11975 return packageNames;
11978 // List of package names for whom the suspended state has changed.
11979 List<String> changedPackages = new ArrayList<>(packageNames.length);
11980 // List of package names for whom the suspended state is not set as requested in this
11982 List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11983 long callingId = Binder.clearCallingIdentity();
11985 for (int i = 0; i < packageNames.length; i++) {
11986 String packageName = packageNames[i];
11987 boolean changed = false;
11989 synchronized (mPackages) {
11990 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11991 if (pkgSetting == null) {
11992 Slog.w(TAG, "Could not find package setting for package \"" + packageName
11993 + "\". Skipping suspending/un-suspending.");
11994 unactionedPackages.add(packageName);
11997 appId = pkgSetting.appId;
11998 if (pkgSetting.getSuspended(userId) != suspended) {
11999 if (!canSuspendPackageForUserLocked(packageName, userId)) {
12000 unactionedPackages.add(packageName);
12003 pkgSetting.setSuspended(suspended, userId);
12004 mSettings.writePackageRestrictionsLPr(userId);
12006 changedPackages.add(packageName);
12010 if (changed && suspended) {
12011 killApplication(packageName, UserHandle.getUid(userId, appId),
12012 "suspending package");
12016 Binder.restoreCallingIdentity(callingId);
12019 if (!changedPackages.isEmpty()) {
12020 sendPackagesSuspendedForUser(changedPackages.toArray(
12021 new String[changedPackages.size()]), userId, suspended);
12024 return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12028 public boolean isPackageSuspendedForUser(String packageName, int userId) {
12029 enforceCrossUserPermission(Binder.getCallingUid(), userId,
12030 true /* requireFullPermission */, false /* checkShell */,
12031 "isPackageSuspendedForUser for user " + userId);
12032 synchronized (mPackages) {
12033 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12034 if (pkgSetting == null) {
12035 throw new IllegalArgumentException("Unknown target package: " + packageName);
12037 return pkgSetting.getSuspended(userId);
12041 private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12042 if (isPackageDeviceAdmin(packageName, userId)) {
12043 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12044 + "\": has an active device admin");
12048 String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12049 if (packageName.equals(activeLauncherPackageName)) {
12050 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12051 + "\": contains the active launcher");
12055 if (packageName.equals(mRequiredInstallerPackage)) {
12056 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12057 + "\": required for package installation");
12061 if (packageName.equals(mRequiredUninstallerPackage)) {
12062 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12063 + "\": required for package uninstallation");
12067 if (packageName.equals(mRequiredVerifierPackage)) {
12068 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12069 + "\": required for package verification");
12073 if (packageName.equals(getDefaultDialerPackageName(userId))) {
12074 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12075 + "\": is the default dialer");
12079 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12080 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12081 + "\": protected package");
12088 private String getActiveLauncherPackageName(int userId) {
12089 Intent intent = new Intent(Intent.ACTION_MAIN);
12090 intent.addCategory(Intent.CATEGORY_HOME);
12091 ResolveInfo resolveInfo = resolveIntent(
12093 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12094 PackageManager.MATCH_DEFAULT_ONLY,
12097 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12100 private String getDefaultDialerPackageName(int userId) {
12101 synchronized (mPackages) {
12102 return mSettings.getDefaultDialerPackageNameLPw(userId);
12107 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12108 mContext.enforceCallingOrSelfPermission(
12109 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12110 "Only package verification agents can verify applications");
12112 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12113 final PackageVerificationResponse response = new PackageVerificationResponse(
12114 verificationCode, Binder.getCallingUid());
12116 msg.obj = response;
12117 mHandler.sendMessage(msg);
12121 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12122 long millisecondsToDelay) {
12123 mContext.enforceCallingOrSelfPermission(
12124 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12125 "Only package verification agents can extend verification timeouts");
12127 final PackageVerificationState state = mPendingVerification.get(id);
12128 final PackageVerificationResponse response = new PackageVerificationResponse(
12129 verificationCodeAtTimeout, Binder.getCallingUid());
12131 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12132 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12134 if (millisecondsToDelay < 0) {
12135 millisecondsToDelay = 0;
12137 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12138 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12139 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12142 if ((state != null) && !state.timeoutExtended()) {
12143 state.extendTimeout();
12145 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12147 msg.obj = response;
12148 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12152 private void broadcastPackageVerified(int verificationId, Uri packageUri,
12153 int verificationCode, UserHandle user) {
12154 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12155 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12156 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12157 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12158 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12160 mContext.sendBroadcastAsUser(intent, user,
12161 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12164 private ComponentName matchComponentForVerifier(String packageName,
12165 List<ResolveInfo> receivers) {
12166 ActivityInfo targetReceiver = null;
12168 final int NR = receivers.size();
12169 for (int i = 0; i < NR; i++) {
12170 final ResolveInfo info = receivers.get(i);
12171 if (info.activityInfo == null) {
12175 if (packageName.equals(info.activityInfo.packageName)) {
12176 targetReceiver = info.activityInfo;
12181 if (targetReceiver == null) {
12185 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12188 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12189 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12190 if (pkgInfo.verifiers.length == 0) {
12194 final int N = pkgInfo.verifiers.length;
12195 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12196 for (int i = 0; i < N; i++) {
12197 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12199 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12201 if (comp == null) {
12205 final int verifierUid = getUidForVerifier(verifierInfo);
12206 if (verifierUid == -1) {
12210 if (DEBUG_VERIFY) {
12211 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12212 + " with the correct signature");
12214 sufficientVerifiers.add(comp);
12215 verificationState.addSufficientVerifier(verifierUid);
12218 return sufficientVerifiers;
12221 private int getUidForVerifier(VerifierInfo verifierInfo) {
12222 synchronized (mPackages) {
12223 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12226 } else if (pkg.mSignatures.length != 1) {
12227 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12228 + " has more than one signature; ignoring");
12233 * If the public key of the package's signature does not match
12234 * our expected public key, then this is a different package and
12238 final byte[] expectedPublicKey;
12240 final Signature verifierSig = pkg.mSignatures[0];
12241 final PublicKey publicKey = verifierSig.getPublicKey();
12242 expectedPublicKey = publicKey.getEncoded();
12243 } catch (CertificateException e) {
12247 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12249 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12250 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12251 + " does not have the expected public key; ignoring");
12255 return pkg.applicationInfo.uid;
12260 public void finishPackageInstall(int token, boolean didLaunch) {
12261 enforceSystemOrRoot("Only the system is allowed to finish installs");
12263 if (DEBUG_INSTALL) {
12264 Slog.v(TAG, "BM finishing package install for " + token);
12266 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12268 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12269 mHandler.sendMessage(msg);
12273 * Get the verification agent timeout.
12275 * @return verification timeout in milliseconds
12277 private long getVerificationTimeout() {
12278 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12279 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12280 DEFAULT_VERIFICATION_TIMEOUT);
12284 * Get the default verification agent response code.
12286 * @return default verification response code
12288 private int getDefaultVerificationResponse() {
12289 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12290 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12291 DEFAULT_VERIFICATION_RESPONSE);
12295 * Check whether or not package verification has been enabled.
12297 * @return true if verification should be performed
12299 private boolean isVerificationEnabled(int userId, int installFlags) {
12300 if (!DEFAULT_VERIFY_ENABLE) {
12303 // Ephemeral apps don't get the full verification treatment
12304 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12305 if (DEBUG_EPHEMERAL) {
12306 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12311 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12313 // Check if installing from ADB
12314 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12315 // Do not run verification in a test harness environment
12316 if (ActivityManager.isRunningInTestHarness()) {
12319 if (ensureVerifyAppsEnabled) {
12322 // Check if the developer does not want package verification for ADB installs
12323 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12324 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12329 if (ensureVerifyAppsEnabled) {
12333 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12334 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12338 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12339 throws RemoteException {
12340 mContext.enforceCallingOrSelfPermission(
12341 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12342 "Only intentfilter verification agents can verify applications");
12344 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12345 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12346 Binder.getCallingUid(), verificationCode, failedDomains);
12348 msg.obj = response;
12349 mHandler.sendMessage(msg);
12353 public int getIntentVerificationStatus(String packageName, int userId) {
12354 synchronized (mPackages) {
12355 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12360 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12361 mContext.enforceCallingOrSelfPermission(
12362 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12364 boolean result = false;
12365 synchronized (mPackages) {
12366 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12369 scheduleWritePackageRestrictionsLocked(userId);
12375 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12376 String packageName) {
12377 synchronized (mPackages) {
12378 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12383 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12384 if (TextUtils.isEmpty(packageName)) {
12385 return ParceledListSlice.emptyList();
12387 synchronized (mPackages) {
12388 PackageParser.Package pkg = mPackages.get(packageName);
12389 if (pkg == null || pkg.activities == null) {
12390 return ParceledListSlice.emptyList();
12392 final int count = pkg.activities.size();
12393 ArrayList<IntentFilter> result = new ArrayList<>();
12394 for (int n=0; n<count; n++) {
12395 PackageParser.Activity activity = pkg.activities.get(n);
12396 if (activity.intents != null && activity.intents.size() > 0) {
12397 result.addAll(activity.intents);
12400 return new ParceledListSlice<>(result);
12405 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12406 mContext.enforceCallingOrSelfPermission(
12407 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12409 synchronized (mPackages) {
12410 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12411 if (packageName != null) {
12412 result |= updateIntentVerificationStatus(packageName,
12413 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12415 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12416 packageName, userId);
12423 public String getDefaultBrowserPackageName(int userId) {
12424 synchronized (mPackages) {
12425 return mSettings.getDefaultBrowserPackageNameLPw(userId);
12430 * Get the "allow unknown sources" setting.
12432 * @return the current "allow unknown sources" setting
12434 private int getUnknownSourcesSettings() {
12435 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12436 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12441 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12442 final int uid = Binder.getCallingUid();
12444 synchronized (mPackages) {
12445 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12446 if (targetPackageSetting == null) {
12447 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12450 PackageSetting installerPackageSetting;
12451 if (installerPackageName != null) {
12452 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12453 if (installerPackageSetting == null) {
12454 throw new IllegalArgumentException("Unknown installer package: "
12455 + installerPackageName);
12458 installerPackageSetting = null;
12461 Signature[] callerSignature;
12462 Object obj = mSettings.getUserIdLPr(uid);
12464 if (obj instanceof SharedUserSetting) {
12465 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12466 } else if (obj instanceof PackageSetting) {
12467 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12469 throw new SecurityException("Bad object " + obj + " for uid " + uid);
12472 throw new SecurityException("Unknown calling UID: " + uid);
12475 // Verify: can't set installerPackageName to a package that is
12476 // not signed with the same cert as the caller.
12477 if (installerPackageSetting != null) {
12478 if (compareSignatures(callerSignature,
12479 installerPackageSetting.signatures.mSignatures)
12480 != PackageManager.SIGNATURE_MATCH) {
12481 throw new SecurityException(
12482 "Caller does not have same cert as new installer package "
12483 + installerPackageName);
12487 // Verify: if target already has an installer package, it must
12488 // be signed with the same cert as the caller.
12489 if (targetPackageSetting.installerPackageName != null) {
12490 PackageSetting setting = mSettings.mPackages.get(
12491 targetPackageSetting.installerPackageName);
12492 // If the currently set package isn't valid, then it's always
12493 // okay to change it.
12494 if (setting != null) {
12495 if (compareSignatures(callerSignature,
12496 setting.signatures.mSignatures)
12497 != PackageManager.SIGNATURE_MATCH) {
12498 throw new SecurityException(
12499 "Caller does not have same cert as old installer package "
12500 + targetPackageSetting.installerPackageName);
12506 targetPackageSetting.installerPackageName = installerPackageName;
12507 if (installerPackageName != null) {
12508 mSettings.mInstallerPackages.add(installerPackageName);
12510 scheduleWriteSettingsLocked();
12514 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12515 // Queue up an async operation since the package installation may take a little while.
12516 mHandler.post(new Runnable() {
12517 public void run() {
12518 mHandler.removeCallbacks(this);
12519 // Result object to be returned
12520 PackageInstalledInfo res = new PackageInstalledInfo();
12521 res.setReturnCode(currentStatus);
12524 res.removedInfo = null;
12525 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12526 args.doPreInstall(res.returnCode);
12527 synchronized (mInstallLock) {
12528 installPackageTracedLI(args, res);
12530 args.doPostInstall(res.returnCode, res.uid);
12533 // A restore should be performed at this point if (a) the install
12534 // succeeded, (b) the operation is not an update, and (c) the new
12535 // package has not opted out of backup participation.
12536 final boolean update = res.removedInfo != null
12537 && res.removedInfo.removedPackage != null;
12538 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12539 boolean doRestore = !update
12540 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12542 // Set up the post-install work request bookkeeping. This will be used
12543 // and cleaned up by the post-install event handling regardless of whether
12544 // there's a restore pass performed. Token values are >= 1.
12546 if (mNextInstallToken < 0) mNextInstallToken = 1;
12547 token = mNextInstallToken++;
12549 PostInstallData data = new PostInstallData(args, res);
12550 mRunningInstalls.put(token, data);
12551 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12553 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12554 // Pass responsibility to the Backup Manager. It will perform a
12555 // restore if appropriate, then pass responsibility back to the
12556 // Package Manager to run the post-install observer callbacks
12558 IBackupManager bm = IBackupManager.Stub.asInterface(
12559 ServiceManager.getService(Context.BACKUP_SERVICE));
12561 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12562 + " to BM for possible restore");
12563 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12565 // TODO: http://b/22388012
12566 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12567 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12571 } catch (RemoteException e) {
12572 // can't happen; the backup manager is local
12573 } catch (Exception e) {
12574 Slog.e(TAG, "Exception trying to enqueue restore", e);
12578 Slog.e(TAG, "Backup Manager not found!");
12584 // No restore possible, or the Backup Manager was mysteriously not
12585 // available -- just fire the post-install work request directly.
12586 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12588 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12590 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12591 mHandler.sendMessage(msg);
12598 * Callback from PackageSettings whenever an app is first transitioned out of the
12599 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if
12600 * the app was "launched" for a restoreAtInstall operation. Therefore we check
12601 * here whether the app is the target of an ongoing install, and only send the
12602 * broadcast immediately if it is not in that state. If it *is* undergoing a restore,
12603 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12606 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12607 // Serialize this with the rest of the install-process message chain. In the
12608 // restore-at-install case, this Runnable will necessarily run before the
12609 // POST_INSTALL message is processed, so the contents of mRunningInstalls
12610 // are coherent. In the non-restore case, the app has already completed install
12611 // and been launched through some other means, so it is not in a problematic
12612 // state for observers to see the FIRST_LAUNCH signal.
12613 mHandler.post(new Runnable() {
12615 public void run() {
12616 for (int i = 0; i < mRunningInstalls.size(); i++) {
12617 final PostInstallData data = mRunningInstalls.valueAt(i);
12618 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12621 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12622 // right package; but is it for the right user?
12623 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12624 if (userId == data.res.newUsers[uIndex]) {
12625 if (DEBUG_BACKUP) {
12626 Slog.i(TAG, "Package " + pkgName
12627 + " being restored so deferring FIRST_LAUNCH");
12634 // didn't find it, so not being restored
12635 if (DEBUG_BACKUP) {
12636 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12638 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12643 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12644 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12645 installerPkg, null, userIds);
12648 private abstract class HandlerParams {
12649 private static final int MAX_RETRIES = 4;
12652 * Number of times startCopy() has been attempted and had a non-fatal
12655 private int mRetries = 0;
12657 /** User handle for the user requesting the information or installation. */
12658 private final UserHandle mUser;
12659 String traceMethod;
12662 HandlerParams(UserHandle user) {
12666 UserHandle getUser() {
12670 HandlerParams setTraceMethod(String traceMethod) {
12671 this.traceMethod = traceMethod;
12675 HandlerParams setTraceCookie(int traceCookie) {
12676 this.traceCookie = traceCookie;
12680 final boolean startCopy() {
12683 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12685 if (++mRetries > MAX_RETRIES) {
12686 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12687 mHandler.sendEmptyMessage(MCS_GIVE_UP);
12688 handleServiceError();
12694 } catch (RemoteException e) {
12695 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12696 mHandler.sendEmptyMessage(MCS_RECONNECT);
12699 handleReturnCode();
12703 final void serviceError() {
12704 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12705 handleServiceError();
12706 handleReturnCode();
12709 abstract void handleStartCopy() throws RemoteException;
12710 abstract void handleServiceError();
12711 abstract void handleReturnCode();
12714 class MeasureParams extends HandlerParams {
12715 private final PackageStats mStats;
12716 private boolean mSuccess;
12718 private final IPackageStatsObserver mObserver;
12720 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12721 super(new UserHandle(stats.userHandle));
12722 mObserver = observer;
12727 public String toString() {
12728 return "MeasureParams{"
12729 + Integer.toHexString(System.identityHashCode(this))
12730 + " " + mStats.packageName + "}";
12734 void handleStartCopy() throws RemoteException {
12735 synchronized (mInstallLock) {
12736 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12740 boolean mounted = false;
12742 final String status = Environment.getExternalStorageState();
12743 mounted = (Environment.MEDIA_MOUNTED.equals(status)
12744 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12745 } catch (Exception e) {
12749 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12751 mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12752 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12754 mStats.externalDataSize = calculateDirectorySize(mContainerService,
12755 userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12757 // Always subtract cache size, since it's a subdirectory
12758 mStats.externalDataSize -= mStats.externalCacheSize;
12760 mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12761 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12763 mStats.externalObbSize = calculateDirectorySize(mContainerService,
12764 userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12770 void handleReturnCode() {
12771 if (mObserver != null) {
12773 mObserver.onGetStatsCompleted(mStats, mSuccess);
12774 } catch (RemoteException e) {
12775 Slog.i(TAG, "Observer no longer exists.");
12781 void handleServiceError() {
12782 Slog.e(TAG, "Could not measure application " + mStats.packageName
12783 + " external storage");
12787 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12788 throws RemoteException {
12790 for (File path : paths) {
12791 result += mcs.calculateDirectorySize(path.getAbsolutePath());
12796 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12797 for (File path : paths) {
12799 mcs.clearDirectory(path.getAbsolutePath());
12800 } catch (RemoteException e) {
12805 static class OriginInfo {
12807 * Location where install is coming from, before it has been
12808 * copied/renamed into place. This could be a single monolithic APK
12809 * file, or a cluster directory. This location may be untrusted.
12815 * Flag indicating that {@link #file} or {@link #cid} has already been
12816 * staged, meaning downstream users don't need to defensively copy the
12819 final boolean staged;
12822 * Flag indicating that {@link #file} or {@link #cid} is an already
12823 * installed app that is being moved.
12825 final boolean existing;
12827 final String resolvedPath;
12828 final File resolvedFile;
12830 static OriginInfo fromNothing() {
12831 return new OriginInfo(null, null, false, false);
12834 static OriginInfo fromUntrustedFile(File file) {
12835 return new OriginInfo(file, null, false, false);
12838 static OriginInfo fromExistingFile(File file) {
12839 return new OriginInfo(file, null, false, true);
12842 static OriginInfo fromStagedFile(File file) {
12843 return new OriginInfo(file, null, true, false);
12846 static OriginInfo fromStagedContainer(String cid) {
12847 return new OriginInfo(null, cid, true, false);
12850 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12853 this.staged = staged;
12854 this.existing = existing;
12857 resolvedPath = PackageHelper.getSdDir(cid);
12858 resolvedFile = new File(resolvedPath);
12859 } else if (file != null) {
12860 resolvedPath = file.getAbsolutePath();
12861 resolvedFile = file;
12863 resolvedPath = null;
12864 resolvedFile = null;
12869 static class MoveInfo {
12871 final String fromUuid;
12872 final String toUuid;
12873 final String packageName;
12874 final String dataAppName;
12876 final String seinfo;
12877 final int targetSdkVersion;
12879 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12880 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12881 this.moveId = moveId;
12882 this.fromUuid = fromUuid;
12883 this.toUuid = toUuid;
12884 this.packageName = packageName;
12885 this.dataAppName = dataAppName;
12886 this.appId = appId;
12887 this.seinfo = seinfo;
12888 this.targetSdkVersion = targetSdkVersion;
12892 static class VerificationInfo {
12893 /** A constant used to indicate that a uid value is not present. */
12894 public static final int NO_UID = -1;
12896 /** URI referencing where the package was downloaded from. */
12897 final Uri originatingUri;
12899 /** HTTP referrer URI associated with the originatingURI. */
12900 final Uri referrer;
12902 /** UID of the application that the install request originated from. */
12903 final int originatingUid;
12905 /** UID of application requesting the install */
12906 final int installerUid;
12908 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12909 this.originatingUri = originatingUri;
12910 this.referrer = referrer;
12911 this.originatingUid = originatingUid;
12912 this.installerUid = installerUid;
12916 class InstallParams extends HandlerParams {
12917 final OriginInfo origin;
12918 final MoveInfo move;
12919 final IPackageInstallObserver2 observer;
12921 final String installerPackageName;
12922 final String volumeUuid;
12923 private InstallArgs mArgs;
12925 final String packageAbiOverride;
12926 final String[] grantedRuntimePermissions;
12927 final VerificationInfo verificationInfo;
12928 final Certificate[][] certificates;
12930 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12931 int installFlags, String installerPackageName, String volumeUuid,
12932 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12933 String[] grantedPermissions, Certificate[][] certificates) {
12935 this.origin = origin;
12937 this.observer = observer;
12938 this.installFlags = installFlags;
12939 this.installerPackageName = installerPackageName;
12940 this.volumeUuid = volumeUuid;
12941 this.verificationInfo = verificationInfo;
12942 this.packageAbiOverride = packageAbiOverride;
12943 this.grantedRuntimePermissions = grantedPermissions;
12944 this.certificates = certificates;
12948 public String toString() {
12949 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12950 + " file=" + origin.file + " cid=" + origin.cid + "}";
12953 private int installLocationPolicy(PackageInfoLite pkgLite) {
12954 String packageName = pkgLite.packageName;
12955 int installLocation = pkgLite.installLocation;
12956 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12958 synchronized (mPackages) {
12959 // Currently installed package which the new package is attempting to replace or
12960 // null if no such package is installed.
12961 PackageParser.Package installedPkg = mPackages.get(packageName);
12962 // Package which currently owns the data which the new package will own if installed.
12963 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12964 // will be null whereas dataOwnerPkg will contain information about the package
12965 // which was uninstalled while keeping its data.
12966 PackageParser.Package dataOwnerPkg = installedPkg;
12967 if (dataOwnerPkg == null) {
12968 PackageSetting ps = mSettings.mPackages.get(packageName);
12970 dataOwnerPkg = ps.pkg;
12974 if (dataOwnerPkg != null) {
12975 // If installed, the package will get access to data left on the device by its
12976 // predecessor. As a security measure, this is permited only if this is not a
12977 // version downgrade or if the predecessor package is marked as debuggable and
12978 // a downgrade is explicitly requested.
12980 // On debuggable platform builds, downgrades are permitted even for
12981 // non-debuggable packages to make testing easier. Debuggable platform builds do
12982 // not offer security guarantees and thus it's OK to disable some security
12983 // mechanisms to make debugging/testing easier on those builds. However, even on
12984 // debuggable builds downgrades of packages are permitted only if requested via
12985 // installFlags. This is because we aim to keep the behavior of debuggable
12986 // platform builds as close as possible to the behavior of non-debuggable
12987 // platform builds.
12988 final boolean downgradeRequested =
12989 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12990 final boolean packageDebuggable =
12991 (dataOwnerPkg.applicationInfo.flags
12992 & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12993 final boolean downgradePermitted =
12994 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12995 if (!downgradePermitted) {
12997 checkDowngrade(dataOwnerPkg, pkgLite);
12998 } catch (PackageManagerException e) {
12999 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13000 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13005 if (installedPkg != null) {
13006 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13007 // Check for updated system application.
13008 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13010 Slog.w(TAG, "Cannot install update to system app on sdcard");
13011 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13013 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13016 // Install flag overrides everything.
13017 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13019 // If current upgrade specifies particular preference
13020 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13021 // Application explicitly specified internal.
13022 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13023 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13024 // App explictly prefers external. Let policy decide
13026 // Prefer previous location
13027 if (isExternal(installedPkg)) {
13028 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13030 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13034 // Invalid install. Return error code
13035 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13039 // All the special cases have been taken care of.
13040 // Return result based on recommended install location.
13042 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13044 return pkgLite.recommendedInstallLocation;
13048 * Invoke remote method to get package information and install
13049 * location values. Override install location based on default
13050 * policy if needed and then create install arguments based
13051 * on the install location.
13053 public void handleStartCopy() throws RemoteException {
13054 int ret = PackageManager.INSTALL_SUCCEEDED;
13056 // If we're already staged, we've firmly committed to an install location
13057 if (origin.staged) {
13058 if (origin.file != null) {
13059 installFlags |= PackageManager.INSTALL_INTERNAL;
13060 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13061 } else if (origin.cid != null) {
13062 installFlags |= PackageManager.INSTALL_EXTERNAL;
13063 installFlags &= ~PackageManager.INSTALL_INTERNAL;
13065 throw new IllegalStateException("Invalid stage location");
13069 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13070 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13071 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13072 PackageInfoLite pkgLite = null;
13074 if (onInt && onSd) {
13075 // Check if both bits are set.
13076 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13077 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13078 } else if (onSd && ephemeral) {
13079 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external");
13080 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13082 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13083 packageAbiOverride);
13085 if (DEBUG_EPHEMERAL && ephemeral) {
13086 Slog.v(TAG, "pkgLite for install: " + pkgLite);
13090 * If we have too little free space, try to free cache
13091 * before giving up.
13093 if (!origin.staged && pkgLite.recommendedInstallLocation
13094 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13095 // TODO: focus freeing disk space on the target device
13096 final StorageManager storage = StorageManager.from(mContext);
13097 final long lowThreshold = storage.getStorageLowBytes(
13098 Environment.getDataDirectory());
13100 final long sizeBytes = mContainerService.calculateInstalledSize(
13101 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13104 mInstaller.freeCache(null, sizeBytes + lowThreshold);
13105 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13106 installFlags, packageAbiOverride);
13107 } catch (InstallerException e) {
13108 Slog.w(TAG, "Failed to free cache", e);
13112 * The cache free must have deleted the file we
13113 * downloaded to install.
13115 * TODO: fix the "freeCache" call to not delete
13116 * the file we care about.
13118 if (pkgLite.recommendedInstallLocation
13119 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13120 pkgLite.recommendedInstallLocation
13121 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13126 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13127 int loc = pkgLite.recommendedInstallLocation;
13128 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13129 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13130 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13131 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13132 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13133 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13134 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13135 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13136 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13137 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13138 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13139 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13141 // Override with defaults if needed.
13142 loc = installLocationPolicy(pkgLite);
13143 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13144 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13145 } else if (!onSd && !onInt) {
13146 // Override install location with flags
13147 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13148 // Set the flag to install on external media.
13149 installFlags |= PackageManager.INSTALL_EXTERNAL;
13150 installFlags &= ~PackageManager.INSTALL_INTERNAL;
13151 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13152 if (DEBUG_EPHEMERAL) {
13153 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13155 installFlags |= PackageManager.INSTALL_EPHEMERAL;
13156 installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13157 |PackageManager.INSTALL_INTERNAL);
13159 // Make sure the flag for installing on external
13161 installFlags |= PackageManager.INSTALL_INTERNAL;
13162 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13168 final InstallArgs args = createInstallArgs(this);
13171 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13172 // TODO: http://b/22976637
13173 // Apps installed for "all" users use the device owner to verify the app
13174 UserHandle verifierUser = getUser();
13175 if (verifierUser == UserHandle.ALL) {
13176 verifierUser = UserHandle.SYSTEM;
13180 * Determine if we have any installed package verifiers. If we
13181 * do, then we'll defer to them to verify the packages.
13183 final int requiredUid = mRequiredVerifierPackage == null ? -1
13184 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13185 verifierUser.getIdentifier());
13186 if (!origin.existing && requiredUid != -1
13187 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13188 final Intent verification = new Intent(
13189 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13190 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13191 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13192 PACKAGE_MIME_TYPE);
13193 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13195 // Query all live verifiers based on current user state
13196 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13197 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13199 if (DEBUG_VERIFY) {
13200 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13201 + verification.toString() + " with " + pkgLite.verifiers.length
13202 + " optional verifiers");
13205 final int verificationId = mPendingVerificationToken++;
13207 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13209 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13210 installerPackageName);
13212 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13215 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13216 pkgLite.packageName);
13218 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13219 pkgLite.versionCode);
13221 if (verificationInfo != null) {
13222 if (verificationInfo.originatingUri != null) {
13223 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13224 verificationInfo.originatingUri);
13226 if (verificationInfo.referrer != null) {
13227 verification.putExtra(Intent.EXTRA_REFERRER,
13228 verificationInfo.referrer);
13230 if (verificationInfo.originatingUid >= 0) {
13231 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13232 verificationInfo.originatingUid);
13234 if (verificationInfo.installerUid >= 0) {
13235 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13236 verificationInfo.installerUid);
13240 final PackageVerificationState verificationState = new PackageVerificationState(
13241 requiredUid, args);
13243 mPendingVerification.append(verificationId, verificationState);
13245 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13246 receivers, verificationState);
13249 * If any sufficient verifiers were listed in the package
13250 * manifest, attempt to ask them.
13252 if (sufficientVerifiers != null) {
13253 final int N = sufficientVerifiers.size();
13255 Slog.i(TAG, "Additional verifiers required, but none installed.");
13256 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13258 for (int i = 0; i < N; i++) {
13259 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13261 final Intent sufficientIntent = new Intent(verification);
13262 sufficientIntent.setComponent(verifierComponent);
13263 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13268 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13269 mRequiredVerifierPackage, receivers);
13270 if (ret == PackageManager.INSTALL_SUCCEEDED
13271 && mRequiredVerifierPackage != null) {
13272 Trace.asyncTraceBegin(
13273 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13275 * Send the intent to the required verification agent,
13276 * but only start the verification timeout after the
13277 * target BroadcastReceivers have run.
13279 verification.setComponent(requiredVerifierComponent);
13280 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13281 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13282 new BroadcastReceiver() {
13284 public void onReceive(Context context, Intent intent) {
13285 final Message msg = mHandler
13286 .obtainMessage(CHECK_PENDING_VERIFICATION);
13287 msg.arg1 = verificationId;
13288 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13290 }, null, 0, null, null);
13293 * We don't want the copy to proceed until verification
13294 * succeeds, so null out this field.
13300 * No package verification is enabled, so immediately start
13301 * the remote call to initiate copy using temporary file.
13303 ret = args.copyApk(mContainerService, true);
13311 void handleReturnCode() {
13312 // If mArgs is null, then MCS couldn't be reached. When it
13313 // reconnects, it will try again to install. At that point, this
13315 if (mArgs != null) {
13316 processPendingInstall(mArgs, mRet);
13321 void handleServiceError() {
13322 mArgs = createInstallArgs(this);
13323 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13326 public boolean isForwardLocked() {
13327 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13332 * Used during creation of InstallArgs
13334 * @param installFlags package installation flags
13335 * @return true if should be installed on external storage
13337 private static boolean installOnExternalAsec(int installFlags) {
13338 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13341 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13348 * Used during creation of InstallArgs
13350 * @param installFlags package installation flags
13351 * @return true if should be installed as forward locked
13353 private static boolean installForwardLocked(int installFlags) {
13354 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13357 private InstallArgs createInstallArgs(InstallParams params) {
13358 if (params.move != null) {
13359 return new MoveInstallArgs(params);
13360 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13361 return new AsecInstallArgs(params);
13363 return new FileInstallArgs(params);
13368 * Create args that describe an existing installed package. Typically used
13369 * when cleaning up old installs, or used as a move source.
13371 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13372 String resourcePath, String[] instructionSets) {
13373 final boolean isInAsec;
13374 if (installOnExternalAsec(installFlags)) {
13375 /* Apps on SD card are always in ASEC containers. */
13377 } else if (installForwardLocked(installFlags)
13378 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13380 * Forward-locked apps are only in ASEC containers if they're the
13389 return new AsecInstallArgs(codePath, instructionSets,
13390 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13392 return new FileInstallArgs(codePath, resourcePath, instructionSets);
13396 static abstract class InstallArgs {
13397 /** @see InstallParams#origin */
13398 final OriginInfo origin;
13399 /** @see InstallParams#move */
13400 final MoveInfo move;
13402 final IPackageInstallObserver2 observer;
13403 // Always refers to PackageManager flags only
13404 final int installFlags;
13405 final String installerPackageName;
13406 final String volumeUuid;
13407 final UserHandle user;
13408 final String abiOverride;
13409 final String[] installGrantPermissions;
13410 /** If non-null, drop an async trace when the install completes */
13411 final String traceMethod;
13412 final int traceCookie;
13413 final Certificate[][] certificates;
13415 // The list of instruction sets supported by this app. This is currently
13416 // only used during the rmdex() phase to clean up resources. We can get rid of this
13417 // if we move dex files under the common app path.
13418 /* nullable */ String[] instructionSets;
13420 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13421 int installFlags, String installerPackageName, String volumeUuid,
13422 UserHandle user, String[] instructionSets,
13423 String abiOverride, String[] installGrantPermissions,
13424 String traceMethod, int traceCookie, Certificate[][] certificates) {
13425 this.origin = origin;
13427 this.installFlags = installFlags;
13428 this.observer = observer;
13429 this.installerPackageName = installerPackageName;
13430 this.volumeUuid = volumeUuid;
13432 this.instructionSets = instructionSets;
13433 this.abiOverride = abiOverride;
13434 this.installGrantPermissions = installGrantPermissions;
13435 this.traceMethod = traceMethod;
13436 this.traceCookie = traceCookie;
13437 this.certificates = certificates;
13440 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13441 abstract int doPreInstall(int status);
13444 * Rename package into final resting place. All paths on the given
13445 * scanned package should be updated to reflect the rename.
13447 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13448 abstract int doPostInstall(int status, int uid);
13450 /** @see PackageSettingBase#codePathString */
13451 abstract String getCodePath();
13452 /** @see PackageSettingBase#resourcePathString */
13453 abstract String getResourcePath();
13455 // Need installer lock especially for dex file removal.
13456 abstract void cleanUpResourcesLI();
13457 abstract boolean doPostDeleteLI(boolean delete);
13460 * Called before the source arguments are copied. This is used mostly
13461 * for MoveParams when it needs to read the source file to put it in the
13465 return PackageManager.INSTALL_SUCCEEDED;
13469 * Called after the source arguments are copied. This is used mostly for
13470 * MoveParams when it needs to read the source file to put it in the
13473 int doPostCopy(int uid) {
13474 return PackageManager.INSTALL_SUCCEEDED;
13477 protected boolean isFwdLocked() {
13478 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13481 protected boolean isExternalAsec() {
13482 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13485 protected boolean isEphemeral() {
13486 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13489 UserHandle getUser() {
13494 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13495 if (!allCodePaths.isEmpty()) {
13496 if (instructionSets == null) {
13497 throw new IllegalStateException("instructionSet == null");
13499 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13500 for (String codePath : allCodePaths) {
13501 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13503 mInstaller.rmdex(codePath, dexCodeInstructionSet);
13504 } catch (InstallerException ignored) {
13512 * Logic to handle installation of non-ASEC applications, including copying
13513 * and renaming logic.
13515 class FileInstallArgs extends InstallArgs {
13516 private File codeFile;
13517 private File resourceFile;
13519 // Example topology:
13520 // /data/app/com.example/base.apk
13521 // /data/app/com.example/split_foo.apk
13522 // /data/app/com.example/lib/arm/libfoo.so
13523 // /data/app/com.example/lib/arm64/libfoo.so
13524 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13527 FileInstallArgs(InstallParams params) {
13528 super(params.origin, params.move, params.observer, params.installFlags,
13529 params.installerPackageName, params.volumeUuid,
13530 params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13531 params.grantedRuntimePermissions,
13532 params.traceMethod, params.traceCookie, params.certificates);
13533 if (isFwdLocked()) {
13534 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13538 /** Existing install */
13539 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13540 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13541 null, null, null, 0, null /*certificates*/);
13542 this.codeFile = (codePath != null) ? new File(codePath) : null;
13543 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13546 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13549 return doCopyApk(imcs, temp);
13551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13555 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13556 if (origin.staged) {
13557 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13558 codeFile = origin.file;
13559 resourceFile = origin.file;
13560 return PackageManager.INSTALL_SUCCEEDED;
13564 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13565 final File tempDir =
13566 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13567 codeFile = tempDir;
13568 resourceFile = tempDir;
13569 } catch (IOException e) {
13570 Slog.w(TAG, "Failed to create copy file: " + e);
13571 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13574 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13576 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13577 if (!FileUtils.isValidExtFilename(name)) {
13578 throw new IllegalArgumentException("Invalid filename: " + name);
13581 final File file = new File(codeFile, name);
13582 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13583 O_RDWR | O_CREAT, 0644);
13584 Os.chmod(file.getAbsolutePath(), 0644);
13585 return new ParcelFileDescriptor(fd);
13586 } catch (ErrnoException e) {
13587 throw new RemoteException("Failed to open: " + e.getMessage());
13592 int ret = PackageManager.INSTALL_SUCCEEDED;
13593 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13594 if (ret != PackageManager.INSTALL_SUCCEEDED) {
13595 Slog.e(TAG, "Failed to copy package");
13599 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13600 NativeLibraryHelper.Handle handle = null;
13602 handle = NativeLibraryHelper.Handle.create(codeFile);
13603 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13605 } catch (IOException e) {
13606 Slog.e(TAG, "Copying native libraries failed", e);
13607 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13609 IoUtils.closeQuietly(handle);
13615 int doPreInstall(int status) {
13616 if (status != PackageManager.INSTALL_SUCCEEDED) {
13622 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13623 if (status != PackageManager.INSTALL_SUCCEEDED) {
13628 final File targetDir = codeFile.getParentFile();
13629 final File beforeCodeFile = codeFile;
13630 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13632 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13634 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13635 } catch (ErrnoException e) {
13636 Slog.w(TAG, "Failed to rename", e);
13640 if (!SELinux.restoreconRecursive(afterCodeFile)) {
13641 Slog.w(TAG, "Failed to restorecon");
13645 // Reflect the rename internally
13646 codeFile = afterCodeFile;
13647 resourceFile = afterCodeFile;
13649 // Reflect the rename in scanned details
13650 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13651 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13652 afterCodeFile, pkg.baseCodePath));
13653 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13654 afterCodeFile, pkg.splitCodePaths));
13656 // Reflect the rename in app info
13657 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13658 pkg.setApplicationInfoCodePath(pkg.codePath);
13659 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13660 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13661 pkg.setApplicationInfoResourcePath(pkg.codePath);
13662 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13663 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13668 int doPostInstall(int status, int uid) {
13669 if (status != PackageManager.INSTALL_SUCCEEDED) {
13676 String getCodePath() {
13677 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13681 String getResourcePath() {
13682 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13685 private boolean cleanUp() {
13686 if (codeFile == null || !codeFile.exists()) {
13690 removeCodePathLI(codeFile);
13692 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13693 resourceFile.delete();
13699 void cleanUpResourcesLI() {
13700 // Try enumerating all code paths before deleting
13701 List<String> allCodePaths = Collections.EMPTY_LIST;
13702 if (codeFile != null && codeFile.exists()) {
13704 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13705 allCodePaths = pkg.getAllCodePaths();
13706 } catch (PackageParserException e) {
13707 // Ignored; we tried our best
13712 removeDexFiles(allCodePaths, instructionSets);
13715 boolean doPostDeleteLI(boolean delete) {
13716 // XXX err, shouldn't we respect the delete flag?
13717 cleanUpResourcesLI();
13722 private boolean isAsecExternal(String cid) {
13723 final String asecPath = PackageHelper.getSdFilesystem(cid);
13724 return !asecPath.startsWith(mAsecInternalPath);
13727 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13728 PackageManagerException {
13730 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13731 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13732 throw new PackageManagerException(copyRet, message);
13738 * Extract the MountService "container ID" from the full code path of an
13741 static String cidFromCodePath(String fullCodePath) {
13742 int eidx = fullCodePath.lastIndexOf("/");
13743 String subStr1 = fullCodePath.substring(0, eidx);
13744 int sidx = subStr1.lastIndexOf("/");
13745 return subStr1.substring(sidx+1, eidx);
13749 * Logic to handle installation of ASEC applications, including copying and
13752 class AsecInstallArgs extends InstallArgs {
13753 static final String RES_FILE_NAME = "pkg.apk";
13754 static final String PUBLIC_RES_FILE_NAME = "res.zip";
13757 String packagePath;
13758 String resourcePath;
13761 AsecInstallArgs(InstallParams params) {
13762 super(params.origin, params.move, params.observer, params.installFlags,
13763 params.installerPackageName, params.volumeUuid,
13764 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13765 params.grantedRuntimePermissions,
13766 params.traceMethod, params.traceCookie, params.certificates);
13769 /** Existing install */
13770 AsecInstallArgs(String fullCodePath, String[] instructionSets,
13771 boolean isExternal, boolean isForwardLocked) {
13772 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13773 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13774 instructionSets, null, null, null, 0, null /*certificates*/);
13775 // Hackily pretend we're still looking at a full code path
13776 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13777 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13780 // Extract cid from fullCodePath
13781 int eidx = fullCodePath.lastIndexOf("/");
13782 String subStr1 = fullCodePath.substring(0, eidx);
13783 int sidx = subStr1.lastIndexOf("/");
13784 cid = subStr1.substring(sidx+1, eidx);
13785 setMountPath(subStr1);
13788 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13789 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13790 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13791 instructionSets, null, null, null, 0, null /*certificates*/);
13793 setMountPath(PackageHelper.getSdDir(cid));
13796 void createCopyFile() {
13797 cid = mInstallerService.allocateExternalStageCidLegacy();
13800 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13801 if (origin.staged && origin.cid != null) {
13802 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13804 setMountPath(PackageHelper.getSdDir(cid));
13805 return PackageManager.INSTALL_SUCCEEDED;
13812 * Pre-emptively destroy the container since it's destroyed if
13813 * copying fails due to it existing anyway.
13815 PackageHelper.destroySdDir(cid);
13818 final String newMountPath = imcs.copyPackageToContainer(
13819 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13820 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13822 if (newMountPath != null) {
13823 setMountPath(newMountPath);
13824 return PackageManager.INSTALL_SUCCEEDED;
13826 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13831 String getCodePath() {
13832 return packagePath;
13836 String getResourcePath() {
13837 return resourcePath;
13840 int doPreInstall(int status) {
13841 if (status != PackageManager.INSTALL_SUCCEEDED) {
13842 // Destroy container
13843 PackageHelper.destroySdDir(cid);
13845 boolean mounted = PackageHelper.isContainerMounted(cid);
13847 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13848 Process.SYSTEM_UID);
13849 if (newMountPath != null) {
13850 setMountPath(newMountPath);
13852 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13859 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13860 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13861 String newMountPath = null;
13862 if (PackageHelper.isContainerMounted(cid)) {
13863 // Unmount the container
13864 if (!PackageHelper.unMountSdDir(cid)) {
13865 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13869 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13870 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13871 " which might be stale. Will try to clean up.");
13872 // Clean up the stale container and proceed to recreate.
13873 if (!PackageHelper.destroySdDir(newCacheId)) {
13874 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13877 // Successfully cleaned up stale container. Try to rename again.
13878 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13879 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13880 + " inspite of cleaning it up.");
13884 if (!PackageHelper.isContainerMounted(newCacheId)) {
13885 Slog.w(TAG, "Mounting container " + newCacheId);
13886 newMountPath = PackageHelper.mountSdDir(newCacheId,
13887 getEncryptKey(), Process.SYSTEM_UID);
13889 newMountPath = PackageHelper.getSdDir(newCacheId);
13891 if (newMountPath == null) {
13892 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
13895 Log.i(TAG, "Succesfully renamed " + cid +
13896 " to " + newCacheId +
13897 " at new path: " + newMountPath);
13900 final File beforeCodeFile = new File(packagePath);
13901 setMountPath(newMountPath);
13902 final File afterCodeFile = new File(packagePath);
13904 // Reflect the rename in scanned details
13905 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13906 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13907 afterCodeFile, pkg.baseCodePath));
13908 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13909 afterCodeFile, pkg.splitCodePaths));
13911 // Reflect the rename in app info
13912 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13913 pkg.setApplicationInfoCodePath(pkg.codePath);
13914 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13915 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13916 pkg.setApplicationInfoResourcePath(pkg.codePath);
13917 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13918 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13923 private void setMountPath(String mountPath) {
13924 final File mountFile = new File(mountPath);
13926 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13927 if (monolithicFile.exists()) {
13928 packagePath = monolithicFile.getAbsolutePath();
13929 if (isFwdLocked()) {
13930 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13932 resourcePath = packagePath;
13935 packagePath = mountFile.getAbsolutePath();
13936 resourcePath = packagePath;
13940 int doPostInstall(int status, int uid) {
13941 if (status != PackageManager.INSTALL_SUCCEEDED) {
13944 final int groupOwner;
13945 final String protectedFile;
13946 if (isFwdLocked()) {
13947 groupOwner = UserHandle.getSharedAppGid(uid);
13948 protectedFile = RES_FILE_NAME;
13951 protectedFile = null;
13954 if (uid < Process.FIRST_APPLICATION_UID
13955 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13956 Slog.e(TAG, "Failed to finalize " + cid);
13957 PackageHelper.destroySdDir(cid);
13958 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13961 boolean mounted = PackageHelper.isContainerMounted(cid);
13963 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13969 private void cleanUp() {
13970 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13972 // Destroy secure container
13973 PackageHelper.destroySdDir(cid);
13976 private List<String> getAllCodePaths() {
13977 final File codeFile = new File(getCodePath());
13978 if (codeFile != null && codeFile.exists()) {
13980 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13981 return pkg.getAllCodePaths();
13982 } catch (PackageParserException e) {
13983 // Ignored; we tried our best
13986 return Collections.EMPTY_LIST;
13989 void cleanUpResourcesLI() {
13990 // Enumerate all code paths before deleting
13991 cleanUpResourcesLI(getAllCodePaths());
13994 private void cleanUpResourcesLI(List<String> allCodePaths) {
13996 removeDexFiles(allCodePaths, instructionSets);
13999 String getPackageName() {
14000 return getAsecPackageName(cid);
14003 boolean doPostDeleteLI(boolean delete) {
14004 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14005 final List<String> allCodePaths = getAllCodePaths();
14006 boolean mounted = PackageHelper.isContainerMounted(cid);
14009 if (PackageHelper.unMountSdDir(cid)) {
14013 if (!mounted && delete) {
14014 cleanUpResourcesLI(allCodePaths);
14021 if (isFwdLocked()) {
14022 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14023 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14024 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14028 return PackageManager.INSTALL_SUCCEEDED;
14032 int doPostCopy(int uid) {
14033 if (isFwdLocked()) {
14034 if (uid < Process.FIRST_APPLICATION_UID
14035 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14037 Slog.e(TAG, "Failed to finalize " + cid);
14038 PackageHelper.destroySdDir(cid);
14039 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14043 return PackageManager.INSTALL_SUCCEEDED;
14048 * Logic to handle movement of existing installed applications.
14050 class MoveInstallArgs extends InstallArgs {
14051 private File codeFile;
14052 private File resourceFile;
14055 MoveInstallArgs(InstallParams params) {
14056 super(params.origin, params.move, params.observer, params.installFlags,
14057 params.installerPackageName, params.volumeUuid,
14058 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14059 params.grantedRuntimePermissions,
14060 params.traceMethod, params.traceCookie, params.certificates);
14063 int copyApk(IMediaContainerService imcs, boolean temp) {
14064 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14065 + move.fromUuid + " to " + move.toUuid);
14066 synchronized (mInstaller) {
14068 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14069 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14070 } catch (InstallerException e) {
14071 Slog.w(TAG, "Failed to move app", e);
14072 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14076 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14077 resourceFile = codeFile;
14078 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14080 return PackageManager.INSTALL_SUCCEEDED;
14083 int doPreInstall(int status) {
14084 if (status != PackageManager.INSTALL_SUCCEEDED) {
14085 cleanUp(move.toUuid);
14090 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14091 if (status != PackageManager.INSTALL_SUCCEEDED) {
14092 cleanUp(move.toUuid);
14096 // Reflect the move in app info
14097 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14098 pkg.setApplicationInfoCodePath(pkg.codePath);
14099 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14100 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14101 pkg.setApplicationInfoResourcePath(pkg.codePath);
14102 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14103 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14108 int doPostInstall(int status, int uid) {
14109 if (status == PackageManager.INSTALL_SUCCEEDED) {
14110 cleanUp(move.fromUuid);
14112 cleanUp(move.toUuid);
14118 String getCodePath() {
14119 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14123 String getResourcePath() {
14124 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14127 private boolean cleanUp(String volumeUuid) {
14128 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14130 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14131 final int[] userIds = sUserManager.getUserIds();
14132 synchronized (mInstallLock) {
14133 // Clean up both app data and code
14134 // All package moves are frozen until finished
14135 for (int userId : userIds) {
14137 mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14138 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14139 } catch (InstallerException e) {
14140 Slog.w(TAG, String.valueOf(e));
14143 removeCodePathLI(codeFile);
14148 void cleanUpResourcesLI() {
14149 throw new UnsupportedOperationException();
14152 boolean doPostDeleteLI(boolean delete) {
14153 throw new UnsupportedOperationException();
14157 static String getAsecPackageName(String packageCid) {
14158 int idx = packageCid.lastIndexOf("-");
14162 return packageCid.substring(0, idx);
14165 // Utility method used to create code paths based on package name and available index.
14166 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14167 String idxStr = "";
14169 // Fall back to default value of idx=1 if prefix is not
14170 // part of oldCodePath
14171 if (oldCodePath != null) {
14172 String subStr = oldCodePath;
14173 // Drop the suffix right away
14174 if (suffix != null && subStr.endsWith(suffix)) {
14175 subStr = subStr.substring(0, subStr.length() - suffix.length());
14177 // If oldCodePath already contains prefix find out the
14178 // ending index to either increment or decrement.
14179 int sidx = subStr.lastIndexOf(prefix);
14181 subStr = subStr.substring(sidx + prefix.length());
14182 if (subStr != null) {
14183 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14184 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14187 idx = Integer.parseInt(subStr);
14193 } catch(NumberFormatException e) {
14198 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14199 return prefix + idxStr;
14202 private File getNextCodePath(File targetDir, String packageName) {
14206 result = new File(targetDir, packageName + "-" + suffix);
14208 } while (result.exists());
14212 // Utility method that returns the relative package path with respect
14213 // to the installation directory. Like say for /data/data/com.test-1.apk
14214 // string com.test-1 is returned.
14215 static String deriveCodePathName(String codePath) {
14216 if (codePath == null) {
14219 final File codeFile = new File(codePath);
14220 final String name = codeFile.getName();
14221 if (codeFile.isDirectory()) {
14223 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14224 final int lastDot = name.lastIndexOf('.');
14225 return name.substring(0, lastDot);
14227 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14232 static class PackageInstalledInfo {
14235 // The set of users that originally had this package installed.
14237 // The set of users that now have this package installed.
14239 PackageParser.Package pkg;
14242 PackageRemovedInfo removedInfo;
14243 ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14245 public void setError(int code, String msg) {
14246 setReturnCode(code);
14247 setReturnMessage(msg);
14251 public void setError(String msg, PackageParserException e) {
14252 setReturnCode(e.error);
14253 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14254 Slog.w(TAG, msg, e);
14257 public void setError(String msg, PackageManagerException e) {
14258 returnCode = e.error;
14259 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14260 Slog.w(TAG, msg, e);
14263 public void setReturnCode(int returnCode) {
14264 this.returnCode = returnCode;
14265 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14266 for (int i = 0; i < childCount; i++) {
14267 addedChildPackages.valueAt(i).returnCode = returnCode;
14271 private void setReturnMessage(String returnMsg) {
14272 this.returnMsg = returnMsg;
14273 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14274 for (int i = 0; i < childCount; i++) {
14275 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14279 // In some error cases we want to convey more info back to the observer
14280 String origPackage;
14281 String origPermission;
14285 * Install a non-existing package.
14287 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14288 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14289 PackageInstalledInfo res) {
14290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14292 // Remember this for later, in case we need to rollback this install
14293 String pkgName = pkg.packageName;
14295 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14297 synchronized(mPackages) {
14298 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14299 // A package with the same name is already installed, though
14300 // it has been renamed to an older name. The package we
14301 // are trying to install should be installed as an update to
14302 // the existing one, but that has not been requested, so bail.
14303 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14304 + " without first uninstalling package running as "
14305 + mSettings.mRenamedPackages.get(pkgName));
14308 if (mPackages.containsKey(pkgName)) {
14309 // Don't allow installation over an existing package with the same name.
14310 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14311 + " without first uninstalling.");
14317 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14318 System.currentTimeMillis(), user);
14320 updateSettingsLI(newPackage, installerPackageName, null, res, user);
14322 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14323 prepareAppDataAfterInstallLIF(newPackage);
14326 // Remove package from internal structures, but keep around any
14327 // data that might have already existed
14328 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14329 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14331 } catch (PackageManagerException e) {
14332 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14335 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14338 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14339 // Can't rotate keys during boot or if sharedUser.
14340 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14341 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14344 // app is using upgradeKeySets; make sure all are valid
14345 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14346 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14347 for (int i = 0; i < upgradeKeySets.length; i++) {
14348 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14349 Slog.wtf(TAG, "Package "
14350 + (oldPs.name != null ? oldPs.name : "<null>")
14351 + " contains upgrade-key-set reference to unknown key-set: "
14352 + upgradeKeySets[i]
14353 + " reverting to signatures check.");
14360 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14361 // Upgrade keysets are being used. Determine if new package has a superset of the
14363 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14364 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14365 for (int i = 0; i < upgradeKeySets.length; i++) {
14366 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14367 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14374 private static void updateDigest(MessageDigest digest, File file) throws IOException {
14375 try (DigestInputStream digestStream =
14376 new DigestInputStream(new FileInputStream(file), digest)) {
14377 while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14381 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14382 UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14383 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14385 final PackageParser.Package oldPackage;
14386 final String pkgName = pkg.packageName;
14387 final int[] allUsers;
14388 final int[] installedUsers;
14390 synchronized(mPackages) {
14391 oldPackage = mPackages.get(pkgName);
14392 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14394 // don't allow upgrade to target a release SDK from a pre-release SDK
14395 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14396 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14397 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14398 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14399 if (oldTargetsPreRelease
14400 && !newTargetsPreRelease
14401 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14402 Slog.w(TAG, "Can't install package targeting released sdk");
14403 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14407 // don't allow an upgrade from full to ephemeral
14408 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14409 if (isEphemeral && !oldIsEphemeral) {
14410 // can't downgrade from full to ephemeral
14411 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14412 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14416 // verify signatures are valid
14417 final PackageSetting ps = mSettings.mPackages.get(pkgName);
14418 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14419 if (!checkUpgradeKeySetLP(ps, pkg)) {
14420 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14421 "New package not signed by keys specified by upgrade-keysets: "
14426 // default to original signature matching
14427 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14428 != PackageManager.SIGNATURE_MATCH) {
14429 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14430 "New package has a different signature: " + pkgName);
14435 // don't allow a system upgrade unless the upgrade hash matches
14436 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14437 byte[] digestBytes = null;
14439 final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14440 updateDigest(digest, new File(pkg.baseCodePath));
14441 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14442 for (String path : pkg.splitCodePaths) {
14443 updateDigest(digest, new File(path));
14446 digestBytes = digest.digest();
14447 } catch (NoSuchAlgorithmException | IOException e) {
14448 res.setError(INSTALL_FAILED_INVALID_APK,
14449 "Could not compute hash: " + pkgName);
14452 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14453 res.setError(INSTALL_FAILED_INVALID_APK,
14454 "New package fails restrict-update check: " + pkgName);
14457 // retain upgrade restriction
14458 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14461 // Check for shared user id changes
14462 String invalidPackageName =
14463 getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14464 if (invalidPackageName != null) {
14465 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14466 "Package " + invalidPackageName + " tried to change user "
14467 + oldPackage.mSharedUserId);
14471 // In case of rollback, remember per-user/profile install state
14472 allUsers = sUserManager.getUserIds();
14473 installedUsers = ps.queryInstalledUsers(allUsers, true);
14476 // Update what is removed
14477 res.removedInfo = new PackageRemovedInfo();
14478 res.removedInfo.uid = oldPackage.applicationInfo.uid;
14479 res.removedInfo.removedPackage = oldPackage.packageName;
14480 res.removedInfo.isUpdate = true;
14481 res.removedInfo.origUsers = installedUsers;
14482 final int childCount = (oldPackage.childPackages != null)
14483 ? oldPackage.childPackages.size() : 0;
14484 for (int i = 0; i < childCount; i++) {
14485 boolean childPackageUpdated = false;
14486 PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14487 if (res.addedChildPackages != null) {
14488 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14489 if (childRes != null) {
14490 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14491 childRes.removedInfo.removedPackage = childPkg.packageName;
14492 childRes.removedInfo.isUpdate = true;
14493 childPackageUpdated = true;
14496 if (!childPackageUpdated) {
14497 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14498 childRemovedRes.removedPackage = childPkg.packageName;
14499 childRemovedRes.isUpdate = false;
14500 childRemovedRes.dataRemoved = true;
14501 synchronized (mPackages) {
14502 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14503 if (childPs != null) {
14504 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14507 if (res.removedInfo.removedChildPackages == null) {
14508 res.removedInfo.removedChildPackages = new ArrayMap<>();
14510 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14514 boolean sysPkg = (isSystemApp(oldPackage));
14516 // Set the system/privileged flags as needed
14517 final boolean privileged =
14518 (oldPackage.applicationInfo.privateFlags
14519 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14520 final int systemPolicyFlags = policyFlags
14521 | PackageParser.PARSE_IS_SYSTEM
14522 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14524 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14525 user, allUsers, installerPackageName, res);
14527 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14528 user, allUsers, installerPackageName, res);
14532 public List<String> getPreviousCodePaths(String packageName) {
14533 final PackageSetting ps = mSettings.mPackages.get(packageName);
14534 final List<String> result = new ArrayList<String>();
14535 if (ps != null && ps.oldCodePaths != null) {
14536 result.addAll(ps.oldCodePaths);
14541 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14542 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14543 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14544 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14547 String pkgName = deletedPackage.packageName;
14548 boolean deletedPkg = true;
14549 boolean addedPkg = false;
14550 boolean updatedSettings = false;
14551 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14552 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14553 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14555 final long origUpdateTime = (pkg.mExtras != null)
14556 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14558 // First delete the existing package while retaining the data directory
14559 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14560 res.removedInfo, true, pkg)) {
14561 // If the existing package wasn't successfully deleted
14562 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14563 deletedPkg = false;
14565 // Successfully deleted the old package; proceed with replace.
14567 // If deleted package lived in a container, give users a chance to
14568 // relinquish resources before killing.
14569 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14570 if (DEBUG_INSTALL) {
14571 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14573 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14574 final ArrayList<String> pkgList = new ArrayList<String>(1);
14575 pkgList.add(deletedPackage.applicationInfo.packageName);
14576 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14579 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14580 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14581 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14584 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14585 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14586 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14588 // Update the in-memory copy of the previous code paths.
14589 PackageSetting ps = mSettings.mPackages.get(pkgName);
14591 if (ps.oldCodePaths == null) {
14592 ps.oldCodePaths = new ArraySet<>();
14594 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14595 if (deletedPackage.splitCodePaths != null) {
14596 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14599 ps.oldCodePaths = null;
14601 if (ps.childPackageNames != null) {
14602 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14603 final String childPkgName = ps.childPackageNames.get(i);
14604 final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14605 childPs.oldCodePaths = ps.oldCodePaths;
14608 prepareAppDataAfterInstallLIF(newPackage);
14610 } catch (PackageManagerException e) {
14611 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14615 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14616 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14618 // Revert all internal state mutations and added folders for the failed install
14620 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14621 res.removedInfo, true, null);
14624 // Restore the old package
14626 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14627 File restoreFile = new File(deletedPackage.codePath);
14628 // Parse old package
14629 boolean oldExternal = isExternal(deletedPackage);
14630 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
14631 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14632 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14633 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14635 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14637 } catch (PackageManagerException e) {
14638 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14643 synchronized (mPackages) {
14644 // Ensure the installer package name up to date
14645 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14647 // Update permissions for restored package
14648 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14650 mSettings.writeLPr();
14653 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14656 synchronized (mPackages) {
14657 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14659 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14660 if (res.removedInfo.removedChildPackages != null) {
14661 final int childCount = res.removedInfo.removedChildPackages.size();
14662 // Iterate in reverse as we may modify the collection
14663 for (int i = childCount - 1; i >= 0; i--) {
14664 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14665 if (res.addedChildPackages.containsKey(childPackageName)) {
14666 res.removedInfo.removedChildPackages.removeAt(i);
14668 PackageRemovedInfo childInfo = res.removedInfo
14669 .removedChildPackages.valueAt(i);
14670 childInfo.removedForAllUsers = mPackages.get(
14671 childInfo.removedPackage) == null;
14680 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14681 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14682 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14683 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14684 + ", old=" + deletedPackage);
14686 final boolean disabledSystem;
14688 // Remove existing system package
14689 removePackageLI(deletedPackage, true);
14691 synchronized (mPackages) {
14692 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14694 if (!disabledSystem) {
14695 // We didn't need to disable the .apk as a current system package,
14696 // which means we are replacing another update that is already
14697 // installed. We need to make sure to delete the older one's .apk.
14698 res.removedInfo.args = createInstallArgsForExisting(0,
14699 deletedPackage.applicationInfo.getCodePath(),
14700 deletedPackage.applicationInfo.getResourcePath(),
14701 getAppDexInstructionSets(deletedPackage.applicationInfo));
14703 res.removedInfo.args = null;
14706 // Successfully disabled the old package. Now proceed with re-installation
14707 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14708 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14709 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14711 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14712 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14713 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14715 PackageParser.Package newPackage = null;
14717 // Add the package to the internal data structures
14718 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14720 // Set the update and install times
14721 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14722 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14723 System.currentTimeMillis());
14725 // Update the package dynamic state if succeeded
14726 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14727 // Now that the install succeeded make sure we remove data
14728 // directories for any child package the update removed.
14729 final int deletedChildCount = (deletedPackage.childPackages != null)
14730 ? deletedPackage.childPackages.size() : 0;
14731 final int newChildCount = (newPackage.childPackages != null)
14732 ? newPackage.childPackages.size() : 0;
14733 for (int i = 0; i < deletedChildCount; i++) {
14734 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14735 boolean childPackageDeleted = true;
14736 for (int j = 0; j < newChildCount; j++) {
14737 PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14738 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14739 childPackageDeleted = false;
14743 if (childPackageDeleted) {
14744 PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14745 deletedChildPkg.packageName);
14746 if (ps != null && res.removedInfo.removedChildPackages != null) {
14747 PackageRemovedInfo removedChildRes = res.removedInfo
14748 .removedChildPackages.get(deletedChildPkg.packageName);
14749 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14750 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14755 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14756 prepareAppDataAfterInstallLIF(newPackage);
14758 } catch (PackageManagerException e) {
14759 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14760 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14763 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14764 // Re installation failed. Restore old information
14765 // Remove new pkg information
14766 if (newPackage != null) {
14767 removeInstalledPackageLI(newPackage, true);
14769 // Add back the old system package
14771 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14772 } catch (PackageManagerException e) {
14773 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14776 synchronized (mPackages) {
14777 if (disabledSystem) {
14778 enableSystemPackageLPw(deletedPackage);
14781 // Ensure the installer package name up to date
14782 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14784 // Update permissions for restored package
14785 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14787 mSettings.writeLPr();
14790 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14791 + " after failed upgrade");
14796 * Checks whether the parent or any of the child packages have a change shared
14797 * user. For a package to be a valid update the shred users of the parent and
14798 * the children should match. We may later support changing child shared users.
14799 * @param oldPkg The updated package.
14800 * @param newPkg The update package.
14801 * @return The shared user that change between the versions.
14803 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14804 PackageParser.Package newPkg) {
14805 // Check parent shared user
14806 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14807 return newPkg.packageName;
14809 // Check child shared users
14810 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14811 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14812 for (int i = 0; i < newChildCount; i++) {
14813 PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14814 // If this child was present, did it have the same shared user?
14815 for (int j = 0; j < oldChildCount; j++) {
14816 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14817 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14818 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14819 return newChildPkg.packageName;
14826 private void removeNativeBinariesLI(PackageSetting ps) {
14827 // Remove the lib path for the parent package
14829 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14830 // Remove the lib path for the child packages
14831 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14832 for (int i = 0; i < childCount; i++) {
14833 PackageSetting childPs = null;
14834 synchronized (mPackages) {
14835 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14837 if (childPs != null) {
14838 NativeLibraryHelper.removeNativeBinariesLI(childPs
14839 .legacyNativeLibraryPathString);
14845 private void enableSystemPackageLPw(PackageParser.Package pkg) {
14846 // Enable the parent package
14847 mSettings.enableSystemPackageLPw(pkg.packageName);
14848 // Enable the child packages
14849 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14850 for (int i = 0; i < childCount; i++) {
14851 PackageParser.Package childPkg = pkg.childPackages.get(i);
14852 mSettings.enableSystemPackageLPw(childPkg.packageName);
14856 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14857 PackageParser.Package newPkg) {
14858 // Disable the parent package (parent always replaced)
14859 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14860 // Disable the child packages
14861 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14862 for (int i = 0; i < childCount; i++) {
14863 PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14864 final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14865 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14870 private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14871 String installerPackageName) {
14872 // Enable the parent package
14873 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14874 // Enable the child packages
14875 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14876 for (int i = 0; i < childCount; i++) {
14877 PackageParser.Package childPkg = pkg.childPackages.get(i);
14878 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14882 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14883 // Collect all used permissions in the UID
14884 ArraySet<String> usedPermissions = new ArraySet<>();
14885 final int packageCount = su.packages.size();
14886 for (int i = 0; i < packageCount; i++) {
14887 PackageSetting ps = su.packages.valueAt(i);
14888 if (ps.pkg == null) {
14891 final int requestedPermCount = ps.pkg.requestedPermissions.size();
14892 for (int j = 0; j < requestedPermCount; j++) {
14893 String permission = ps.pkg.requestedPermissions.get(j);
14894 BasePermission bp = mSettings.mPermissions.get(permission);
14896 usedPermissions.add(permission);
14901 PermissionsState permissionsState = su.getPermissionsState();
14902 // Prune install permissions
14903 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14904 final int installPermCount = installPermStates.size();
14905 for (int i = installPermCount - 1; i >= 0; i--) {
14906 PermissionState permissionState = installPermStates.get(i);
14907 if (!usedPermissions.contains(permissionState.getName())) {
14908 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14910 permissionsState.revokeInstallPermission(bp);
14911 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14912 PackageManager.MASK_PERMISSION_FLAGS, 0);
14917 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14919 // Prune runtime permissions
14920 for (int userId : allUserIds) {
14921 List<PermissionState> runtimePermStates = permissionsState
14922 .getRuntimePermissionStates(userId);
14923 final int runtimePermCount = runtimePermStates.size();
14924 for (int i = runtimePermCount - 1; i >= 0; i--) {
14925 PermissionState permissionState = runtimePermStates.get(i);
14926 if (!usedPermissions.contains(permissionState.getName())) {
14927 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14929 permissionsState.revokeRuntimePermission(bp, userId);
14930 permissionsState.updatePermissionFlags(bp, userId,
14931 PackageManager.MASK_PERMISSION_FLAGS, 0);
14932 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14933 runtimePermissionChangedUserIds, userId);
14939 return runtimePermissionChangedUserIds;
14942 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14943 int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14944 // Update the parent package setting
14945 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14947 // Update the child packages setting
14948 final int childCount = (newPackage.childPackages != null)
14949 ? newPackage.childPackages.size() : 0;
14950 for (int i = 0; i < childCount; i++) {
14951 PackageParser.Package childPackage = newPackage.childPackages.get(i);
14952 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14953 updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14954 childRes.origUsers, childRes, user);
14958 private void updateSettingsInternalLI(PackageParser.Package newPackage,
14959 String installerPackageName, int[] allUsers, int[] installedForUsers,
14960 PackageInstalledInfo res, UserHandle user) {
14961 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14963 String pkgName = newPackage.packageName;
14964 synchronized (mPackages) {
14965 //write settings. the installStatus will be incomplete at this stage.
14966 //note that the new package setting would have already been
14967 //added to mPackages. It hasn't been persisted yet.
14968 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14969 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14970 mSettings.writeLPr();
14971 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14974 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14975 synchronized (mPackages) {
14976 updatePermissionsLPw(newPackage.packageName, newPackage,
14977 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14978 ? UPDATE_PERMISSIONS_ALL : 0));
14979 // For system-bundled packages, we assume that installing an upgraded version
14980 // of the package implies that the user actually wants to run that new code,
14981 // so we enable the package.
14982 PackageSetting ps = mSettings.mPackages.get(pkgName);
14983 final int userId = user.getIdentifier();
14985 if (isSystemApp(newPackage)) {
14986 if (DEBUG_INSTALL) {
14987 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14989 // Enable system package for requested users
14990 if (res.origUsers != null) {
14991 for (int origUserId : res.origUsers) {
14992 if (userId == UserHandle.USER_ALL || userId == origUserId) {
14993 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14994 origUserId, installerPackageName);
14998 // Also convey the prior install/uninstall state
14999 if (allUsers != null && installedForUsers != null) {
15000 for (int currentUserId : allUsers) {
15001 final boolean installed = ArrayUtils.contains(
15002 installedForUsers, currentUserId);
15003 if (DEBUG_INSTALL) {
15004 Slog.d(TAG, " user " + currentUserId + " => " + installed);
15006 ps.setInstalled(installed, currentUserId);
15008 // these install state changes will be persisted in the
15009 // upcoming call to mSettings.writeLPr().
15012 // It's implied that when a user requests installation, they want the app to be
15013 // installed and enabled.
15014 if (userId != UserHandle.USER_ALL) {
15015 ps.setInstalled(true, userId);
15016 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15019 res.name = pkgName;
15020 res.uid = newPackage.applicationInfo.uid;
15021 res.pkg = newPackage;
15022 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15023 mSettings.setInstallerPackageName(pkgName, installerPackageName);
15024 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15025 //to update install status
15026 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15027 mSettings.writeLPr();
15028 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15031 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15034 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15036 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15037 installPackageLI(args, res);
15039 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15043 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15044 final int installFlags = args.installFlags;
15045 final String installerPackageName = args.installerPackageName;
15046 final String volumeUuid = args.volumeUuid;
15047 final File tmpPackageFile = new File(args.getCodePath());
15048 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15049 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15050 || (args.volumeUuid != null));
15051 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15052 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15053 boolean replace = false;
15054 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15055 if (args.move != null) {
15056 // moving a complete application; perform an initial scan on the new install location
15057 scanFlags |= SCAN_INITIAL;
15059 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15060 scanFlags |= SCAN_DONT_KILL_APP;
15063 // Result object to be returned
15064 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15066 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15069 if (ephemeral && (forwardLocked || onExternal)) {
15070 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15071 + " external=" + onExternal);
15072 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15076 // Retrieve PackageSettings and parse package
15077 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15078 | PackageParser.PARSE_ENFORCE_CODE
15079 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15080 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15081 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15082 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15083 PackageParser pp = new PackageParser();
15084 pp.setSeparateProcesses(mSeparateProcesses);
15085 pp.setDisplayMetrics(mMetrics);
15087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15088 final PackageParser.Package pkg;
15090 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15091 } catch (PackageParserException e) {
15092 res.setError("Failed parse during installPackageLI", e);
15095 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15098 // If we are installing a clustered package add results for the children
15099 if (pkg.childPackages != null) {
15100 synchronized (mPackages) {
15101 final int childCount = pkg.childPackages.size();
15102 for (int i = 0; i < childCount; i++) {
15103 PackageParser.Package childPkg = pkg.childPackages.get(i);
15104 PackageInstalledInfo childRes = new PackageInstalledInfo();
15105 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15106 childRes.pkg = childPkg;
15107 childRes.name = childPkg.packageName;
15108 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15109 if (childPs != null) {
15110 childRes.origUsers = childPs.queryInstalledUsers(
15111 sUserManager.getUserIds(), true);
15113 if ((mPackages.containsKey(childPkg.packageName))) {
15114 childRes.removedInfo = new PackageRemovedInfo();
15115 childRes.removedInfo.removedPackage = childPkg.packageName;
15117 if (res.addedChildPackages == null) {
15118 res.addedChildPackages = new ArrayMap<>();
15120 res.addedChildPackages.put(childPkg.packageName, childRes);
15125 // If package doesn't declare API override, mark that we have an install
15126 // time CPU ABI override.
15127 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15128 pkg.cpuAbiOverride = args.abiOverride;
15131 String pkgName = res.name = pkg.packageName;
15132 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15133 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15134 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15140 // either use what we've been given or parse directly from the APK
15141 if (args.certificates != null) {
15143 PackageParser.populateCertificates(pkg, args.certificates);
15144 } catch (PackageParserException e) {
15145 // there was something wrong with the certificates we were given;
15146 // try to pull them from the APK
15147 PackageParser.collectCertificates(pkg, parseFlags);
15150 PackageParser.collectCertificates(pkg, parseFlags);
15152 } catch (PackageParserException e) {
15153 res.setError("Failed collect during installPackageLI", e);
15157 // Get rid of all references to package scan path via parser.
15159 String oldCodePath = null;
15160 boolean systemApp = false;
15161 synchronized (mPackages) {
15162 // Check if installing already existing package
15163 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15164 String oldName = mSettings.mRenamedPackages.get(pkgName);
15165 if (pkg.mOriginalPackages != null
15166 && pkg.mOriginalPackages.contains(oldName)
15167 && mPackages.containsKey(oldName)) {
15168 // This package is derived from an original package,
15169 // and this device has been updating from that original
15170 // name. We must continue using the original name, so
15171 // rename the new package here.
15172 pkg.setPackageName(oldName);
15173 pkgName = pkg.packageName;
15175 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15176 + oldName + " pkgName=" + pkgName);
15177 } else if (mPackages.containsKey(pkgName)) {
15178 // This package, under its official name, already exists
15179 // on the device; we should replace it.
15181 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15184 // Child packages are installed through the parent package
15185 if (pkg.parentPackage != null) {
15186 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15187 "Package " + pkg.packageName + " is child of package "
15188 + pkg.parentPackage.parentPackage + ". Child packages "
15189 + "can be updated only through the parent package.");
15194 // Prevent apps opting out from runtime permissions
15195 PackageParser.Package oldPackage = mPackages.get(pkgName);
15196 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15197 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15198 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15199 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15200 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15201 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15202 + " doesn't support runtime permissions but the old"
15203 + " target SDK " + oldTargetSdk + " does.");
15207 // Prevent installing of child packages
15208 if (oldPackage.parentPackage != null) {
15209 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15210 "Package " + pkg.packageName + " is child of package "
15211 + oldPackage.parentPackage + ". Child packages "
15212 + "can be updated only through the parent package.");
15218 PackageSetting ps = mSettings.mPackages.get(pkgName);
15220 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15222 // Quick sanity check that we're signed correctly if updating;
15223 // we'll check this again later when scanning, but we want to
15224 // bail early here before tripping over redefined permissions.
15225 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15226 if (!checkUpgradeKeySetLP(ps, pkg)) {
15227 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15228 + pkg.packageName + " upgrade keys do not match the "
15229 + "previously installed version");
15234 verifySignaturesLP(ps, pkg);
15235 } catch (PackageManagerException e) {
15236 res.setError(e.error, e.getMessage());
15241 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15242 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15243 systemApp = (ps.pkg.applicationInfo.flags &
15244 ApplicationInfo.FLAG_SYSTEM) != 0;
15246 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15249 // Check whether the newly-scanned package wants to define an already-defined perm
15250 int N = pkg.permissions.size();
15251 for (int i = N-1; i >= 0; i--) {
15252 PackageParser.Permission perm = pkg.permissions.get(i);
15253 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15255 // If the defining package is signed with our cert, it's okay. This
15256 // also includes the "updating the same package" case, of course.
15257 // "updating same package" could also involve key-rotation.
15258 final boolean sigsOk;
15259 if (bp.sourcePackage.equals(pkg.packageName)
15260 && (bp.packageSetting instanceof PackageSetting)
15261 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15263 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15265 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15266 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15269 // If the owning package is the system itself, we log but allow
15270 // install to proceed; we fail the install on all other permission
15272 if (!bp.sourcePackage.equals("android")) {
15273 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15274 + pkg.packageName + " attempting to redeclare permission "
15275 + perm.info.name + " already owned by " + bp.sourcePackage);
15276 res.origPermission = perm.info.name;
15277 res.origPackage = bp.sourcePackage;
15280 Slog.w(TAG, "Package " + pkg.packageName
15281 + " attempting to redeclare system permission "
15282 + perm.info.name + "; ignoring new declaration");
15283 pkg.permissions.remove(i);
15285 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15286 // Prevent apps to change protection level to dangerous from any other
15287 // type as this would allow a privilege escalation where an app adds a
15288 // normal/signature permission in other app's group and later redefines
15289 // it as dangerous leading to the group auto-grant.
15290 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15291 == PermissionInfo.PROTECTION_DANGEROUS) {
15292 if (bp != null && !bp.isRuntime()) {
15293 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15294 + "non-runtime permission " + perm.info.name
15295 + " to runtime; keeping old protection level");
15296 perm.info.protectionLevel = bp.protectionLevel;
15306 // Abort update; system app can't be replaced with app on sdcard
15307 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15308 "Cannot install updates to system apps on sdcard");
15310 } else if (ephemeral) {
15311 // Abort update; system app can't be replaced with an ephemeral app
15312 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15313 "Cannot update a system app with an ephemeral app");
15318 if (args.move != null) {
15319 // We did an in-place move, so dex is ready to roll
15320 scanFlags |= SCAN_NO_DEX;
15321 scanFlags |= SCAN_MOVE;
15323 synchronized (mPackages) {
15324 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15326 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15327 "Missing settings for moved package " + pkgName);
15330 // We moved the entire application as-is, so bring over the
15331 // previously derived ABI information.
15332 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15333 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15336 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15337 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15338 scanFlags |= SCAN_NO_DEX;
15341 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15342 args.abiOverride : pkg.cpuAbiOverride);
15343 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15344 true /* extract libs */);
15345 } catch (PackageManagerException pme) {
15346 Slog.e(TAG, "Error deriving application ABI", pme);
15347 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15351 // Shared libraries for the package need to be updated.
15352 synchronized (mPackages) {
15354 updateSharedLibrariesLPw(pkg, null);
15355 } catch (PackageManagerException e) {
15356 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15360 // Do not run PackageDexOptimizer through the local performDexOpt
15361 // method because `pkg` may not be in `mPackages` yet.
15363 // Also, don't fail application installs if the dexopt step fails.
15364 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15365 null /* instructionSets */, false /* checkProfiles */,
15366 getCompilerFilterForReason(REASON_INSTALL),
15367 getOrCreateCompilerPackageStats(pkg));
15368 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15370 // Notify BackgroundDexOptService that the package has been changed.
15371 // If this is an update of a package which used to fail to compile,
15372 // BDOS will remove it from its blacklist.
15373 BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15376 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15377 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15381 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15383 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15384 "installPackageLI")) {
15386 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15387 installerPackageName, res);
15389 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15390 args.user, installerPackageName, volumeUuid, res);
15393 synchronized (mPackages) {
15394 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15396 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15399 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15400 for (int i = 0; i < childCount; i++) {
15401 PackageParser.Package childPkg = pkg.childPackages.get(i);
15402 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15403 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15404 if (childPs != null) {
15405 childRes.newUsers = childPs.queryInstalledUsers(
15406 sUserManager.getUserIds(), true);
15412 private void startIntentFilterVerifications(int userId, boolean replacing,
15413 PackageParser.Package pkg) {
15414 if (mIntentFilterVerifierComponent == null) {
15415 Slog.w(TAG, "No IntentFilter verification will not be done as "
15416 + "there is no IntentFilterVerifier available!");
15420 final int verifierUid = getPackageUid(
15421 mIntentFilterVerifierComponent.getPackageName(),
15422 MATCH_DEBUG_TRIAGED_MISSING,
15423 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15425 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15426 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15427 mHandler.sendMessage(msg);
15429 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15430 for (int i = 0; i < childCount; i++) {
15431 PackageParser.Package childPkg = pkg.childPackages.get(i);
15432 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15433 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15434 mHandler.sendMessage(msg);
15438 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15439 PackageParser.Package pkg) {
15440 int size = pkg.activities.size();
15442 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15443 "No activity, so no need to verify any IntentFilter!");
15447 final boolean hasDomainURLs = hasDomainURLs(pkg);
15448 if (!hasDomainURLs) {
15449 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15450 "No domain URLs, so no need to verify any IntentFilter!");
15454 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15455 + " if any IntentFilter from the " + size
15456 + " Activities needs verification ...");
15459 final String packageName = pkg.packageName;
15461 synchronized (mPackages) {
15462 // If this is a new install and we see that we've already run verification for this
15463 // package, we have nothing to do: it means the state was restored from backup.
15465 IntentFilterVerificationInfo ivi =
15466 mSettings.getIntentFilterVerificationLPr(packageName);
15468 if (DEBUG_DOMAIN_VERIFICATION) {
15469 Slog.i(TAG, "Package " + packageName+ " already verified: status="
15470 + ivi.getStatusString());
15476 // If any filters need to be verified, then all need to be.
15477 boolean needToVerify = false;
15478 for (PackageParser.Activity a : pkg.activities) {
15479 for (ActivityIntentInfo filter : a.intents) {
15480 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15481 if (DEBUG_DOMAIN_VERIFICATION) {
15482 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15484 needToVerify = true;
15490 if (needToVerify) {
15491 final int verificationId = mIntentFilterVerificationToken++;
15492 for (PackageParser.Activity a : pkg.activities) {
15493 for (ActivityIntentInfo filter : a.intents) {
15494 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15495 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15496 "Verification needed for IntentFilter:" + filter.toString());
15497 mIntentFilterVerifier.addOneIntentFilterVerification(
15498 verifierUid, userId, verificationId, filter, packageName);
15507 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15508 + " IntentFilter verification" + (count > 1 ? "s" : "")
15509 + " for userId:" + userId);
15510 mIntentFilterVerifier.startVerifications(userId);
15512 if (DEBUG_DOMAIN_VERIFICATION) {
15513 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15518 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15519 final ComponentName cn = filter.activity.getComponentName();
15520 final String packageName = cn.getPackageName();
15522 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15527 int status = ivi.getStatus();
15529 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15530 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15539 private static boolean isMultiArch(ApplicationInfo info) {
15540 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15543 private static boolean isExternal(PackageParser.Package pkg) {
15544 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15547 private static boolean isExternal(PackageSetting ps) {
15548 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15551 private static boolean isEphemeral(PackageParser.Package pkg) {
15552 return pkg.applicationInfo.isEphemeralApp();
15555 private static boolean isEphemeral(PackageSetting ps) {
15556 return ps.pkg != null && isEphemeral(ps.pkg);
15559 private static boolean isSystemApp(PackageParser.Package pkg) {
15560 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15563 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15564 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15567 private static boolean hasDomainURLs(PackageParser.Package pkg) {
15568 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15571 private static boolean isSystemApp(PackageSetting ps) {
15572 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15575 private static boolean isUpdatedSystemApp(PackageSetting ps) {
15576 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15579 private int packageFlagsToInstallFlags(PackageSetting ps) {
15580 int installFlags = 0;
15581 if (isEphemeral(ps)) {
15582 installFlags |= PackageManager.INSTALL_EPHEMERAL;
15584 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15585 // This existing package was an external ASEC install when we have
15586 // the external flag without a UUID
15587 installFlags |= PackageManager.INSTALL_EXTERNAL;
15589 if (ps.isForwardLocked()) {
15590 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15592 return installFlags;
15595 private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15596 if (isExternal(pkg)) {
15597 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15598 return StorageManager.UUID_PRIMARY_PHYSICAL;
15600 return pkg.volumeUuid;
15603 return StorageManager.UUID_PRIVATE_INTERNAL;
15607 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15608 if (isExternal(pkg)) {
15609 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15610 return mSettings.getExternalVersion();
15612 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15615 return mSettings.getInternalVersion();
15619 private void deleteTempPackageFiles() {
15620 final FilenameFilter filter = new FilenameFilter() {
15621 public boolean accept(File dir, String name) {
15622 return name.startsWith("vmdl") && name.endsWith(".tmp");
15625 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15631 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15633 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15638 public void deletePackage(final String packageName,
15639 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15640 mContext.enforceCallingOrSelfPermission(
15641 android.Manifest.permission.DELETE_PACKAGES, null);
15642 Preconditions.checkNotNull(packageName);
15643 Preconditions.checkNotNull(observer);
15644 final int uid = Binder.getCallingUid();
15645 if (!isOrphaned(packageName)
15646 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15648 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15649 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15650 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15651 observer.onUserActionRequired(intent);
15652 } catch (RemoteException re) {
15656 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15657 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15658 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15659 mContext.enforceCallingOrSelfPermission(
15660 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15661 "deletePackage for user " + userId);
15664 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15666 observer.onPackageDeleted(packageName,
15667 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15668 } catch (RemoteException re) {
15673 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15675 observer.onPackageDeleted(packageName,
15676 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15677 } catch (RemoteException re) {
15682 if (DEBUG_REMOVE) {
15683 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15684 + " deleteAllUsers: " + deleteAllUsers );
15686 // Queue up an async operation since the package deletion may take a little while.
15687 mHandler.post(new Runnable() {
15688 public void run() {
15689 mHandler.removeCallbacks(this);
15691 if (!deleteAllUsers) {
15692 returnCode = deletePackageX(packageName, userId, deleteFlags);
15694 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15695 // If nobody is blocking uninstall, proceed with delete for all users
15696 if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15697 returnCode = deletePackageX(packageName, userId, deleteFlags);
15699 // Otherwise uninstall individually for users with blockUninstalls=false
15700 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15701 for (int userId : users) {
15702 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15703 returnCode = deletePackageX(packageName, userId, userFlags);
15704 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15705 Slog.w(TAG, "Package delete failed for user " + userId
15706 + ", returnCode " + returnCode);
15710 // The app has only been marked uninstalled for certain users.
15711 // We still need to report that delete was blocked
15712 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15716 observer.onPackageDeleted(packageName, returnCode, null);
15717 } catch (RemoteException e) {
15718 Log.i(TAG, "Observer no longer exists.");
15724 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15725 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15726 || callingUid == Process.SYSTEM_UID) {
15729 final int callingUserId = UserHandle.getUserId(callingUid);
15730 // If the caller installed the pkgName, then allow it to silently uninstall.
15731 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15735 // Allow package verifier to silently uninstall.
15736 if (mRequiredVerifierPackage != null &&
15737 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15741 // Allow package uninstaller to silently uninstall.
15742 if (mRequiredUninstallerPackage != null &&
15743 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15747 // Allow storage manager to silently uninstall.
15748 if (mStorageManagerPackage != null &&
15749 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15755 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15756 int[] result = EMPTY_INT_ARRAY;
15757 for (int userId : userIds) {
15758 if (getBlockUninstallForUser(packageName, userId)) {
15759 result = ArrayUtils.appendInt(result, userId);
15766 public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15767 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15770 private boolean isPackageDeviceAdmin(String packageName, int userId) {
15771 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15772 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15775 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15776 /* callingUserOnly =*/ false);
15777 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15778 : deviceOwnerComponentName.getPackageName();
15779 // Does the package contains the device owner?
15780 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise,
15781 // this check is probably not needed, since DO should be registered as a device
15782 // admin on some user too. (Original bug for this: b/17657954)
15783 if (packageName.equals(deviceOwnerPackageName)) {
15786 // Does it contain a device admin for any user?
15788 if (userId == UserHandle.USER_ALL) {
15789 users = sUserManager.getUserIds();
15791 users = new int[]{userId};
15793 for (int i = 0; i < users.length; ++i) {
15794 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15799 } catch (RemoteException e) {
15804 private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15805 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15809 * This method is an internal method that could be get invoked either
15810 * to delete an installed package or to clean up a failed installation.
15811 * After deleting an installed package, a broadcast is sent to notify any
15812 * listeners that the package has been removed. For cleaning up a failed
15813 * installation, the broadcast is not necessary since the package's
15814 * installation wouldn't have sent the initial broadcast either
15815 * The key steps in deleting a package are
15816 * deleting the package information in internal structures like mPackages,
15817 * deleting the packages base directories through installd
15818 * updating mSettings to reflect current status
15819 * persisting settings for later use
15820 * sending a broadcast if necessary
15822 private int deletePackageX(String packageName, int userId, int deleteFlags) {
15823 final PackageRemovedInfo info = new PackageRemovedInfo();
15826 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15827 ? UserHandle.USER_ALL : userId;
15829 if (isPackageDeviceAdmin(packageName, removeUser)) {
15830 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15831 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15834 PackageSetting uninstalledPs = null;
15836 // for the uninstall-updates case and restricted profiles, remember the per-
15837 // user handle installed state
15839 synchronized (mPackages) {
15840 uninstalledPs = mSettings.mPackages.get(packageName);
15841 if (uninstalledPs == null) {
15842 Slog.w(TAG, "Not removing non-existent package " + packageName);
15843 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15845 allUsers = sUserManager.getUserIds();
15846 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15849 final int freezeUser;
15850 if (isUpdatedSystemApp(uninstalledPs)
15851 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15852 // We're downgrading a system app, which will apply to all users, so
15853 // freeze them all during the downgrade
15854 freezeUser = UserHandle.USER_ALL;
15856 freezeUser = removeUser;
15859 synchronized (mInstallLock) {
15860 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15861 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15862 deleteFlags, "deletePackageX")) {
15863 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15864 deleteFlags | REMOVE_CHATTY, info, true, null);
15866 synchronized (mPackages) {
15868 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15874 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15875 info.sendPackageRemovedBroadcasts(killApp);
15876 info.sendSystemPackageUpdatedBroadcasts();
15877 info.sendSystemPackageAppearedBroadcasts();
15879 // Force a gc here.
15880 Runtime.getRuntime().gc();
15881 // Delete the resources here after sending the broadcast to let
15882 // other processes clean up before deleting resources.
15883 if (info.args != null) {
15884 synchronized (mInstallLock) {
15885 info.args.doPostDeleteLI(true);
15889 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15892 class PackageRemovedInfo {
15893 String removedPackage;
15895 int removedAppId = -1;
15897 int[] removedUsers = null;
15898 boolean isRemovedPackageSystemUpdate = false;
15900 boolean dataRemoved;
15901 boolean removedForAllUsers;
15902 // Clean up resources deleted packages.
15903 InstallArgs args = null;
15904 ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15905 ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15907 void sendPackageRemovedBroadcasts(boolean killApp) {
15908 sendPackageRemovedBroadcastInternal(killApp);
15909 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15910 for (int i = 0; i < childCount; i++) {
15911 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15912 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15916 void sendSystemPackageUpdatedBroadcasts() {
15917 if (isRemovedPackageSystemUpdate) {
15918 sendSystemPackageUpdatedBroadcastsInternal();
15919 final int childCount = (removedChildPackages != null)
15920 ? removedChildPackages.size() : 0;
15921 for (int i = 0; i < childCount; i++) {
15922 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15923 if (childInfo.isRemovedPackageSystemUpdate) {
15924 childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15930 void sendSystemPackageAppearedBroadcasts() {
15931 final int packageCount = (appearedChildPackages != null)
15932 ? appearedChildPackages.size() : 0;
15933 for (int i = 0; i < packageCount; i++) {
15934 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15935 for (int userId : installedInfo.newUsers) {
15936 sendPackageAddedForUser(installedInfo.name, true,
15937 UserHandle.getAppId(installedInfo.uid), userId);
15942 private void sendSystemPackageUpdatedBroadcastsInternal() {
15943 Bundle extras = new Bundle(2);
15944 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15945 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15946 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15947 extras, 0, null, null, null);
15948 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15949 extras, 0, null, null, null);
15950 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15951 null, 0, removedPackage, null, null);
15954 private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15955 Bundle extras = new Bundle(2);
15956 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15957 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15958 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15959 if (isUpdate || isRemovedPackageSystemUpdate) {
15960 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15962 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15963 if (removedPackage != null) {
15964 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15965 extras, 0, null, null, removedUsers);
15966 if (dataRemoved && !isRemovedPackageSystemUpdate) {
15967 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15968 removedPackage, extras, 0, null, null, removedUsers);
15971 if (removedAppId >= 0) {
15972 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15979 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15980 * flag is not set, the data directory is removed as well.
15981 * make sure this flag is set for partially installed apps. If not its meaningless to
15982 * delete a partially installed application.
15984 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15985 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15986 String packageName = ps.name;
15987 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15988 // Retrieve object to delete permissions for shared user later on
15989 final PackageParser.Package deletedPkg;
15990 final PackageSetting deletedPs;
15992 synchronized (mPackages) {
15993 deletedPkg = mPackages.get(packageName);
15994 deletedPs = mSettings.mPackages.get(packageName);
15995 if (outInfo != null) {
15996 outInfo.removedPackage = packageName;
15997 outInfo.removedUsers = deletedPs != null
15998 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16003 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16005 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16006 final PackageParser.Package resolvedPkg;
16007 if (deletedPkg != null) {
16008 resolvedPkg = deletedPkg;
16010 // We don't have a parsed package when it lives on an ejected
16011 // adopted storage device, so fake something together
16012 resolvedPkg = new PackageParser.Package(ps.name);
16013 resolvedPkg.setVolumeUuid(ps.volumeUuid);
16015 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16016 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16017 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16018 if (outInfo != null) {
16019 outInfo.dataRemoved = true;
16021 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16025 synchronized (mPackages) {
16026 if (deletedPs != null) {
16027 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16028 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16029 clearDefaultBrowserIfNeeded(packageName);
16030 if (outInfo != null) {
16031 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16032 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16034 updatePermissionsLPw(deletedPs.name, null, 0);
16035 if (deletedPs.sharedUser != null) {
16036 // Remove permissions associated with package. Since runtime
16037 // permissions are per user we have to kill the removed package
16038 // or packages running under the shared user of the removed
16039 // package if revoking the permissions requested only by the removed
16040 // package is successful and this causes a change in gids.
16041 for (int userId : UserManagerService.getInstance().getUserIds()) {
16042 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16044 if (userIdToKill == UserHandle.USER_ALL
16045 || userIdToKill >= UserHandle.USER_SYSTEM) {
16046 // If gids changed for this user, kill all affected packages.
16047 mHandler.post(new Runnable() {
16049 public void run() {
16050 // This has to happen with no lock held.
16051 killApplication(deletedPs.name, deletedPs.appId,
16052 KILL_APP_REASON_GIDS_CHANGED);
16059 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16061 // make sure to preserve per-user disabled state if this removal was just
16062 // a downgrade of a system app to the factory package
16063 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16064 if (DEBUG_REMOVE) {
16065 Slog.d(TAG, "Propagating install state across downgrade");
16067 for (int userId : allUserHandles) {
16068 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16069 if (DEBUG_REMOVE) {
16070 Slog.d(TAG, " user " + userId + " => " + installed);
16072 ps.setInstalled(installed, userId);
16076 // can downgrade to reader
16077 if (writeSettings) {
16078 // Save settings now
16079 mSettings.writeLPr();
16082 if (outInfo != null) {
16083 // A user ID was deleted here. Go through all users and remove it
16085 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16089 static boolean locationIsPrivileged(File path) {
16091 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16092 .getCanonicalPath();
16093 return path.getCanonicalPath().startsWith(privilegedAppDir);
16094 } catch (IOException e) {
16095 Slog.e(TAG, "Unable to access code path " + path);
16101 * Tries to delete system package.
16103 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16104 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16105 boolean writeSettings) {
16106 if (deletedPs.parentPackageName != null) {
16107 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16111 final boolean applyUserRestrictions
16112 = (allUserHandles != null) && (outInfo.origUsers != null);
16113 final PackageSetting disabledPs;
16114 // Confirm if the system package has been updated
16115 // An updated system app can be deleted. This will also have to restore
16116 // the system pkg from system partition
16118 synchronized (mPackages) {
16119 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16122 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16123 + " disabledPs=" + disabledPs);
16125 if (disabledPs == null) {
16126 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16128 } else if (DEBUG_REMOVE) {
16129 Slog.d(TAG, "Deleting system pkg from data partition");
16132 if (DEBUG_REMOVE) {
16133 if (applyUserRestrictions) {
16134 Slog.d(TAG, "Remembering install states:");
16135 for (int userId : allUserHandles) {
16136 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16137 Slog.d(TAG, " u=" + userId + " inst=" + finstalled);
16142 // Delete the updated package
16143 outInfo.isRemovedPackageSystemUpdate = true;
16144 if (outInfo.removedChildPackages != null) {
16145 final int childCount = (deletedPs.childPackageNames != null)
16146 ? deletedPs.childPackageNames.size() : 0;
16147 for (int i = 0; i < childCount; i++) {
16148 String childPackageName = deletedPs.childPackageNames.get(i);
16149 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16150 .contains(childPackageName)) {
16151 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16153 if (childInfo != null) {
16154 childInfo.isRemovedPackageSystemUpdate = true;
16160 if (disabledPs.versionCode < deletedPs.versionCode) {
16161 // Delete data for downgrades
16162 flags &= ~PackageManager.DELETE_KEEP_DATA;
16164 // Preserve data by setting flag
16165 flags |= PackageManager.DELETE_KEEP_DATA;
16168 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16169 outInfo, writeSettings, disabledPs.pkg);
16175 synchronized (mPackages) {
16176 // Reinstate the old system package
16177 enableSystemPackageLPw(disabledPs.pkg);
16178 // Remove any native libraries from the upgraded package.
16179 removeNativeBinariesLI(deletedPs);
16182 // Install the system package
16183 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16184 int parseFlags = mDefParseFlags
16185 | PackageParser.PARSE_MUST_BE_APK
16186 | PackageParser.PARSE_IS_SYSTEM
16187 | PackageParser.PARSE_IS_SYSTEM_DIR;
16188 if (locationIsPrivileged(disabledPs.codePath)) {
16189 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16192 final PackageParser.Package newPkg;
16194 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16195 } catch (PackageManagerException e) {
16196 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16201 // update shared libraries for the newly re-installed system package
16202 updateSharedLibrariesLPw(newPkg, null);
16203 } catch (PackageManagerException e) {
16204 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16207 prepareAppDataAfterInstallLIF(newPkg);
16210 synchronized (mPackages) {
16211 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16213 // Propagate the permissions state as we do not want to drop on the floor
16214 // runtime permissions. The update permissions method below will take
16215 // care of removing obsolete permissions and grant install permissions.
16216 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16217 updatePermissionsLPw(newPkg.packageName, newPkg,
16218 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16220 if (applyUserRestrictions) {
16221 if (DEBUG_REMOVE) {
16222 Slog.d(TAG, "Propagating install state across reinstall");
16224 for (int userId : allUserHandles) {
16225 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16226 if (DEBUG_REMOVE) {
16227 Slog.d(TAG, " user " + userId + " => " + installed);
16229 ps.setInstalled(installed, userId);
16231 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16233 // Regardless of writeSettings we need to ensure that this restriction
16234 // state propagation is persisted
16235 mSettings.writeAllUsersPackageRestrictionsLPr();
16237 // can downgrade to reader here
16238 if (writeSettings) {
16239 mSettings.writeLPr();
16245 private boolean deleteInstalledPackageLIF(PackageSetting ps,
16246 boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16247 PackageRemovedInfo outInfo, boolean writeSettings,
16248 PackageParser.Package replacingPackage) {
16249 synchronized (mPackages) {
16250 if (outInfo != null) {
16251 outInfo.uid = ps.appId;
16254 if (outInfo != null && outInfo.removedChildPackages != null) {
16255 final int childCount = (ps.childPackageNames != null)
16256 ? ps.childPackageNames.size() : 0;
16257 for (int i = 0; i < childCount; i++) {
16258 String childPackageName = ps.childPackageNames.get(i);
16259 PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16260 if (childPs == null) {
16263 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16265 if (childInfo != null) {
16266 childInfo.uid = childPs.appId;
16272 // Delete package data from internal structures and also remove data if flag is set
16273 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16275 // Delete the child packages data
16276 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16277 for (int i = 0; i < childCount; i++) {
16278 PackageSetting childPs;
16279 synchronized (mPackages) {
16280 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16282 if (childPs != null) {
16283 PackageRemovedInfo childOutInfo = (outInfo != null
16284 && outInfo.removedChildPackages != null)
16285 ? outInfo.removedChildPackages.get(childPs.name) : null;
16286 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16287 && (replacingPackage != null
16288 && !replacingPackage.hasChildPackage(childPs.name))
16289 ? flags & ~DELETE_KEEP_DATA : flags;
16290 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16291 deleteFlags, writeSettings);
16295 // Delete application code and resources only for parent packages
16296 if (ps.parentPackageName == null) {
16297 if (deleteCodeAndResources && (outInfo != null)) {
16298 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16299 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16300 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16308 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16310 mContext.enforceCallingOrSelfPermission(
16311 android.Manifest.permission.DELETE_PACKAGES, null);
16312 synchronized (mPackages) {
16313 PackageSetting ps = mSettings.mPackages.get(packageName);
16315 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16318 if (!ps.getInstalled(userId)) {
16319 // Can't block uninstall for an app that is not installed or enabled.
16320 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16323 ps.setBlockUninstall(blockUninstall, userId);
16324 mSettings.writePackageRestrictionsLPr(userId);
16330 public boolean getBlockUninstallForUser(String packageName, int userId) {
16331 synchronized (mPackages) {
16332 PackageSetting ps = mSettings.mPackages.get(packageName);
16334 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16337 return ps.getBlockUninstall(userId);
16342 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16343 int callingUid = Binder.getCallingUid();
16344 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16345 throw new SecurityException(
16346 "setRequiredForSystemUser can only be run by the system or root");
16348 synchronized (mPackages) {
16349 PackageSetting ps = mSettings.mPackages.get(packageName);
16351 Log.w(TAG, "Package doesn't exist: " + packageName);
16354 if (systemUserApp) {
16355 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16357 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16359 mSettings.writeLPr();
16365 * This method handles package deletion in general
16367 private boolean deletePackageLIF(String packageName, UserHandle user,
16368 boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16369 PackageRemovedInfo outInfo, boolean writeSettings,
16370 PackageParser.Package replacingPackage) {
16371 if (packageName == null) {
16372 Slog.w(TAG, "Attempt to delete null packageName.");
16376 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16380 synchronized (mPackages) {
16381 ps = mSettings.mPackages.get(packageName);
16383 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16387 if (ps.parentPackageName != null && (!isSystemApp(ps)
16388 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16389 if (DEBUG_REMOVE) {
16390 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16391 + ((user == null) ? UserHandle.USER_ALL : user));
16393 final int removedUserId = (user != null) ? user.getIdentifier()
16394 : UserHandle.USER_ALL;
16395 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16398 markPackageUninstalledForUserLPw(ps, user);
16399 scheduleWritePackageRestrictionsLocked(user);
16404 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16405 && user.getIdentifier() != UserHandle.USER_ALL)) {
16406 // The caller is asking that the package only be deleted for a single
16407 // user. To do this, we just mark its uninstalled state and delete
16408 // its data. If this is a system app, we only allow this to happen if
16409 // they have set the special DELETE_SYSTEM_APP which requests different
16410 // semantics than normal for uninstalling system apps.
16411 markPackageUninstalledForUserLPw(ps, user);
16413 if (!isSystemApp(ps)) {
16414 // Do not uninstall the APK if an app should be cached
16415 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16416 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16417 // Other user still have this package installed, so all
16418 // we need to do is clear this user's data and save that
16419 // it is uninstalled.
16420 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16421 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16424 scheduleWritePackageRestrictionsLocked(user);
16427 // We need to set it back to 'installed' so the uninstall
16428 // broadcasts will be sent correctly.
16429 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16430 ps.setInstalled(true, user.getIdentifier());
16433 // This is a system app, so we assume that the
16434 // other users still have this package installed, so all
16435 // we need to do is clear this user's data and save that
16436 // it is uninstalled.
16437 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16438 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16441 scheduleWritePackageRestrictionsLocked(user);
16446 // If we are deleting a composite package for all users, keep track
16447 // of result for each child.
16448 if (ps.childPackageNames != null && outInfo != null) {
16449 synchronized (mPackages) {
16450 final int childCount = ps.childPackageNames.size();
16451 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16452 for (int i = 0; i < childCount; i++) {
16453 String childPackageName = ps.childPackageNames.get(i);
16454 PackageRemovedInfo childInfo = new PackageRemovedInfo();
16455 childInfo.removedPackage = childPackageName;
16456 outInfo.removedChildPackages.put(childPackageName, childInfo);
16457 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16458 if (childPs != null) {
16459 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16465 boolean ret = false;
16466 if (isSystemApp(ps)) {
16467 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16468 // When an updated system application is deleted we delete the existing resources
16469 // as well and fall back to existing code in system partition
16470 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16472 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16473 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16474 outInfo, writeSettings, replacingPackage);
16477 // Take a note whether we deleted the package for all users
16478 if (outInfo != null) {
16479 outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16480 if (outInfo.removedChildPackages != null) {
16481 synchronized (mPackages) {
16482 final int childCount = outInfo.removedChildPackages.size();
16483 for (int i = 0; i < childCount; i++) {
16484 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16485 if (childInfo != null) {
16486 childInfo.removedForAllUsers = mPackages.get(
16487 childInfo.removedPackage) == null;
16492 // If we uninstalled an update to a system app there may be some
16493 // child packages that appeared as they are declared in the system
16494 // app but were not declared in the update.
16495 if (isSystemApp(ps)) {
16496 synchronized (mPackages) {
16497 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16498 final int childCount = (updatedPs.childPackageNames != null)
16499 ? updatedPs.childPackageNames.size() : 0;
16500 for (int i = 0; i < childCount; i++) {
16501 String childPackageName = updatedPs.childPackageNames.get(i);
16502 if (outInfo.removedChildPackages == null
16503 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16504 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16505 if (childPs == null) {
16508 PackageInstalledInfo installRes = new PackageInstalledInfo();
16509 installRes.name = childPackageName;
16510 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16511 installRes.pkg = mPackages.get(childPackageName);
16512 installRes.uid = childPs.pkg.applicationInfo.uid;
16513 if (outInfo.appearedChildPackages == null) {
16514 outInfo.appearedChildPackages = new ArrayMap<>();
16516 outInfo.appearedChildPackages.put(childPackageName, installRes);
16526 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16527 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16528 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16529 for (int nextUserId : userIds) {
16530 if (DEBUG_REMOVE) {
16531 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16533 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16534 false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16535 false /*hidden*/, false /*suspended*/, null, null, null,
16536 false /*blockUninstall*/,
16537 ps.readUserState(nextUserId).domainVerificationStatus, 0);
16541 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16542 PackageRemovedInfo outInfo) {
16543 final PackageParser.Package pkg;
16544 synchronized (mPackages) {
16545 pkg = mPackages.get(ps.name);
16548 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16549 : new int[] {userId};
16550 for (int nextUserId : userIds) {
16551 if (DEBUG_REMOVE) {
16552 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16556 destroyAppDataLIF(pkg, userId,
16557 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16558 destroyAppProfilesLIF(pkg, userId);
16559 removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16560 schedulePackageCleaning(ps.name, nextUserId, false);
16561 synchronized (mPackages) {
16562 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16563 scheduleWritePackageRestrictionsLocked(nextUserId);
16565 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16569 if (outInfo != null) {
16570 outInfo.removedPackage = ps.name;
16571 outInfo.removedAppId = ps.appId;
16572 outInfo.removedUsers = userIds;
16578 private final class ClearStorageConnection implements ServiceConnection {
16579 IMediaContainerService mContainerService;
16582 public void onServiceConnected(ComponentName name, IBinder service) {
16583 synchronized (this) {
16584 mContainerService = IMediaContainerService.Stub.asInterface(service);
16590 public void onServiceDisconnected(ComponentName name) {
16594 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16595 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16597 final boolean mounted;
16598 if (Environment.isExternalStorageEmulated()) {
16601 final String status = Environment.getExternalStorageState();
16603 mounted = status.equals(Environment.MEDIA_MOUNTED)
16604 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16611 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16613 if (userId == UserHandle.USER_ALL) {
16614 users = sUserManager.getUserIds();
16616 users = new int[] { userId };
16618 final ClearStorageConnection conn = new ClearStorageConnection();
16619 if (mContext.bindServiceAsUser(
16620 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16622 for (int curUser : users) {
16623 long timeout = SystemClock.uptimeMillis() + 5000;
16624 synchronized (conn) {
16626 while (conn.mContainerService == null &&
16627 (now = SystemClock.uptimeMillis()) < timeout) {
16629 conn.wait(timeout - now);
16630 } catch (InterruptedException e) {
16634 if (conn.mContainerService == null) {
16638 final UserEnvironment userEnv = new UserEnvironment(curUser);
16639 clearDirectory(conn.mContainerService,
16640 userEnv.buildExternalStorageAppCacheDirs(packageName));
16642 clearDirectory(conn.mContainerService,
16643 userEnv.buildExternalStorageAppDataDirs(packageName));
16644 clearDirectory(conn.mContainerService,
16645 userEnv.buildExternalStorageAppMediaDirs(packageName));
16649 mContext.unbindService(conn);
16655 public void clearApplicationProfileData(String packageName) {
16656 enforceSystemOrRoot("Only the system can clear all profile data");
16658 final PackageParser.Package pkg;
16659 synchronized (mPackages) {
16660 pkg = mPackages.get(packageName);
16663 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16664 synchronized (mInstallLock) {
16665 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16666 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16667 true /* removeBaseMarker */);
16673 public void clearApplicationUserData(final String packageName,
16674 final IPackageDataObserver observer, final int userId) {
16675 mContext.enforceCallingOrSelfPermission(
16676 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16678 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16679 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16681 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16682 throw new SecurityException("Cannot clear data for a protected package: "
16685 // Queue up an async operation since the package deletion may take a little while.
16686 mHandler.post(new Runnable() {
16687 public void run() {
16688 mHandler.removeCallbacks(this);
16689 final boolean succeeded;
16690 try (PackageFreezer freezer = freezePackage(packageName,
16691 "clearApplicationUserData")) {
16692 synchronized (mInstallLock) {
16693 succeeded = clearApplicationUserDataLIF(packageName, userId);
16695 clearExternalStorageDataSync(packageName, userId, true);
16698 // invoke DeviceStorageMonitor's update method to clear any notifications
16699 DeviceStorageMonitorInternal dsm = LocalServices
16700 .getService(DeviceStorageMonitorInternal.class);
16705 if(observer != null) {
16707 observer.onRemoveCompleted(packageName, succeeded);
16708 } catch (RemoteException e) {
16709 Log.i(TAG, "Observer no longer exists.");
16711 } //end if observer
16716 private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16717 if (packageName == null) {
16718 Slog.w(TAG, "Attempt to delete null packageName.");
16722 // Try finding details about the requested package
16723 PackageParser.Package pkg;
16724 synchronized (mPackages) {
16725 pkg = mPackages.get(packageName);
16727 final PackageSetting ps = mSettings.mPackages.get(packageName);
16734 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16738 PackageSetting ps = (PackageSetting) pkg.mExtras;
16739 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16742 clearAppDataLIF(pkg, userId,
16743 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16745 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16746 removeKeystoreDataIfNeeded(userId, appId);
16748 UserManagerInternal umInternal = getUserManagerInternal();
16750 if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16751 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16752 } else if (umInternal.isUserRunning(userId)) {
16753 flags = StorageManager.FLAG_STORAGE_DE;
16757 prepareAppDataContentsLIF(pkg, userId, flags);
16763 * Reverts user permission state changes (permissions and flags) in
16764 * all packages for a given user.
16766 * @param userId The device user for which to do a reset.
16768 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16769 final int packageCount = mPackages.size();
16770 for (int i = 0; i < packageCount; i++) {
16771 PackageParser.Package pkg = mPackages.valueAt(i);
16772 PackageSetting ps = (PackageSetting) pkg.mExtras;
16773 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16777 private void resetNetworkPolicies(int userId) {
16778 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16782 * Reverts user permission state changes (permissions and flags).
16784 * @param ps The package for which to reset.
16785 * @param userId The device user for which to do a reset.
16787 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16788 final PackageSetting ps, final int userId) {
16789 if (ps.pkg == null) {
16793 // These are flags that can change base on user actions.
16794 final int userSettableMask = FLAG_PERMISSION_USER_SET
16795 | FLAG_PERMISSION_USER_FIXED
16796 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16797 | FLAG_PERMISSION_REVIEW_REQUIRED;
16799 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16800 | FLAG_PERMISSION_POLICY_FIXED;
16802 boolean writeInstallPermissions = false;
16803 boolean writeRuntimePermissions = false;
16805 final int permissionCount = ps.pkg.requestedPermissions.size();
16806 for (int i = 0; i < permissionCount; i++) {
16807 String permission = ps.pkg.requestedPermissions.get(i);
16809 BasePermission bp = mSettings.mPermissions.get(permission);
16814 // If shared user we just reset the state to which only this app contributed.
16815 if (ps.sharedUser != null) {
16816 boolean used = false;
16817 final int packageCount = ps.sharedUser.packages.size();
16818 for (int j = 0; j < packageCount; j++) {
16819 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16820 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16821 && pkg.pkg.requestedPermissions.contains(permission)) {
16831 PermissionsState permissionsState = ps.getPermissionsState();
16833 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16835 // Always clear the user settable flags.
16836 final boolean hasInstallState = permissionsState.getInstallPermissionState(
16838 // If permission review is enabled and this is a legacy app, mark the
16839 // permission as requiring a review as this is the initial state.
16841 if (Build.PERMISSIONS_REVIEW_REQUIRED
16842 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16843 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16845 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16846 if (hasInstallState) {
16847 writeInstallPermissions = true;
16849 writeRuntimePermissions = true;
16853 // Below is only runtime permission handling.
16854 if (!bp.isRuntime()) {
16858 // Never clobber system or policy.
16859 if ((oldFlags & policyOrSystemFlags) != 0) {
16863 // If this permission was granted by default, make sure it is.
16864 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16865 if (permissionsState.grantRuntimePermission(bp, userId)
16866 != PERMISSION_OPERATION_FAILURE) {
16867 writeRuntimePermissions = true;
16869 // If permission review is enabled the permissions for a legacy apps
16870 // are represented as constantly granted runtime ones, so don't revoke.
16871 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16872 // Otherwise, reset the permission.
16873 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16874 switch (revokeResult) {
16875 case PERMISSION_OPERATION_SUCCESS:
16876 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16877 writeRuntimePermissions = true;
16878 final int appId = ps.appId;
16879 mHandler.post(new Runnable() {
16881 public void run() {
16882 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16890 // Synchronously write as we are taking permissions away.
16891 if (writeRuntimePermissions) {
16892 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16895 // Synchronously write as we are taking permissions away.
16896 if (writeInstallPermissions) {
16897 mSettings.writeLPr();
16902 * Remove entries from the keystore daemon. Will only remove it if the
16903 * {@code appId} is valid.
16905 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16910 final KeyStore keyStore = KeyStore.getInstance();
16911 if (keyStore != null) {
16912 if (userId == UserHandle.USER_ALL) {
16913 for (final int individual : sUserManager.getUserIds()) {
16914 keyStore.clearUid(UserHandle.getUid(individual, appId));
16917 keyStore.clearUid(UserHandle.getUid(userId, appId));
16920 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16925 public void deleteApplicationCacheFiles(final String packageName,
16926 final IPackageDataObserver observer) {
16927 final int userId = UserHandle.getCallingUserId();
16928 deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16932 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16933 final IPackageDataObserver observer) {
16934 mContext.enforceCallingOrSelfPermission(
16935 android.Manifest.permission.DELETE_CACHE_FILES, null);
16936 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16937 /* requireFullPermission= */ true, /* checkShell= */ false,
16938 "delete application cache files");
16940 final PackageParser.Package pkg;
16941 synchronized (mPackages) {
16942 pkg = mPackages.get(packageName);
16945 // Queue up an async operation since the package deletion may take a little while.
16946 mHandler.post(new Runnable() {
16947 public void run() {
16948 synchronized (mInstallLock) {
16949 final int flags = StorageManager.FLAG_STORAGE_DE
16950 | StorageManager.FLAG_STORAGE_CE;
16951 // We're only clearing cache files, so we don't care if the
16952 // app is unfrozen and still able to run
16953 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16954 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16956 clearExternalStorageDataSync(packageName, userId, false);
16957 if (observer != null) {
16959 observer.onRemoveCompleted(packageName, true);
16960 } catch (RemoteException e) {
16961 Log.i(TAG, "Observer no longer exists.");
16969 public void getPackageSizeInfo(final String packageName, int userHandle,
16970 final IPackageStatsObserver observer) {
16971 mContext.enforceCallingOrSelfPermission(
16972 android.Manifest.permission.GET_PACKAGE_SIZE, null);
16973 if (packageName == null) {
16974 throw new IllegalArgumentException("Attempt to get size of null packageName");
16977 PackageStats stats = new PackageStats(packageName, userHandle);
16980 * Queue up an async operation since the package measurement may take a
16983 Message msg = mHandler.obtainMessage(INIT_COPY);
16984 msg.obj = new MeasureParams(stats, observer);
16985 mHandler.sendMessage(msg);
16988 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16989 final PackageSetting ps;
16990 synchronized (mPackages) {
16991 ps = mSettings.mPackages.get(packageName);
16993 Slog.w(TAG, "Failed to find settings for " + packageName);
16998 mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16999 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17000 ps.getCeDataInode(userId), ps.codePathString, stats);
17001 } catch (InstallerException e) {
17002 Slog.w(TAG, String.valueOf(e));
17006 // For now, ignore code size of packages on system partition
17007 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17008 stats.codeSize = 0;
17014 private int getUidTargetSdkVersionLockedLPr(int uid) {
17015 Object obj = mSettings.getUserIdLPr(uid);
17016 if (obj instanceof SharedUserSetting) {
17017 final SharedUserSetting sus = (SharedUserSetting) obj;
17018 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17019 final Iterator<PackageSetting> it = sus.packages.iterator();
17020 while (it.hasNext()) {
17021 final PackageSetting ps = it.next();
17022 if (ps.pkg != null) {
17023 int v = ps.pkg.applicationInfo.targetSdkVersion;
17024 if (v < vers) vers = v;
17028 } else if (obj instanceof PackageSetting) {
17029 final PackageSetting ps = (PackageSetting) obj;
17030 if (ps.pkg != null) {
17031 return ps.pkg.applicationInfo.targetSdkVersion;
17034 return Build.VERSION_CODES.CUR_DEVELOPMENT;
17038 public void addPreferredActivity(IntentFilter filter, int match,
17039 ComponentName[] set, ComponentName activity, int userId) {
17040 addPreferredActivityInternal(filter, match, set, activity, true, userId,
17041 "Adding preferred");
17044 private void addPreferredActivityInternal(IntentFilter filter, int match,
17045 ComponentName[] set, ComponentName activity, boolean always, int userId,
17048 int callingUid = Binder.getCallingUid();
17049 enforceCrossUserPermission(callingUid, userId,
17050 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17051 if (filter.countActions() == 0) {
17052 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17055 synchronized (mPackages) {
17056 if (mContext.checkCallingOrSelfPermission(
17057 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17058 != PackageManager.PERMISSION_GRANTED) {
17059 if (getUidTargetSdkVersionLockedLPr(callingUid)
17060 < Build.VERSION_CODES.FROYO) {
17061 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17065 mContext.enforceCallingOrSelfPermission(
17066 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17069 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17070 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17072 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17073 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17074 scheduleWritePackageRestrictionsLocked(userId);
17075 postPreferredActivityChangedBroadcast(userId);
17079 private void postPreferredActivityChangedBroadcast(int userId) {
17080 mHandler.post(() -> {
17081 final IActivityManager am = ActivityManagerNative.getDefault();
17086 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17087 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17089 am.broadcastIntent(null, intent, null, null,
17090 0, null, null, null, android.app.AppOpsManager.OP_NONE,
17091 null, false, false, userId);
17092 } catch (RemoteException e) {
17098 public void replacePreferredActivity(IntentFilter filter, int match,
17099 ComponentName[] set, ComponentName activity, int userId) {
17100 if (filter.countActions() != 1) {
17101 throw new IllegalArgumentException(
17102 "replacePreferredActivity expects filter to have only 1 action.");
17104 if (filter.countDataAuthorities() != 0
17105 || filter.countDataPaths() != 0
17106 || filter.countDataSchemes() > 1
17107 || filter.countDataTypes() != 0) {
17108 throw new IllegalArgumentException(
17109 "replacePreferredActivity expects filter to have no data authorities, " +
17110 "paths, or types; and at most one scheme.");
17113 final int callingUid = Binder.getCallingUid();
17114 enforceCrossUserPermission(callingUid, userId,
17115 true /* requireFullPermission */, false /* checkShell */,
17116 "replace preferred activity");
17117 synchronized (mPackages) {
17118 if (mContext.checkCallingOrSelfPermission(
17119 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17120 != PackageManager.PERMISSION_GRANTED) {
17121 if (getUidTargetSdkVersionLockedLPr(callingUid)
17122 < Build.VERSION_CODES.FROYO) {
17123 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17124 + Binder.getCallingUid());
17127 mContext.enforceCallingOrSelfPermission(
17128 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17131 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17133 // Get all of the existing entries that exactly match this filter.
17134 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17135 if (existing != null && existing.size() == 1) {
17136 PreferredActivity cur = existing.get(0);
17137 if (DEBUG_PREFERRED) {
17138 Slog.i(TAG, "Checking replace of preferred:");
17139 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17140 if (!cur.mPref.mAlways) {
17141 Slog.i(TAG, " -- CUR; not mAlways!");
17143 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
17144 Slog.i(TAG, " -- CUR: mSet="
17145 + Arrays.toString(cur.mPref.mSetComponents));
17146 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
17147 Slog.i(TAG, " -- NEW: mMatch="
17148 + (match&IntentFilter.MATCH_CATEGORY_MASK));
17149 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
17150 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
17153 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17154 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17155 && cur.mPref.sameSet(set)) {
17156 // Setting the preferred activity to what it happens to be already
17157 if (DEBUG_PREFERRED) {
17158 Slog.i(TAG, "Replacing with same preferred activity "
17159 + cur.mPref.mShortComponent + " for user "
17161 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17167 if (existing != null) {
17168 if (DEBUG_PREFERRED) {
17169 Slog.i(TAG, existing.size() + " existing preferred matches for:");
17170 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17172 for (int i = 0; i < existing.size(); i++) {
17173 PreferredActivity pa = existing.get(i);
17174 if (DEBUG_PREFERRED) {
17175 Slog.i(TAG, "Removing existing preferred activity "
17176 + pa.mPref.mComponent + ":");
17177 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
17179 pir.removeFilter(pa);
17183 addPreferredActivityInternal(filter, match, set, activity, true, userId,
17184 "Replacing preferred");
17189 public void clearPackagePreferredActivities(String packageName) {
17190 final int uid = Binder.getCallingUid();
17192 synchronized (mPackages) {
17193 PackageParser.Package pkg = mPackages.get(packageName);
17194 if (pkg == null || pkg.applicationInfo.uid != uid) {
17195 if (mContext.checkCallingOrSelfPermission(
17196 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17197 != PackageManager.PERMISSION_GRANTED) {
17198 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17199 < Build.VERSION_CODES.FROYO) {
17200 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17201 + Binder.getCallingUid());
17204 mContext.enforceCallingOrSelfPermission(
17205 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17209 int user = UserHandle.getCallingUserId();
17210 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17211 scheduleWritePackageRestrictionsLocked(user);
17216 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17217 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17218 ArrayList<PreferredActivity> removed = null;
17219 boolean changed = false;
17220 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17221 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17222 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17223 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17226 Iterator<PreferredActivity> it = pir.filterIterator();
17227 while (it.hasNext()) {
17228 PreferredActivity pa = it.next();
17229 // Mark entry for removal only if it matches the package name
17230 // and the entry is of type "always".
17231 if (packageName == null ||
17232 (pa.mPref.mComponent.getPackageName().equals(packageName)
17233 && pa.mPref.mAlways)) {
17234 if (removed == null) {
17235 removed = new ArrayList<PreferredActivity>();
17240 if (removed != null) {
17241 for (int j=0; j<removed.size(); j++) {
17242 PreferredActivity pa = removed.get(j);
17243 pir.removeFilter(pa);
17249 postPreferredActivityChangedBroadcast(userId);
17254 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17255 private void clearIntentFilterVerificationsLPw(int userId) {
17256 final int packageCount = mPackages.size();
17257 for (int i = 0; i < packageCount; i++) {
17258 PackageParser.Package pkg = mPackages.valueAt(i);
17259 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17263 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17264 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17265 if (userId == UserHandle.USER_ALL) {
17266 if (mSettings.removeIntentFilterVerificationLPw(packageName,
17267 sUserManager.getUserIds())) {
17268 for (int oneUserId : sUserManager.getUserIds()) {
17269 scheduleWritePackageRestrictionsLocked(oneUserId);
17273 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17274 scheduleWritePackageRestrictionsLocked(userId);
17279 void clearDefaultBrowserIfNeeded(String packageName) {
17280 for (int oneUserId : sUserManager.getUserIds()) {
17281 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17282 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17283 if (packageName.equals(defaultBrowserPackageName)) {
17284 setDefaultBrowserPackageName(null, oneUserId);
17290 public void resetApplicationPreferences(int userId) {
17291 mContext.enforceCallingOrSelfPermission(
17292 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17293 final long identity = Binder.clearCallingIdentity();
17296 synchronized (mPackages) {
17297 clearPackagePreferredActivitiesLPw(null, userId);
17298 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17299 // TODO: We have to reset the default SMS and Phone. This requires
17300 // significant refactoring to keep all default apps in the package
17301 // manager (cleaner but more work) or have the services provide
17302 // callbacks to the package manager to request a default app reset.
17303 applyFactoryDefaultBrowserLPw(userId);
17304 clearIntentFilterVerificationsLPw(userId);
17305 primeDomainVerificationsLPw(userId);
17306 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17307 scheduleWritePackageRestrictionsLocked(userId);
17309 resetNetworkPolicies(userId);
17311 Binder.restoreCallingIdentity(identity);
17316 public int getPreferredActivities(List<IntentFilter> outFilters,
17317 List<ComponentName> outActivities, String packageName) {
17320 final int userId = UserHandle.getCallingUserId();
17322 synchronized (mPackages) {
17323 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17325 final Iterator<PreferredActivity> it = pir.filterIterator();
17326 while (it.hasNext()) {
17327 final PreferredActivity pa = it.next();
17328 if (packageName == null
17329 || (pa.mPref.mComponent.getPackageName().equals(packageName)
17330 && pa.mPref.mAlways)) {
17331 if (outFilters != null) {
17332 outFilters.add(new IntentFilter(pa));
17334 if (outActivities != null) {
17335 outActivities.add(pa.mPref.mComponent);
17346 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17348 int callingUid = Binder.getCallingUid();
17349 if (callingUid != Process.SYSTEM_UID) {
17350 throw new SecurityException(
17351 "addPersistentPreferredActivity can only be run by the system");
17353 if (filter.countActions() == 0) {
17354 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17357 synchronized (mPackages) {
17358 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17360 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17361 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17362 new PersistentPreferredActivity(filter, activity));
17363 scheduleWritePackageRestrictionsLocked(userId);
17364 postPreferredActivityChangedBroadcast(userId);
17369 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17370 int callingUid = Binder.getCallingUid();
17371 if (callingUid != Process.SYSTEM_UID) {
17372 throw new SecurityException(
17373 "clearPackagePersistentPreferredActivities can only be run by the system");
17375 ArrayList<PersistentPreferredActivity> removed = null;
17376 boolean changed = false;
17377 synchronized (mPackages) {
17378 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17379 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17380 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17382 if (userId != thisUserId) {
17385 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17386 while (it.hasNext()) {
17387 PersistentPreferredActivity ppa = it.next();
17388 // Mark entry for removal only if it matches the package name.
17389 if (ppa.mComponent.getPackageName().equals(packageName)) {
17390 if (removed == null) {
17391 removed = new ArrayList<PersistentPreferredActivity>();
17396 if (removed != null) {
17397 for (int j=0; j<removed.size(); j++) {
17398 PersistentPreferredActivity ppa = removed.get(j);
17399 ppir.removeFilter(ppa);
17406 scheduleWritePackageRestrictionsLocked(userId);
17407 postPreferredActivityChangedBroadcast(userId);
17413 * Common machinery for picking apart a restored XML blob and passing
17414 * it to a caller-supplied functor to be applied to the running system.
17416 private void restoreFromXml(XmlPullParser parser, int userId,
17417 String expectedStartTag, BlobXmlRestorer functor)
17418 throws IOException, XmlPullParserException {
17420 while ((type = parser.next()) != XmlPullParser.START_TAG
17421 && type != XmlPullParser.END_DOCUMENT) {
17423 if (type != XmlPullParser.START_TAG) {
17424 // oops didn't find a start tag?!
17425 if (DEBUG_BACKUP) {
17426 Slog.e(TAG, "Didn't find start tag during restore");
17430 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17431 // this is supposed to be TAG_PREFERRED_BACKUP
17432 if (!expectedStartTag.equals(parser.getName())) {
17433 if (DEBUG_BACKUP) {
17434 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17439 // skip interfering stuff, then we're aligned with the backing implementation
17440 while ((type = parser.next()) == XmlPullParser.TEXT) { }
17441 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17442 functor.apply(parser, userId);
17445 private interface BlobXmlRestorer {
17446 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17450 * Non-Binder method, support for the backup/restore mechanism: write the
17451 * full set of preferred activities in its canonical XML format. Returns the
17452 * XML output as a byte array, or null if there is none.
17455 public byte[] getPreferredActivityBackup(int userId) {
17456 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17457 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17460 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17462 final XmlSerializer serializer = new FastXmlSerializer();
17463 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17464 serializer.startDocument(null, true);
17465 serializer.startTag(null, TAG_PREFERRED_BACKUP);
17467 synchronized (mPackages) {
17468 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17471 serializer.endTag(null, TAG_PREFERRED_BACKUP);
17472 serializer.endDocument();
17473 serializer.flush();
17474 } catch (Exception e) {
17475 if (DEBUG_BACKUP) {
17476 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17481 return dataStream.toByteArray();
17485 public void restorePreferredActivities(byte[] backup, int userId) {
17486 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17487 throw new SecurityException("Only the system may call restorePreferredActivities()");
17491 final XmlPullParser parser = Xml.newPullParser();
17492 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17493 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17494 new BlobXmlRestorer() {
17496 public void apply(XmlPullParser parser, int userId)
17497 throws XmlPullParserException, IOException {
17498 synchronized (mPackages) {
17499 mSettings.readPreferredActivitiesLPw(parser, userId);
17503 } catch (Exception e) {
17504 if (DEBUG_BACKUP) {
17505 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17511 * Non-Binder method, support for the backup/restore mechanism: write the
17512 * default browser (etc) settings in its canonical XML format. Returns the default
17513 * browser XML representation as a byte array, or null if there is none.
17516 public byte[] getDefaultAppsBackup(int userId) {
17517 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17518 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17521 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17523 final XmlSerializer serializer = new FastXmlSerializer();
17524 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17525 serializer.startDocument(null, true);
17526 serializer.startTag(null, TAG_DEFAULT_APPS);
17528 synchronized (mPackages) {
17529 mSettings.writeDefaultAppsLPr(serializer, userId);
17532 serializer.endTag(null, TAG_DEFAULT_APPS);
17533 serializer.endDocument();
17534 serializer.flush();
17535 } catch (Exception e) {
17536 if (DEBUG_BACKUP) {
17537 Slog.e(TAG, "Unable to write default apps for backup", e);
17542 return dataStream.toByteArray();
17546 public void restoreDefaultApps(byte[] backup, int userId) {
17547 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17548 throw new SecurityException("Only the system may call restoreDefaultApps()");
17552 final XmlPullParser parser = Xml.newPullParser();
17553 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17554 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17555 new BlobXmlRestorer() {
17557 public void apply(XmlPullParser parser, int userId)
17558 throws XmlPullParserException, IOException {
17559 synchronized (mPackages) {
17560 mSettings.readDefaultAppsLPw(parser, userId);
17564 } catch (Exception e) {
17565 if (DEBUG_BACKUP) {
17566 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17572 public byte[] getIntentFilterVerificationBackup(int userId) {
17573 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17574 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
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_INTENT_FILTER_VERIFICATION);
17584 synchronized (mPackages) {
17585 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17588 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
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 restoreIntentFilterVerification(byte[] backup, int userId) {
17603 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17604 throw new SecurityException("Only the system may call restorePreferredActivities()");
17608 final XmlPullParser parser = Xml.newPullParser();
17609 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17610 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17611 new BlobXmlRestorer() {
17613 public void apply(XmlPullParser parser, int userId)
17614 throws XmlPullParserException, IOException {
17615 synchronized (mPackages) {
17616 mSettings.readAllDomainVerificationsLPr(parser, userId);
17617 mSettings.writeLPr();
17621 } catch (Exception e) {
17622 if (DEBUG_BACKUP) {
17623 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17629 public byte[] getPermissionGrantBackup(int userId) {
17630 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17631 throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17634 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17636 final XmlSerializer serializer = new FastXmlSerializer();
17637 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17638 serializer.startDocument(null, true);
17639 serializer.startTag(null, TAG_PERMISSION_BACKUP);
17641 synchronized (mPackages) {
17642 serializeRuntimePermissionGrantsLPr(serializer, userId);
17645 serializer.endTag(null, TAG_PERMISSION_BACKUP);
17646 serializer.endDocument();
17647 serializer.flush();
17648 } catch (Exception e) {
17649 if (DEBUG_BACKUP) {
17650 Slog.e(TAG, "Unable to write default apps for backup", e);
17655 return dataStream.toByteArray();
17659 public void restorePermissionGrants(byte[] backup, int userId) {
17660 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17661 throw new SecurityException("Only the system may call restorePermissionGrants()");
17665 final XmlPullParser parser = Xml.newPullParser();
17666 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17667 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17668 new BlobXmlRestorer() {
17670 public void apply(XmlPullParser parser, int userId)
17671 throws XmlPullParserException, IOException {
17672 synchronized (mPackages) {
17673 processRestoredPermissionGrantsLPr(parser, userId);
17677 } catch (Exception e) {
17678 if (DEBUG_BACKUP) {
17679 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17684 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17685 throws IOException {
17686 serializer.startTag(null, TAG_ALL_GRANTS);
17688 final int N = mSettings.mPackages.size();
17689 for (int i = 0; i < N; i++) {
17690 final PackageSetting ps = mSettings.mPackages.valueAt(i);
17691 boolean pkgGrantsKnown = false;
17693 PermissionsState packagePerms = ps.getPermissionsState();
17695 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17696 final int grantFlags = state.getFlags();
17697 // only look at grants that are not system/policy fixed
17698 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17699 final boolean isGranted = state.isGranted();
17700 // And only back up the user-twiddled state bits
17701 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17702 final String packageName = mSettings.mPackages.keyAt(i);
17703 if (!pkgGrantsKnown) {
17704 serializer.startTag(null, TAG_GRANT);
17705 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17706 pkgGrantsKnown = true;
17709 final boolean userSet =
17710 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17711 final boolean userFixed =
17712 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17713 final boolean revoke =
17714 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17716 serializer.startTag(null, TAG_PERMISSION);
17717 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17719 serializer.attribute(null, ATTR_IS_GRANTED, "true");
17722 serializer.attribute(null, ATTR_USER_SET, "true");
17725 serializer.attribute(null, ATTR_USER_FIXED, "true");
17728 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17730 serializer.endTag(null, TAG_PERMISSION);
17735 if (pkgGrantsKnown) {
17736 serializer.endTag(null, TAG_GRANT);
17740 serializer.endTag(null, TAG_ALL_GRANTS);
17743 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17744 throws XmlPullParserException, IOException {
17745 String pkgName = null;
17746 int outerDepth = parser.getDepth();
17748 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17749 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17750 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17754 final String tagName = parser.getName();
17755 if (tagName.equals(TAG_GRANT)) {
17756 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17757 if (DEBUG_BACKUP) {
17758 Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17760 } else if (tagName.equals(TAG_PERMISSION)) {
17762 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17763 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17765 int newFlagSet = 0;
17766 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17767 newFlagSet |= FLAG_PERMISSION_USER_SET;
17769 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17770 newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17772 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17773 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17775 if (DEBUG_BACKUP) {
17776 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName
17777 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17779 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17781 // Already installed so we apply the grant immediately
17782 if (DEBUG_BACKUP) {
17783 Slog.v(TAG, " + already installed; applying");
17785 PermissionsState perms = ps.getPermissionsState();
17786 BasePermission bp = mSettings.mPermissions.get(permName);
17789 perms.grantRuntimePermission(bp, userId);
17791 if (newFlagSet != 0) {
17792 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17796 // Need to wait for post-restore install to apply the grant
17797 if (DEBUG_BACKUP) {
17798 Slog.v(TAG, " - not yet installed; saving for later");
17800 mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17801 isGranted, newFlagSet, userId);
17804 PackageManagerService.reportSettingsProblem(Log.WARN,
17805 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17806 XmlUtils.skipCurrentTag(parser);
17810 scheduleWriteSettingsLocked();
17811 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17815 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17816 int sourceUserId, int targetUserId, int flags) {
17817 mContext.enforceCallingOrSelfPermission(
17818 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17819 int callingUid = Binder.getCallingUid();
17820 enforceOwnerRights(ownerPackage, callingUid);
17821 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17822 if (intentFilter.countActions() == 0) {
17823 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17826 synchronized (mPackages) {
17827 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17828 ownerPackage, targetUserId, flags);
17829 CrossProfileIntentResolver resolver =
17830 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17831 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17832 // We have all those whose filter is equal. Now checking if the rest is equal as well.
17833 if (existing != null) {
17834 int size = existing.size();
17835 for (int i = 0; i < size; i++) {
17836 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17841 resolver.addFilter(newFilter);
17842 scheduleWritePackageRestrictionsLocked(sourceUserId);
17847 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17848 mContext.enforceCallingOrSelfPermission(
17849 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17850 int callingUid = Binder.getCallingUid();
17851 enforceOwnerRights(ownerPackage, callingUid);
17852 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17853 synchronized (mPackages) {
17854 CrossProfileIntentResolver resolver =
17855 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17856 ArraySet<CrossProfileIntentFilter> set =
17857 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17858 for (CrossProfileIntentFilter filter : set) {
17859 if (filter.getOwnerPackage().equals(ownerPackage)) {
17860 resolver.removeFilter(filter);
17863 scheduleWritePackageRestrictionsLocked(sourceUserId);
17867 // Enforcing that callingUid is owning pkg on userId
17868 private void enforceOwnerRights(String pkg, int callingUid) {
17869 // The system owns everything.
17870 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17873 int callingUserId = UserHandle.getUserId(callingUid);
17874 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17876 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17879 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17880 throw new SecurityException("Calling uid " + callingUid
17881 + " does not own package " + pkg);
17886 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17887 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17890 private Intent getHomeIntent() {
17891 Intent intent = new Intent(Intent.ACTION_MAIN);
17892 intent.addCategory(Intent.CATEGORY_HOME);
17893 intent.addCategory(Intent.CATEGORY_DEFAULT);
17897 private IntentFilter getHomeFilter() {
17898 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17899 filter.addCategory(Intent.CATEGORY_HOME);
17900 filter.addCategory(Intent.CATEGORY_DEFAULT);
17904 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17906 Intent intent = getHomeIntent();
17907 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17908 PackageManager.GET_META_DATA, userId);
17909 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17910 true, false, false, userId);
17912 allHomeCandidates.clear();
17913 if (list != null) {
17914 for (ResolveInfo ri : list) {
17915 allHomeCandidates.add(ri);
17918 return (preferred == null || preferred.activityInfo == null)
17920 : new ComponentName(preferred.activityInfo.packageName,
17921 preferred.activityInfo.name);
17925 public void setHomeActivity(ComponentName comp, int userId) {
17926 ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17927 getHomeActivitiesAsUser(homeActivities, userId);
17929 boolean found = false;
17931 final int size = homeActivities.size();
17932 final ComponentName[] set = new ComponentName[size];
17933 for (int i = 0; i < size; i++) {
17934 final ResolveInfo candidate = homeActivities.get(i);
17935 final ActivityInfo info = candidate.activityInfo;
17936 final ComponentName activityName = new ComponentName(info.packageName, info.name);
17937 set[i] = activityName;
17938 if (!found && activityName.equals(comp)) {
17943 throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17946 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17947 set, comp, userId);
17950 private @Nullable String getSetupWizardPackageName() {
17951 final Intent intent = new Intent(Intent.ACTION_MAIN);
17952 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17954 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17955 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17956 | MATCH_DISABLED_COMPONENTS,
17957 UserHandle.myUserId());
17958 if (matches.size() == 1) {
17959 return matches.get(0).getComponentInfo().packageName;
17961 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17962 + ": matches=" + matches);
17967 private @Nullable String getStorageManagerPackageName() {
17968 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17970 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17971 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17972 | MATCH_DISABLED_COMPONENTS,
17973 UserHandle.myUserId());
17974 if (matches.size() == 1) {
17975 return matches.get(0).getComponentInfo().packageName;
17977 Slog.e(TAG, "There should probably be exactly one storage manager; found "
17978 + matches.size() + ": matches=" + matches);
17984 public void setApplicationEnabledSetting(String appPackageName,
17985 int newState, int flags, int userId, String callingPackage) {
17986 if (!sUserManager.exists(userId)) return;
17987 if (callingPackage == null) {
17988 callingPackage = Integer.toString(Binder.getCallingUid());
17990 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17994 public void setComponentEnabledSetting(ComponentName componentName,
17995 int newState, int flags, int userId) {
17996 if (!sUserManager.exists(userId)) return;
17997 setEnabledSetting(componentName.getPackageName(),
17998 componentName.getClassName(), newState, flags, userId, null);
18001 private void setEnabledSetting(final String packageName, String className, int newState,
18002 final int flags, int userId, String callingPackage) {
18003 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18004 || newState == COMPONENT_ENABLED_STATE_ENABLED
18005 || newState == COMPONENT_ENABLED_STATE_DISABLED
18006 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18007 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18008 throw new IllegalArgumentException("Invalid new component state: "
18011 PackageSetting pkgSetting;
18012 final int uid = Binder.getCallingUid();
18013 final int permission;
18014 if (uid == Process.SYSTEM_UID) {
18015 permission = PackageManager.PERMISSION_GRANTED;
18017 permission = mContext.checkCallingOrSelfPermission(
18018 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18020 enforceCrossUserPermission(uid, userId,
18021 false /* requireFullPermission */, true /* checkShell */, "set enabled");
18022 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18023 boolean sendNow = false;
18024 boolean isApp = (className == null);
18025 String componentName = isApp ? packageName : className;
18026 int packageUid = -1;
18027 ArrayList<String> components;
18030 synchronized (mPackages) {
18031 pkgSetting = mSettings.mPackages.get(packageName);
18032 if (pkgSetting == null) {
18033 if (className == null) {
18034 throw new IllegalArgumentException("Unknown package: " + packageName);
18036 throw new IllegalArgumentException(
18037 "Unknown component: " + packageName + "/" + className);
18041 // Limit who can change which apps
18042 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18043 // Don't allow apps that don't have permission to modify other apps
18044 if (!allowedByPermission) {
18045 throw new SecurityException(
18046 "Permission Denial: attempt to change component state from pid="
18047 + Binder.getCallingPid()
18048 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18050 // Don't allow changing protected packages.
18051 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18052 throw new SecurityException("Cannot disable a protected package: " + packageName);
18056 synchronized (mPackages) {
18057 if (uid == Process.SHELL_UID) {
18058 // Shell can only change whole packages between ENABLED and DISABLED_USER states
18059 int oldState = pkgSetting.getEnabled(userId);
18060 if (className == null
18062 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18063 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18064 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18066 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18067 || newState == COMPONENT_ENABLED_STATE_DEFAULT
18068 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18071 throw new SecurityException(
18072 "Shell cannot change component state for " + packageName + "/"
18073 + className + " to " + newState);
18076 if (className == null) {
18077 // We're dealing with an application/package level state change
18078 if (pkgSetting.getEnabled(userId) == newState) {
18082 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18083 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18084 // Don't care about who enables an app.
18085 callingPackage = null;
18087 pkgSetting.setEnabled(newState, userId, callingPackage);
18088 // pkgSetting.pkg.mSetEnabled = newState;
18090 // We're dealing with a component level state change
18091 // First, verify that this is a valid class name.
18092 PackageParser.Package pkg = pkgSetting.pkg;
18093 if (pkg == null || !pkg.hasComponentClassName(className)) {
18095 pkg.applicationInfo.targetSdkVersion >=
18096 Build.VERSION_CODES.JELLY_BEAN) {
18097 throw new IllegalArgumentException("Component class " + className
18098 + " does not exist in " + packageName);
18100 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18101 + className + " does not exist in " + packageName);
18104 switch (newState) {
18105 case COMPONENT_ENABLED_STATE_ENABLED:
18106 if (!pkgSetting.enableComponentLPw(className, userId)) {
18110 case COMPONENT_ENABLED_STATE_DISABLED:
18111 if (!pkgSetting.disableComponentLPw(className, userId)) {
18115 case COMPONENT_ENABLED_STATE_DEFAULT:
18116 if (!pkgSetting.restoreComponentLPw(className, userId)) {
18121 Slog.e(TAG, "Invalid new component state: " + newState);
18125 scheduleWritePackageRestrictionsLocked(userId);
18126 components = mPendingBroadcasts.get(userId, packageName);
18127 final boolean newPackage = components == null;
18129 components = new ArrayList<String>();
18131 if (!components.contains(componentName)) {
18132 components.add(componentName);
18134 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18136 // Purge entry from pending broadcast list if another one exists already
18137 // since we are sending one right away.
18138 mPendingBroadcasts.remove(userId, packageName);
18141 mPendingBroadcasts.put(userId, packageName, components);
18143 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18144 // Schedule a message
18145 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18150 long callingId = Binder.clearCallingIdentity();
18153 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18154 sendPackageChangedBroadcast(packageName,
18155 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18158 Binder.restoreCallingIdentity(callingId);
18163 public void flushPackageRestrictionsAsUser(int userId) {
18164 if (!sUserManager.exists(userId)) {
18167 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18168 false /* checkShell */, "flushPackageRestrictions");
18169 synchronized (mPackages) {
18170 mSettings.writePackageRestrictionsLPr(userId);
18171 mDirtyUsers.remove(userId);
18172 if (mDirtyUsers.isEmpty()) {
18173 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18178 private void sendPackageChangedBroadcast(String packageName,
18179 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18181 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18183 Bundle extras = new Bundle(4);
18184 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18185 String nameList[] = new String[componentNames.size()];
18186 componentNames.toArray(nameList);
18187 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18188 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18189 extras.putInt(Intent.EXTRA_UID, packageUid);
18190 // If this is not reporting a change of the overall package, then only send it
18191 // to registered receivers. We don't want to launch a swath of apps for every
18192 // little component state change.
18193 final int flags = !componentNames.contains(packageName)
18194 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18195 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null,
18196 new int[] {UserHandle.getUserId(packageUid)});
18200 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18201 if (!sUserManager.exists(userId)) return;
18202 final int uid = Binder.getCallingUid();
18203 final int permission = mContext.checkCallingOrSelfPermission(
18204 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18205 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18206 enforceCrossUserPermission(uid, userId,
18207 true /* requireFullPermission */, true /* checkShell */, "stop package");
18209 synchronized (mPackages) {
18210 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18211 allowedByPermission, uid, userId)) {
18212 scheduleWritePackageRestrictionsLocked(userId);
18218 public String getInstallerPackageName(String packageName) {
18220 synchronized (mPackages) {
18221 return mSettings.getInstallerPackageNameLPr(packageName);
18225 public boolean isOrphaned(String packageName) {
18227 synchronized (mPackages) {
18228 return mSettings.isOrphaned(packageName);
18233 public int getApplicationEnabledSetting(String packageName, int userId) {
18234 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18235 int uid = Binder.getCallingUid();
18236 enforceCrossUserPermission(uid, userId,
18237 false /* requireFullPermission */, false /* checkShell */, "get enabled");
18239 synchronized (mPackages) {
18240 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18245 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18246 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18247 int uid = Binder.getCallingUid();
18248 enforceCrossUserPermission(uid, userId,
18249 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18251 synchronized (mPackages) {
18252 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18257 public void enterSafeMode() {
18258 enforceSystemOrRoot("Only the system can request entering safe mode");
18260 if (!mSystemReady) {
18266 public void systemReady() {
18267 mSystemReady = true;
18269 // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18270 // disabled after already being started.
18271 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18272 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18274 // Read the compatibilty setting when the system is ready.
18275 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18276 mContext.getContentResolver(),
18277 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18278 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18279 if (DEBUG_SETTINGS) {
18280 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18283 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18285 synchronized (mPackages) {
18286 // Verify that all of the preferred activity components actually
18287 // exist. It is possible for applications to be updated and at
18288 // that point remove a previously declared activity component that
18289 // had been set as a preferred activity. We try to clean this up
18290 // the next time we encounter that preferred activity, but it is
18291 // possible for the user flow to never be able to return to that
18292 // situation so here we do a sanity check to make sure we haven't
18293 // left any junk around.
18294 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18295 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18296 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18298 for (PreferredActivity pa : pir.filterSet()) {
18299 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18303 if (removed.size() > 0) {
18304 for (int r=0; r<removed.size(); r++) {
18305 PreferredActivity pa = removed.get(r);
18306 Slog.w(TAG, "Removing dangling preferred activity: "
18307 + pa.mPref.mComponent);
18308 pir.removeFilter(pa);
18310 mSettings.writePackageRestrictionsLPr(
18311 mSettings.mPreferredActivities.keyAt(i));
18315 for (int userId : UserManagerService.getInstance().getUserIds()) {
18316 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18317 grantPermissionsUserIds = ArrayUtils.appendInt(
18318 grantPermissionsUserIds, userId);
18322 sUserManager.systemReady();
18324 // If we upgraded grant all default permissions before kicking off.
18325 for (int userId : grantPermissionsUserIds) {
18326 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18329 // If we did not grant default permissions, we preload from this the
18330 // default permission exceptions lazily to ensure we don't hit the
18331 // disk on a new user creation.
18332 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18333 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18336 // Kick off any messages waiting for system ready
18337 if (mPostSystemReadyMessages != null) {
18338 for (Message msg : mPostSystemReadyMessages) {
18339 msg.sendToTarget();
18341 mPostSystemReadyMessages = null;
18344 // Watch for external volumes that come and go over time
18345 final StorageManager storage = mContext.getSystemService(StorageManager.class);
18346 storage.registerListener(mStorageListener);
18348 mInstallerService.systemReady();
18349 mPackageDexOptimizer.systemReady();
18351 MountServiceInternal mountServiceInternal = LocalServices.getService(
18352 MountServiceInternal.class);
18353 mountServiceInternal.addExternalStoragePolicy(
18354 new MountServiceInternal.ExternalStorageMountPolicy() {
18356 public int getMountMode(int uid, String packageName) {
18357 if (Process.isIsolated(uid)) {
18358 return Zygote.MOUNT_EXTERNAL_NONE;
18360 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18361 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18363 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18364 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18366 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18367 return Zygote.MOUNT_EXTERNAL_READ;
18369 return Zygote.MOUNT_EXTERNAL_WRITE;
18373 public boolean hasExternalStorage(int uid, String packageName) {
18378 // Now that we're mostly running, clean up stale users and apps
18379 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18380 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18384 public boolean isSafeMode() {
18389 public boolean hasSystemUidErrors() {
18390 return mHasSystemUidErrors;
18393 static String arrayToString(int[] array) {
18394 StringBuffer buf = new StringBuffer(128);
18396 if (array != null) {
18397 for (int i=0; i<array.length; i++) {
18398 if (i > 0) buf.append(", ");
18399 buf.append(array[i]);
18403 return buf.toString();
18406 static class DumpState {
18407 public static final int DUMP_LIBS = 1 << 0;
18408 public static final int DUMP_FEATURES = 1 << 1;
18409 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18410 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18411 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18412 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18413 public static final int DUMP_PERMISSIONS = 1 << 6;
18414 public static final int DUMP_PACKAGES = 1 << 7;
18415 public static final int DUMP_SHARED_USERS = 1 << 8;
18416 public static final int DUMP_MESSAGES = 1 << 9;
18417 public static final int DUMP_PROVIDERS = 1 << 10;
18418 public static final int DUMP_VERIFIERS = 1 << 11;
18419 public static final int DUMP_PREFERRED = 1 << 12;
18420 public static final int DUMP_PREFERRED_XML = 1 << 13;
18421 public static final int DUMP_KEYSETS = 1 << 14;
18422 public static final int DUMP_VERSION = 1 << 15;
18423 public static final int DUMP_INSTALLS = 1 << 16;
18424 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18425 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18426 public static final int DUMP_FROZEN = 1 << 19;
18427 public static final int DUMP_DEXOPT = 1 << 20;
18428 public static final int DUMP_COMPILER_STATS = 1 << 21;
18430 public static final int OPTION_SHOW_FILTERS = 1 << 0;
18432 private int mTypes;
18434 private int mOptions;
18436 private boolean mTitlePrinted;
18438 private SharedUserSetting mSharedUser;
18440 public boolean isDumping(int type) {
18441 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18445 return (mTypes & type) != 0;
18448 public void setDump(int type) {
18452 public boolean isOptionEnabled(int option) {
18453 return (mOptions & option) != 0;
18456 public void setOptionEnabled(int option) {
18457 mOptions |= option;
18460 public boolean onTitlePrinted() {
18461 final boolean printed = mTitlePrinted;
18462 mTitlePrinted = true;
18466 public boolean getTitlePrinted() {
18467 return mTitlePrinted;
18470 public void setTitlePrinted(boolean enabled) {
18471 mTitlePrinted = enabled;
18474 public SharedUserSetting getSharedUser() {
18475 return mSharedUser;
18478 public void setSharedUser(SharedUserSetting user) {
18479 mSharedUser = user;
18484 public void onShellCommand(FileDescriptor in, FileDescriptor out,
18485 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18486 (new PackageManagerShellCommand(this)).exec(
18487 this, in, out, err, args, resultReceiver);
18491 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18492 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18493 != PackageManager.PERMISSION_GRANTED) {
18494 pw.println("Permission Denial: can't dump ActivityManager from from pid="
18495 + Binder.getCallingPid()
18496 + ", uid=" + Binder.getCallingUid()
18497 + " without permission "
18498 + android.Manifest.permission.DUMP);
18502 DumpState dumpState = new DumpState();
18503 boolean fullPreferred = false;
18504 boolean checkin = false;
18506 String packageName = null;
18507 ArraySet<String> permissionNames = null;
18510 while (opti < args.length) {
18511 String opt = args[opti];
18512 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18517 if ("-a".equals(opt)) {
18518 // Right now we only know how to print all.
18519 } else if ("-h".equals(opt)) {
18520 pw.println("Package manager dump options:");
18521 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
18522 pw.println(" --checkin: dump for a checkin");
18523 pw.println(" -f: print details of intent filters");
18524 pw.println(" -h: print this help");
18525 pw.println(" cmd may be one of:");
18526 pw.println(" l[ibraries]: list known shared libraries");
18527 pw.println(" f[eatures]: list device features");
18528 pw.println(" k[eysets]: print known keysets");
18529 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18530 pw.println(" perm[issions]: dump permissions");
18531 pw.println(" permission [name ...]: dump declaration and use of given permission");
18532 pw.println(" pref[erred]: print preferred package settings");
18533 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
18534 pw.println(" prov[iders]: dump content providers");
18535 pw.println(" p[ackages]: dump installed packages");
18536 pw.println(" s[hared-users]: dump shared user IDs");
18537 pw.println(" m[essages]: print collected runtime messages");
18538 pw.println(" v[erifiers]: print package verifier info");
18539 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
18540 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18541 pw.println(" version: print database version info");
18542 pw.println(" write: write current settings now");
18543 pw.println(" installs: details about install sessions");
18544 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
18545 pw.println(" dexopt: dump dexopt state");
18546 pw.println(" compiler-stats: dump compiler statistics");
18547 pw.println(" <package.name>: info about given package");
18549 } else if ("--checkin".equals(opt)) {
18551 } else if ("-f".equals(opt)) {
18552 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18554 pw.println("Unknown argument: " + opt + "; use -h for help");
18558 // Is the caller requesting to dump a particular piece of data?
18559 if (opti < args.length) {
18560 String cmd = args[opti];
18562 // Is this a package name?
18563 if ("android".equals(cmd) || cmd.contains(".")) {
18565 // When dumping a single package, we always dump all of its
18566 // filter information since the amount of data will be reasonable.
18567 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18568 } else if ("check-permission".equals(cmd)) {
18569 if (opti >= args.length) {
18570 pw.println("Error: check-permission missing permission argument");
18573 String perm = args[opti];
18575 if (opti >= args.length) {
18576 pw.println("Error: check-permission missing package argument");
18579 String pkg = args[opti];
18581 int user = UserHandle.getUserId(Binder.getCallingUid());
18582 if (opti < args.length) {
18584 user = Integer.parseInt(args[opti]);
18585 } catch (NumberFormatException e) {
18586 pw.println("Error: check-permission user argument is not a number: "
18591 pw.println(checkPermission(perm, pkg, user));
18593 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18594 dumpState.setDump(DumpState.DUMP_LIBS);
18595 } else if ("f".equals(cmd) || "features".equals(cmd)) {
18596 dumpState.setDump(DumpState.DUMP_FEATURES);
18597 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18598 if (opti >= args.length) {
18599 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18600 | DumpState.DUMP_SERVICE_RESOLVERS
18601 | DumpState.DUMP_RECEIVER_RESOLVERS
18602 | DumpState.DUMP_CONTENT_RESOLVERS);
18604 while (opti < args.length) {
18605 String name = args[opti];
18606 if ("a".equals(name) || "activity".equals(name)) {
18607 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18608 } else if ("s".equals(name) || "service".equals(name)) {
18609 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18610 } else if ("r".equals(name) || "receiver".equals(name)) {
18611 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18612 } else if ("c".equals(name) || "content".equals(name)) {
18613 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18615 pw.println("Error: unknown resolver table type: " + name);
18621 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18622 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18623 } else if ("permission".equals(cmd)) {
18624 if (opti >= args.length) {
18625 pw.println("Error: permission requires permission name");
18628 permissionNames = new ArraySet<>();
18629 while (opti < args.length) {
18630 permissionNames.add(args[opti]);
18633 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18634 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18635 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18636 dumpState.setDump(DumpState.DUMP_PREFERRED);
18637 } else if ("preferred-xml".equals(cmd)) {
18638 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18639 if (opti < args.length && "--full".equals(args[opti])) {
18640 fullPreferred = true;
18643 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18644 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18645 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18646 dumpState.setDump(DumpState.DUMP_PACKAGES);
18647 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18648 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18649 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18650 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18651 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18652 dumpState.setDump(DumpState.DUMP_MESSAGES);
18653 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18654 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18655 } else if ("i".equals(cmd) || "ifv".equals(cmd)
18656 || "intent-filter-verifiers".equals(cmd)) {
18657 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18658 } else if ("version".equals(cmd)) {
18659 dumpState.setDump(DumpState.DUMP_VERSION);
18660 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18661 dumpState.setDump(DumpState.DUMP_KEYSETS);
18662 } else if ("installs".equals(cmd)) {
18663 dumpState.setDump(DumpState.DUMP_INSTALLS);
18664 } else if ("frozen".equals(cmd)) {
18665 dumpState.setDump(DumpState.DUMP_FROZEN);
18666 } else if ("dexopt".equals(cmd)) {
18667 dumpState.setDump(DumpState.DUMP_DEXOPT);
18668 } else if ("compiler-stats".equals(cmd)) {
18669 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18670 } else if ("write".equals(cmd)) {
18671 synchronized (mPackages) {
18672 mSettings.writeLPr();
18673 pw.println("Settings written.");
18680 pw.println("vers,1");
18684 synchronized (mPackages) {
18685 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18687 if (dumpState.onTitlePrinted())
18689 pw.println("Database versions:");
18690 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
18694 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18696 if (dumpState.onTitlePrinted())
18698 pw.println("Verifiers:");
18699 pw.print(" Required: ");
18700 pw.print(mRequiredVerifierPackage);
18701 pw.print(" (uid=");
18702 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18703 UserHandle.USER_SYSTEM));
18705 } else if (mRequiredVerifierPackage != null) {
18706 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18708 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18709 UserHandle.USER_SYSTEM));
18713 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18714 packageName == null) {
18715 if (mIntentFilterVerifierComponent != null) {
18716 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18718 if (dumpState.onTitlePrinted())
18720 pw.println("Intent Filter Verifier:");
18721 pw.print(" Using: ");
18722 pw.print(verifierPackageName);
18723 pw.print(" (uid=");
18724 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18725 UserHandle.USER_SYSTEM));
18727 } else if (verifierPackageName != null) {
18728 pw.print("ifv,"); pw.print(verifierPackageName);
18730 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18731 UserHandle.USER_SYSTEM));
18735 pw.println("No Intent Filter Verifier available!");
18739 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18740 boolean printedHeader = false;
18741 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18742 while (it.hasNext()) {
18743 String name = it.next();
18744 SharedLibraryEntry ent = mSharedLibraries.get(name);
18746 if (!printedHeader) {
18747 if (dumpState.onTitlePrinted())
18749 pw.println("Libraries:");
18750 printedHeader = true;
18760 if (ent.path != null) {
18762 pw.print("(jar) ");
18763 pw.print(ent.path);
18766 pw.print(ent.path);
18770 pw.print("(apk) ");
18781 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18782 if (dumpState.onTitlePrinted())
18785 pw.println("Features:");
18788 for (FeatureInfo feat : mAvailableFeatures.values()) {
18791 pw.print(feat.name);
18793 pw.println(feat.version);
18796 pw.print(feat.name);
18797 if (feat.version > 0) {
18798 pw.print(" version=");
18799 pw.print(feat.version);
18806 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18807 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18808 : "Activity Resolver Table:", " ", packageName,
18809 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18810 dumpState.setTitlePrinted(true);
18813 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18814 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18815 : "Receiver Resolver Table:", " ", packageName,
18816 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18817 dumpState.setTitlePrinted(true);
18820 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18821 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18822 : "Service Resolver Table:", " ", packageName,
18823 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18824 dumpState.setTitlePrinted(true);
18827 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18828 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18829 : "Provider Resolver Table:", " ", packageName,
18830 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18831 dumpState.setTitlePrinted(true);
18835 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18836 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18837 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18838 int user = mSettings.mPreferredActivities.keyAt(i);
18840 dumpState.getTitlePrinted()
18841 ? "\nPreferred Activities User " + user + ":"
18842 : "Preferred Activities User " + user + ":", " ",
18843 packageName, true, false)) {
18844 dumpState.setTitlePrinted(true);
18849 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18851 FileOutputStream fout = new FileOutputStream(fd);
18852 BufferedOutputStream str = new BufferedOutputStream(fout);
18853 XmlSerializer serializer = new FastXmlSerializer();
18855 serializer.setOutput(str, StandardCharsets.UTF_8.name());
18856 serializer.startDocument(null, true);
18857 serializer.setFeature(
18858 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18859 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18860 serializer.endDocument();
18861 serializer.flush();
18862 } catch (IllegalArgumentException e) {
18863 pw.println("Failed writing: " + e);
18864 } catch (IllegalStateException e) {
18865 pw.println("Failed writing: " + e);
18866 } catch (IOException e) {
18867 pw.println("Failed writing: " + e);
18872 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18873 && packageName == null) {
18875 int count = mSettings.mPackages.size();
18877 pw.println("No applications!");
18880 final String prefix = " ";
18881 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18882 if (allPackageSettings.size() == 0) {
18883 pw.println("No domain preferred apps!");
18886 pw.println("App verification status:");
18889 for (PackageSetting ps : allPackageSettings) {
18890 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18891 if (ivi == null || ivi.getPackageName() == null) continue;
18892 pw.println(prefix + "Package: " + ivi.getPackageName());
18893 pw.println(prefix + "Domains: " + ivi.getDomainsString());
18894 pw.println(prefix + "Status: " + ivi.getStatusString());
18899 pw.println(prefix + "No app verification established.");
18902 for (int userId : sUserManager.getUserIds()) {
18903 pw.println("App linkages for user " + userId + ":");
18906 for (PackageSetting ps : allPackageSettings) {
18907 final long status = ps.getDomainVerificationStatusForUser(userId);
18908 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18911 pw.println(prefix + "Package: " + ps.name);
18912 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18913 String statusStr = IntentFilterVerificationInfo.
18914 getStatusStringFromValue(status);
18915 pw.println(prefix + "Status: " + statusStr);
18920 pw.println(prefix + "No configured app linkages.");
18928 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18929 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18930 if (packageName == null && permissionNames == null) {
18931 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18933 if (dumpState.onTitlePrinted())
18935 pw.println("AppOp Permissions:");
18937 pw.print(" AppOp Permission ");
18938 pw.print(mAppOpPermissionPackages.keyAt(iperm));
18940 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18941 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18942 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
18948 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18949 boolean printedSomething = false;
18950 for (PackageParser.Provider p : mProviders.mProviders.values()) {
18951 if (packageName != null && !packageName.equals(p.info.packageName)) {
18954 if (!printedSomething) {
18955 if (dumpState.onTitlePrinted())
18957 pw.println("Registered ContentProviders:");
18958 printedSomething = true;
18960 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
18961 pw.print(" "); pw.println(p.toString());
18963 printedSomething = false;
18964 for (Map.Entry<String, PackageParser.Provider> entry :
18965 mProvidersByAuthority.entrySet()) {
18966 PackageParser.Provider p = entry.getValue();
18967 if (packageName != null && !packageName.equals(p.info.packageName)) {
18970 if (!printedSomething) {
18971 if (dumpState.onTitlePrinted())
18973 pw.println("ContentProvider Authorities:");
18974 printedSomething = true;
18976 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
18977 pw.print(" "); pw.println(p.toString());
18978 if (p.info != null && p.info.applicationInfo != null) {
18979 final String appInfo = p.info.applicationInfo.toString();
18980 pw.print(" applicationInfo="); pw.println(appInfo);
18985 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18986 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18989 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18990 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18993 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18994 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18997 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18998 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19001 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19002 // XXX should handle packageName != null by dumping only install data that
19003 // the given package is involved with.
19004 if (dumpState.onTitlePrinted()) pw.println();
19005 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
19008 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19009 // XXX should handle packageName != null by dumping only install data that
19010 // the given package is involved with.
19011 if (dumpState.onTitlePrinted()) pw.println();
19013 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19015 ipw.println("Frozen packages:");
19016 ipw.increaseIndent();
19017 if (mFrozenPackages.size() == 0) {
19018 ipw.println("(none)");
19020 for (int i = 0; i < mFrozenPackages.size(); i++) {
19021 ipw.println(mFrozenPackages.valueAt(i));
19024 ipw.decreaseIndent();
19027 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19028 if (dumpState.onTitlePrinted()) pw.println();
19029 dumpDexoptStateLPr(pw, packageName);
19032 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19033 if (dumpState.onTitlePrinted()) pw.println();
19034 dumpCompilerStatsLPr(pw, packageName);
19037 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19038 if (dumpState.onTitlePrinted()) pw.println();
19039 mSettings.dumpReadMessagesLPr(pw, dumpState);
19042 pw.println("Package warning messages:");
19043 BufferedReader in = null;
19044 String line = null;
19046 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19047 while ((line = in.readLine()) != null) {
19048 if (line.contains("ignored: updated version")) continue;
19051 } catch (IOException ignored) {
19053 IoUtils.closeQuietly(in);
19057 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19058 BufferedReader in = null;
19059 String line = null;
19061 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19062 while ((line = in.readLine()) != null) {
19063 if (line.contains("ignored: updated version")) continue;
19067 } catch (IOException ignored) {
19069 IoUtils.closeQuietly(in);
19075 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19076 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19078 ipw.println("Dexopt state:");
19079 ipw.increaseIndent();
19080 Collection<PackageParser.Package> packages = null;
19081 if (packageName != null) {
19082 PackageParser.Package targetPackage = mPackages.get(packageName);
19083 if (targetPackage != null) {
19084 packages = Collections.singletonList(targetPackage);
19086 ipw.println("Unable to find package: " + packageName);
19090 packages = mPackages.values();
19093 for (PackageParser.Package pkg : packages) {
19094 ipw.println("[" + pkg.packageName + "]");
19095 ipw.increaseIndent();
19096 mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19097 ipw.decreaseIndent();
19101 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19102 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19104 ipw.println("Compiler stats:");
19105 ipw.increaseIndent();
19106 Collection<PackageParser.Package> packages = null;
19107 if (packageName != null) {
19108 PackageParser.Package targetPackage = mPackages.get(packageName);
19109 if (targetPackage != null) {
19110 packages = Collections.singletonList(targetPackage);
19112 ipw.println("Unable to find package: " + packageName);
19116 packages = mPackages.values();
19119 for (PackageParser.Package pkg : packages) {
19120 ipw.println("[" + pkg.packageName + "]");
19121 ipw.increaseIndent();
19123 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19124 if (stats == null) {
19125 ipw.println("(No recorded stats)");
19129 ipw.decreaseIndent();
19133 private String dumpDomainString(String packageName) {
19134 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19136 List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19138 ArraySet<String> result = new ArraySet<>();
19139 if (iviList.size() > 0) {
19140 for (IntentFilterVerificationInfo ivi : iviList) {
19141 for (String host : ivi.getDomains()) {
19146 if (filters != null && filters.size() > 0) {
19147 for (IntentFilter filter : filters) {
19148 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19149 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19150 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19151 result.addAll(filter.getHostsList());
19156 StringBuilder sb = new StringBuilder(result.size() * 16);
19157 for (String domain : result) {
19158 if (sb.length() > 0) sb.append(" ");
19161 return sb.toString();
19164 // ------- apps on sdcard specific code -------
19165 static final boolean DEBUG_SD_INSTALL = false;
19167 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19169 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19171 private boolean mMediaMounted = false;
19173 static String getEncryptKey() {
19175 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19176 SD_ENCRYPTION_KEYSTORE_NAME);
19177 if (sdEncKey == null) {
19178 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19179 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19180 if (sdEncKey == null) {
19181 Slog.e(TAG, "Failed to create encryption keys");
19186 } catch (NoSuchAlgorithmException nsae) {
19187 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19189 } catch (IOException ioe) {
19190 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19196 * Update media status on PackageManager.
19199 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19200 int callingUid = Binder.getCallingUid();
19201 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19202 throw new SecurityException("Media status can only be updated by the system");
19204 // reader; this apparently protects mMediaMounted, but should probably
19205 // be a different lock in that case.
19206 synchronized (mPackages) {
19207 Log.i(TAG, "Updating external media status from "
19208 + (mMediaMounted ? "mounted" : "unmounted") + " to "
19209 + (mediaStatus ? "mounted" : "unmounted"));
19210 if (DEBUG_SD_INSTALL)
19211 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19212 + ", mMediaMounted=" + mMediaMounted);
19213 if (mediaStatus == mMediaMounted) {
19214 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19216 mHandler.sendMessage(msg);
19219 mMediaMounted = mediaStatus;
19221 // Queue up an async operation since the package installation may take a
19223 mHandler.post(new Runnable() {
19224 public void run() {
19225 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19231 * Called by MountService when the initial ASECs to scan are available.
19232 * Should block until all the ASEC containers are finished being scanned.
19234 public void scanAvailableAsecs() {
19235 updateExternalMediaStatusInner(true, false, false);
19239 * Collect information of applications on external media, map them against
19240 * existing containers and update information based on current mount status.
19241 * Please note that we always have to report status if reportStatus has been
19242 * set to true especially when unloading packages.
19244 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19245 boolean externalStorage) {
19246 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19247 int[] uidArr = EmptyArray.INT;
19249 final String[] list = PackageHelper.getSecureContainerList();
19250 if (ArrayUtils.isEmpty(list)) {
19251 Log.i(TAG, "No secure containers found");
19253 // Process list of secure containers and categorize them
19254 // as active or stale based on their package internal state.
19257 synchronized (mPackages) {
19258 for (String cid : list) {
19259 // Leave stages untouched for now; installer service owns them
19260 if (PackageInstallerService.isStageName(cid)) continue;
19262 if (DEBUG_SD_INSTALL)
19263 Log.i(TAG, "Processing container " + cid);
19264 String pkgName = getAsecPackageName(cid);
19265 if (pkgName == null) {
19266 Slog.i(TAG, "Found stale container " + cid + " with no package name");
19269 if (DEBUG_SD_INSTALL)
19270 Log.i(TAG, "Looking for pkg : " + pkgName);
19272 final PackageSetting ps = mSettings.mPackages.get(pkgName);
19274 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19279 * Skip packages that are not external if we're unmounting
19280 * external storage.
19282 if (externalStorage && !isMounted && !isExternal(ps)) {
19286 final AsecInstallArgs args = new AsecInstallArgs(cid,
19287 getAppDexInstructionSets(ps), ps.isForwardLocked());
19288 // The package status is changed only if the code path
19289 // matches between settings and the container id.
19290 if (ps.codePathString != null
19291 && ps.codePathString.startsWith(args.getCodePath())) {
19292 if (DEBUG_SD_INSTALL) {
19293 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19294 + " at code path: " + ps.codePathString);
19297 // We do have a valid package installed on sdcard
19298 processCids.put(args, ps.codePathString);
19299 final int uid = ps.appId;
19301 uidArr = ArrayUtils.appendInt(uidArr, uid);
19304 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19305 + ps.codePathString);
19310 Arrays.sort(uidArr);
19313 // Process packages with valid entries.
19315 if (DEBUG_SD_INSTALL)
19316 Log.i(TAG, "Loading packages");
19317 loadMediaPackages(processCids, uidArr, externalStorage);
19318 startCleaningPackages();
19319 mInstallerService.onSecureContainersAvailable();
19321 if (DEBUG_SD_INSTALL)
19322 Log.i(TAG, "Unloading packages");
19323 unloadMediaPackages(processCids, uidArr, reportStatus);
19327 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19328 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19329 final int size = infos.size();
19330 final String[] packageNames = new String[size];
19331 final int[] packageUids = new int[size];
19332 for (int i = 0; i < size; i++) {
19333 final ApplicationInfo info = infos.get(i);
19334 packageNames[i] = info.packageName;
19335 packageUids[i] = info.uid;
19337 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19341 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19342 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19343 sendResourcesChangedBroadcast(mediaStatus, replacing,
19344 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19347 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19348 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19349 int size = pkgList.length;
19351 // Send broadcasts here
19352 Bundle extras = new Bundle();
19353 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19354 if (uidArr != null) {
19355 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19358 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19360 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19361 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19362 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19367 * Look at potentially valid container ids from processCids If package
19368 * information doesn't match the one on record or package scanning fails,
19369 * the cid is added to list of removeCids. We currently don't delete stale
19372 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19373 boolean externalStorage) {
19374 ArrayList<String> pkgList = new ArrayList<String>();
19375 Set<AsecInstallArgs> keys = processCids.keySet();
19377 for (AsecInstallArgs args : keys) {
19378 String codePath = processCids.get(args);
19379 if (DEBUG_SD_INSTALL)
19380 Log.i(TAG, "Loading container : " + args.cid);
19381 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19383 // Make sure there are no container errors first.
19384 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19385 Slog.e(TAG, "Failed to mount cid : " + args.cid
19386 + " when installing from sdcard");
19389 // Check code path here.
19390 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19391 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19392 + " does not match one in settings " + codePath);
19396 int parseFlags = mDefParseFlags;
19397 if (args.isExternalAsec()) {
19398 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19400 if (args.isFwdLocked()) {
19401 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19404 synchronized (mInstallLock) {
19405 PackageParser.Package pkg = null;
19407 // Sadly we don't know the package name yet to freeze it
19408 pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19409 SCAN_IGNORE_FROZEN, 0, null);
19410 } catch (PackageManagerException e) {
19411 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19413 // Scan the package
19416 * TODO why is the lock being held? doPostInstall is
19417 * called in other places without the lock. This needs
19418 * to be straightened out.
19421 synchronized (mPackages) {
19422 retCode = PackageManager.INSTALL_SUCCEEDED;
19423 pkgList.add(pkg.packageName);
19424 // Post process args
19425 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19426 pkg.applicationInfo.uid);
19429 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
19434 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19435 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19440 synchronized (mPackages) {
19441 // If the platform SDK has changed since the last time we booted,
19442 // we need to re-grant app permission to catch any new ones that
19443 // appear. This is really a hack, and means that apps can in some
19444 // cases get permissions that the user didn't initially explicitly
19445 // allow... it would be nice to have some better way to handle
19447 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19448 : mSettings.getInternalVersion();
19449 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19450 : StorageManager.UUID_PRIVATE_INTERNAL;
19452 int updateFlags = UPDATE_PERMISSIONS_ALL;
19453 if (ver.sdkVersion != mSdkVersion) {
19454 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19455 + mSdkVersion + "; regranting permissions for external");
19456 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19458 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19460 // Yay, everything is now upgraded
19461 ver.forceCurrent();
19463 // can downgrade to reader
19464 // Persist settings
19465 mSettings.writeLPr();
19467 // Send a broadcast to let everyone know we are done processing
19468 if (pkgList.size() > 0) {
19469 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19474 * Utility method to unload a list of specified containers
19476 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19477 // Just unmount all valid containers.
19478 for (AsecInstallArgs arg : cidArgs) {
19479 synchronized (mInstallLock) {
19480 arg.doPostDeleteLI(false);
19486 * Unload packages mounted on external media. This involves deleting package
19487 * data from internal structures, sending broadcasts about disabled packages,
19488 * gc'ing to free up references, unmounting all secure containers
19489 * corresponding to packages on external media, and posting a
19490 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19491 * that we always have to post this message if status has been requested no
19494 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19495 final boolean reportStatus) {
19496 if (DEBUG_SD_INSTALL)
19497 Log.i(TAG, "unloading media packages");
19498 ArrayList<String> pkgList = new ArrayList<String>();
19499 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19500 final Set<AsecInstallArgs> keys = processCids.keySet();
19501 for (AsecInstallArgs args : keys) {
19502 String pkgName = args.getPackageName();
19503 if (DEBUG_SD_INSTALL)
19504 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19505 // Delete package internally
19506 PackageRemovedInfo outInfo = new PackageRemovedInfo();
19507 synchronized (mInstallLock) {
19508 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19510 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19511 "unloadMediaPackages")) {
19512 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19516 pkgList.add(pkgName);
19518 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19519 failedList.add(args);
19525 synchronized (mPackages) {
19526 // We didn't update the settings after removing each package;
19527 // write them now for all packages.
19528 mSettings.writeLPr();
19531 // We have to absolutely send UPDATED_MEDIA_STATUS only
19532 // after confirming that all the receivers processed the ordered
19533 // broadcast when packages get disabled, force a gc to clean things up.
19534 // and unload all the containers.
19535 if (pkgList.size() > 0) {
19536 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19537 new IIntentReceiver.Stub() {
19538 public void performReceive(Intent intent, int resultCode, String data,
19539 Bundle extras, boolean ordered, boolean sticky,
19540 int sendingUser) throws RemoteException {
19541 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19542 reportStatus ? 1 : 0, 1, keys);
19543 mHandler.sendMessage(msg);
19547 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19549 mHandler.sendMessage(msg);
19553 private void loadPrivatePackages(final VolumeInfo vol) {
19554 mHandler.post(new Runnable() {
19556 public void run() {
19557 loadPrivatePackagesInner(vol);
19562 private void loadPrivatePackagesInner(VolumeInfo vol) {
19563 final String volumeUuid = vol.fsUuid;
19564 if (TextUtils.isEmpty(volumeUuid)) {
19565 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19569 final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19570 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19571 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19573 final VersionInfo ver;
19574 final List<PackageSetting> packages;
19575 synchronized (mPackages) {
19576 ver = mSettings.findOrCreateVersion(volumeUuid);
19577 packages = mSettings.getVolumePackagesLPr(volumeUuid);
19580 for (PackageSetting ps : packages) {
19581 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19582 synchronized (mInstallLock) {
19583 final PackageParser.Package pkg;
19585 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19586 loaded.add(pkg.applicationInfo);
19588 } catch (PackageManagerException e) {
19589 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19592 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19593 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19594 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19595 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19600 // Reconcile app data for all started/unlocked users
19601 final StorageManager sm = mContext.getSystemService(StorageManager.class);
19602 final UserManager um = mContext.getSystemService(UserManager.class);
19603 UserManagerInternal umInternal = getUserManagerInternal();
19604 for (UserInfo user : um.getUsers()) {
19606 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19607 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19608 } else if (umInternal.isUserRunning(user.id)) {
19609 flags = StorageManager.FLAG_STORAGE_DE;
19615 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19616 synchronized (mInstallLock) {
19617 reconcileAppsDataLI(volumeUuid, user.id, flags);
19619 } catch (IllegalStateException e) {
19620 // Device was probably ejected, and we'll process that event momentarily
19621 Slog.w(TAG, "Failed to prepare storage: " + e);
19625 synchronized (mPackages) {
19626 int updateFlags = UPDATE_PERMISSIONS_ALL;
19627 if (ver.sdkVersion != mSdkVersion) {
19628 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19629 + mSdkVersion + "; regranting permissions for " + volumeUuid);
19630 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19632 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19634 // Yay, everything is now upgraded
19635 ver.forceCurrent();
19637 mSettings.writeLPr();
19640 for (PackageFreezer freezer : freezers) {
19644 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19645 sendResourcesChangedBroadcast(true, false, loaded, null);
19648 private void unloadPrivatePackages(final VolumeInfo vol) {
19649 mHandler.post(new Runnable() {
19651 public void run() {
19652 unloadPrivatePackagesInner(vol);
19657 private void unloadPrivatePackagesInner(VolumeInfo vol) {
19658 final String volumeUuid = vol.fsUuid;
19659 if (TextUtils.isEmpty(volumeUuid)) {
19660 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19664 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19665 synchronized (mInstallLock) {
19666 synchronized (mPackages) {
19667 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19668 for (PackageSetting ps : packages) {
19669 if (ps.pkg == null) continue;
19671 final ApplicationInfo info = ps.pkg.applicationInfo;
19672 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19673 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19675 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19676 "unloadPrivatePackagesInner")) {
19677 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19679 unloaded.add(info);
19681 Slog.w(TAG, "Failed to unload " + ps.codePath);
19685 // Try very hard to release any references to this package
19686 // so we don't risk the system server being killed due to
19688 AttributeCache.instance().removePackage(ps.name);
19691 mSettings.writeLPr();
19695 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19696 sendResourcesChangedBroadcast(false, false, unloaded, null);
19698 // Try very hard to release any references to this path so we don't risk
19699 // the system server being killed due to open FDs
19700 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19702 for (int i = 0; i < 3; i++) {
19704 System.runFinalization();
19709 * Prepare storage areas for given user on all mounted devices.
19711 void prepareUserData(int userId, int userSerial, int flags) {
19712 synchronized (mInstallLock) {
19713 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19714 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19715 final String volumeUuid = vol.getFsUuid();
19716 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19721 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19722 boolean allowRecover) {
19723 // Prepare storage and verify that serial numbers are consistent; if
19724 // there's a mismatch we need to destroy to avoid leaking data
19725 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19727 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19729 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19730 UserManagerService.enforceSerialNumber(
19731 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19732 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19733 UserManagerService.enforceSerialNumber(
19734 Environment.getDataSystemDeDirectory(userId), userSerial);
19737 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19738 UserManagerService.enforceSerialNumber(
19739 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19740 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19741 UserManagerService.enforceSerialNumber(
19742 Environment.getDataSystemCeDirectory(userId), userSerial);
19746 synchronized (mInstallLock) {
19747 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19749 } catch (Exception e) {
19750 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19751 + " because we failed to prepare: " + e);
19752 destroyUserDataLI(volumeUuid, userId,
19753 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19755 if (allowRecover) {
19756 // Try one last time; if we fail again we're really in trouble
19757 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19763 * Destroy storage areas for given user on all mounted devices.
19765 void destroyUserData(int userId, int flags) {
19766 synchronized (mInstallLock) {
19767 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19768 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19769 final String volumeUuid = vol.getFsUuid();
19770 destroyUserDataLI(volumeUuid, userId, flags);
19775 private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19776 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19778 // Clean up app data, profile data, and media data
19779 mInstaller.destroyUserData(volumeUuid, userId, flags);
19781 // Clean up system data
19782 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19783 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19784 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19785 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19787 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19788 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19792 // Data with special labels is now gone, so finish the job
19793 storage.destroyUserStorage(volumeUuid, userId, flags);
19795 } catch (Exception e) {
19796 logCriticalInfo(Log.WARN,
19797 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19802 * Examine all users present on given mounted volume, and destroy data
19803 * belonging to users that are no longer valid, or whose user ID has been
19806 private void reconcileUsers(String volumeUuid) {
19807 final List<File> files = new ArrayList<>();
19808 Collections.addAll(files, FileUtils
19809 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19810 Collections.addAll(files, FileUtils
19811 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19812 Collections.addAll(files, FileUtils
19813 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19814 Collections.addAll(files, FileUtils
19815 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19816 for (File file : files) {
19817 if (!file.isDirectory()) continue;
19820 final UserInfo info;
19822 userId = Integer.parseInt(file.getName());
19823 info = sUserManager.getUserInfo(userId);
19824 } catch (NumberFormatException e) {
19825 Slog.w(TAG, "Invalid user directory " + file);
19829 boolean destroyUser = false;
19830 if (info == null) {
19831 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19832 + " because no matching user was found");
19833 destroyUser = true;
19834 } else if (!mOnlyCore) {
19836 UserManagerService.enforceSerialNumber(file, info.serialNumber);
19837 } catch (IOException e) {
19838 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19839 + " because we failed to enforce serial number: " + e);
19840 destroyUser = true;
19845 synchronized (mInstallLock) {
19846 destroyUserDataLI(volumeUuid, userId,
19847 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19853 private void assertPackageKnown(String volumeUuid, String packageName)
19854 throws PackageManagerException {
19855 synchronized (mPackages) {
19856 // Normalize package name to handle renamed packages
19857 packageName = normalizePackageNameLPr(packageName);
19859 final PackageSetting ps = mSettings.mPackages.get(packageName);
19861 throw new PackageManagerException("Package " + packageName + " is unknown");
19862 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19863 throw new PackageManagerException(
19864 "Package " + packageName + " found on unknown volume " + volumeUuid
19865 + "; expected volume " + ps.volumeUuid);
19870 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19871 throws PackageManagerException {
19872 synchronized (mPackages) {
19873 // Normalize package name to handle renamed packages
19874 packageName = normalizePackageNameLPr(packageName);
19876 final PackageSetting ps = mSettings.mPackages.get(packageName);
19878 throw new PackageManagerException("Package " + packageName + " is unknown");
19879 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19880 throw new PackageManagerException(
19881 "Package " + packageName + " found on unknown volume " + volumeUuid
19882 + "; expected volume " + ps.volumeUuid);
19883 } else if (!ps.getInstalled(userId)) {
19884 throw new PackageManagerException(
19885 "Package " + packageName + " not installed for user " + userId);
19891 * Examine all apps present on given mounted volume, and destroy apps that
19892 * aren't expected, either due to uninstallation or reinstallation on
19895 private void reconcileApps(String volumeUuid) {
19896 final File[] files = FileUtils
19897 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19898 for (File file : files) {
19899 final boolean isPackage = (isApkFile(file) || file.isDirectory())
19900 && !PackageInstallerService.isStageName(file.getName());
19902 // Ignore entries which are not packages
19907 final PackageLite pkg = PackageParser.parsePackageLite(file,
19908 PackageParser.PARSE_MUST_BE_APK);
19909 assertPackageKnown(volumeUuid, pkg.packageName);
19911 } catch (PackageParserException | PackageManagerException e) {
19912 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19913 synchronized (mInstallLock) {
19914 removeCodePathLI(file);
19921 * Reconcile all app data for the given user.
19923 * Verifies that directories exist and that ownership and labeling is
19924 * correct for all installed apps on all mounted volumes.
19926 void reconcileAppsData(int userId, int flags) {
19927 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19928 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19929 final String volumeUuid = vol.getFsUuid();
19930 synchronized (mInstallLock) {
19931 reconcileAppsDataLI(volumeUuid, userId, flags);
19937 * Reconcile all app data on given mounted volume.
19939 * Destroys app data that isn't expected, either due to uninstallation or
19940 * reinstallation on another volume.
19942 * Verifies that directories exist and that ownership and labeling is
19943 * correct for all installed apps.
19945 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19946 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19947 + Integer.toHexString(flags));
19949 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19950 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19952 // First look for stale data that doesn't belong, and check if things
19953 // have changed since we did our last restorecon
19954 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19955 if (StorageManager.isFileEncryptedNativeOrEmulated()
19956 && !StorageManager.isUserKeyUnlocked(userId)) {
19957 throw new RuntimeException(
19958 "Yikes, someone asked us to reconcile CE storage while " + userId
19959 + " was still locked; this would have caused massive data loss!");
19962 final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19963 for (File file : files) {
19964 final String packageName = file.getName();
19966 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19967 } catch (PackageManagerException e) {
19968 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19970 mInstaller.destroyAppData(volumeUuid, packageName, userId,
19971 StorageManager.FLAG_STORAGE_CE, 0);
19972 } catch (InstallerException e2) {
19973 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19978 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19979 final File[] files = FileUtils.listFilesOrEmpty(deDir);
19980 for (File file : files) {
19981 final String packageName = file.getName();
19983 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19984 } catch (PackageManagerException e) {
19985 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19987 mInstaller.destroyAppData(volumeUuid, packageName, userId,
19988 StorageManager.FLAG_STORAGE_DE, 0);
19989 } catch (InstallerException e2) {
19990 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19996 // Ensure that data directories are ready to roll for all packages
19997 // installed for this volume and user
19998 final List<PackageSetting> packages;
19999 synchronized (mPackages) {
20000 packages = mSettings.getVolumePackagesLPr(volumeUuid);
20002 int preparedCount = 0;
20003 for (PackageSetting ps : packages) {
20004 final String packageName = ps.name;
20005 if (ps.pkg == null) {
20006 Slog.w(TAG, "Odd, missing scanned package " + packageName);
20007 // TODO: might be due to legacy ASEC apps; we should circle back
20008 // and reconcile again once they're scanned
20012 if (ps.getInstalled(userId)) {
20013 prepareAppDataLIF(ps.pkg, userId, flags);
20015 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
20016 // We may have just shuffled around app data directories, so
20017 // prepare them one more time
20018 prepareAppDataLIF(ps.pkg, userId, flags);
20025 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20029 * Prepare app data for the given app just after it was installed or
20030 * upgraded. This method carefully only touches users that it's installed
20031 * for, and it forces a restorecon to handle any seinfo changes.
20033 * Verifies that directories exist and that ownership and labeling is
20034 * correct for all installed apps. If there is an ownership mismatch, it
20035 * will try recovering system apps by wiping data; third-party app data is
20038 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20040 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20041 final PackageSetting ps;
20042 synchronized (mPackages) {
20043 ps = mSettings.mPackages.get(pkg.packageName);
20044 mSettings.writeKernelMappingLPr(ps);
20047 final UserManager um = mContext.getSystemService(UserManager.class);
20048 UserManagerInternal umInternal = getUserManagerInternal();
20049 for (UserInfo user : um.getUsers()) {
20051 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20052 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20053 } else if (umInternal.isUserRunning(user.id)) {
20054 flags = StorageManager.FLAG_STORAGE_DE;
20059 if (ps.getInstalled(user.id)) {
20060 // TODO: when user data is locked, mark that we're still dirty
20061 prepareAppDataLIF(pkg, user.id, flags);
20067 * Prepare app data for the given app.
20069 * Verifies that directories exist and that ownership and labeling is
20070 * correct for all installed apps. If there is an ownership mismatch, this
20071 * will try recovering system apps by wiping data; third-party app data is
20074 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20076 Slog.wtf(TAG, "Package was null!", new Throwable());
20079 prepareAppDataLeafLIF(pkg, userId, flags);
20080 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20081 for (int i = 0; i < childCount; i++) {
20082 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20086 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20087 if (DEBUG_APP_DATA) {
20088 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20089 + Integer.toHexString(flags));
20092 final String volumeUuid = pkg.volumeUuid;
20093 final String packageName = pkg.packageName;
20094 final ApplicationInfo app = pkg.applicationInfo;
20095 final int appId = UserHandle.getAppId(app.uid);
20097 Preconditions.checkNotNull(app.seinfo);
20100 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20101 appId, app.seinfo, app.targetSdkVersion);
20102 } catch (InstallerException e) {
20103 if (app.isSystemApp()) {
20104 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20105 + ", but trying to recover: " + e);
20106 destroyAppDataLeafLIF(pkg, userId, flags);
20108 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20109 appId, app.seinfo, app.targetSdkVersion);
20110 logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20111 } catch (InstallerException e2) {
20112 logCriticalInfo(Log.DEBUG, "Recovery failed!");
20115 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20119 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20121 // CE storage is unlocked right now, so read out the inode and
20122 // remember for use later when it's locked
20123 // TODO: mark this structure as dirty so we persist it!
20124 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20125 StorageManager.FLAG_STORAGE_CE);
20126 synchronized (mPackages) {
20127 final PackageSetting ps = mSettings.mPackages.get(packageName);
20129 ps.setCeDataInode(ceDataInode, userId);
20132 } catch (InstallerException e) {
20133 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20137 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20140 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20142 Slog.wtf(TAG, "Package was null!", new Throwable());
20145 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20146 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20147 for (int i = 0; i < childCount; i++) {
20148 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20152 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20153 final String volumeUuid = pkg.volumeUuid;
20154 final String packageName = pkg.packageName;
20155 final ApplicationInfo app = pkg.applicationInfo;
20157 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20158 // Create a native library symlink only if we have native libraries
20159 // and if the native libraries are 32 bit libraries. We do not provide
20160 // this symlink for 64 bit libraries.
20161 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20162 final String nativeLibPath = app.nativeLibraryDir;
20164 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20165 nativeLibPath, userId);
20166 } catch (InstallerException e) {
20167 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20174 * For system apps on non-FBE devices, this method migrates any existing
20175 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20176 * requested by the app.
20178 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20179 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20180 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20181 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20182 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20184 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20186 } catch (InstallerException e) {
20187 logCriticalInfo(Log.WARN,
20188 "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20196 public PackageFreezer freezePackage(String packageName, String killReason) {
20197 return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20200 public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20201 return new PackageFreezer(packageName, userId, killReason);
20204 public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20205 String killReason) {
20206 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20209 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20210 String killReason) {
20211 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20212 return new PackageFreezer();
20214 return freezePackage(packageName, userId, killReason);
20218 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20219 String killReason) {
20220 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20223 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20224 String killReason) {
20225 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20226 return new PackageFreezer();
20228 return freezePackage(packageName, userId, killReason);
20233 * Class that freezes and kills the given package upon creation, and
20234 * unfreezes it upon closing. This is typically used when doing surgery on
20235 * app code/data to prevent the app from running while you're working.
20237 private class PackageFreezer implements AutoCloseable {
20238 private final String mPackageName;
20239 private final PackageFreezer[] mChildren;
20241 private final boolean mWeFroze;
20243 private final AtomicBoolean mClosed = new AtomicBoolean();
20244 private final CloseGuard mCloseGuard = CloseGuard.get();
20247 * Create and return a stub freezer that doesn't actually do anything,
20248 * typically used when someone requested
20249 * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20250 * {@link PackageManager#DELETE_DONT_KILL_APP}.
20252 public PackageFreezer() {
20253 mPackageName = null;
20256 mCloseGuard.open("close");
20259 public PackageFreezer(String packageName, int userId, String killReason) {
20260 synchronized (mPackages) {
20261 mPackageName = packageName;
20262 mWeFroze = mFrozenPackages.add(mPackageName);
20264 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20266 killApplication(ps.name, ps.appId, userId, killReason);
20269 final PackageParser.Package p = mPackages.get(packageName);
20270 if (p != null && p.childPackages != null) {
20271 final int N = p.childPackages.size();
20272 mChildren = new PackageFreezer[N];
20273 for (int i = 0; i < N; i++) {
20274 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20275 userId, killReason);
20281 mCloseGuard.open("close");
20285 protected void finalize() throws Throwable {
20287 mCloseGuard.warnIfOpen();
20295 public void close() {
20296 mCloseGuard.close();
20297 if (mClosed.compareAndSet(false, true)) {
20298 synchronized (mPackages) {
20300 mFrozenPackages.remove(mPackageName);
20303 if (mChildren != null) {
20304 for (PackageFreezer freezer : mChildren) {
20314 * Verify that given package is currently frozen.
20316 private void checkPackageFrozen(String packageName) {
20317 synchronized (mPackages) {
20318 if (!mFrozenPackages.contains(packageName)) {
20319 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20325 public int movePackage(final String packageName, final String volumeUuid) {
20326 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20328 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20329 final int moveId = mNextMoveId.getAndIncrement();
20330 mHandler.post(new Runnable() {
20332 public void run() {
20334 movePackageInternal(packageName, volumeUuid, moveId, user);
20335 } catch (PackageManagerException e) {
20336 Slog.w(TAG, "Failed to move " + packageName, e);
20337 mMoveCallbacks.notifyStatusChanged(moveId,
20338 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20345 private void movePackageInternal(final String packageName, final String volumeUuid,
20346 final int moveId, UserHandle user) throws PackageManagerException {
20347 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20348 final PackageManager pm = mContext.getPackageManager();
20350 final boolean currentAsec;
20351 final String currentVolumeUuid;
20352 final File codeFile;
20353 final String installerPackageName;
20354 final String packageAbiOverride;
20356 final String seinfo;
20357 final String label;
20358 final int targetSdkVersion;
20359 final PackageFreezer freezer;
20360 final int[] installedUserIds;
20363 synchronized (mPackages) {
20364 final PackageParser.Package pkg = mPackages.get(packageName);
20365 final PackageSetting ps = mSettings.mPackages.get(packageName);
20366 if (pkg == null || ps == null) {
20367 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20370 if (pkg.applicationInfo.isSystemApp()) {
20371 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20372 "Cannot move system application");
20375 if (pkg.applicationInfo.isExternalAsec()) {
20376 currentAsec = true;
20377 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20378 } else if (pkg.applicationInfo.isForwardLocked()) {
20379 currentAsec = true;
20380 currentVolumeUuid = "forward_locked";
20382 currentAsec = false;
20383 currentVolumeUuid = ps.volumeUuid;
20385 final File probe = new File(pkg.codePath);
20386 final File probeOat = new File(probe, "oat");
20387 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20388 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20389 "Move only supported for modern cluster style installs");
20393 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20394 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20395 "Package already moved to " + volumeUuid);
20397 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20398 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20399 "Device admin cannot be moved");
20402 if (mFrozenPackages.contains(packageName)) {
20403 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20404 "Failed to move already frozen package");
20407 codeFile = new File(pkg.codePath);
20408 installerPackageName = ps.installerPackageName;
20409 packageAbiOverride = ps.cpuAbiOverrideString;
20410 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20411 seinfo = pkg.applicationInfo.seinfo;
20412 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20413 targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20414 freezer = freezePackage(packageName, "movePackageInternal");
20415 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20418 final Bundle extras = new Bundle();
20419 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20420 extras.putString(Intent.EXTRA_TITLE, label);
20421 mMoveCallbacks.notifyCreated(moveId, extras);
20424 final boolean moveCompleteApp;
20425 final File measurePath;
20427 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20428 installFlags = INSTALL_INTERNAL;
20429 moveCompleteApp = !currentAsec;
20430 measurePath = Environment.getDataAppDirectory(volumeUuid);
20431 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20432 installFlags = INSTALL_EXTERNAL;
20433 moveCompleteApp = false;
20434 measurePath = storage.getPrimaryPhysicalVolume().getPath();
20436 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20437 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20438 || !volume.isMountedWritable()) {
20440 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20441 "Move location not mounted private volume");
20444 Preconditions.checkState(!currentAsec);
20446 installFlags = INSTALL_INTERNAL;
20447 moveCompleteApp = true;
20448 measurePath = Environment.getDataAppDirectory(volumeUuid);
20451 final PackageStats stats = new PackageStats(null, -1);
20452 synchronized (mInstaller) {
20453 for (int userId : installedUserIds) {
20454 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20456 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20457 "Failed to measure package size");
20462 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20465 final long startFreeBytes = measurePath.getFreeSpace();
20466 final long sizeBytes;
20467 if (moveCompleteApp) {
20468 sizeBytes = stats.codeSize + stats.dataSize;
20470 sizeBytes = stats.codeSize;
20473 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20475 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20476 "Not enough free space to move");
20479 mMoveCallbacks.notifyStatusChanged(moveId, 10);
20481 final CountDownLatch installedLatch = new CountDownLatch(1);
20482 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20484 public void onUserActionRequired(Intent intent) throws RemoteException {
20485 throw new IllegalStateException();
20489 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20490 Bundle extras) throws RemoteException {
20491 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20492 + PackageManager.installStatusToString(returnCode, msg));
20494 installedLatch.countDown();
20497 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20499 case PackageInstaller.STATUS_SUCCESS:
20500 mMoveCallbacks.notifyStatusChanged(moveId,
20501 PackageManager.MOVE_SUCCEEDED);
20503 case PackageInstaller.STATUS_FAILURE_STORAGE:
20504 mMoveCallbacks.notifyStatusChanged(moveId,
20505 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20508 mMoveCallbacks.notifyStatusChanged(moveId,
20509 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20515 final MoveInfo move;
20516 if (moveCompleteApp) {
20517 // Kick off a thread to report progress estimates
20520 public void run() {
20523 if (installedLatch.await(1, TimeUnit.SECONDS)) {
20526 } catch (InterruptedException ignored) {
20529 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20530 final int progress = 10 + (int) MathUtils.constrain(
20531 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20532 mMoveCallbacks.notifyStatusChanged(moveId, progress);
20537 final String dataAppName = codeFile.getName();
20538 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20539 dataAppName, appId, seinfo, targetSdkVersion);
20544 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20546 final Message msg = mHandler.obtainMessage(INIT_COPY);
20547 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20548 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20549 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20550 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20551 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20554 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20555 System.identityHashCode(msg.obj));
20556 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20557 System.identityHashCode(msg.obj));
20559 mHandler.sendMessage(msg);
20563 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20564 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20566 final int realMoveId = mNextMoveId.getAndIncrement();
20567 final Bundle extras = new Bundle();
20568 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20569 mMoveCallbacks.notifyCreated(realMoveId, extras);
20571 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20573 public void onCreated(int moveId, Bundle extras) {
20578 public void onStatusChanged(int moveId, int status, long estMillis) {
20579 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20583 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20584 storage.setPrimaryStorageUuid(volumeUuid, callback);
20589 public int getMoveStatus(int moveId) {
20590 mContext.enforceCallingOrSelfPermission(
20591 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20592 return mMoveCallbacks.mLastStatus.get(moveId);
20596 public void registerMoveCallback(IPackageMoveObserver callback) {
20597 mContext.enforceCallingOrSelfPermission(
20598 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20599 mMoveCallbacks.register(callback);
20603 public void unregisterMoveCallback(IPackageMoveObserver callback) {
20604 mContext.enforceCallingOrSelfPermission(
20605 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20606 mMoveCallbacks.unregister(callback);
20610 public boolean setInstallLocation(int loc) {
20611 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20613 if (getInstallLocation() == loc) {
20616 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20617 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20618 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20619 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20626 public int getInstallLocation() {
20627 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20628 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20629 PackageHelper.APP_INSTALL_AUTO);
20632 /** Called by UserManagerService */
20633 void cleanUpUser(UserManagerService userManager, int userHandle) {
20634 synchronized (mPackages) {
20635 mDirtyUsers.remove(userHandle);
20636 mUserNeedsBadging.delete(userHandle);
20637 mSettings.removeUserLPw(userHandle);
20638 mPendingBroadcasts.remove(userHandle);
20639 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20640 removeUnusedPackagesLPw(userManager, userHandle);
20645 * We're removing userHandle and would like to remove any downloaded packages
20646 * that are no longer in use by any other user.
20647 * @param userHandle the user being removed
20649 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20650 final boolean DEBUG_CLEAN_APKS = false;
20651 int [] users = userManager.getUserIds();
20652 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20653 while (psit.hasNext()) {
20654 PackageSetting ps = psit.next();
20655 if (ps.pkg == null) {
20658 final String packageName = ps.pkg.packageName;
20659 // Skip over if system app
20660 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20663 if (DEBUG_CLEAN_APKS) {
20664 Slog.i(TAG, "Checking package " + packageName);
20666 boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20668 if (DEBUG_CLEAN_APKS) {
20669 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO");
20672 for (int i = 0; i < users.length; i++) {
20673 if (users[i] != userHandle && ps.getInstalled(users[i])) {
20675 if (DEBUG_CLEAN_APKS) {
20676 Slog.i(TAG, " Keeping package " + packageName + " for user "
20684 if (DEBUG_CLEAN_APKS) {
20685 Slog.i(TAG, " Removing package " + packageName);
20687 mHandler.post(new Runnable() {
20688 public void run() {
20689 deletePackageX(packageName, userHandle, 0);
20696 /** Called by UserManagerService */
20697 void createNewUser(int userId) {
20698 synchronized (mInstallLock) {
20699 mSettings.createNewUserLI(this, mInstaller, userId);
20701 synchronized (mPackages) {
20702 scheduleWritePackageRestrictionsLocked(userId);
20703 scheduleWritePackageListLocked(userId);
20704 applyFactoryDefaultBrowserLPw(userId);
20705 primeDomainVerificationsLPw(userId);
20709 void onNewUserCreated(final int userId) {
20710 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20711 // If permission review for legacy apps is required, we represent
20712 // dagerous permissions for such apps as always granted runtime
20713 // permissions to keep per user flag state whether review is needed.
20714 // Hence, if a new user is added we have to propagate dangerous
20715 // permission grants for these legacy apps.
20716 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20717 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20718 | UPDATE_PERMISSIONS_REPLACE_ALL);
20723 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20724 mContext.enforceCallingOrSelfPermission(
20725 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20726 "Only package verification agents can read the verifier device identity");
20728 synchronized (mPackages) {
20729 return mSettings.getVerifierDeviceIdentityLPw();
20734 public void setPermissionEnforced(String permission, boolean enforced) {
20735 // TODO: Now that we no longer change GID for storage, this should to away.
20736 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20737 "setPermissionEnforced");
20738 if (READ_EXTERNAL_STORAGE.equals(permission)) {
20739 synchronized (mPackages) {
20740 if (mSettings.mReadExternalStorageEnforced == null
20741 || mSettings.mReadExternalStorageEnforced != enforced) {
20742 mSettings.mReadExternalStorageEnforced = enforced;
20743 mSettings.writeLPr();
20746 // kill any non-foreground processes so we restart them and
20747 // grant/revoke the GID.
20748 final IActivityManager am = ActivityManagerNative.getDefault();
20750 final long token = Binder.clearCallingIdentity();
20752 am.killProcessesBelowForeground("setPermissionEnforcement");
20753 } catch (RemoteException e) {
20755 Binder.restoreCallingIdentity(token);
20759 throw new IllegalArgumentException("No selective enforcement for " + permission);
20765 public boolean isPermissionEnforced(String permission) {
20770 public boolean isStorageLow() {
20771 final long token = Binder.clearCallingIdentity();
20773 final DeviceStorageMonitorInternal
20774 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20776 return dsm.isMemoryLow();
20781 Binder.restoreCallingIdentity(token);
20786 public IPackageInstaller getPackageInstaller() {
20787 return mInstallerService;
20790 private boolean userNeedsBadging(int userId) {
20791 int index = mUserNeedsBadging.indexOfKey(userId);
20793 final UserInfo userInfo;
20794 final long token = Binder.clearCallingIdentity();
20796 userInfo = sUserManager.getUserInfo(userId);
20798 Binder.restoreCallingIdentity(token);
20801 if (userInfo != null && userInfo.isManagedProfile()) {
20806 mUserNeedsBadging.put(userId, b);
20809 return mUserNeedsBadging.valueAt(index);
20813 public KeySet getKeySetByAlias(String packageName, String alias) {
20814 if (packageName == null || alias == null) {
20817 synchronized(mPackages) {
20818 final PackageParser.Package pkg = mPackages.get(packageName);
20820 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20821 throw new IllegalArgumentException("Unknown package: " + packageName);
20823 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20824 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20829 public KeySet getSigningKeySet(String packageName) {
20830 if (packageName == null) {
20833 synchronized(mPackages) {
20834 final PackageParser.Package pkg = mPackages.get(packageName);
20836 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20837 throw new IllegalArgumentException("Unknown package: " + packageName);
20839 if (pkg.applicationInfo.uid != Binder.getCallingUid()
20840 && Process.SYSTEM_UID != Binder.getCallingUid()) {
20841 throw new SecurityException("May not access signing KeySet of other apps.");
20843 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20844 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20849 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20850 if (packageName == null || ks == null) {
20853 synchronized(mPackages) {
20854 final PackageParser.Package pkg = mPackages.get(packageName);
20856 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20857 throw new IllegalArgumentException("Unknown package: " + packageName);
20859 IBinder ksh = ks.getToken();
20860 if (ksh instanceof KeySetHandle) {
20861 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20862 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20869 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20870 if (packageName == null || ks == 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 IBinder ksh = ks.getToken();
20880 if (ksh instanceof KeySetHandle) {
20881 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20882 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20888 private void deletePackageIfUnusedLPr(final String packageName) {
20889 PackageSetting ps = mSettings.mPackages.get(packageName);
20893 if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20894 // TODO Implement atomic delete if package is unused
20895 // It is currently possible that the package will be deleted even if it is installed
20896 // after this method returns.
20897 mHandler.post(new Runnable() {
20898 public void run() {
20899 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20906 * Check and throw if the given before/after packages would be considered a
20909 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20910 throws PackageManagerException {
20911 if (after.versionCode < before.mVersionCode) {
20912 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20913 "Update version code " + after.versionCode + " is older than current "
20914 + before.mVersionCode);
20915 } else if (after.versionCode == before.mVersionCode) {
20916 if (after.baseRevisionCode < before.baseRevisionCode) {
20917 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20918 "Update base revision code " + after.baseRevisionCode
20919 + " is older than current " + before.baseRevisionCode);
20922 if (!ArrayUtils.isEmpty(after.splitNames)) {
20923 for (int i = 0; i < after.splitNames.length; i++) {
20924 final String splitName = after.splitNames[i];
20925 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20927 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20928 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20929 "Update split " + splitName + " revision code "
20930 + after.splitRevisionCodes[i] + " is older than current "
20931 + before.splitRevisionCodes[j]);
20939 private static class MoveCallbacks extends Handler {
20940 private static final int MSG_CREATED = 1;
20941 private static final int MSG_STATUS_CHANGED = 2;
20943 private final RemoteCallbackList<IPackageMoveObserver>
20944 mCallbacks = new RemoteCallbackList<>();
20946 private final SparseIntArray mLastStatus = new SparseIntArray();
20948 public MoveCallbacks(Looper looper) {
20952 public void register(IPackageMoveObserver callback) {
20953 mCallbacks.register(callback);
20956 public void unregister(IPackageMoveObserver callback) {
20957 mCallbacks.unregister(callback);
20961 public void handleMessage(Message msg) {
20962 final SomeArgs args = (SomeArgs) msg.obj;
20963 final int n = mCallbacks.beginBroadcast();
20964 for (int i = 0; i < n; i++) {
20965 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20967 invokeCallback(callback, msg.what, args);
20968 } catch (RemoteException ignored) {
20971 mCallbacks.finishBroadcast();
20975 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20976 throws RemoteException {
20978 case MSG_CREATED: {
20979 callback.onCreated(args.argi1, (Bundle) args.arg2);
20982 case MSG_STATUS_CHANGED: {
20983 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20989 private void notifyCreated(int moveId, Bundle extras) {
20990 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20992 final SomeArgs args = SomeArgs.obtain();
20993 args.argi1 = moveId;
20994 args.arg2 = extras;
20995 obtainMessage(MSG_CREATED, args).sendToTarget();
20998 private void notifyStatusChanged(int moveId, int status) {
20999 notifyStatusChanged(moveId, status, -1);
21002 private void notifyStatusChanged(int moveId, int status, long estMillis) {
21003 Slog.v(TAG, "Move " + moveId + " status " + status);
21005 final SomeArgs args = SomeArgs.obtain();
21006 args.argi1 = moveId;
21007 args.argi2 = status;
21008 args.arg3 = estMillis;
21009 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21011 synchronized (mLastStatus) {
21012 mLastStatus.put(moveId, status);
21017 private final static class OnPermissionChangeListeners extends Handler {
21018 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21020 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21021 new RemoteCallbackList<>();
21023 public OnPermissionChangeListeners(Looper looper) {
21028 public void handleMessage(Message msg) {
21029 switch (msg.what) {
21030 case MSG_ON_PERMISSIONS_CHANGED: {
21031 final int uid = msg.arg1;
21032 handleOnPermissionsChanged(uid);
21037 public void addListenerLocked(IOnPermissionsChangeListener listener) {
21038 mPermissionListeners.register(listener);
21042 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21043 mPermissionListeners.unregister(listener);
21046 public void onPermissionsChanged(int uid) {
21047 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21048 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21052 private void handleOnPermissionsChanged(int uid) {
21053 final int count = mPermissionListeners.beginBroadcast();
21055 for (int i = 0; i < count; i++) {
21056 IOnPermissionsChangeListener callback = mPermissionListeners
21057 .getBroadcastItem(i);
21059 callback.onPermissionsChanged(uid);
21060 } catch (RemoteException e) {
21061 Log.e(TAG, "Permission listener is dead", e);
21065 mPermissionListeners.finishBroadcast();
21070 private class PackageManagerInternalImpl extends PackageManagerInternal {
21072 public void setLocationPackagesProvider(PackagesProvider provider) {
21073 synchronized (mPackages) {
21074 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21079 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21080 synchronized (mPackages) {
21081 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21086 public void setSmsAppPackagesProvider(PackagesProvider provider) {
21087 synchronized (mPackages) {
21088 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21093 public void setDialerAppPackagesProvider(PackagesProvider provider) {
21094 synchronized (mPackages) {
21095 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21100 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21101 synchronized (mPackages) {
21102 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21107 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21108 synchronized (mPackages) {
21109 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21114 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21115 synchronized (mPackages) {
21116 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21117 packageName, userId);
21122 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21123 synchronized (mPackages) {
21124 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21125 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21126 packageName, userId);
21131 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21132 synchronized (mPackages) {
21133 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21134 packageName, userId);
21139 public void setKeepUninstalledPackages(final List<String> packageList) {
21140 Preconditions.checkNotNull(packageList);
21141 List<String> removedFromList = null;
21142 synchronized (mPackages) {
21143 if (mKeepUninstalledPackages != null) {
21144 final int packagesCount = mKeepUninstalledPackages.size();
21145 for (int i = 0; i < packagesCount; i++) {
21146 String oldPackage = mKeepUninstalledPackages.get(i);
21147 if (packageList != null && packageList.contains(oldPackage)) {
21150 if (removedFromList == null) {
21151 removedFromList = new ArrayList<>();
21153 removedFromList.add(oldPackage);
21156 mKeepUninstalledPackages = new ArrayList<>(packageList);
21157 if (removedFromList != null) {
21158 final int removedCount = removedFromList.size();
21159 for (int i = 0; i < removedCount; i++) {
21160 deletePackageIfUnusedLPr(removedFromList.get(i));
21167 public boolean isPermissionsReviewRequired(String packageName, int userId) {
21168 synchronized (mPackages) {
21169 // If we do not support permission review, done.
21170 if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
21174 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21175 if (packageSetting == null) {
21179 // Permission review applies only to apps not supporting the new permission model.
21180 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21184 // Legacy apps have the permission and get user consent on launch.
21185 PermissionsState permissionsState = packageSetting.getPermissionsState();
21186 return permissionsState.isPermissionReviewRequired(userId);
21191 public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21192 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21196 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21198 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21202 public void setDeviceAndProfileOwnerPackages(
21203 int deviceOwnerUserId, String deviceOwnerPackage,
21204 SparseArray<String> profileOwnerPackages) {
21205 mProtectedPackages.setDeviceAndProfileOwnerPackages(
21206 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21210 public boolean isPackageDataProtected(int userId, String packageName) {
21211 return mProtectedPackages.isPackageDataProtected(userId, packageName);
21215 public boolean wasPackageEverLaunched(String packageName, int userId) {
21216 synchronized (mPackages) {
21217 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21223 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21224 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21225 synchronized (mPackages) {
21226 final long identity = Binder.clearCallingIdentity();
21228 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21229 packageNames, userId);
21231 Binder.restoreCallingIdentity(identity);
21236 private static void enforceSystemOrPhoneCaller(String tag) {
21237 int callingUid = Binder.getCallingUid();
21238 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21239 throw new SecurityException(
21240 "Cannot call " + tag + " from UID " + callingUid);
21244 boolean isHistoricalPackageUsageAvailable() {
21245 return mPackageUsage.isHistoricalPackageUsageAvailable();
21249 * Return a <b>copy</b> of the collection of packages known to the package manager.
21250 * @return A copy of the values of mPackages.
21252 Collection<PackageParser.Package> getPackages() {
21253 synchronized (mPackages) {
21254 return new ArrayList<>(mPackages.values());
21259 * Logs process start information (including base APK hash) to the security log.
21262 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21263 String apkFile, int pid) {
21264 if (!SecurityLog.isLoggingEnabled()) {
21267 Bundle data = new Bundle();
21268 data.putLong("startTimestamp", System.currentTimeMillis());
21269 data.putString("processName", processName);
21270 data.putInt("uid", uid);
21271 data.putString("seinfo", seinfo);
21272 data.putString("apkFile", apkFile);
21273 data.putInt("pid", pid);
21274 Message msg = mProcessLoggingHandler.obtainMessage(
21275 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21277 mProcessLoggingHandler.sendMessage(msg);
21280 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21281 return mCompilerStats.getPackageStats(pkgName);
21284 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21285 return getOrCreateCompilerPackageStats(pkg.packageName);
21288 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21289 return mCompilerStats.getOrCreatePackageStats(pkgName);
21292 public void deleteCompilerPackageStats(String pkgName) {
21293 mCompilerStats.deletePackageStats(pkgName);