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.Binder;
169 import android.os.Build;
170 import android.os.Bundle;
171 import android.os.Debug;
172 import android.os.Environment;
173 import android.os.Environment.UserEnvironment;
174 import android.os.FileUtils;
175 import android.os.Handler;
176 import android.os.IBinder;
177 import android.os.Looper;
178 import android.os.Message;
179 import android.os.Parcel;
180 import android.os.ParcelFileDescriptor;
181 import android.os.PatternMatcher;
182 import android.os.Process;
183 import android.os.RemoteCallbackList;
184 import android.os.RemoteException;
185 import android.os.ResultReceiver;
186 import android.os.SELinux;
187 import android.os.ServiceManager;
188 import android.os.SystemClock;
189 import android.os.SystemProperties;
190 import android.os.Trace;
191 import android.os.UserHandle;
192 import android.os.UserManager;
193 import android.os.UserManagerInternal;
194 import android.os.storage.IMountService;
195 import android.os.storage.MountServiceInternal;
196 import android.os.storage.StorageEventListener;
197 import android.os.storage.StorageManager;
198 import android.os.storage.VolumeInfo;
199 import android.os.storage.VolumeRecord;
200 import android.provider.Settings.Global;
201 import android.provider.Settings.Secure;
202 import android.security.KeyStore;
203 import android.security.SystemKeyStore;
204 import android.system.ErrnoException;
205 import android.system.Os;
206 import android.text.TextUtils;
207 import android.text.format.DateUtils;
208 import android.util.ArrayMap;
209 import android.util.ArraySet;
210 import android.util.DisplayMetrics;
211 import android.util.EventLog;
212 import android.util.ExceptionUtils;
213 import android.util.Log;
214 import android.util.LogPrinter;
215 import android.util.MathUtils;
216 import android.util.Pair;
217 import android.util.PrintStreamPrinter;
218 import android.util.Slog;
219 import android.util.SparseArray;
220 import android.util.SparseBooleanArray;
221 import android.util.SparseIntArray;
222 import android.util.Xml;
223 import android.util.jar.StrictJarFile;
224 import android.view.Display;
226 import com.android.internal.R;
227 import com.android.internal.annotations.GuardedBy;
228 import com.android.internal.app.IMediaContainerService;
229 import com.android.internal.app.ResolverActivity;
230 import com.android.internal.content.NativeLibraryHelper;
231 import com.android.internal.content.PackageHelper;
232 import com.android.internal.logging.MetricsLogger;
233 import com.android.internal.os.IParcelFileDescriptorFactory;
234 import com.android.internal.os.InstallerConnection.InstallerException;
235 import com.android.internal.os.SomeArgs;
236 import com.android.internal.os.Zygote;
237 import com.android.internal.telephony.CarrierAppUtils;
238 import com.android.internal.util.ArrayUtils;
239 import com.android.internal.util.FastPrintWriter;
240 import com.android.internal.util.FastXmlSerializer;
241 import com.android.internal.util.IndentingPrintWriter;
242 import com.android.internal.util.Preconditions;
243 import com.android.internal.util.XmlUtils;
244 import com.android.server.AttributeCache;
245 import com.android.server.EventLogTags;
246 import com.android.server.FgThread;
247 import com.android.server.IntentResolver;
248 import com.android.server.LocalServices;
249 import com.android.server.ServiceThread;
250 import com.android.server.SystemConfig;
251 import com.android.server.Watchdog;
252 import com.android.server.net.NetworkPolicyManagerInternal;
253 import com.android.server.pm.PermissionsState.PermissionState;
254 import com.android.server.pm.Settings.DatabaseVersion;
255 import com.android.server.pm.Settings.VersionInfo;
256 import com.android.server.storage.DeviceStorageMonitorInternal;
258 import dalvik.system.CloseGuard;
259 import dalvik.system.DexFile;
260 import dalvik.system.VMRuntime;
262 import libcore.io.IoUtils;
263 import libcore.util.EmptyArray;
265 import org.xmlpull.v1.XmlPullParser;
266 import org.xmlpull.v1.XmlPullParserException;
267 import org.xmlpull.v1.XmlSerializer;
269 import java.io.BufferedOutputStream;
270 import java.io.BufferedReader;
271 import java.io.ByteArrayInputStream;
272 import java.io.ByteArrayOutputStream;
274 import java.io.FileDescriptor;
275 import java.io.FileInputStream;
276 import java.io.FileNotFoundException;
277 import java.io.FileOutputStream;
278 import java.io.FileReader;
279 import java.io.FilenameFilter;
280 import java.io.IOException;
281 import java.io.PrintWriter;
282 import java.nio.charset.StandardCharsets;
283 import java.security.DigestInputStream;
284 import java.security.MessageDigest;
285 import java.security.NoSuchAlgorithmException;
286 import java.security.PublicKey;
287 import java.security.cert.Certificate;
288 import java.security.cert.CertificateEncodingException;
289 import java.security.cert.CertificateException;
290 import java.text.SimpleDateFormat;
291 import java.util.ArrayList;
292 import java.util.Arrays;
293 import java.util.Collection;
294 import java.util.Collections;
295 import java.util.Comparator;
296 import java.util.Date;
297 import java.util.HashSet;
298 import java.util.Iterator;
299 import java.util.List;
300 import java.util.Map;
301 import java.util.Objects;
302 import java.util.Set;
303 import java.util.concurrent.CountDownLatch;
304 import java.util.concurrent.TimeUnit;
305 import java.util.concurrent.atomic.AtomicBoolean;
306 import java.util.concurrent.atomic.AtomicInteger;
309 * Keep track of all those APKs everywhere.
311 * Internally there are two important locks:
313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
314 * and other related state. It is a fine-grained lock that should only be held
315 * momentarily, as it's one of the most contended locks in the system.
316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
317 * operations typically involve heavy lifting of application data on disk. Since
318 * {@code installd} is single-threaded, and it's operations can often be slow,
319 * this lock should never be acquired while already holding {@link #mPackages}.
320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
321 * holding {@link #mInstallLock}.
323 * Many internal methods rely on the caller to hold the appropriate locks, and
324 * this contract is expressed through method name suffixes:
326 * <li>fooLI(): the caller must hold {@link #mInstallLock}
327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
328 * being modified must be frozen
329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
333 * Because this class is very central to the platform's security; please run all
334 * CTS and unit tests whenever making modifications:
337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
341 public class PackageManagerService extends IPackageManager.Stub {
342 static final String TAG = "PackageManager";
343 static final boolean DEBUG_SETTINGS = false;
344 static final boolean DEBUG_PREFERRED = false;
345 static final boolean DEBUG_UPGRADE = false;
346 static final boolean DEBUG_DOMAIN_VERIFICATION = false;
347 private static final boolean DEBUG_BACKUP = false;
348 private static final boolean DEBUG_INSTALL = false;
349 private static final boolean DEBUG_REMOVE = false;
350 private static final boolean DEBUG_BROADCASTS = false;
351 private static final boolean DEBUG_SHOW_INFO = false;
352 private static final boolean DEBUG_PACKAGE_INFO = false;
353 private static final boolean DEBUG_INTENT_MATCHING = false;
354 private static final boolean DEBUG_PACKAGE_SCANNING = false;
355 private static final boolean DEBUG_VERIFY = false;
356 private static final boolean DEBUG_FILTERS = false;
358 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
359 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
360 // user, but by default initialize to this.
361 static final boolean DEBUG_DEXOPT = false;
363 private static final boolean DEBUG_ABI_SELECTION = false;
364 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
365 private static final boolean DEBUG_TRIAGED_MISSING = false;
366 private static final boolean DEBUG_APP_DATA = false;
368 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
370 private static final boolean DISABLE_EPHEMERAL_APPS = false;
371 private static final boolean HIDE_EPHEMERAL_APIS = true;
373 private static final int RADIO_UID = Process.PHONE_UID;
374 private static final int LOG_UID = Process.LOG_UID;
375 private static final int NFC_UID = Process.NFC_UID;
376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
377 private static final int SHELL_UID = Process.SHELL_UID;
379 // Cap the size of permission trees that 3rd party apps can define
380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text
382 // Suffix used during package installation when copying/moving
383 // package apks to install directory.
384 private static final String INSTALL_PACKAGE_SUFFIX = "-";
386 static final int SCAN_NO_DEX = 1<<1;
387 static final int SCAN_FORCE_DEX = 1<<2;
388 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
389 static final int SCAN_NEW_INSTALL = 1<<4;
390 static final int SCAN_NO_PATHS = 1<<5;
391 static final int SCAN_UPDATE_TIME = 1<<6;
392 static final int SCAN_DEFER_DEX = 1<<7;
393 static final int SCAN_BOOTING = 1<<8;
394 static final int SCAN_TRUSTED_OVERLAY = 1<<9;
395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
396 static final int SCAN_REPLACING = 1<<11;
397 static final int SCAN_REQUIRE_KNOWN = 1<<12;
398 static final int SCAN_MOVE = 1<<13;
399 static final int SCAN_INITIAL = 1<<14;
400 static final int SCAN_CHECK_ONLY = 1<<15;
401 static final int SCAN_DONT_KILL_APP = 1<<17;
402 static final int SCAN_IGNORE_FROZEN = 1<<18;
404 static final int REMOVE_CHATTY = 1<<16;
406 private static final int[] EMPTY_INT_ARRAY = new int[0];
409 * Timeout (in milliseconds) after which the watchdog should declare that
410 * our handler thread is wedged. The usual default for such things is one
411 * minute but we sometimes do very lengthy I/O operations on this thread,
412 * such as installing multi-gigabyte applications, so ours needs to be longer.
414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes
417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
419 * settings entry if available, otherwise we use the hardcoded default. If it's been
420 * more than this long since the last fstrim, we force one during the boot sequence.
422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle,
423 * one gets run at the next available charging+idle time. This final mandatory
424 * no-fstrim check kicks in only of the other scheduling criteria is never met.
426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429 * Whether verification is enabled by default.
431 private static final boolean DEFAULT_VERIFY_ENABLE = true;
434 * The default maximum time to wait for the verification agent to return in
437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440 * The default response for package verification timeout.
442 * This can be either PackageManager.VERIFICATION_ALLOW or
443 * PackageManager.VERIFICATION_REJECT.
445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
447 static final String PLATFORM_PACKAGE_NAME = "android";
449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
452 DEFAULT_CONTAINER_PACKAGE,
453 "com.android.defcontainer.DefaultContainerService");
455 private static final String KILL_APP_REASON_GIDS_CHANGED =
456 "permission grant or revoke changed gids";
458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
459 "permissions revoked";
461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
463 private static final String PACKAGE_SCHEME = "package";
465 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
467 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
468 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
469 * VENDOR_OVERLAY_DIR.
471 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
473 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
474 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
476 /** Permission grant: not grant the permission. */
477 private static final int GRANT_DENIED = 1;
479 /** Permission grant: grant the permission as an install permission. */
480 private static final int GRANT_INSTALL = 2;
482 /** Permission grant: grant the permission as a runtime one. */
483 private static final int GRANT_RUNTIME = 3;
485 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
486 private static final int GRANT_UPGRADE = 4;
488 /** Canonical intent used to identify what counts as a "web browser" app */
489 private static final Intent sBrowserIntent;
491 sBrowserIntent = new Intent();
492 sBrowserIntent.setAction(Intent.ACTION_VIEW);
493 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
494 sBrowserIntent.setData(Uri.parse("http:"));
498 * The set of all protected actions [i.e. those actions for which a high priority
499 * intent filter is disallowed].
501 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
503 PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
504 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
505 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
506 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
509 // Compilation reasons.
510 public static final int REASON_FIRST_BOOT = 0;
511 public static final int REASON_BOOT = 1;
512 public static final int REASON_INSTALL = 2;
513 public static final int REASON_BACKGROUND_DEXOPT = 3;
514 public static final int REASON_AB_OTA = 4;
515 public static final int REASON_NON_SYSTEM_LIBRARY = 5;
516 public static final int REASON_SHARED_APK = 6;
517 public static final int REASON_FORCED_DEXOPT = 7;
518 public static final int REASON_CORE_APP = 8;
520 public static final int REASON_LAST = REASON_CORE_APP;
522 /** Special library name that skips shared libraries check during compilation. */
523 private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
525 final ServiceThread mHandlerThread;
527 final PackageHandler mHandler;
529 private final ProcessLoggingHandler mProcessLoggingHandler;
532 * Messages for {@link #mHandler} that need to wait for system ready before
535 private ArrayList<Message> mPostSystemReadyMessages;
537 final int mSdkVersion = Build.VERSION.SDK_INT;
539 final Context mContext;
540 final boolean mFactoryTest;
541 final boolean mOnlyCore;
542 final DisplayMetrics mMetrics;
543 final int mDefParseFlags;
544 final String[] mSeparateProcesses;
545 final boolean mIsUpgrade;
546 final boolean mIsPreNUpgrade;
547 final boolean mIsPreNMR1Upgrade;
549 @GuardedBy("mPackages")
550 private boolean mDexOptDialogShown;
552 /** The location for ASEC container files on internal storage. */
553 final String mAsecInternalPath;
555 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
556 // LOCK HELD. Can be called with mInstallLock held.
557 @GuardedBy("mInstallLock")
558 final Installer mInstaller;
560 /** Directory where installed third-party apps stored */
561 final File mAppInstallDir;
562 final File mEphemeralInstallDir;
565 * Directory to which applications installed internally have their
566 * 32 bit native libraries copied.
568 private File mAppLib32InstallDir;
570 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
572 final File mDrmAppPrivateInstallDir;
574 // ----------------------------------------------------------------
576 // Lock for state used when installing and doing other long running
577 // operations. Methods that must be called with this lock held have
579 final Object mInstallLock = new Object();
581 // ----------------------------------------------------------------
583 // Keys are String (package name), values are Package. This also serves
584 // as the lock for the global state. Methods that must be called with
585 // this lock held have the prefix "LP".
586 @GuardedBy("mPackages")
587 final ArrayMap<String, PackageParser.Package> mPackages =
588 new ArrayMap<String, PackageParser.Package>();
590 final ArrayMap<String, Set<String>> mKnownCodebase =
591 new ArrayMap<String, Set<String>>();
593 // Tracks available target package names -> overlay package paths.
594 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
595 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
598 * Tracks new system packages [received in an OTA] that we expect to
599 * find updated user-installed versions. Keys are package name, values
600 * are package location.
602 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
604 * Tracks high priority intent filters for protected actions. During boot, certain
605 * filter actions are protected and should never be allowed to have a high priority
606 * intent filter for them. However, there is one, and only one exception -- the
607 * setup wizard. It must be able to define a high priority intent filter for these
608 * actions to ensure there are no escapes from the wizard. We need to delay processing
609 * of these during boot as we need to look at all of the system packages in order
610 * to know which component is the setup wizard.
612 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
614 * Whether or not processing protected filters should be deferred.
616 private boolean mDeferProtectedFilters = true;
619 * Tracks existing system packages prior to receiving an OTA. Keys are package name.
621 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
623 * Whether or not system app permissions should be promoted from install to runtime.
625 boolean mPromoteSystemApps;
627 @GuardedBy("mPackages")
628 final Settings mSettings;
631 * Set of package names that are currently "frozen", which means active
632 * surgery is being done on the code/data for that package. The platform
633 * will refuse to launch frozen packages to avoid race conditions.
635 * @see PackageFreezer
637 @GuardedBy("mPackages")
638 final ArraySet<String> mFrozenPackages = new ArraySet<>();
640 final ProtectedPackages mProtectedPackages;
644 // System configuration read by SystemConfig.
645 final int[] mGlobalGids;
646 final SparseArray<ArraySet<String>> mSystemPermissions;
647 final ArrayMap<String, FeatureInfo> mAvailableFeatures;
649 // If mac_permissions.xml was found for seinfo labeling.
650 boolean mFoundPolicyFile;
652 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
654 public static final class SharedLibraryEntry {
655 public final String path;
656 public final String apk;
658 SharedLibraryEntry(String _path, String _apk) {
664 // Currently known shared libraries.
665 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
666 new ArrayMap<String, SharedLibraryEntry>();
668 // All available activities, for your resolving pleasure.
669 final ActivityIntentResolver mActivities =
670 new ActivityIntentResolver();
672 // All available receivers, for your resolving pleasure.
673 final ActivityIntentResolver mReceivers =
674 new ActivityIntentResolver();
676 // All available services, for your resolving pleasure.
677 final ServiceIntentResolver mServices = new ServiceIntentResolver();
679 // All available providers, for your resolving pleasure.
680 final ProviderIntentResolver mProviders = new ProviderIntentResolver();
682 // Mapping from provider base names (first directory in content URI codePath)
683 // to the provider information.
684 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
685 new ArrayMap<String, PackageParser.Provider>();
687 // Mapping from instrumentation class names to info about them.
688 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
689 new ArrayMap<ComponentName, PackageParser.Instrumentation>();
691 // Mapping from permission names to info about them.
692 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
693 new ArrayMap<String, PackageParser.PermissionGroup>();
695 // Packages whose data we have transfered into another package, thus
696 // should no longer exist.
697 final ArraySet<String> mTransferedPackages = new ArraySet<String>();
699 // Broadcast actions that are only available to the system.
700 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
702 /** List of packages waiting for verification. */
703 final SparseArray<PackageVerificationState> mPendingVerification
704 = new SparseArray<PackageVerificationState>();
706 /** Set of packages associated with each app op permission. */
707 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
709 final PackageInstallerService mInstallerService;
711 private final PackageDexOptimizer mPackageDexOptimizer;
713 private AtomicInteger mNextMoveId = new AtomicInteger();
714 private final MoveCallbacks mMoveCallbacks;
716 private final OnPermissionChangeListeners mOnPermissionChangeListeners;
718 // Cache of users who need badging.
719 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
721 /** Token for keys in mPendingVerification. */
722 private int mPendingVerificationToken = 0;
724 volatile boolean mSystemReady;
725 volatile boolean mSafeMode;
726 volatile boolean mHasSystemUidErrors;
728 ApplicationInfo mAndroidApplication;
729 final ActivityInfo mResolveActivity = new ActivityInfo();
730 final ResolveInfo mResolveInfo = new ResolveInfo();
731 ComponentName mResolveComponentName;
732 PackageParser.Package mPlatformPackage;
733 ComponentName mCustomResolverComponentName;
735 boolean mResolverReplaced = false;
737 private final @Nullable ComponentName mIntentFilterVerifierComponent;
738 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
740 private int mIntentFilterVerificationToken = 0;
742 /** Component that knows whether or not an ephemeral application exists */
743 final ComponentName mEphemeralResolverComponent;
744 /** The service connection to the ephemeral resolver */
745 final EphemeralResolverConnection mEphemeralResolverConnection;
747 /** Component used to install ephemeral applications */
748 final ComponentName mEphemeralInstallerComponent;
749 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
750 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
752 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
753 = new SparseArray<IntentFilterVerificationState>();
755 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
757 // List of packages names to keep cached, even if they are uninstalled for all users
758 private List<String> mKeepUninstalledPackages;
760 private UserManagerInternal mUserManagerInternal;
762 private static class IFVerificationParams {
763 PackageParser.Package pkg;
768 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
769 int _userId, int _verifierUid) {
771 replacing = _replacing;
773 replacing = _replacing;
774 verifierUid = _verifierUid;
778 private interface IntentFilterVerifier<T extends IntentFilter> {
779 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
780 T filter, String packageName);
781 void startVerifications(int userId);
782 void receiveVerificationResponse(int verificationId);
785 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
786 private Context mContext;
787 private ComponentName mIntentFilterVerifierComponent;
788 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
790 public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
792 mIntentFilterVerifierComponent = verifierComponent;
795 private String getDefaultScheme() {
796 return IntentFilter.SCHEME_HTTPS;
800 public void startVerifications(int userId) {
801 // Launch verifications requests
802 int count = mCurrentIntentFilterVerifications.size();
803 for (int n=0; n<count; n++) {
804 int verificationId = mCurrentIntentFilterVerifications.get(n);
805 final IntentFilterVerificationState ivs =
806 mIntentFilterVerificationStates.get(verificationId);
808 String packageName = ivs.getPackageName();
810 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
811 final int filterCount = filters.size();
812 ArraySet<String> domainsSet = new ArraySet<>();
813 for (int m=0; m<filterCount; m++) {
814 PackageParser.ActivityIntentInfo filter = filters.get(m);
815 domainsSet.addAll(filter.getHostsList());
817 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
818 synchronized (mPackages) {
819 if (mSettings.createIntentFilterVerificationIfNeededLPw(
820 packageName, domainsList) != null) {
821 scheduleWriteSettingsLocked();
824 sendVerificationRequest(userId, verificationId, ivs);
826 mCurrentIntentFilterVerifications.clear();
829 private void sendVerificationRequest(int userId, int verificationId,
830 IntentFilterVerificationState ivs) {
832 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
833 verificationIntent.putExtra(
834 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
836 verificationIntent.putExtra(
837 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
839 verificationIntent.putExtra(
840 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
841 ivs.getHostsString());
842 verificationIntent.putExtra(
843 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
844 ivs.getPackageName());
845 verificationIntent.setComponent(mIntentFilterVerifierComponent);
846 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
848 UserHandle user = new UserHandle(userId);
849 mContext.sendBroadcastAsUser(verificationIntent, user);
850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
851 "Sending IntentFilter verification broadcast");
854 public void receiveVerificationResponse(int verificationId) {
855 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
857 final boolean verified = ivs.isVerified();
859 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
860 final int count = filters.size();
861 if (DEBUG_DOMAIN_VERIFICATION) {
862 Slog.i(TAG, "Received verification response " + verificationId
863 + " for " + count + " filters, verified=" + verified);
865 for (int n=0; n<count; n++) {
866 PackageParser.ActivityIntentInfo filter = filters.get(n);
867 filter.setVerified(verified);
869 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
870 + " verified with result:" + verified + " and hosts:"
871 + ivs.getHostsString());
874 mIntentFilterVerificationStates.remove(verificationId);
876 final String packageName = ivs.getPackageName();
877 IntentFilterVerificationInfo ivi = null;
879 synchronized (mPackages) {
880 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
883 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
884 + verificationId + " packageName:" + packageName);
887 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
888 "Updating IntentFilterVerificationInfo for package " + packageName
889 +" verificationId:" + verificationId);
891 synchronized (mPackages) {
893 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
895 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
897 scheduleWriteSettingsLocked();
899 final int userId = ivs.getUserId();
900 if (userId != UserHandle.USER_ALL) {
901 final int userStatus =
902 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
904 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
905 boolean needUpdate = false;
907 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
908 // already been set by the User thru the Disambiguation dialog
909 switch (userStatus) {
910 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
912 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
919 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
921 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
931 mSettings.updateIntentFilterVerificationStatusLPw(
932 packageName, updatedStatus, userId);
933 scheduleWritePackageRestrictionsLocked(userId);
940 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
941 ActivityIntentInfo filter, String packageName) {
942 if (!hasValidDomains(filter)) {
945 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
947 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
950 if (DEBUG_DOMAIN_VERIFICATION) {
951 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
953 ivs.addFilter(filter);
957 private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
958 int userId, int verificationId, String packageName) {
959 IntentFilterVerificationState ivs = new IntentFilterVerificationState(
960 verifierUid, userId, packageName);
961 ivs.setPendingState();
962 synchronized (mPackages) {
963 mIntentFilterVerificationStates.append(verificationId, ivs);
964 mCurrentIntentFilterVerifications.add(verificationId);
970 private static boolean hasValidDomains(ActivityIntentInfo filter) {
971 return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
972 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
973 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
976 // Set of pending broadcasts for aggregating enable/disable of components.
977 static class PendingPackageBroadcasts {
978 // for each user id, a map of <package name -> components within that package>
979 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
981 public PendingPackageBroadcasts() {
982 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
985 public ArrayList<String> get(int userId, String packageName) {
986 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
987 return packages.get(packageName);
990 public void put(int userId, String packageName, ArrayList<String> components) {
991 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
992 packages.put(packageName, components);
995 public void remove(int userId, String packageName) {
996 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
997 if (packages != null) {
998 packages.remove(packageName);
1002 public void remove(int userId) {
1003 mUidMap.remove(userId);
1006 public int userIdCount() {
1007 return mUidMap.size();
1010 public int userIdAt(int n) {
1011 return mUidMap.keyAt(n);
1014 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1015 return mUidMap.get(userId);
1019 // total number of pending broadcast entries across all userIds
1021 for (int i = 0; i< mUidMap.size(); i++) {
1022 num += mUidMap.valueAt(i).size();
1027 public void clear() {
1031 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1032 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1034 map = new ArrayMap<String, ArrayList<String>>();
1035 mUidMap.put(userId, map);
1040 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1042 // Service Connection to remote media container service to copy
1043 // package uri's from external media onto secure containers
1044 // or internal storage.
1045 private IMediaContainerService mContainerService = null;
1047 static final int SEND_PENDING_BROADCAST = 1;
1048 static final int MCS_BOUND = 3;
1049 static final int END_COPY = 4;
1050 static final int INIT_COPY = 5;
1051 static final int MCS_UNBIND = 6;
1052 static final int START_CLEANING_PACKAGE = 7;
1053 static final int FIND_INSTALL_LOC = 8;
1054 static final int POST_INSTALL = 9;
1055 static final int MCS_RECONNECT = 10;
1056 static final int MCS_GIVE_UP = 11;
1057 static final int UPDATED_MEDIA_STATUS = 12;
1058 static final int WRITE_SETTINGS = 13;
1059 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1060 static final int PACKAGE_VERIFIED = 15;
1061 static final int CHECK_PENDING_VERIFICATION = 16;
1062 static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1063 static final int INTENT_FILTER_VERIFIED = 18;
1064 static final int WRITE_PACKAGE_LIST = 19;
1066 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
1068 // Delay time in millisecs
1069 static final int BROADCAST_DELAY = 10 * 1000;
1071 static UserManagerService sUserManager;
1073 // Stores a list of users whose package restrictions file needs to be updated
1074 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1076 final private DefaultContainerConnection mDefContainerConn =
1077 new DefaultContainerConnection();
1078 class DefaultContainerConnection implements ServiceConnection {
1079 public void onServiceConnected(ComponentName name, IBinder service) {
1080 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1081 IMediaContainerService imcs =
1082 IMediaContainerService.Stub.asInterface(service);
1083 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1086 public void onServiceDisconnected(ComponentName name) {
1087 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1091 // Recordkeeping of restore-after-install operations that are currently in flight
1092 // between the Package Manager and the Backup Manager
1093 static class PostInstallData {
1094 public InstallArgs args;
1095 public PackageInstalledInfo res;
1097 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1103 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1104 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
1106 // XML tags for backup/restore of various bits of state
1107 private static final String TAG_PREFERRED_BACKUP = "pa";
1108 private static final String TAG_DEFAULT_APPS = "da";
1109 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1111 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1112 private static final String TAG_ALL_GRANTS = "rt-grants";
1113 private static final String TAG_GRANT = "grant";
1114 private static final String ATTR_PACKAGE_NAME = "pkg";
1116 private static final String TAG_PERMISSION = "perm";
1117 private static final String ATTR_PERMISSION_NAME = "name";
1118 private static final String ATTR_IS_GRANTED = "g";
1119 private static final String ATTR_USER_SET = "set";
1120 private static final String ATTR_USER_FIXED = "fixed";
1121 private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1123 // System/policy permission grants are not backed up
1124 private static final int SYSTEM_RUNTIME_GRANT_MASK =
1125 FLAG_PERMISSION_POLICY_FIXED
1126 | FLAG_PERMISSION_SYSTEM_FIXED
1127 | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1129 // And we back up these user-adjusted states
1130 private static final int USER_RUNTIME_GRANT_MASK =
1131 FLAG_PERMISSION_USER_SET
1132 | FLAG_PERMISSION_USER_FIXED
1133 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1135 final @Nullable String mRequiredVerifierPackage;
1136 final @NonNull String mRequiredInstallerPackage;
1137 final @NonNull String mRequiredUninstallerPackage;
1138 final @Nullable String mSetupWizardPackage;
1139 final @Nullable String mStorageManagerPackage;
1140 final @NonNull String mServicesSystemSharedLibraryPackageName;
1141 final @NonNull String mSharedSystemSharedLibraryPackageName;
1143 final boolean mPermissionReviewRequired;
1145 private final PackageUsage mPackageUsage = new PackageUsage();
1146 private final CompilerStats mCompilerStats = new CompilerStats();
1148 class PackageHandler extends Handler {
1149 private boolean mBound = false;
1150 final ArrayList<HandlerParams> mPendingInstalls =
1151 new ArrayList<HandlerParams>();
1153 private boolean connectToService() {
1154 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1155 " DefaultContainerService");
1156 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1157 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1158 if (mContext.bindServiceAsUser(service, mDefContainerConn,
1159 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1160 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1164 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1168 private void disconnectService() {
1169 mContainerService = null;
1171 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1172 mContext.unbindService(mDefContainerConn);
1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1176 PackageHandler(Looper looper) {
1180 public void handleMessage(Message msg) {
1182 doHandleMessage(msg);
1184 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1188 void doHandleMessage(Message msg) {
1191 HandlerParams params = (HandlerParams) msg.obj;
1192 int idx = mPendingInstalls.size();
1193 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1194 // If a bind was already initiated we dont really
1195 // need to do anything. The pending install
1196 // will be processed later on.
1198 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1199 System.identityHashCode(mHandler));
1200 // If this is the only one pending we might
1201 // have to bind to the service again.
1202 if (!connectToService()) {
1203 Slog.e(TAG, "Failed to bind to media container service");
1204 params.serviceError();
1205 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1206 System.identityHashCode(mHandler));
1207 if (params.traceMethod != null) {
1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1209 params.traceCookie);
1213 // Once we bind to the service, the first
1214 // pending request will be processed.
1215 mPendingInstalls.add(idx, params);
1218 mPendingInstalls.add(idx, params);
1219 // Already bound to the service. Just make
1220 // sure we trigger off processing the first request.
1222 mHandler.sendEmptyMessage(MCS_BOUND);
1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1229 if (msg.obj != null) {
1230 mContainerService = (IMediaContainerService) msg.obj;
1231 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1232 System.identityHashCode(mHandler));
1234 if (mContainerService == null) {
1236 // Something seriously wrong since we are not bound and we are not
1237 // waiting for connection. Bail out.
1238 Slog.e(TAG, "Cannot bind to media container service");
1239 for (HandlerParams params : mPendingInstalls) {
1240 // Indicate service bind error
1241 params.serviceError();
1242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1243 System.identityHashCode(params));
1244 if (params.traceMethod != null) {
1245 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1246 params.traceMethod, params.traceCookie);
1250 mPendingInstalls.clear();
1252 Slog.w(TAG, "Waiting to connect to media container service");
1254 } else if (mPendingInstalls.size() > 0) {
1255 HandlerParams params = mPendingInstalls.get(0);
1256 if (params != null) {
1257 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1258 System.identityHashCode(params));
1259 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1260 if (params.startCopy()) {
1261 // We are done... look for more work or to
1263 if (DEBUG_SD_INSTALL) Log.i(TAG,
1264 "Checking for more work or unbind...");
1265 // Delete pending install
1266 if (mPendingInstalls.size() > 0) {
1267 mPendingInstalls.remove(0);
1269 if (mPendingInstalls.size() == 0) {
1271 if (DEBUG_SD_INSTALL) Log.i(TAG,
1272 "Posting delayed MCS_UNBIND");
1273 removeMessages(MCS_UNBIND);
1274 Message ubmsg = obtainMessage(MCS_UNBIND);
1275 // Unbind after a little delay, to avoid
1276 // continual thrashing.
1277 sendMessageDelayed(ubmsg, 10000);
1280 // There are more pending requests in queue.
1281 // Just post MCS_BOUND message to trigger processing
1282 // of next pending install.
1283 if (DEBUG_SD_INSTALL) Log.i(TAG,
1284 "Posting MCS_BOUND for next work");
1285 mHandler.sendEmptyMessage(MCS_BOUND);
1288 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1291 // Should never happen ideally.
1292 Slog.w(TAG, "Empty queue");
1296 case MCS_RECONNECT: {
1297 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1298 if (mPendingInstalls.size() > 0) {
1300 disconnectService();
1302 if (!connectToService()) {
1303 Slog.e(TAG, "Failed to bind to media container service");
1304 for (HandlerParams params : mPendingInstalls) {
1305 // Indicate service bind error
1306 params.serviceError();
1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1308 System.identityHashCode(params));
1310 mPendingInstalls.clear();
1316 // If there is no actual work left, then time to unbind.
1317 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1319 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1321 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1323 disconnectService();
1325 } else if (mPendingInstalls.size() > 0) {
1326 // There are more pending requests in queue.
1327 // Just post MCS_BOUND message to trigger processing
1328 // of next pending install.
1329 mHandler.sendEmptyMessage(MCS_BOUND);
1335 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1336 HandlerParams params = mPendingInstalls.remove(0);
1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1338 System.identityHashCode(params));
1341 case SEND_PENDING_BROADCAST: {
1343 ArrayList<String> components[];
1346 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1347 synchronized (mPackages) {
1348 if (mPendingBroadcasts == null) {
1351 size = mPendingBroadcasts.size();
1353 // Nothing to be done. Just return
1356 packages = new String[size];
1357 components = new ArrayList[size];
1358 uids = new int[size];
1359 int i = 0; // filling out the above arrays
1361 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1362 int packageUserId = mPendingBroadcasts.userIdAt(n);
1363 Iterator<Map.Entry<String, ArrayList<String>>> it
1364 = mPendingBroadcasts.packagesForUserId(packageUserId)
1365 .entrySet().iterator();
1366 while (it.hasNext() && i < size) {
1367 Map.Entry<String, ArrayList<String>> ent = it.next();
1368 packages[i] = ent.getKey();
1369 components[i] = ent.getValue();
1370 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1371 uids[i] = (ps != null)
1372 ? UserHandle.getUid(packageUserId, ps.appId)
1378 mPendingBroadcasts.clear();
1381 for (int i = 0; i < size; i++) {
1382 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1384 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387 case START_CLEANING_PACKAGE: {
1388 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1389 final String packageName = (String)msg.obj;
1390 final int userId = msg.arg1;
1391 final boolean andCode = msg.arg2 != 0;
1392 synchronized (mPackages) {
1393 if (userId == UserHandle.USER_ALL) {
1394 int[] users = sUserManager.getUserIds();
1395 for (int user : users) {
1396 mSettings.addPackageToCleanLPw(
1397 new PackageCleanItem(user, packageName, andCode));
1400 mSettings.addPackageToCleanLPw(
1401 new PackageCleanItem(userId, packageName, andCode));
1404 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405 startCleaningPackages();
1407 case POST_INSTALL: {
1408 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1410 PostInstallData data = mRunningInstalls.get(msg.arg1);
1411 final boolean didRestore = (msg.arg2 != 0);
1412 mRunningInstalls.delete(msg.arg1);
1415 InstallArgs args = data.args;
1416 PackageInstalledInfo parentRes = data.res;
1418 final boolean grantPermissions = (args.installFlags
1419 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1420 final boolean killApp = (args.installFlags
1421 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1422 final String[] grantedPermissions = args.installGrantPermissions;
1424 // Handle the parent package
1425 handlePackagePostInstall(parentRes, grantPermissions, killApp,
1426 grantedPermissions, didRestore, args.installerPackageName,
1429 // Handle the child packages
1430 final int childCount = (parentRes.addedChildPackages != null)
1431 ? parentRes.addedChildPackages.size() : 0;
1432 for (int i = 0; i < childCount; i++) {
1433 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1434 handlePackagePostInstall(childRes, grantPermissions, killApp,
1435 grantedPermissions, false, args.installerPackageName,
1439 // Log tracing if needed
1440 if (args.traceMethod != null) {
1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1445 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1448 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1450 case UPDATED_MEDIA_STATUS: {
1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1452 boolean reportStatus = msg.arg1 == 1;
1453 boolean doGc = msg.arg2 == 1;
1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1456 // Force a gc to clear up stale containers.
1457 Runtime.getRuntime().gc();
1459 if (msg.obj != null) {
1460 @SuppressWarnings("unchecked")
1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1463 // Unload containers
1464 unloadAllContainers(args);
1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1469 PackageHelper.getMountService().finishMediaUpdate();
1470 } catch (RemoteException e) {
1471 Log.e(TAG, "MountService not running?");
1475 case WRITE_SETTINGS: {
1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1477 synchronized (mPackages) {
1478 removeMessages(WRITE_SETTINGS);
1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1480 mSettings.writeLPr();
1481 mDirtyUsers.clear();
1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485 case WRITE_PACKAGE_RESTRICTIONS: {
1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487 synchronized (mPackages) {
1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1489 for (int userId : mDirtyUsers) {
1490 mSettings.writePackageRestrictionsLPr(userId);
1492 mDirtyUsers.clear();
1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496 case WRITE_PACKAGE_LIST: {
1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498 synchronized (mPackages) {
1499 removeMessages(WRITE_PACKAGE_LIST);
1500 mSettings.writePackageListLPr(msg.arg1);
1502 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504 case CHECK_PENDING_VERIFICATION: {
1505 final int verificationId = msg.arg1;
1506 final PackageVerificationState state = mPendingVerification.get(verificationId);
1508 if ((state != null) && !state.timeoutExtended()) {
1509 final InstallArgs args = state.getInstallArgs();
1510 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512 Slog.i(TAG, "Verification timed out for " + originUri);
1513 mPendingVerification.remove(verificationId);
1515 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1517 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1518 Slog.i(TAG, "Continuing with installation of " + originUri);
1519 state.setVerifierResponse(Binder.getCallingUid(),
1520 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1521 broadcastPackageVerified(verificationId, originUri,
1522 PackageManager.VERIFICATION_ALLOW,
1523 state.getInstallArgs().getUser());
1525 ret = args.copyApk(mContainerService, true);
1526 } catch (RemoteException e) {
1527 Slog.e(TAG, "Could not contact the ContainerService");
1530 broadcastPackageVerified(verificationId, originUri,
1531 PackageManager.VERIFICATION_REJECT,
1532 state.getInstallArgs().getUser());
1535 Trace.asyncTraceEnd(
1536 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1538 processPendingInstall(args, ret);
1539 mHandler.sendEmptyMessage(MCS_UNBIND);
1543 case PACKAGE_VERIFIED: {
1544 final int verificationId = msg.arg1;
1546 final PackageVerificationState state = mPendingVerification.get(verificationId);
1547 if (state == null) {
1548 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1552 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1554 state.setVerifierResponse(response.callerUid, response.code);
1556 if (state.isVerificationComplete()) {
1557 mPendingVerification.remove(verificationId);
1559 final InstallArgs args = state.getInstallArgs();
1560 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1563 if (state.isInstallAllowed()) {
1564 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1565 broadcastPackageVerified(verificationId, originUri,
1566 response.code, state.getInstallArgs().getUser());
1568 ret = args.copyApk(mContainerService, true);
1569 } catch (RemoteException e) {
1570 Slog.e(TAG, "Could not contact the ContainerService");
1573 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1576 Trace.asyncTraceEnd(
1577 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1579 processPendingInstall(args, ret);
1580 mHandler.sendEmptyMessage(MCS_UNBIND);
1585 case START_INTENT_FILTER_VERIFICATIONS: {
1586 IFVerificationParams params = (IFVerificationParams) msg.obj;
1587 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1588 params.replacing, params.pkg);
1591 case INTENT_FILTER_VERIFIED: {
1592 final int verificationId = msg.arg1;
1594 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1596 if (state == null) {
1597 Slog.w(TAG, "Invalid IntentFilter verification token "
1598 + verificationId + " received");
1602 final int userId = state.getUserId();
1604 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1605 "Processing IntentFilter verification with token:"
1606 + verificationId + " and userId:" + userId);
1608 final IntentFilterVerificationResponse response =
1609 (IntentFilterVerificationResponse) msg.obj;
1611 state.setVerifierResponse(response.callerUid, response.code);
1613 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614 "IntentFilter verification with token:" + verificationId
1615 + " and userId:" + userId
1616 + " is settings verifier response with response code:"
1619 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1621 + response.getFailedDomainsString());
1624 if (state.isVerificationComplete()) {
1625 mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1628 "IntentFilter verification with token:" + verificationId
1629 + " was not said to be complete");
1638 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1639 boolean killApp, String[] grantedPermissions,
1640 boolean launchedForRestore, String installerPackage,
1641 IPackageInstallObserver2 installObserver) {
1642 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1643 // Send the removed broadcasts
1644 if (res.removedInfo != null) {
1645 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1648 // Now that we successfully installed the package, grant runtime
1649 // permissions if requested before broadcasting the install.
1650 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1651 >= Build.VERSION_CODES.M) {
1652 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1655 final boolean update = res.removedInfo != null
1656 && res.removedInfo.removedPackage != null;
1658 // If this is the first time we have child packages for a disabled privileged
1659 // app that had no children, we grant requested runtime permissions to the new
1660 // children if the parent on the system image had them already granted.
1661 if (res.pkg.parentPackage != null) {
1662 synchronized (mPackages) {
1663 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1667 synchronized (mPackages) {
1668 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1671 final String packageName = res.pkg.applicationInfo.packageName;
1672 Bundle extras = new Bundle(1);
1673 extras.putInt(Intent.EXTRA_UID, res.uid);
1675 // Determine the set of users who are adding this package for
1676 // the first time vs. those who are seeing an update.
1677 int[] firstUsers = EMPTY_INT_ARRAY;
1678 int[] updateUsers = EMPTY_INT_ARRAY;
1679 if (res.origUsers == null || res.origUsers.length == 0) {
1680 firstUsers = res.newUsers;
1682 for (int newUser : res.newUsers) {
1683 boolean isNew = true;
1684 for (int origUser : res.origUsers) {
1685 if (origUser == newUser) {
1691 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1693 updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1698 // Send installed broadcasts if the install/update is not ephemeral
1699 if (!isEphemeral(res.pkg)) {
1700 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1702 // Send added for users that see the package for the first time
1703 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1704 extras, 0 /*flags*/, null /*targetPackage*/,
1705 null /*finishedReceiver*/, firstUsers);
1707 // Send added for users that don't see the package for the first time
1709 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1711 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1712 extras, 0 /*flags*/, null /*targetPackage*/,
1713 null /*finishedReceiver*/, updateUsers);
1715 // Send replaced for users that don't see the package for the first time
1717 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1718 packageName, extras, 0 /*flags*/,
1719 null /*targetPackage*/, null /*finishedReceiver*/,
1721 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1722 null /*package*/, null /*extras*/, 0 /*flags*/,
1723 packageName /*targetPackage*/,
1724 null /*finishedReceiver*/, updateUsers);
1725 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1726 // First-install and we did a restore, so we're responsible for the
1727 // first-launch broadcast.
1729 Slog.i(TAG, "Post-restore of " + packageName
1730 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1732 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1735 // Send broadcast package appeared if forward locked/external for all users
1736 // treat asec-hosted packages like removable media on upgrade
1737 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1738 if (DEBUG_INSTALL) {
1739 Slog.i(TAG, "upgrading pkg " + res.pkg
1740 + " is ASEC-hosted -> AVAILABLE");
1742 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1743 ArrayList<String> pkgList = new ArrayList<>(1);
1744 pkgList.add(packageName);
1745 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1749 // Work that needs to happen on first install within each user
1750 if (firstUsers != null && firstUsers.length > 0) {
1751 synchronized (mPackages) {
1752 for (int userId : firstUsers) {
1753 // If this app is a browser and it's newly-installed for some
1754 // users, clear any default-browser state in those users. The
1755 // app's nature doesn't depend on the user, so we can just check
1756 // its browser nature in any user and generalize.
1757 if (packageIsBrowser(packageName, userId)) {
1758 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1761 // We may also need to apply pending (restored) runtime
1762 // permission grants within these users.
1763 mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1768 // Log current value of "unknown sources" setting
1769 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1770 getUnknownSourcesSettings());
1772 // Force a gc to clear up things
1773 Runtime.getRuntime().gc();
1775 // Remove the replaced package's older resources safely now
1776 // We delete after a gc for applications on sdcard.
1777 if (res.removedInfo != null && res.removedInfo.args != null) {
1778 synchronized (mInstallLock) {
1779 res.removedInfo.args.doPostDeleteLI(true);
1784 // If someone is watching installs - notify them
1785 if (installObserver != null) {
1787 Bundle extras = extrasForInstallResult(res);
1788 installObserver.onPackageInstalled(res.name, res.returnCode,
1789 res.returnMsg, extras);
1790 } catch (RemoteException e) {
1791 Slog.i(TAG, "Observer no longer exists.");
1796 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1797 PackageParser.Package pkg) {
1798 if (pkg.parentPackage == null) {
1801 if (pkg.requestedPermissions == null) {
1804 final PackageSetting disabledSysParentPs = mSettings
1805 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1806 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1807 || !disabledSysParentPs.isPrivileged()
1808 || (disabledSysParentPs.childPackageNames != null
1809 && !disabledSysParentPs.childPackageNames.isEmpty())) {
1812 final int[] allUserIds = sUserManager.getUserIds();
1813 final int permCount = pkg.requestedPermissions.size();
1814 for (int i = 0; i < permCount; i++) {
1815 String permission = pkg.requestedPermissions.get(i);
1816 BasePermission bp = mSettings.mPermissions.get(permission);
1817 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1820 for (int userId : allUserIds) {
1821 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1822 permission, userId)) {
1823 grantRuntimePermission(pkg.packageName, permission, userId);
1829 private StorageEventListener mStorageListener = new StorageEventListener() {
1831 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1832 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1833 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1834 final String volumeUuid = vol.getFsUuid();
1836 // Clean up any users or apps that were removed or recreated
1837 // while this volume was missing
1838 reconcileUsers(volumeUuid);
1839 reconcileApps(volumeUuid);
1841 // Clean up any install sessions that expired or were
1842 // cancelled while this volume was missing
1843 mInstallerService.onPrivateVolumeMounted(volumeUuid);
1845 loadPrivatePackages(vol);
1847 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1848 unloadPrivatePackages(vol);
1852 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1853 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1854 updateExternalMediaStatus(true, false);
1855 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1856 updateExternalMediaStatus(false, false);
1862 public void onVolumeForgotten(String fsUuid) {
1863 if (TextUtils.isEmpty(fsUuid)) {
1864 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1868 // Remove any apps installed on the forgotten volume
1869 synchronized (mPackages) {
1870 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1871 for (PackageSetting ps : packages) {
1872 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1873 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1874 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1877 mSettings.onVolumeForgotten(fsUuid);
1878 mSettings.writeLPr();
1883 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1884 String[] grantedPermissions) {
1885 for (int userId : userIds) {
1886 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1889 // We could have touched GID membership, so flush out packages.list
1890 synchronized (mPackages) {
1891 mSettings.writePackageListLPr();
1895 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1896 String[] grantedPermissions) {
1897 SettingBase sb = (SettingBase) pkg.mExtras;
1902 PermissionsState permissionsState = sb.getPermissionsState();
1904 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1905 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1907 for (String permission : pkg.requestedPermissions) {
1908 final BasePermission bp;
1909 synchronized (mPackages) {
1910 bp = mSettings.mPermissions.get(permission);
1912 if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1913 && (grantedPermissions == null
1914 || ArrayUtils.contains(grantedPermissions, permission))) {
1915 final int flags = permissionsState.getPermissionFlags(permission, userId);
1916 // Installer cannot change immutable permissions.
1917 if ((flags & immutableFlags) == 0) {
1918 grantRuntimePermission(pkg.packageName, permission, userId);
1924 Bundle extrasForInstallResult(PackageInstalledInfo res) {
1925 Bundle extras = null;
1926 switch (res.returnCode) {
1927 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1928 extras = new Bundle();
1929 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1930 res.origPermission);
1931 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1935 case PackageManager.INSTALL_SUCCEEDED: {
1936 extras = new Bundle();
1937 extras.putBoolean(Intent.EXTRA_REPLACING,
1938 res.removedInfo != null && res.removedInfo.removedPackage != null);
1945 void scheduleWriteSettingsLocked() {
1946 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1947 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1951 void scheduleWritePackageListLocked(int userId) {
1952 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1953 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1955 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1959 void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1960 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1961 scheduleWritePackageRestrictionsLocked(userId);
1964 void scheduleWritePackageRestrictionsLocked(int userId) {
1965 final int[] userIds = (userId == UserHandle.USER_ALL)
1966 ? sUserManager.getUserIds() : new int[]{userId};
1967 for (int nextUserId : userIds) {
1968 if (!sUserManager.exists(nextUserId)) return;
1969 mDirtyUsers.add(nextUserId);
1970 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1971 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1976 public static PackageManagerService main(Context context, Installer installer,
1977 boolean factoryTest, boolean onlyCore) {
1978 // Self-check for initial settings.
1979 PackageManagerServiceCompilerMapping.checkProperties();
1981 PackageManagerService m = new PackageManagerService(context, installer,
1982 factoryTest, onlyCore);
1983 m.enableSystemUserPackages();
1984 ServiceManager.addService("package", m);
1988 private void enableSystemUserPackages() {
1989 if (!UserManager.isSplitSystemUser()) {
1992 // For system user, enable apps based on the following conditions:
1993 // - app is whitelisted or belong to one of these groups:
1994 // -- system app which has no launcher icons
1995 // -- system app which has INTERACT_ACROSS_USERS permission
1996 // -- system IME app
1997 // - app is not in the blacklist
1998 AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1999 Set<String> enableApps = new ArraySet<>();
2000 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2001 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2002 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2003 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2004 enableApps.addAll(wlApps);
2005 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2006 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2007 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2008 enableApps.removeAll(blApps);
2009 Log.i(TAG, "Applications installed for system user: " + enableApps);
2010 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2012 final int allAppsSize = allAps.size();
2013 synchronized (mPackages) {
2014 for (int i = 0; i < allAppsSize; i++) {
2015 String pName = allAps.get(i);
2016 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2017 // Should not happen, but we shouldn't be failing if it does
2018 if (pkgSetting == null) {
2021 boolean install = enableApps.contains(pName);
2022 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2023 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2024 + " for system user");
2025 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2031 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2032 DisplayManager displayManager = (DisplayManager) context.getSystemService(
2033 Context.DISPLAY_SERVICE);
2034 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2038 * Requests that files preopted on a secondary system partition be copied to the data partition
2039 * if possible. Note that the actual copying of the files is accomplished by init for security
2040 * reasons. This simply requests that the copy takes place and awaits confirmation of its
2041 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2043 private static void requestCopyPreoptedFiles() {
2044 final int WAIT_TIME_MS = 100;
2045 final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2046 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2047 SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2048 // We will wait for up to 100 seconds.
2049 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2050 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2052 Thread.sleep(WAIT_TIME_MS);
2053 } catch (InterruptedException e) {
2056 if (SystemClock.uptimeMillis() > timeEnd) {
2057 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2058 Slog.wtf(TAG, "cppreopt did not finish!");
2065 public PackageManagerService(Context context, Installer installer,
2066 boolean factoryTest, boolean onlyCore) {
2067 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2068 SystemClock.uptimeMillis());
2070 if (mSdkVersion <= 0) {
2071 Slog.w(TAG, "**** ro.build.version.sdk not set!");
2076 mPermissionReviewRequired = context.getResources().getBoolean(
2077 R.bool.config_permissionReviewRequired);
2079 mFactoryTest = factoryTest;
2080 mOnlyCore = onlyCore;
2081 mMetrics = new DisplayMetrics();
2082 mSettings = new Settings(mPackages);
2083 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2084 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2085 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2086 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2087 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2088 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2089 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2090 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2091 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2092 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2093 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2094 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096 String separateProcesses = SystemProperties.get("debug.separate_processes");
2097 if (separateProcesses != null && separateProcesses.length() > 0) {
2098 if ("*".equals(separateProcesses)) {
2099 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2100 mSeparateProcesses = null;
2101 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2104 mSeparateProcesses = separateProcesses.split(",");
2105 Slog.w(TAG, "Running with debug.separate_processes: "
2106 + separateProcesses);
2110 mSeparateProcesses = null;
2113 mInstaller = installer;
2114 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2116 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2118 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2119 FgThread.get().getLooper());
2121 getDefaultDisplayMetrics(context, mMetrics);
2123 SystemConfig systemConfig = SystemConfig.getInstance();
2124 mGlobalGids = systemConfig.getGlobalGids();
2125 mSystemPermissions = systemConfig.getSystemPermissions();
2126 mAvailableFeatures = systemConfig.getAvailableFeatures();
2128 mProtectedPackages = new ProtectedPackages(mContext);
2130 synchronized (mInstallLock) {
2132 synchronized (mPackages) {
2133 mHandlerThread = new ServiceThread(TAG,
2134 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2135 mHandlerThread.start();
2136 mHandler = new PackageHandler(mHandlerThread.getLooper());
2137 mProcessLoggingHandler = new ProcessLoggingHandler();
2138 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2140 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2142 File dataDir = Environment.getDataDirectory();
2143 mAppInstallDir = new File(dataDir, "app");
2144 mAppLib32InstallDir = new File(dataDir, "app-lib");
2145 mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2146 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2147 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2149 sUserManager = new UserManagerService(context, this, mPackages);
2151 // Propagate permission configuration in to package manager.
2152 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2153 = systemConfig.getPermissions();
2154 for (int i=0; i<permConfig.size(); i++) {
2155 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2156 BasePermission bp = mSettings.mPermissions.get(perm.name);
2158 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2159 mSettings.mPermissions.put(perm.name, bp);
2161 if (perm.gids != null) {
2162 bp.setGids(perm.gids, perm.perUser);
2166 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2167 for (int i=0; i<libConfig.size(); i++) {
2168 mSharedLibraries.put(libConfig.keyAt(i),
2169 new SharedLibraryEntry(libConfig.valueAt(i), null));
2172 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2174 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2176 // Clean up orphaned packages for which the code path doesn't exist
2177 // and they are an update to a system app - caused by bug/32321269
2178 final int packageSettingCount = mSettings.mPackages.size();
2179 for (int i = packageSettingCount - 1; i >= 0; i--) {
2180 PackageSetting ps = mSettings.mPackages.valueAt(i);
2181 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2182 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2183 mSettings.mPackages.removeAt(i);
2184 mSettings.enableSystemPackageLPw(ps.name);
2189 requestCopyPreoptedFiles();
2192 String customResolverActivity = Resources.getSystem().getString(
2193 R.string.config_customResolverActivity);
2194 if (TextUtils.isEmpty(customResolverActivity)) {
2195 customResolverActivity = null;
2197 mCustomResolverComponentName = ComponentName.unflattenFromString(
2198 customResolverActivity);
2201 long startTime = SystemClock.uptimeMillis();
2203 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2206 // Set flag to monitor and not change apk file paths when
2207 // scanning install directories.
2208 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2210 final String bootClassPath = System.getenv("BOOTCLASSPATH");
2211 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2213 if (bootClassPath == null) {
2214 Slog.w(TAG, "No BOOTCLASSPATH found!");
2217 if (systemServerClassPath == null) {
2218 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2221 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2222 final String[] dexCodeInstructionSets =
2223 getDexCodeInstructionSets(
2224 allInstructionSets.toArray(new String[allInstructionSets.size()]));
2227 * Ensure all external libraries have had dexopt run on them.
2229 if (mSharedLibraries.size() > 0) {
2230 // NOTE: For now, we're compiling these system "shared libraries"
2231 // (and framework jars) into all available architectures. It's possible
2232 // to compile them only when we come across an app that uses them (there's
2233 // already logic for that in scanPackageLI) but that adds some complexity.
2234 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2235 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2236 final String lib = libEntry.path;
2242 // Shared libraries do not have profiles so we perform a full
2243 // AOT compilation (if needed).
2244 int dexoptNeeded = DexFile.getDexOptNeeded(
2245 lib, dexCodeInstructionSet,
2246 getCompilerFilterForReason(REASON_SHARED_APK),
2247 false /* newProfile */);
2248 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2249 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2250 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2251 getCompilerFilterForReason(REASON_SHARED_APK),
2252 StorageManager.UUID_PRIVATE_INTERNAL,
2253 SKIP_SHARED_LIBRARY_CHECK);
2255 } catch (FileNotFoundException e) {
2256 Slog.w(TAG, "Library not found: " + lib);
2257 } catch (IOException | InstallerException e) {
2258 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2265 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2267 final VersionInfo ver = mSettings.getInternalVersion();
2268 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2270 // when upgrading from pre-M, promote system app permissions from install to runtime
2271 mPromoteSystemApps =
2272 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2274 // When upgrading from pre-N, we need to handle package extraction like first boot,
2275 // as there is no profiling data available.
2276 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2278 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2280 // save off the names of pre-existing system packages prior to scanning; we don't
2281 // want to automatically grant runtime permissions for new system apps
2282 if (mPromoteSystemApps) {
2283 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2284 while (pkgSettingIter.hasNext()) {
2285 PackageSetting ps = pkgSettingIter.next();
2286 if (isSystemApp(ps)) {
2287 mExistingSystemPackages.add(ps.name);
2292 // Collect vendor overlay packages. (Do this before scanning any apps.)
2293 // For security and version matching reason, only consider
2294 // overlay packages if they reside in the right directory.
2295 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2296 if (!overlayThemeDir.isEmpty()) {
2297 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2298 | PackageParser.PARSE_IS_SYSTEM
2299 | PackageParser.PARSE_IS_SYSTEM_DIR
2300 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2302 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2303 | PackageParser.PARSE_IS_SYSTEM
2304 | PackageParser.PARSE_IS_SYSTEM_DIR
2305 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2307 // Find base frameworks (resource packages without code).
2308 scanDirTracedLI(frameworkDir, mDefParseFlags
2309 | PackageParser.PARSE_IS_SYSTEM
2310 | PackageParser.PARSE_IS_SYSTEM_DIR
2311 | PackageParser.PARSE_IS_PRIVILEGED,
2312 scanFlags | SCAN_NO_DEX, 0);
2314 // Collected privileged system packages.
2315 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2316 scanDirTracedLI(privilegedAppDir, mDefParseFlags
2317 | PackageParser.PARSE_IS_SYSTEM
2318 | PackageParser.PARSE_IS_SYSTEM_DIR
2319 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2321 // Collect ordinary system packages.
2322 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2323 scanDirTracedLI(systemAppDir, mDefParseFlags
2324 | PackageParser.PARSE_IS_SYSTEM
2325 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2327 // Collect all vendor packages.
2328 File vendorAppDir = new File("/vendor/app");
2330 vendorAppDir = vendorAppDir.getCanonicalFile();
2331 } catch (IOException e) {
2332 // failed to look up canonical path, continue with original one
2334 scanDirTracedLI(vendorAppDir, mDefParseFlags
2335 | PackageParser.PARSE_IS_SYSTEM
2336 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2338 // Collect all OEM packages.
2339 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2340 scanDirTracedLI(oemAppDir, mDefParseFlags
2341 | PackageParser.PARSE_IS_SYSTEM
2342 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2344 // Prune any system packages that no longer exist.
2345 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2347 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2348 while (psit.hasNext()) {
2349 PackageSetting ps = psit.next();
2352 * If this is not a system app, it can't be a
2353 * disable system app.
2355 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2360 * If the package is scanned, it's not erased.
2362 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2363 if (scannedPkg != null) {
2365 * If the system app is both scanned and in the
2366 * disabled packages list, then it must have been
2367 * added via OTA. Remove it from the currently
2368 * scanned package so the previously user-installed
2369 * application can be scanned.
2371 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2372 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2373 + ps.name + "; removing system app. Last known codePath="
2374 + ps.codePathString + ", installStatus=" + ps.installStatus
2375 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2376 + scannedPkg.mVersionCode);
2377 removePackageLI(scannedPkg, true);
2378 mExpectingBetter.put(ps.name, ps.codePath);
2384 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2386 logCriticalInfo(Log.WARN, "System package " + ps.name
2387 + " no longer exists; it's data will be wiped");
2388 // Actual deletion of code and data will be handled by later
2389 // reconciliation step
2391 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2392 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2393 possiblyDeletedUpdatedSystemApps.add(ps.name);
2399 //look for any incomplete package installations
2400 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2401 for (int i = 0; i < deletePkgsList.size(); i++) {
2402 // Actual deletion of code and data will be handled by later
2403 // reconciliation step
2404 final String packageName = deletePkgsList.get(i).name;
2405 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2406 synchronized (mPackages) {
2407 mSettings.removePackageLPw(packageName);
2412 deleteTempPackageFiles();
2414 // Remove any shared userIDs that have no associated packages
2415 mSettings.pruneSharedUsersLPw();
2418 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2419 SystemClock.uptimeMillis());
2420 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2422 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2423 | PackageParser.PARSE_FORWARD_LOCK,
2424 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2426 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2427 | PackageParser.PARSE_IS_EPHEMERAL,
2428 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2431 * Remove disable package settings for any updated system
2432 * apps that were removed via an OTA. If they're not a
2433 * previously-updated app, remove them completely.
2434 * Otherwise, just revoke their system-level permissions.
2436 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2437 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2438 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2441 if (deletedPkg == null) {
2442 msg = "Updated system package " + deletedAppName
2443 + " no longer exists; it's data will be wiped";
2444 // Actual deletion of code and data will be handled by later
2445 // reconciliation step
2447 msg = "Updated system app + " + deletedAppName
2448 + " no longer present; removing system privileges for "
2451 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2453 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2454 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2456 logCriticalInfo(Log.WARN, msg);
2460 * Make sure all system apps that we expected to appear on
2461 * the userdata partition actually showed up. If they never
2462 * appeared, crawl back and revive the system version.
2464 for (int i = 0; i < mExpectingBetter.size(); i++) {
2465 final String packageName = mExpectingBetter.keyAt(i);
2466 if (!mPackages.containsKey(packageName)) {
2467 final File scanFile = mExpectingBetter.valueAt(i);
2469 logCriticalInfo(Log.WARN, "Expected better " + packageName
2470 + " but never showed up; reverting to system");
2472 int reparseFlags = mDefParseFlags;
2473 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2474 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2475 | PackageParser.PARSE_IS_SYSTEM_DIR
2476 | PackageParser.PARSE_IS_PRIVILEGED;
2477 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2478 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2479 | PackageParser.PARSE_IS_SYSTEM_DIR;
2480 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2481 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2482 | PackageParser.PARSE_IS_SYSTEM_DIR;
2483 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2484 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2485 | PackageParser.PARSE_IS_SYSTEM_DIR;
2487 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2491 mSettings.enableSystemPackageLPw(packageName);
2494 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2495 } catch (PackageManagerException e) {
2496 Slog.e(TAG, "Failed to parse original system package: "
2502 mExpectingBetter.clear();
2504 // Resolve the storage manager.
2505 mStorageManagerPackage = getStorageManagerPackageName();
2507 // Resolve protected action filters. Only the setup wizard is allowed to
2508 // have a high priority filter for these actions.
2509 mSetupWizardPackage = getSetupWizardPackageName();
2510 if (mProtectedFilters.size() > 0) {
2511 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2512 Slog.i(TAG, "No setup wizard;"
2513 + " All protected intents capped to priority 0");
2515 for (ActivityIntentInfo filter : mProtectedFilters) {
2516 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2517 if (DEBUG_FILTERS) {
2518 Slog.i(TAG, "Found setup wizard;"
2519 + " allow priority " + filter.getPriority() + ";"
2520 + " package: " + filter.activity.info.packageName
2521 + " activity: " + filter.activity.className
2522 + " priority: " + filter.getPriority());
2524 // skip setup wizard; allow it to keep the high priority filter
2527 Slog.w(TAG, "Protected action; cap priority to 0;"
2528 + " package: " + filter.activity.info.packageName
2529 + " activity: " + filter.activity.className
2530 + " origPrio: " + filter.getPriority());
2531 filter.setPriority(0);
2534 mDeferProtectedFilters = false;
2535 mProtectedFilters.clear();
2537 // Now that we know all of the shared libraries, update all clients to have
2538 // the correct library paths.
2539 updateAllSharedLibrariesLPw();
2541 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2542 // NOTE: We ignore potential failures here during a system scan (like
2543 // the rest of the commands above) because there's precious little we
2544 // can do about it. A settings error is reported, though.
2545 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2546 false /* boot complete */);
2549 // Now that we know all the packages we are keeping,
2550 // read and update their last usage times.
2551 mPackageUsage.read(mPackages);
2552 mCompilerStats.read();
2554 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2555 SystemClock.uptimeMillis());
2556 Slog.i(TAG, "Time to scan packages: "
2557 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2560 // If the platform SDK has changed since the last time we booted,
2561 // we need to re-grant app permission to catch any new ones that
2562 // appear. This is really a hack, and means that apps can in some
2563 // cases get permissions that the user didn't initially explicitly
2564 // allow... it would be nice to have some better way to handle
2566 int updateFlags = UPDATE_PERMISSIONS_ALL;
2567 if (ver.sdkVersion != mSdkVersion) {
2568 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2569 + mSdkVersion + "; regranting permissions for internal storage");
2570 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2572 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2573 ver.sdkVersion = mSdkVersion;
2575 // If this is the first boot or an update from pre-M, and it is a normal
2576 // boot, then we need to initialize the default preferred apps across
2577 // all defined users.
2578 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2579 for (UserInfo user : sUserManager.getUsers(true)) {
2580 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2581 applyFactoryDefaultBrowserLPw(user.id);
2582 primeDomainVerificationsLPw(user.id);
2586 // Prepare storage for system user really early during boot,
2587 // since core system apps like SettingsProvider and SystemUI
2588 // can't wait for user to start
2589 final int storageFlags;
2590 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2591 storageFlags = StorageManager.FLAG_STORAGE_DE;
2593 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2595 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2598 // If this is first boot after an OTA, and a normal boot, then
2599 // we need to clear code cache directories.
2600 // Note that we do *not* clear the application profiles. These remain valid
2601 // across OTAs and are used to drive profile verification (post OTA) and
2602 // profile compilation (without waiting to collect a fresh set of profiles).
2603 if (mIsUpgrade && !onlyCore) {
2604 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2605 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2606 final PackageSetting ps = mSettings.mPackages.valueAt(i);
2607 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2608 // No apps are running this early, so no need to freeze
2609 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2610 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2611 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2614 ver.fingerprint = Build.FINGERPRINT;
2617 checkDefaultBrowser();
2619 // clear only after permissions and other defaults have been updated
2620 mExistingSystemPackages.clear();
2621 mPromoteSystemApps = false;
2623 // All the changes are done during package scanning.
2624 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2626 // can downgrade to reader
2627 mSettings.writeLPr();
2629 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2630 // early on (before the package manager declares itself as early) because other
2631 // components in the system server might ask for package contexts for these apps.
2633 // Note that "onlyCore" in this context means the system is encrypted or encrypting
2634 // (i.e, that the data partition is unavailable).
2635 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2636 long start = System.nanoTime();
2637 List<PackageParser.Package> coreApps = new ArrayList<>();
2638 for (PackageParser.Package pkg : mPackages.values()) {
2644 int[] stats = performDexOptUpgrade(coreApps, false,
2645 getCompilerFilterForReason(REASON_CORE_APP));
2647 final int elapsedTimeSeconds =
2648 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2649 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2652 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2653 stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2657 // TODO: Should we log these stats to tron too ?
2658 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2659 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2660 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2661 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2664 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2665 SystemClock.uptimeMillis());
2668 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2669 mRequiredInstallerPackage = getRequiredInstallerLPr();
2670 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2671 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2672 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2673 mIntentFilterVerifierComponent);
2674 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2675 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2676 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2677 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2679 mRequiredVerifierPackage = null;
2680 mRequiredInstallerPackage = null;
2681 mRequiredUninstallerPackage = null;
2682 mIntentFilterVerifierComponent = null;
2683 mIntentFilterVerifier = null;
2684 mServicesSystemSharedLibraryPackageName = null;
2685 mSharedSystemSharedLibraryPackageName = null;
2688 mInstallerService = new PackageInstallerService(context, this);
2690 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2691 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2692 // both the installer and resolver must be present to enable ephemeral
2693 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2694 if (DEBUG_EPHEMERAL) {
2695 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2696 + " installer:" + ephemeralInstallerComponent);
2698 mEphemeralResolverComponent = ephemeralResolverComponent;
2699 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2700 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2701 mEphemeralResolverConnection =
2702 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2704 if (DEBUG_EPHEMERAL) {
2705 final String missingComponent =
2706 (ephemeralResolverComponent == null)
2707 ? (ephemeralInstallerComponent == null)
2708 ? "resolver and installer"
2711 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2713 mEphemeralResolverComponent = null;
2714 mEphemeralInstallerComponent = null;
2715 mEphemeralResolverConnection = null;
2718 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2719 } // synchronized (mPackages)
2720 } // synchronized (mInstallLock)
2722 // Now after opening every single application zip, make sure they
2723 // are all flushed. Not really needed, but keeps things nice and
2725 Runtime.getRuntime().gc();
2727 // The initial scanning above does many calls into installd while
2728 // holding the mPackages lock, but we're mostly interested in yelling
2729 // once we have a booted system.
2730 mInstaller.setWarnIfHeld(mPackages);
2732 // Expose private service for system components to use.
2733 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2737 public boolean isFirstBoot() {
2742 public boolean isOnlyCoreApps() {
2747 public boolean isUpgrade() {
2751 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2752 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2754 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2755 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2756 UserHandle.USER_SYSTEM);
2757 if (matches.size() == 1) {
2758 return matches.get(0).getComponentInfo().packageName;
2759 } else if (matches.size() == 0) {
2760 Log.e(TAG, "There should probably be a verifier, but, none were found");
2763 throw new RuntimeException("There must be exactly one verifier; found " + matches);
2766 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2767 synchronized (mPackages) {
2768 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2769 if (libraryEntry == null) {
2770 throw new IllegalStateException("Missing required shared library:" + libraryName);
2772 return libraryEntry.apk;
2776 private @NonNull String getRequiredInstallerLPr() {
2777 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2778 intent.addCategory(Intent.CATEGORY_DEFAULT);
2779 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2781 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2782 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2783 UserHandle.USER_SYSTEM);
2784 if (matches.size() == 1) {
2785 ResolveInfo resolveInfo = matches.get(0);
2786 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2787 throw new RuntimeException("The installer must be a privileged app");
2789 return matches.get(0).getComponentInfo().packageName;
2791 throw new RuntimeException("There must be exactly one installer; found " + matches);
2795 private @NonNull String getRequiredUninstallerLPr() {
2796 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2797 intent.addCategory(Intent.CATEGORY_DEFAULT);
2798 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2800 final ResolveInfo resolveInfo = resolveIntent(intent, null,
2801 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2802 UserHandle.USER_SYSTEM);
2803 if (resolveInfo == null ||
2804 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2805 throw new RuntimeException("There must be exactly one uninstaller; found "
2808 return resolveInfo.getComponentInfo().packageName;
2811 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2812 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2814 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2815 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2816 UserHandle.USER_SYSTEM);
2817 ResolveInfo best = null;
2818 final int N = matches.size();
2819 for (int i = 0; i < N; i++) {
2820 final ResolveInfo cur = matches.get(i);
2821 final String packageName = cur.getComponentInfo().packageName;
2822 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2823 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2827 if (best == null || cur.priority > best.priority) {
2833 return best.getComponentInfo().getComponentName();
2835 throw new RuntimeException("There must be at least one intent filter verifier");
2839 private @Nullable ComponentName getEphemeralResolverLPr() {
2840 final String[] packageArray =
2841 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2842 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2843 if (DEBUG_EPHEMERAL) {
2844 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2849 final int resolveFlags =
2850 MATCH_DIRECT_BOOT_AWARE
2851 | MATCH_DIRECT_BOOT_UNAWARE
2852 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2853 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2854 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2855 resolveFlags, UserHandle.USER_SYSTEM);
2857 final int N = resolvers.size();
2859 if (DEBUG_EPHEMERAL) {
2860 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2865 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2866 for (int i = 0; i < N; i++) {
2867 final ResolveInfo info = resolvers.get(i);
2869 if (info.serviceInfo == null) {
2873 final String packageName = info.serviceInfo.packageName;
2874 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2875 if (DEBUG_EPHEMERAL) {
2876 Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2877 + " pkg: " + packageName + ", info:" + info);
2882 if (DEBUG_EPHEMERAL) {
2883 Slog.v(TAG, "Ephemeral resolver found;"
2884 + " pkg: " + packageName + ", info:" + info);
2886 return new ComponentName(packageName, info.serviceInfo.name);
2888 if (DEBUG_EPHEMERAL) {
2889 Slog.v(TAG, "Ephemeral resolver NOT found");
2894 private @Nullable ComponentName getEphemeralInstallerLPr() {
2895 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2896 intent.addCategory(Intent.CATEGORY_DEFAULT);
2897 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2899 final int resolveFlags =
2900 MATCH_DIRECT_BOOT_AWARE
2901 | MATCH_DIRECT_BOOT_UNAWARE
2902 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2903 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2904 resolveFlags, UserHandle.USER_SYSTEM);
2905 if (matches.size() == 0) {
2907 } else if (matches.size() == 1) {
2908 return matches.get(0).getComponentInfo().getComponentName();
2910 throw new RuntimeException(
2911 "There must be at most one ephemeral installer; found " + matches);
2915 private void primeDomainVerificationsLPw(int userId) {
2916 if (DEBUG_DOMAIN_VERIFICATION) {
2917 Slog.d(TAG, "Priming domain verifications in user " + userId);
2920 SystemConfig systemConfig = SystemConfig.getInstance();
2921 ArraySet<String> packages = systemConfig.getLinkedApps();
2922 ArraySet<String> domains = new ArraySet<String>();
2924 for (String packageName : packages) {
2925 PackageParser.Package pkg = mPackages.get(packageName);
2927 if (!pkg.isSystemApp()) {
2928 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2933 for (PackageParser.Activity a : pkg.activities) {
2934 for (ActivityIntentInfo filter : a.intents) {
2935 if (hasValidDomains(filter)) {
2936 domains.addAll(filter.getHostsList());
2941 if (domains.size() > 0) {
2942 if (DEBUG_DOMAIN_VERIFICATION) {
2943 Slog.v(TAG, " + " + packageName);
2945 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2946 // state w.r.t. the formal app-linkage "no verification attempted" state;
2947 // and then 'always' in the per-user state actually used for intent resolution.
2948 final IntentFilterVerificationInfo ivi;
2949 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2950 new ArrayList<String>(domains));
2951 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2952 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2953 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2955 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2956 + "' does not handle web links");
2959 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2963 scheduleWritePackageRestrictionsLocked(userId);
2964 scheduleWriteSettingsLocked();
2967 private void applyFactoryDefaultBrowserLPw(int userId) {
2968 // The default browser app's package name is stored in a string resource,
2969 // with a product-specific overlay used for vendor customization.
2970 String browserPkg = mContext.getResources().getString(
2971 com.android.internal.R.string.default_browser);
2972 if (!TextUtils.isEmpty(browserPkg)) {
2973 // non-empty string => required to be a known package
2974 PackageSetting ps = mSettings.mPackages.get(browserPkg);
2976 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2979 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2983 // Nothing valid explicitly set? Make the factory-installed browser the explicit
2984 // default. If there's more than one, just leave everything alone.
2985 if (browserPkg == null) {
2986 calculateDefaultBrowserLPw(userId);
2990 private void calculateDefaultBrowserLPw(int userId) {
2991 List<String> allBrowsers = resolveAllBrowserApps(userId);
2992 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2993 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2996 private List<String> resolveAllBrowserApps(int userId) {
2997 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2998 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2999 PackageManager.MATCH_ALL, userId);
3001 final int count = list.size();
3002 List<String> result = new ArrayList<String>(count);
3003 for (int i=0; i<count; i++) {
3004 ResolveInfo info = list.get(i);
3005 if (info.activityInfo == null
3006 || !info.handleAllWebDataURI
3007 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3008 || result.contains(info.activityInfo.packageName)) {
3011 result.add(info.activityInfo.packageName);
3017 private boolean packageIsBrowser(String packageName, int userId) {
3018 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3019 PackageManager.MATCH_ALL, userId);
3020 final int N = list.size();
3021 for (int i = 0; i < N; i++) {
3022 ResolveInfo info = list.get(i);
3023 if (packageName.equals(info.activityInfo.packageName)) {
3030 private void checkDefaultBrowser() {
3031 final int myUserId = UserHandle.myUserId();
3032 final String packageName = getDefaultBrowserPackageName(myUserId);
3033 if (packageName != null) {
3034 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3036 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3037 synchronized (mPackages) {
3038 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
3045 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3046 throws RemoteException {
3048 return super.onTransact(code, data, reply, flags);
3049 } catch (RuntimeException e) {
3050 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3051 Slog.wtf(TAG, "Package Manager Crash", e);
3057 static int[] appendInts(int[] cur, int[] add) {
3058 if (add == null) return cur;
3059 if (cur == null) return add;
3060 final int N = add.length;
3061 for (int i=0; i<N; i++) {
3062 cur = appendInt(cur, add[i]);
3067 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3068 if (!sUserManager.exists(userId)) return null;
3072 final PackageParser.Package p = ps.pkg;
3077 final PermissionsState permissionsState = ps.getPermissionsState();
3079 // Compute GIDs only if requested
3080 final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3081 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3082 // Compute granted permissions only if package has requested permissions
3083 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3084 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3085 final PackageUserState state = ps.readUserState(userId);
3087 return PackageParser.generatePackageInfo(p, gids, flags,
3088 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3092 public void checkPackageStartable(String packageName, int userId) {
3093 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3095 synchronized (mPackages) {
3096 final PackageSetting ps = mSettings.mPackages.get(packageName);
3098 throw new SecurityException("Package " + packageName + " was not found!");
3101 if (!ps.getInstalled(userId)) {
3102 throw new SecurityException(
3103 "Package " + packageName + " was not installed for user " + userId + "!");
3106 if (mSafeMode && !ps.isSystem()) {
3107 throw new SecurityException("Package " + packageName + " not a system app!");
3110 if (mFrozenPackages.contains(packageName)) {
3111 throw new SecurityException("Package " + packageName + " is currently frozen!");
3114 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3115 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3116 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3122 public boolean isPackageAvailable(String packageName, int userId) {
3123 if (!sUserManager.exists(userId)) return false;
3124 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3125 false /* requireFullPermission */, false /* checkShell */, "is package available");
3126 synchronized (mPackages) {
3127 PackageParser.Package p = mPackages.get(packageName);
3129 final PackageSetting ps = (PackageSetting) p.mExtras;
3131 final PackageUserState state = ps.readUserState(userId);
3132 if (state != null) {
3133 return PackageParser.isAvailable(state);
3142 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3143 if (!sUserManager.exists(userId)) return null;
3144 flags = updateFlagsForPackage(flags, userId, packageName);
3145 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3146 false /* requireFullPermission */, false /* checkShell */, "get package info");
3149 synchronized (mPackages) {
3150 // Normalize package name to hanlde renamed packages
3151 packageName = normalizePackageNameLPr(packageName);
3153 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3154 PackageParser.Package p = null;
3155 if (matchFactoryOnly) {
3156 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3158 return generatePackageInfo(ps, flags, userId);
3162 p = mPackages.get(packageName);
3163 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3167 if (DEBUG_PACKAGE_INFO)
3168 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3170 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3172 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3173 final PackageSetting ps = mSettings.mPackages.get(packageName);
3174 return generatePackageInfo(ps, flags, userId);
3181 public String[] currentToCanonicalPackageNames(String[] names) {
3182 String[] out = new String[names.length];
3184 synchronized (mPackages) {
3185 for (int i=names.length-1; i>=0; i--) {
3186 PackageSetting ps = mSettings.mPackages.get(names[i]);
3187 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3194 public String[] canonicalToCurrentPackageNames(String[] names) {
3195 String[] out = new String[names.length];
3197 synchronized (mPackages) {
3198 for (int i=names.length-1; i>=0; i--) {
3199 String cur = mSettings.mRenamedPackages.get(names[i]);
3200 out[i] = cur != null ? cur : names[i];
3207 public int getPackageUid(String packageName, int flags, int userId) {
3208 if (!sUserManager.exists(userId)) return -1;
3209 flags = updateFlagsForPackage(flags, userId, packageName);
3210 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3211 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3214 synchronized (mPackages) {
3215 final PackageParser.Package p = mPackages.get(packageName);
3216 if (p != null && p.isMatch(flags)) {
3217 return UserHandle.getUid(userId, p.applicationInfo.uid);
3219 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3220 final PackageSetting ps = mSettings.mPackages.get(packageName);
3221 if (ps != null && ps.isMatch(flags)) {
3222 return UserHandle.getUid(userId, ps.appId);
3231 public int[] getPackageGids(String packageName, int flags, int userId) {
3232 if (!sUserManager.exists(userId)) return null;
3233 flags = updateFlagsForPackage(flags, userId, packageName);
3234 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3235 false /* requireFullPermission */, false /* checkShell */,
3239 synchronized (mPackages) {
3240 final PackageParser.Package p = mPackages.get(packageName);
3241 if (p != null && p.isMatch(flags)) {
3242 PackageSetting ps = (PackageSetting) p.mExtras;
3243 return ps.getPermissionsState().computeGids(userId);
3245 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3246 final PackageSetting ps = mSettings.mPackages.get(packageName);
3247 if (ps != null && ps.isMatch(flags)) {
3248 return ps.getPermissionsState().computeGids(userId);
3256 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3257 if (bp.perm != null) {
3258 return PackageParser.generatePermissionInfo(bp.perm, flags);
3260 PermissionInfo pi = new PermissionInfo();
3262 pi.packageName = bp.sourcePackage;
3263 pi.nonLocalizedLabel = bp.name;
3264 pi.protectionLevel = bp.protectionLevel;
3269 public PermissionInfo getPermissionInfo(String name, int flags) {
3271 synchronized (mPackages) {
3272 final BasePermission p = mSettings.mPermissions.get(name);
3274 return generatePermissionInfo(p, flags);
3281 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3284 synchronized (mPackages) {
3285 if (group != null && !mPermissionGroups.containsKey(group)) {
3286 // This is thrown as NameNotFoundException
3290 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3291 for (BasePermission p : mSettings.mPermissions.values()) {
3292 if (group == null) {
3293 if (p.perm == null || p.perm.info.group == null) {
3294 out.add(generatePermissionInfo(p, flags));
3297 if (p.perm != null && group.equals(p.perm.info.group)) {
3298 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3302 return new ParceledListSlice<>(out);
3307 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3309 synchronized (mPackages) {
3310 return PackageParser.generatePermissionGroupInfo(
3311 mPermissionGroups.get(name), flags);
3316 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3318 synchronized (mPackages) {
3319 final int N = mPermissionGroups.size();
3320 ArrayList<PermissionGroupInfo> out
3321 = new ArrayList<PermissionGroupInfo>(N);
3322 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3323 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3325 return new ParceledListSlice<>(out);
3329 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3331 if (!sUserManager.exists(userId)) return null;
3332 PackageSetting ps = mSettings.mPackages.get(packageName);
3334 if (ps.pkg == null) {
3335 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3336 if (pInfo != null) {
3337 return pInfo.applicationInfo;
3341 return PackageParser.generateApplicationInfo(ps.pkg, flags,
3342 ps.readUserState(userId), userId);
3348 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3349 if (!sUserManager.exists(userId)) return null;
3350 flags = updateFlagsForApplication(flags, userId, packageName);
3351 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3352 false /* requireFullPermission */, false /* checkShell */, "get application info");
3355 synchronized (mPackages) {
3356 // Normalize package name to hanlde renamed packages
3357 packageName = normalizePackageNameLPr(packageName);
3359 PackageParser.Package p = mPackages.get(packageName);
3360 if (DEBUG_PACKAGE_INFO) Log.v(
3361 TAG, "getApplicationInfo " + packageName
3364 PackageSetting ps = mSettings.mPackages.get(packageName);
3365 if (ps == null) return null;
3366 // Note: isEnabledLP() does not apply here - always return info
3367 return PackageParser.generateApplicationInfo(
3368 p, flags, ps.readUserState(userId), userId);
3370 if ("android".equals(packageName)||"system".equals(packageName)) {
3371 return mAndroidApplication;
3373 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3374 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3380 private String normalizePackageNameLPr(String packageName) {
3381 String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3382 return normalizedPackageName != null ? normalizedPackageName : packageName;
3386 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3387 final IPackageDataObserver observer) {
3388 mContext.enforceCallingOrSelfPermission(
3389 android.Manifest.permission.CLEAR_APP_CACHE, null);
3390 // Queue up an async operation since clearing cache may take a little while.
3391 mHandler.post(new Runnable() {
3393 mHandler.removeCallbacks(this);
3394 boolean success = true;
3395 synchronized (mInstallLock) {
3397 mInstaller.freeCache(volumeUuid, freeStorageSize);
3398 } catch (InstallerException e) {
3399 Slog.w(TAG, "Couldn't clear application caches: " + e);
3403 if (observer != null) {
3405 observer.onRemoveCompleted(null, success);
3406 } catch (RemoteException e) {
3407 Slog.w(TAG, "RemoveException when invoking call back");
3415 public void freeStorage(final String volumeUuid, final long freeStorageSize,
3416 final IntentSender pi) {
3417 mContext.enforceCallingOrSelfPermission(
3418 android.Manifest.permission.CLEAR_APP_CACHE, null);
3419 // Queue up an async operation since clearing cache may take a little while.
3420 mHandler.post(new Runnable() {
3422 mHandler.removeCallbacks(this);
3423 boolean success = true;
3424 synchronized (mInstallLock) {
3426 mInstaller.freeCache(volumeUuid, freeStorageSize);
3427 } catch (InstallerException e) {
3428 Slog.w(TAG, "Couldn't clear application caches: " + e);
3434 // Callback via pending intent
3435 int code = success ? 1 : 0;
3436 pi.sendIntent(null, code, null,
3438 } catch (SendIntentException e1) {
3439 Slog.i(TAG, "Failed to send pending intent");
3446 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3447 synchronized (mInstallLock) {
3449 mInstaller.freeCache(volumeUuid, freeStorageSize);
3450 } catch (InstallerException e) {
3451 throw new IOException("Failed to free enough space", e);
3457 * Update given flags based on encryption status of current user.
3459 private int updateFlags(int flags, int userId) {
3460 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3461 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3462 // Caller expressed an explicit opinion about what encryption
3463 // aware/unaware components they want to see, so fall through and
3464 // give them what they want
3466 // Caller expressed no opinion, so match based on user state
3467 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3468 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3470 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3476 private UserManagerInternal getUserManagerInternal() {
3477 if (mUserManagerInternal == null) {
3478 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3480 return mUserManagerInternal;
3484 * Update given flags when being used to request {@link PackageInfo}.
3486 private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3487 boolean triaged = true;
3488 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3489 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3490 // Caller is asking for component details, so they'd better be
3491 // asking for specific encryption matching behavior, or be triaged
3492 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3493 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3494 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3498 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3499 | PackageManager.MATCH_SYSTEM_ONLY
3500 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3503 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3504 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3505 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3507 return updateFlags(flags, userId);
3511 * Update given flags when being used to request {@link ApplicationInfo}.
3513 private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3514 return updateFlagsForPackage(flags, userId, cookie);
3518 * Update given flags when being used to request {@link ComponentInfo}.
3520 private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3521 if (cookie instanceof Intent) {
3522 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3523 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3527 boolean triaged = true;
3528 // Caller is asking for component details, so they'd better be
3529 // asking for specific encryption matching behavior, or be triaged
3530 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3531 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3532 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3535 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3536 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3537 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3540 return updateFlags(flags, userId);
3544 * Update given flags when being used to request {@link ResolveInfo}.
3546 int updateFlagsForResolve(int flags, int userId, Object cookie) {
3547 // Safe mode means we shouldn't match any third-party components
3549 flags |= PackageManager.MATCH_SYSTEM_ONLY;
3552 return updateFlagsForComponent(flags, userId, cookie);
3556 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3557 if (!sUserManager.exists(userId)) return null;
3558 flags = updateFlagsForComponent(flags, userId, component);
3559 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3560 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3561 synchronized (mPackages) {
3562 PackageParser.Activity a = mActivities.mActivities.get(component);
3564 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3565 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3566 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3567 if (ps == null) return null;
3568 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3571 if (mResolveComponentName.equals(component)) {
3572 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3573 new PackageUserState(), userId);
3580 public boolean activitySupportsIntent(ComponentName component, Intent intent,
3581 String resolvedType) {
3582 synchronized (mPackages) {
3583 if (component.equals(mResolveComponentName)) {
3584 // The resolver supports EVERYTHING!
3587 PackageParser.Activity a = mActivities.mActivities.get(component);
3591 for (int i=0; i<a.intents.size(); i++) {
3592 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3593 intent.getData(), intent.getCategories(), TAG) >= 0) {
3602 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3603 if (!sUserManager.exists(userId)) return null;
3604 flags = updateFlagsForComponent(flags, userId, component);
3605 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3606 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3607 synchronized (mPackages) {
3608 PackageParser.Activity a = mReceivers.mActivities.get(component);
3609 if (DEBUG_PACKAGE_INFO) Log.v(
3610 TAG, "getReceiverInfo " + component + ": " + a);
3611 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3612 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3613 if (ps == null) return null;
3614 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3622 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3623 if (!sUserManager.exists(userId)) return null;
3624 flags = updateFlagsForComponent(flags, userId, component);
3625 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3626 false /* requireFullPermission */, false /* checkShell */, "get service info");
3627 synchronized (mPackages) {
3628 PackageParser.Service s = mServices.mServices.get(component);
3629 if (DEBUG_PACKAGE_INFO) Log.v(
3630 TAG, "getServiceInfo " + component + ": " + s);
3631 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3632 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3633 if (ps == null) return null;
3634 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3642 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3643 if (!sUserManager.exists(userId)) return null;
3644 flags = updateFlagsForComponent(flags, userId, component);
3645 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3646 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3647 synchronized (mPackages) {
3648 PackageParser.Provider p = mProviders.mProviders.get(component);
3649 if (DEBUG_PACKAGE_INFO) Log.v(
3650 TAG, "getProviderInfo " + component + ": " + p);
3651 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3652 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3653 if (ps == null) return null;
3654 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3662 public String[] getSystemSharedLibraryNames() {
3664 synchronized (mPackages) {
3665 libSet = mSharedLibraries.keySet();
3666 int size = libSet.size();
3668 String[] libs = new String[size];
3669 libSet.toArray(libs);
3677 public @NonNull String getServicesSystemSharedLibraryPackageName() {
3678 synchronized (mPackages) {
3679 return mServicesSystemSharedLibraryPackageName;
3684 public @NonNull String getSharedSystemSharedLibraryPackageName() {
3685 synchronized (mPackages) {
3686 return mSharedSystemSharedLibraryPackageName;
3691 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3692 synchronized (mPackages) {
3693 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3695 final FeatureInfo fi = new FeatureInfo();
3696 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3697 FeatureInfo.GL_ES_VERSION_UNDEFINED);
3700 return new ParceledListSlice<>(res);
3705 public boolean hasSystemFeature(String name, int version) {
3706 synchronized (mPackages) {
3707 final FeatureInfo feat = mAvailableFeatures.get(name);
3711 return feat.version >= version;
3717 public int checkPermission(String permName, String pkgName, int userId) {
3718 if (!sUserManager.exists(userId)) {
3719 return PackageManager.PERMISSION_DENIED;
3722 synchronized (mPackages) {
3723 final PackageParser.Package p = mPackages.get(pkgName);
3724 if (p != null && p.mExtras != null) {
3725 final PackageSetting ps = (PackageSetting) p.mExtras;
3726 final PermissionsState permissionsState = ps.getPermissionsState();
3727 if (permissionsState.hasPermission(permName, userId)) {
3728 return PackageManager.PERMISSION_GRANTED;
3730 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3731 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3732 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3733 return PackageManager.PERMISSION_GRANTED;
3738 return PackageManager.PERMISSION_DENIED;
3742 public int checkUidPermission(String permName, int uid) {
3743 final int userId = UserHandle.getUserId(uid);
3745 if (!sUserManager.exists(userId)) {
3746 return PackageManager.PERMISSION_DENIED;
3749 synchronized (mPackages) {
3750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3752 final SettingBase ps = (SettingBase) obj;
3753 final PermissionsState permissionsState = ps.getPermissionsState();
3754 if (permissionsState.hasPermission(permName, userId)) {
3755 return PackageManager.PERMISSION_GRANTED;
3757 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3758 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3759 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3760 return PackageManager.PERMISSION_GRANTED;
3763 ArraySet<String> perms = mSystemPermissions.get(uid);
3764 if (perms != null) {
3765 if (perms.contains(permName)) {
3766 return PackageManager.PERMISSION_GRANTED;
3768 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3769 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3770 return PackageManager.PERMISSION_GRANTED;
3776 return PackageManager.PERMISSION_DENIED;
3780 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3781 if (UserHandle.getCallingUserId() != userId) {
3782 mContext.enforceCallingPermission(
3783 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3784 "isPermissionRevokedByPolicy for user " + userId);
3787 if (checkPermission(permission, packageName, userId)
3788 == PackageManager.PERMISSION_GRANTED) {
3792 final long identity = Binder.clearCallingIdentity();
3794 final int flags = getPermissionFlags(permission, packageName, userId);
3795 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3797 Binder.restoreCallingIdentity(identity);
3802 public String getPermissionControllerPackageName() {
3803 synchronized (mPackages) {
3804 return mRequiredInstallerPackage;
3809 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3810 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3811 * @param checkShell whether to prevent shell from access if there's a debugging restriction
3812 * @param message the message to log on security exception
3814 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3815 boolean checkShell, String message) {
3817 throw new IllegalArgumentException("Invalid userId " + userId);
3820 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3822 if (userId == UserHandle.getUserId(callingUid)) return;
3823 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3824 if (requireFullPermission) {
3825 mContext.enforceCallingOrSelfPermission(
3826 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3829 mContext.enforceCallingOrSelfPermission(
3830 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3831 } catch (SecurityException se) {
3832 mContext.enforceCallingOrSelfPermission(
3833 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3839 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3840 if (callingUid == Process.SHELL_UID) {
3842 && sUserManager.hasUserRestriction(restriction, userHandle)) {
3843 throw new SecurityException("Shell does not have permission to access user "
3845 } else if (userHandle < 0) {
3846 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3847 + Debug.getCallers(3));
3852 private BasePermission findPermissionTreeLP(String permName) {
3853 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3854 if (permName.startsWith(bp.name) &&
3855 permName.length() > bp.name.length() &&
3856 permName.charAt(bp.name.length()) == '.') {
3863 private BasePermission checkPermissionTreeLP(String permName) {
3864 if (permName != null) {
3865 BasePermission bp = findPermissionTreeLP(permName);
3867 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3870 throw new SecurityException("Calling uid "
3871 + Binder.getCallingUid()
3872 + " is not allowed to add to permission tree "
3873 + bp.name + " owned by uid " + bp.uid);
3876 throw new SecurityException("No permission tree found for " + permName);
3879 static boolean compareStrings(CharSequence s1, CharSequence s2) {
3886 if (s1.getClass() != s2.getClass()) {
3889 return s1.equals(s2);
3892 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3893 if (pi1.icon != pi2.icon) return false;
3894 if (pi1.logo != pi2.logo) return false;
3895 if (pi1.protectionLevel != pi2.protectionLevel) return false;
3896 if (!compareStrings(pi1.name, pi2.name)) return false;
3897 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3898 // We'll take care of setting this one.
3899 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3900 // These are not currently stored in settings.
3901 //if (!compareStrings(pi1.group, pi2.group)) return false;
3902 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3903 //if (pi1.labelRes != pi2.labelRes) return false;
3904 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3908 int permissionInfoFootprint(PermissionInfo info) {
3909 int size = info.name.length();
3910 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3911 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3915 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3917 for (BasePermission perm : mSettings.mPermissions.values()) {
3918 if (perm.uid == tree.uid) {
3919 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3925 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3926 // We calculate the max size of permissions defined by this uid and throw
3927 // if that plus the size of 'info' would exceed our stated maximum.
3928 if (tree.uid != Process.SYSTEM_UID) {
3929 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3930 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3931 throw new SecurityException("Permission tree size cap exceeded");
3936 boolean addPermissionLocked(PermissionInfo info, boolean async) {
3937 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3938 throw new SecurityException("Label must be specified in permission");
3940 BasePermission tree = checkPermissionTreeLP(info.name);
3941 BasePermission bp = mSettings.mPermissions.get(info.name);
3942 boolean added = bp == null;
3943 boolean changed = true;
3944 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3946 enforcePermissionCapLocked(info, tree);
3947 bp = new BasePermission(info.name, tree.sourcePackage,
3948 BasePermission.TYPE_DYNAMIC);
3949 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3950 throw new SecurityException(
3951 "Not allowed to modify non-dynamic permission "
3954 if (bp.protectionLevel == fixedLevel
3955 && bp.perm.owner.equals(tree.perm.owner)
3956 && bp.uid == tree.uid
3957 && comparePermissionInfos(bp.perm.info, info)) {
3961 bp.protectionLevel = fixedLevel;
3962 info = new PermissionInfo(info);
3963 info.protectionLevel = fixedLevel;
3964 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3965 bp.perm.info.packageName = tree.perm.info.packageName;
3968 mSettings.mPermissions.put(info.name, bp);
3972 mSettings.writeLPr();
3974 scheduleWriteSettingsLocked();
3981 public boolean addPermission(PermissionInfo info) {
3982 synchronized (mPackages) {
3983 return addPermissionLocked(info, false);
3988 public boolean addPermissionAsync(PermissionInfo info) {
3989 synchronized (mPackages) {
3990 return addPermissionLocked(info, true);
3995 public void removePermission(String name) {
3996 synchronized (mPackages) {
3997 checkPermissionTreeLP(name);
3998 BasePermission bp = mSettings.mPermissions.get(name);
4000 if (bp.type != BasePermission.TYPE_DYNAMIC) {
4001 throw new SecurityException(
4002 "Not allowed to modify non-dynamic permission "
4005 mSettings.mPermissions.remove(name);
4006 mSettings.writeLPr();
4011 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4012 BasePermission bp) {
4013 int index = pkg.requestedPermissions.indexOf(bp.name);
4015 throw new SecurityException("Package " + pkg.packageName
4016 + " has not requested permission " + bp.name);
4018 if (!bp.isRuntime() && !bp.isDevelopment()) {
4019 throw new SecurityException("Permission " + bp.name
4020 + " is not a changeable permission type");
4025 public void grantRuntimePermission(String packageName, String name, final int userId) {
4026 if (!sUserManager.exists(userId)) {
4027 Log.e(TAG, "No such user:" + userId);
4031 mContext.enforceCallingOrSelfPermission(
4032 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4033 "grantRuntimePermission");
4035 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4036 true /* requireFullPermission */, true /* checkShell */,
4037 "grantRuntimePermission");
4040 final SettingBase sb;
4042 synchronized (mPackages) {
4043 final PackageParser.Package pkg = mPackages.get(packageName);
4045 throw new IllegalArgumentException("Unknown package: " + packageName);
4048 final BasePermission bp = mSettings.mPermissions.get(name);
4050 throw new IllegalArgumentException("Unknown permission: " + name);
4053 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4055 // If a permission review is required for legacy apps we represent
4056 // their permissions as always granted runtime ones since we need
4057 // to keep the review required permission flag per user while an
4058 // install permission's state is shared across all users.
4059 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4060 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4061 && bp.isRuntime()) {
4065 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4066 sb = (SettingBase) pkg.mExtras;
4068 throw new IllegalArgumentException("Unknown package: " + packageName);
4071 final PermissionsState permissionsState = sb.getPermissionsState();
4073 final int flags = permissionsState.getPermissionFlags(name, userId);
4074 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4075 throw new SecurityException("Cannot grant system fixed permission "
4076 + name + " for package " + packageName);
4079 if (bp.isDevelopment()) {
4080 // Development permissions must be handled specially, since they are not
4081 // normal runtime permissions. For now they apply to all users.
4082 if (permissionsState.grantInstallPermission(bp) !=
4083 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4084 scheduleWriteSettingsLocked();
4089 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4090 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4094 final int result = permissionsState.grantRuntimePermission(bp, userId);
4096 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4100 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4101 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4102 mHandler.post(new Runnable() {
4105 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4112 mOnPermissionChangeListeners.onPermissionsChanged(uid);
4114 // Not critical if that is lost - app has to request again.
4115 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4118 // Only need to do this if user is initialized. Otherwise it's a new user
4119 // and there are no processes running as the user yet and there's no need
4120 // to make an expensive call to remount processes for the changed permissions.
4121 if (READ_EXTERNAL_STORAGE.equals(name)
4122 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4123 final long token = Binder.clearCallingIdentity();
4125 if (sUserManager.isInitialized(userId)) {
4126 MountServiceInternal mountServiceInternal = LocalServices.getService(
4127 MountServiceInternal.class);
4128 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4131 Binder.restoreCallingIdentity(token);
4137 public void revokeRuntimePermission(String packageName, String name, int userId) {
4138 if (!sUserManager.exists(userId)) {
4139 Log.e(TAG, "No such user:" + userId);
4143 mContext.enforceCallingOrSelfPermission(
4144 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4145 "revokeRuntimePermission");
4147 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4148 true /* requireFullPermission */, true /* checkShell */,
4149 "revokeRuntimePermission");
4153 synchronized (mPackages) {
4154 final PackageParser.Package pkg = mPackages.get(packageName);
4156 throw new IllegalArgumentException("Unknown package: " + packageName);
4159 final BasePermission bp = mSettings.mPermissions.get(name);
4161 throw new IllegalArgumentException("Unknown permission: " + name);
4164 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4166 // If a permission review is required for legacy apps we represent
4167 // their permissions as always granted runtime ones since we need
4168 // to keep the review required permission flag per user while an
4169 // install permission's state is shared across all users.
4170 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4171 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4172 && bp.isRuntime()) {
4176 SettingBase sb = (SettingBase) pkg.mExtras;
4178 throw new IllegalArgumentException("Unknown package: " + packageName);
4181 final PermissionsState permissionsState = sb.getPermissionsState();
4183 final int flags = permissionsState.getPermissionFlags(name, userId);
4184 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4185 throw new SecurityException("Cannot revoke system fixed permission "
4186 + name + " for package " + packageName);
4189 if (bp.isDevelopment()) {
4190 // Development permissions must be handled specially, since they are not
4191 // normal runtime permissions. For now they apply to all users.
4192 if (permissionsState.revokeInstallPermission(bp) !=
4193 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4194 scheduleWriteSettingsLocked();
4199 if (permissionsState.revokeRuntimePermission(bp, userId) ==
4200 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4204 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4206 // Critical, after this call app should never have the permission.
4207 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4209 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4212 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4216 public void resetRuntimePermissions() {
4217 mContext.enforceCallingOrSelfPermission(
4218 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4219 "revokeRuntimePermission");
4221 int callingUid = Binder.getCallingUid();
4222 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4223 mContext.enforceCallingOrSelfPermission(
4224 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4225 "resetRuntimePermissions");
4228 synchronized (mPackages) {
4229 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4230 for (int userId : UserManagerService.getInstance().getUserIds()) {
4231 final int packageCount = mPackages.size();
4232 for (int i = 0; i < packageCount; i++) {
4233 PackageParser.Package pkg = mPackages.valueAt(i);
4234 if (!(pkg.mExtras instanceof PackageSetting)) {
4237 PackageSetting ps = (PackageSetting) pkg.mExtras;
4238 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4245 public int getPermissionFlags(String name, String packageName, int userId) {
4246 if (!sUserManager.exists(userId)) {
4250 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4252 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4253 true /* requireFullPermission */, false /* checkShell */,
4254 "getPermissionFlags");
4256 synchronized (mPackages) {
4257 final PackageParser.Package pkg = mPackages.get(packageName);
4262 final BasePermission bp = mSettings.mPermissions.get(name);
4267 SettingBase sb = (SettingBase) pkg.mExtras;
4272 PermissionsState permissionsState = sb.getPermissionsState();
4273 return permissionsState.getPermissionFlags(name, userId);
4278 public void updatePermissionFlags(String name, String packageName, int flagMask,
4279 int flagValues, int userId) {
4280 if (!sUserManager.exists(userId)) {
4284 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4286 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4287 true /* requireFullPermission */, true /* checkShell */,
4288 "updatePermissionFlags");
4290 // Only the system can change these flags and nothing else.
4291 if (getCallingUid() != Process.SYSTEM_UID) {
4292 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4293 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4294 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4295 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4296 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4299 synchronized (mPackages) {
4300 final PackageParser.Package pkg = mPackages.get(packageName);
4302 throw new IllegalArgumentException("Unknown package: " + packageName);
4305 final BasePermission bp = mSettings.mPermissions.get(name);
4307 throw new IllegalArgumentException("Unknown permission: " + name);
4310 SettingBase sb = (SettingBase) pkg.mExtras;
4312 throw new IllegalArgumentException("Unknown package: " + packageName);
4315 PermissionsState permissionsState = sb.getPermissionsState();
4317 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4319 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4320 // Install and runtime permissions are stored in different places,
4321 // so figure out what permission changed and persist the change.
4322 if (permissionsState.getInstallPermissionState(name) != null) {
4323 scheduleWriteSettingsLocked();
4324 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4326 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4333 * Update the permission flags for all packages and runtime permissions of a user in order
4334 * to allow device or profile owner to remove POLICY_FIXED.
4337 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4338 if (!sUserManager.exists(userId)) {
4342 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4344 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4345 true /* requireFullPermission */, true /* checkShell */,
4346 "updatePermissionFlagsForAllApps");
4348 // Only the system can change system fixed flags.
4349 if (getCallingUid() != Process.SYSTEM_UID) {
4350 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4351 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4354 synchronized (mPackages) {
4355 boolean changed = false;
4356 final int packageCount = mPackages.size();
4357 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4358 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4359 SettingBase sb = (SettingBase) pkg.mExtras;
4363 PermissionsState permissionsState = sb.getPermissionsState();
4364 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4365 userId, flagMask, flagValues);
4368 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4373 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4374 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4375 != PackageManager.PERMISSION_GRANTED
4376 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4377 != PackageManager.PERMISSION_GRANTED) {
4378 throw new SecurityException(message + " requires "
4379 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4380 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4385 public boolean shouldShowRequestPermissionRationale(String permissionName,
4386 String packageName, int userId) {
4387 if (UserHandle.getCallingUserId() != userId) {
4388 mContext.enforceCallingPermission(
4389 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4390 "canShowRequestPermissionRationale for user " + userId);
4393 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4394 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4398 if (checkPermission(permissionName, packageName, userId)
4399 == PackageManager.PERMISSION_GRANTED) {
4405 final long identity = Binder.clearCallingIdentity();
4407 flags = getPermissionFlags(permissionName,
4408 packageName, userId);
4410 Binder.restoreCallingIdentity(identity);
4413 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4414 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4415 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4417 if ((flags & fixedFlags) != 0) {
4421 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4425 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4426 mContext.enforceCallingOrSelfPermission(
4427 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4428 "addOnPermissionsChangeListener");
4430 synchronized (mPackages) {
4431 mOnPermissionChangeListeners.addListenerLocked(listener);
4436 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4437 synchronized (mPackages) {
4438 mOnPermissionChangeListeners.removeListenerLocked(listener);
4443 public boolean isProtectedBroadcast(String actionName) {
4444 synchronized (mPackages) {
4445 if (mProtectedBroadcasts.contains(actionName)) {
4447 } else if (actionName != null) {
4448 // TODO: remove these terrible hacks
4449 if (actionName.startsWith("android.net.netmon.lingerExpired")
4450 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4451 || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4452 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4461 public int checkSignatures(String pkg1, String pkg2) {
4462 synchronized (mPackages) {
4463 final PackageParser.Package p1 = mPackages.get(pkg1);
4464 final PackageParser.Package p2 = mPackages.get(pkg2);
4465 if (p1 == null || p1.mExtras == null
4466 || p2 == null || p2.mExtras == null) {
4467 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4469 return compareSignatures(p1.mSignatures, p2.mSignatures);
4474 public int checkUidSignatures(int uid1, int uid2) {
4475 // Map to base uids.
4476 uid1 = UserHandle.getAppId(uid1);
4477 uid2 = UserHandle.getAppId(uid2);
4479 synchronized (mPackages) {
4482 Object obj = mSettings.getUserIdLPr(uid1);
4484 if (obj instanceof SharedUserSetting) {
4485 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4486 } else if (obj instanceof PackageSetting) {
4487 s1 = ((PackageSetting)obj).signatures.mSignatures;
4489 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4492 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4494 obj = mSettings.getUserIdLPr(uid2);
4496 if (obj instanceof SharedUserSetting) {
4497 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4498 } else if (obj instanceof PackageSetting) {
4499 s2 = ((PackageSetting)obj).signatures.mSignatures;
4501 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4504 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4506 return compareSignatures(s1, s2);
4511 * This method should typically only be used when granting or revoking
4512 * permissions, since the app may immediately restart after this call.
4514 * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4515 * guard your work against the app being relaunched.
4517 private void killUid(int appId, int userId, String reason) {
4518 final long identity = Binder.clearCallingIdentity();
4520 IActivityManager am = ActivityManagerNative.getDefault();
4523 am.killUid(appId, userId, reason);
4524 } catch (RemoteException e) {
4525 /* ignore - same process */
4529 Binder.restoreCallingIdentity(identity);
4534 * Compares two sets of signatures. Returns:
4536 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4538 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4540 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4542 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4544 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4546 static int compareSignatures(Signature[] s1, Signature[] s2) {
4549 ? PackageManager.SIGNATURE_NEITHER_SIGNED
4550 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4554 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4557 if (s1.length != s2.length) {
4558 return PackageManager.SIGNATURE_NO_MATCH;
4561 // Since both signature sets are of size 1, we can compare without HashSets.
4562 if (s1.length == 1) {
4563 return s1[0].equals(s2[0]) ?
4564 PackageManager.SIGNATURE_MATCH :
4565 PackageManager.SIGNATURE_NO_MATCH;
4568 ArraySet<Signature> set1 = new ArraySet<Signature>();
4569 for (Signature sig : s1) {
4572 ArraySet<Signature> set2 = new ArraySet<Signature>();
4573 for (Signature sig : s2) {
4576 // Make sure s2 contains all signatures in s1.
4577 if (set1.equals(set2)) {
4578 return PackageManager.SIGNATURE_MATCH;
4580 return PackageManager.SIGNATURE_NO_MATCH;
4584 * If the database version for this type of package (internal storage or
4585 * external storage) is less than the version where package signatures
4586 * were updated, return true.
4588 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4589 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4590 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4594 * Used for backward compatibility to make sure any packages with
4595 * certificate chains get upgraded to the new style. {@code existingSigs}
4596 * will be in the old format (since they were stored on disk from before the
4597 * system upgrade) and {@code scannedSigs} will be in the newer format.
4599 private int compareSignaturesCompat(PackageSignatures existingSigs,
4600 PackageParser.Package scannedPkg) {
4601 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4602 return PackageManager.SIGNATURE_NO_MATCH;
4605 ArraySet<Signature> existingSet = new ArraySet<Signature>();
4606 for (Signature sig : existingSigs.mSignatures) {
4607 existingSet.add(sig);
4609 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4610 for (Signature sig : scannedPkg.mSignatures) {
4612 Signature[] chainSignatures = sig.getChainSignatures();
4613 for (Signature chainSig : chainSignatures) {
4614 scannedCompatSet.add(chainSig);
4616 } catch (CertificateEncodingException e) {
4617 scannedCompatSet.add(sig);
4621 * Make sure the expanded scanned set contains all signatures in the
4624 if (scannedCompatSet.equals(existingSet)) {
4625 // Migrate the old signatures to the new scheme.
4626 existingSigs.assignSignatures(scannedPkg.mSignatures);
4627 // The new KeySets will be re-added later in the scanning process.
4628 synchronized (mPackages) {
4629 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4631 return PackageManager.SIGNATURE_MATCH;
4633 return PackageManager.SIGNATURE_NO_MATCH;
4636 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4637 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4638 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4641 private int compareSignaturesRecover(PackageSignatures existingSigs,
4642 PackageParser.Package scannedPkg) {
4643 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4644 return PackageManager.SIGNATURE_NO_MATCH;
4649 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4650 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4651 + scannedPkg.packageName);
4652 return PackageManager.SIGNATURE_MATCH;
4654 } catch (CertificateException e) {
4655 msg = e.getMessage();
4658 logCriticalInfo(Log.INFO,
4659 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4660 return PackageManager.SIGNATURE_NO_MATCH;
4664 public List<String> getAllPackages() {
4665 synchronized (mPackages) {
4666 return new ArrayList<String>(mPackages.keySet());
4671 public String[] getPackagesForUid(int uid) {
4672 uid = UserHandle.getAppId(uid);
4674 synchronized (mPackages) {
4675 Object obj = mSettings.getUserIdLPr(uid);
4676 if (obj instanceof SharedUserSetting) {
4677 final SharedUserSetting sus = (SharedUserSetting) obj;
4678 final int N = sus.packages.size();
4679 final String[] res = new String[N];
4680 for (int i = 0; i < N; i++) {
4681 res[i] = sus.packages.valueAt(i).name;
4684 } else if (obj instanceof PackageSetting) {
4685 final PackageSetting ps = (PackageSetting) obj;
4686 return new String[] { ps.name };
4693 public String getNameForUid(int uid) {
4695 synchronized (mPackages) {
4696 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4697 if (obj instanceof SharedUserSetting) {
4698 final SharedUserSetting sus = (SharedUserSetting) obj;
4699 return sus.name + ":" + sus.userId;
4700 } else if (obj instanceof PackageSetting) {
4701 final PackageSetting ps = (PackageSetting) obj;
4709 public int getUidForSharedUser(String sharedUserName) {
4710 if(sharedUserName == null) {
4714 synchronized (mPackages) {
4715 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4724 public int getFlagsForUid(int uid) {
4725 synchronized (mPackages) {
4726 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4727 if (obj instanceof SharedUserSetting) {
4728 final SharedUserSetting sus = (SharedUserSetting) obj;
4729 return sus.pkgFlags;
4730 } else if (obj instanceof PackageSetting) {
4731 final PackageSetting ps = (PackageSetting) obj;
4739 public int getPrivateFlagsForUid(int uid) {
4740 synchronized (mPackages) {
4741 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4742 if (obj instanceof SharedUserSetting) {
4743 final SharedUserSetting sus = (SharedUserSetting) obj;
4744 return sus.pkgPrivateFlags;
4745 } else if (obj instanceof PackageSetting) {
4746 final PackageSetting ps = (PackageSetting) obj;
4747 return ps.pkgPrivateFlags;
4754 public boolean isUidPrivileged(int uid) {
4755 uid = UserHandle.getAppId(uid);
4757 synchronized (mPackages) {
4758 Object obj = mSettings.getUserIdLPr(uid);
4759 if (obj instanceof SharedUserSetting) {
4760 final SharedUserSetting sus = (SharedUserSetting) obj;
4761 final Iterator<PackageSetting> it = sus.packages.iterator();
4762 while (it.hasNext()) {
4763 if (it.next().isPrivileged()) {
4767 } else if (obj instanceof PackageSetting) {
4768 final PackageSetting ps = (PackageSetting) obj;
4769 return ps.isPrivileged();
4776 public String[] getAppOpPermissionPackages(String permissionName) {
4777 synchronized (mPackages) {
4778 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4782 return pkgs.toArray(new String[pkgs.size()]);
4787 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4788 int flags, int userId) {
4790 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4792 if (!sUserManager.exists(userId)) return null;
4793 flags = updateFlagsForResolve(flags, userId, intent);
4794 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4795 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4797 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4798 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4800 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4802 final ResolveInfo bestChoice =
4803 chooseBestActivity(intent, resolvedType, flags, query, userId);
4806 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4811 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4812 IntentFilter filter, int match, ComponentName activity) {
4813 final int userId = UserHandle.getCallingUserId();
4814 if (DEBUG_PREFERRED) {
4815 Log.v(TAG, "setLastChosenActivity intent=" + intent
4816 + " resolvedType=" + resolvedType
4818 + " filter=" + filter
4820 + " activity=" + activity);
4821 filter.dump(new PrintStreamPrinter(System.out), " ");
4823 intent.setComponent(null);
4824 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4826 // Find any earlier preferred or last chosen entries and nuke them
4827 findPreferredActivity(intent, resolvedType,
4828 flags, query, 0, false, true, false, userId);
4829 // Add the new activity as the last chosen for this filter
4830 addPreferredActivityInternal(filter, match, null, activity, false, userId,
4831 "Setting last chosen");
4835 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4836 final int userId = UserHandle.getCallingUserId();
4837 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4838 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4840 return findPreferredActivity(intent, resolvedType, flags, query, 0,
4841 false, false, false, userId);
4844 private boolean isEphemeralDisabled() {
4845 // ephemeral apps have been disabled across the board
4846 if (DISABLE_EPHEMERAL_APPS) {
4849 // system isn't up yet; can't read settings, so, assume no ephemeral apps
4850 if (!mSystemReady) {
4853 // we can't get a content resolver until the system is ready; these checks must happen last
4854 final ContentResolver resolver = mContext.getContentResolver();
4855 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4858 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4861 private boolean isEphemeralAllowed(
4862 Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4863 boolean skipPackageCheck) {
4864 // Short circuit and return early if possible.
4865 if (isEphemeralDisabled()) {
4868 final int callingUser = UserHandle.getCallingUserId();
4869 if (callingUser != UserHandle.USER_SYSTEM) {
4872 if (mEphemeralResolverConnection == null) {
4875 if (intent.getComponent() != null) {
4878 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4881 if (!skipPackageCheck && intent.getPackage() != null) {
4884 final boolean isWebUri = hasWebURI(intent);
4885 if (!isWebUri || intent.getData().getHost() == null) {
4888 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4889 synchronized (mPackages) {
4890 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4891 for (int n = 0; n < count; n++) {
4892 ResolveInfo info = resolvedActivities.get(n);
4893 String packageName = info.activityInfo.packageName;
4894 PackageSetting ps = mSettings.mPackages.get(packageName);
4896 // Try to get the status from User settings first
4897 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4898 int status = (int) (packedStatus >> 32);
4899 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4900 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4901 if (DEBUG_EPHEMERAL) {
4902 Slog.v(TAG, "DENY ephemeral apps;"
4903 + " pkg: " + packageName + ", status: " + status);
4910 // We've exhausted all ways to deny ephemeral application; let the system look for them.
4914 private static EphemeralResolveInfo getEphemeralResolveInfo(
4915 Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4916 String resolvedType, int userId, String packageName) {
4917 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4918 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4919 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4920 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4921 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4922 ephemeralPrefixCount);
4923 final int[] shaPrefix = digest.getDigestPrefix();
4924 final byte[][] digestBytes = digest.getDigestBytes();
4925 final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4926 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4927 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4928 // No hash prefix match; there are no ephemeral apps for this domain.
4932 // Go in reverse order so we match the narrowest scope first.
4933 for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4934 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4935 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4938 final List<IntentFilter> filters = ephemeralApplication.getFilters();
4939 // No filters; this should never happen.
4940 if (filters.isEmpty()) {
4943 if (packageName != null
4944 && !packageName.equals(ephemeralApplication.getPackageName())) {
4947 // We have a domain match; resolve the filters to see if anything matches.
4948 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4949 for (int j = filters.size() - 1; j >= 0; --j) {
4950 final EphemeralResolveIntentInfo intentInfo =
4951 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4952 ephemeralResolver.addFilter(intentInfo);
4954 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4955 intent, resolvedType, false /*defaultOnly*/, userId);
4956 if (!matchedResolveInfoList.isEmpty()) {
4957 return matchedResolveInfoList.get(0);
4961 // Hash or filter mis-match; no ephemeral apps for this domain.
4965 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4966 int flags, List<ResolveInfo> query, int userId) {
4967 if (query != null) {
4968 final int N = query.size();
4970 return query.get(0);
4972 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4973 // If there is more than one activity with the same priority,
4974 // then let the user decide between them.
4975 ResolveInfo r0 = query.get(0);
4976 ResolveInfo r1 = query.get(1);
4977 if (DEBUG_INTENT_MATCHING || debug) {
4978 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4979 + r1.activityInfo.name + "=" + r1.priority);
4981 // If the first activity has a higher priority, or a different
4982 // default, then it is always desirable to pick it.
4983 if (r0.priority != r1.priority
4984 || r0.preferredOrder != r1.preferredOrder
4985 || r0.isDefault != r1.isDefault) {
4986 return query.get(0);
4988 // If we have saved a preference for a preferred activity for
4989 // this Intent, use that.
4990 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4991 flags, query, r0.priority, true, false, debug, userId);
4995 ri = new ResolveInfo(mResolveInfo);
4996 ri.activityInfo = new ActivityInfo(ri.activityInfo);
4997 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4998 // If all of the options come from the same package, show the application's
4999 // label and icon instead of the generic resolver's.
5000 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5001 // and then throw away the ResolveInfo itself, meaning that the caller loses
5002 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5003 // a fallback for this case; we only set the target package's resources on
5004 // the ResolveInfo, not the ActivityInfo.
5005 final String intentPackage = intent.getPackage();
5006 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5007 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5008 ri.resolvePackageName = intentPackage;
5009 if (userNeedsBadging(userId)) {
5010 ri.noResourceId = true;
5012 ri.icon = appi.icon;
5014 ri.iconResourceId = appi.icon;
5015 ri.labelRes = appi.labelRes;
5017 ri.activityInfo.applicationInfo = new ApplicationInfo(
5018 ri.activityInfo.applicationInfo);
5020 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5021 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5023 // Make sure that the resolver is displayable in car mode
5024 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5025 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5033 * Return true if the given list is not empty and all of its contents have
5034 * an activityInfo with the given package name.
5036 private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5037 if (ArrayUtils.isEmpty(list)) {
5040 for (int i = 0, N = list.size(); i < N; i++) {
5041 final ResolveInfo ri = list.get(i);
5042 final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5043 if (ai == null || !packageName.equals(ai.packageName)) {
5050 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5051 int flags, List<ResolveInfo> query, boolean debug, int userId) {
5052 final int N = query.size();
5053 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5055 // Get the list of persistent preferred activities that handle the intent
5056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5057 List<PersistentPreferredActivity> pprefs = ppir != null
5058 ? ppir.queryIntent(intent, resolvedType,
5059 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5061 if (pprefs != null && pprefs.size() > 0) {
5062 final int M = pprefs.size();
5063 for (int i=0; i<M; i++) {
5064 final PersistentPreferredActivity ppa = pprefs.get(i);
5065 if (DEBUG_PREFERRED || debug) {
5066 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5067 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5068 + "\n component=" + ppa.mComponent);
5069 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5071 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5072 flags | MATCH_DISABLED_COMPONENTS, userId);
5073 if (DEBUG_PREFERRED || debug) {
5074 Slog.v(TAG, "Found persistent preferred activity:");
5076 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5078 Slog.v(TAG, " null");
5082 // This previously registered persistent preferred activity
5083 // component is no longer known. Ignore it and do NOT remove it.
5086 for (int j=0; j<N; j++) {
5087 final ResolveInfo ri = query.get(j);
5088 if (!ri.activityInfo.applicationInfo.packageName
5089 .equals(ai.applicationInfo.packageName)) {
5092 if (!ri.activityInfo.name.equals(ai.name)) {
5095 // Found a persistent preference that can handle the intent.
5096 if (DEBUG_PREFERRED || debug) {
5097 Slog.v(TAG, "Returning persistent preferred activity: " +
5098 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5107 // TODO: handle preferred activities missing while user has amnesia
5108 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5109 List<ResolveInfo> query, int priority, boolean always,
5110 boolean removeMatches, boolean debug, int userId) {
5111 if (!sUserManager.exists(userId)) return null;
5112 flags = updateFlagsForResolve(flags, userId, intent);
5114 synchronized (mPackages) {
5115 if (intent.getSelector() != null) {
5116 intent = intent.getSelector();
5118 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5120 // Try to find a matching persistent preferred activity.
5121 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5124 // If a persistent preferred activity matched, use it.
5129 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5130 // Get the list of preferred activities that handle the intent
5131 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5132 List<PreferredActivity> prefs = pir != null
5133 ? pir.queryIntent(intent, resolvedType,
5134 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5136 if (prefs != null && prefs.size() > 0) {
5137 boolean changed = false;
5139 // First figure out how good the original match set is.
5140 // We will only allow preferred activities that came
5141 // from the same match quality.
5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5146 final int N = query.size();
5147 for (int j=0; j<N; j++) {
5148 final ResolveInfo ri = query.get(j);
5149 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5150 + ": 0x" + Integer.toHexString(match));
5151 if (ri.match > match) {
5156 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5157 + Integer.toHexString(match));
5159 match &= IntentFilter.MATCH_CATEGORY_MASK;
5160 final int M = prefs.size();
5161 for (int i=0; i<M; i++) {
5162 final PreferredActivity pa = prefs.get(i);
5163 if (DEBUG_PREFERRED || debug) {
5164 Slog.v(TAG, "Checking PreferredActivity ds="
5165 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5166 + "\n component=" + pa.mPref.mComponent);
5167 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5169 if (pa.mPref.mMatch != match) {
5170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5171 + Integer.toHexString(pa.mPref.mMatch));
5174 // If it's not an "always" type preferred activity and that's what we're
5175 // looking for, skip it.
5176 if (always && !pa.mPref.mAlways) {
5177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5180 final ActivityInfo ai = getActivityInfo(
5181 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5182 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5184 if (DEBUG_PREFERRED || debug) {
5185 Slog.v(TAG, "Found preferred activity:");
5187 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5189 Slog.v(TAG, " null");
5193 // This previously registered preferred activity
5194 // component is no longer known. Most likely an update
5195 // to the app was installed and in the new version this
5196 // component no longer exists. Clean it up by removing
5197 // it from the preferred activities list, and skip it.
5198 Slog.w(TAG, "Removing dangling preferred activity: "
5199 + pa.mPref.mComponent);
5200 pir.removeFilter(pa);
5204 for (int j=0; j<N; j++) {
5205 final ResolveInfo ri = query.get(j);
5206 if (!ri.activityInfo.applicationInfo.packageName
5207 .equals(ai.applicationInfo.packageName)) {
5210 if (!ri.activityInfo.name.equals(ai.name)) {
5214 if (removeMatches) {
5215 pir.removeFilter(pa);
5217 if (DEBUG_PREFERRED) {
5218 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5223 // Okay we found a previously set preferred or last chosen app.
5224 // If the result set is different from when this
5225 // was created, we need to clear it and re-ask the
5226 // user their preference, if we're looking for an "always" type entry.
5227 if (always && !pa.mPref.sameSet(query)) {
5228 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5229 + intent + " type " + resolvedType);
5230 if (DEBUG_PREFERRED) {
5231 Slog.v(TAG, "Removing preferred activity since set changed "
5232 + pa.mPref.mComponent);
5234 pir.removeFilter(pa);
5235 // Re-add the filter as a "last chosen" entry (!always)
5236 PreferredActivity lastChosen = new PreferredActivity(
5237 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5238 pir.addFilter(lastChosen);
5243 // Yay! Either the set matched or we're looking for the last chosen
5244 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5245 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5251 if (DEBUG_PREFERRED) {
5252 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5254 scheduleWritePackageRestrictionsLocked(userId);
5259 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5264 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5267 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5269 mContext.enforceCallingOrSelfPermission(
5270 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5271 List<CrossProfileIntentFilter> matches =
5272 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5273 if (matches != null) {
5274 int size = matches.size();
5275 for (int i = 0; i < size; i++) {
5276 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5279 if (hasWebURI(intent)) {
5280 // cross-profile app linking works only towards the parent.
5281 final UserInfo parent = getProfileParent(sourceUserId);
5282 synchronized(mPackages) {
5283 int flags = updateFlagsForResolve(0, parent.id, intent);
5284 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5285 intent, resolvedType, flags, sourceUserId, parent.id);
5286 return xpDomainInfo != null;
5292 private UserInfo getProfileParent(int userId) {
5293 final long identity = Binder.clearCallingIdentity();
5295 return sUserManager.getProfileParent(userId);
5297 Binder.restoreCallingIdentity(identity);
5301 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5302 String resolvedType, int userId) {
5303 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5304 if (resolver != null) {
5305 return resolver.queryIntent(intent, resolvedType, false, userId);
5311 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5312 String resolvedType, int flags, int userId) {
5314 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5316 return new ParceledListSlice<>(
5317 queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5319 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5323 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5324 String resolvedType, int flags, int userId) {
5325 if (!sUserManager.exists(userId)) return Collections.emptyList();
5326 flags = updateFlagsForResolve(flags, userId, intent);
5327 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5328 false /* requireFullPermission */, false /* checkShell */,
5329 "query intent activities");
5330 ComponentName comp = intent.getComponent();
5332 if (intent.getSelector() != null) {
5333 intent = intent.getSelector();
5334 comp = intent.getComponent();
5339 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5340 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5342 final ResolveInfo ri = new ResolveInfo();
5343 ri.activityInfo = ai;
5350 boolean sortResult = false;
5351 boolean addEphemeral = false;
5352 boolean matchEphemeralPackage = false;
5353 List<ResolveInfo> result;
5354 final String pkgName = intent.getPackage();
5355 synchronized (mPackages) {
5356 if (pkgName == null) {
5357 List<CrossProfileIntentFilter> matchingFilters =
5358 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5359 // Check for results that need to skip the current profile.
5360 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
5361 resolvedType, flags, userId);
5362 if (xpResolveInfo != null) {
5363 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5364 xpResult.add(xpResolveInfo);
5365 return filterIfNotSystemUser(xpResult, userId);
5368 // Check for results in the current profile.
5369 result = filterIfNotSystemUser(mActivities.queryIntent(
5370 intent, resolvedType, flags, userId), userId);
5372 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5374 // Check for cross profile results.
5375 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5376 xpResolveInfo = queryCrossProfileIntents(
5377 matchingFilters, intent, resolvedType, flags, userId,
5378 hasNonNegativePriorityResult);
5379 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5380 boolean isVisibleToUser = filterIfNotSystemUser(
5381 Collections.singletonList(xpResolveInfo), userId).size() > 0;
5382 if (isVisibleToUser) {
5383 result.add(xpResolveInfo);
5387 if (hasWebURI(intent)) {
5388 CrossProfileDomainInfo xpDomainInfo = null;
5389 final UserInfo parent = getProfileParent(userId);
5390 if (parent != null) {
5391 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5392 flags, userId, parent.id);
5394 if (xpDomainInfo != null) {
5395 if (xpResolveInfo != null) {
5396 // If we didn't remove it, the cross-profile ResolveInfo would be twice
5398 result.remove(xpResolveInfo);
5400 if (result.size() == 0 && !addEphemeral) {
5401 // No result in current profile, but found candidate in parent user.
5402 // And we are not going to add emphemeral app, so we can return the
5403 // result straight away.
5404 result.add(xpDomainInfo.resolveInfo);
5407 } else if (result.size() <= 1 && !addEphemeral) {
5408 // No result in parent user and <= 1 result in current profile, and we
5409 // are not going to add emphemeral app, so we can return the result without
5410 // further processing.
5413 // We have more than one candidate (combining results from current and parent
5414 // profile), so we need filtering and sorting.
5415 result = filterCandidatesWithDomainPreferredActivitiesLPr(
5416 intent, flags, result, xpDomainInfo, userId);
5420 final PackageParser.Package pkg = mPackages.get(pkgName);
5422 result = filterIfNotSystemUser(
5423 mActivities.queryIntentForPackage(
5424 intent, resolvedType, flags, pkg.activities, userId),
5427 // the caller wants to resolve for a particular package; however, there
5428 // were no installed results, so, try to find an ephemeral result
5429 addEphemeral = isEphemeralAllowed(
5430 intent, null /*result*/, userId, true /*skipPackageCheck*/);
5431 matchEphemeralPackage = true;
5432 result = new ArrayList<ResolveInfo>();
5437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5438 final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5439 mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5440 matchEphemeralPackage ? pkgName : null);
5442 if (DEBUG_EPHEMERAL) {
5443 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5445 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5446 ephemeralInstaller.ephemeralResolveInfo = ai;
5447 // make sure this resolver is the default
5448 ephemeralInstaller.isDefault = true;
5449 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5450 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5451 // add a non-generic filter
5452 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5453 ephemeralInstaller.filter.addDataPath(
5454 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5455 result.add(ephemeralInstaller);
5457 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5460 Collections.sort(result, mResolvePrioritySorter);
5465 private static class CrossProfileDomainInfo {
5466 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5467 ResolveInfo resolveInfo;
5468 /* Best domain verification status of the activities found in the other profile */
5469 int bestDomainVerificationStatus;
5472 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5473 String resolvedType, int flags, int sourceUserId, int parentUserId) {
5474 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5478 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5479 resolvedType, flags, parentUserId);
5481 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5484 CrossProfileDomainInfo result = null;
5485 int size = resultTargetUser.size();
5486 for (int i = 0; i < size; i++) {
5487 ResolveInfo riTargetUser = resultTargetUser.get(i);
5488 // Intent filter verification is only for filters that specify a host. So don't return
5489 // those that handle all web uris.
5490 if (riTargetUser.handleAllWebDataURI) {
5493 String packageName = riTargetUser.activityInfo.packageName;
5494 PackageSetting ps = mSettings.mPackages.get(packageName);
5498 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5499 int status = (int)(verificationState >> 32);
5500 if (result == null) {
5501 result = new CrossProfileDomainInfo();
5502 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5503 sourceUserId, parentUserId);
5504 result.bestDomainVerificationStatus = status;
5506 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5507 result.bestDomainVerificationStatus);
5510 // Don't consider matches with status NEVER across profiles.
5511 if (result != null && result.bestDomainVerificationStatus
5512 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5519 * Verification statuses are ordered from the worse to the best, except for
5520 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5522 private int bestDomainVerificationStatus(int status1, int status2) {
5523 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5526 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5529 return (int) MathUtils.max(status1, status2);
5532 private boolean isUserEnabled(int userId) {
5533 long callingId = Binder.clearCallingIdentity();
5535 UserInfo userInfo = sUserManager.getUserInfo(userId);
5536 return userInfo != null && userInfo.isEnabled();
5538 Binder.restoreCallingIdentity(callingId);
5543 * Filter out activities with systemUserOnly flag set, when current user is not System.
5545 * @return filtered list
5547 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5548 if (userId == UserHandle.USER_SYSTEM) {
5549 return resolveInfos;
5551 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5552 ResolveInfo info = resolveInfos.get(i);
5553 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5554 resolveInfos.remove(i);
5557 return resolveInfos;
5561 * @param resolveInfos list of resolve infos in descending priority order
5562 * @return if the list contains a resolve info with non-negative priority
5564 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5565 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5568 private static boolean hasWebURI(Intent intent) {
5569 if (intent.getData() == null) {
5572 final String scheme = intent.getScheme();
5573 if (TextUtils.isEmpty(scheme)) {
5576 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5579 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5580 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5582 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5584 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5585 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5589 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5590 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5591 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5592 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5593 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5594 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5596 synchronized (mPackages) {
5597 final int count = candidates.size();
5598 // First, try to use linked apps. Partition the candidates into four lists:
5599 // one for the final results, one for the "do not use ever", one for "undefined status"
5600 // and finally one for "browser app type".
5601 for (int n=0; n<count; n++) {
5602 ResolveInfo info = candidates.get(n);
5603 String packageName = info.activityInfo.packageName;
5604 PackageSetting ps = mSettings.mPackages.get(packageName);
5606 // Add to the special match all list (Browser use case)
5607 if (info.handleAllWebDataURI) {
5608 matchAllList.add(info);
5611 // Try to get the status from User settings first
5612 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5613 int status = (int)(packedStatus >> 32);
5614 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5615 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5616 if (DEBUG_DOMAIN_VERIFICATION) {
5617 Slog.i(TAG, " + always: " + info.activityInfo.packageName
5618 + " : linkgen=" + linkGeneration);
5620 // Use link-enabled generation as preferredOrder, i.e.
5621 // prefer newly-enabled over earlier-enabled.
5622 info.preferredOrder = linkGeneration;
5623 alwaysList.add(info);
5624 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5625 if (DEBUG_DOMAIN_VERIFICATION) {
5626 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
5628 neverList.add(info);
5629 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5630 if (DEBUG_DOMAIN_VERIFICATION) {
5631 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
5633 alwaysAskList.add(info);
5634 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5635 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5636 if (DEBUG_DOMAIN_VERIFICATION) {
5637 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
5639 undefinedList.add(info);
5644 // We'll want to include browser possibilities in a few cases
5645 boolean includeBrowser = false;
5647 // First try to add the "always" resolution(s) for the current user, if any
5648 if (alwaysList.size() > 0) {
5649 result.addAll(alwaysList);
5651 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5652 result.addAll(undefinedList);
5653 // Maybe add one for the other profile.
5654 if (xpDomainInfo != null && (
5655 xpDomainInfo.bestDomainVerificationStatus
5656 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5657 result.add(xpDomainInfo.resolveInfo);
5659 includeBrowser = true;
5662 // The presence of any 'always ask' alternatives means we'll also offer browsers.
5663 // If there were 'always' entries their preferred order has been set, so we also
5664 // back that off to make the alternatives equivalent
5665 if (alwaysAskList.size() > 0) {
5666 for (ResolveInfo i : result) {
5667 i.preferredOrder = 0;
5669 result.addAll(alwaysAskList);
5670 includeBrowser = true;
5673 if (includeBrowser) {
5674 // Also add browsers (all of them or only the default one)
5675 if (DEBUG_DOMAIN_VERIFICATION) {
5676 Slog.v(TAG, " ...including browsers in candidate set");
5678 if ((matchFlags & MATCH_ALL) != 0) {
5679 result.addAll(matchAllList);
5681 // Browser/generic handling case. If there's a default browser, go straight
5682 // to that (but only if there is no other higher-priority match).
5683 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5684 int maxMatchPrio = 0;
5685 ResolveInfo defaultBrowserMatch = null;
5686 final int numCandidates = matchAllList.size();
5687 for (int n = 0; n < numCandidates; n++) {
5688 ResolveInfo info = matchAllList.get(n);
5689 // track the highest overall match priority...
5690 if (info.priority > maxMatchPrio) {
5691 maxMatchPrio = info.priority;
5693 // ...and the highest-priority default browser match
5694 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5695 if (defaultBrowserMatch == null
5696 || (defaultBrowserMatch.priority < info.priority)) {
5698 Slog.v(TAG, "Considering default browser match " + info);
5700 defaultBrowserMatch = info;
5704 if (defaultBrowserMatch != null
5705 && defaultBrowserMatch.priority >= maxMatchPrio
5706 && !TextUtils.isEmpty(defaultBrowserPackageName))
5709 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5711 result.add(defaultBrowserMatch);
5713 result.addAll(matchAllList);
5717 // If there is nothing selected, add all candidates and remove the ones that the user
5718 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5719 if (result.size() == 0) {
5720 result.addAll(candidates);
5721 result.removeAll(neverList);
5725 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5726 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5728 for (ResolveInfo info : result) {
5729 Slog.v(TAG, " + " + info.activityInfo);
5735 // Returns a packed value as a long:
5737 // high 'int'-sized word: link status: undefined/ask/never/always.
5738 // low 'int'-sized word: relative priority among 'always' results.
5739 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5740 long result = ps.getDomainVerificationStatusForUser(userId);
5741 // if none available, get the master status
5742 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5743 if (ps.getIntentFilterVerificationInfo() != null) {
5744 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5750 private ResolveInfo querySkipCurrentProfileIntents(
5751 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5752 int flags, int sourceUserId) {
5753 if (matchingFilters != null) {
5754 int size = matchingFilters.size();
5755 for (int i = 0; i < size; i ++) {
5756 CrossProfileIntentFilter filter = matchingFilters.get(i);
5757 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5758 // Checking if there are activities in the target user that can handle the
5760 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5761 resolvedType, flags, sourceUserId);
5762 if (resolveInfo != null) {
5771 // Return matching ResolveInfo in target user if any.
5772 private ResolveInfo queryCrossProfileIntents(
5773 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5774 int flags, int sourceUserId, boolean matchInCurrentProfile) {
5775 if (matchingFilters != null) {
5776 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5777 // match the same intent. For performance reasons, it is better not to
5778 // run queryIntent twice for the same userId
5779 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5780 int size = matchingFilters.size();
5781 for (int i = 0; i < size; i++) {
5782 CrossProfileIntentFilter filter = matchingFilters.get(i);
5783 int targetUserId = filter.getTargetUserId();
5784 boolean skipCurrentProfile =
5785 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5786 boolean skipCurrentProfileIfNoMatchFound =
5787 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5788 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5789 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5790 // Checking if there are activities in the target user that can handle the
5792 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5793 resolvedType, flags, sourceUserId);
5794 if (resolveInfo != null) return resolveInfo;
5795 alreadyTriedUserIds.put(targetUserId, true);
5803 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5804 * will forward the intent to the filter's target user.
5805 * Otherwise, returns null.
5807 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5808 String resolvedType, int flags, int sourceUserId) {
5809 int targetUserId = filter.getTargetUserId();
5810 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5811 resolvedType, flags, targetUserId);
5812 if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5813 // If all the matches in the target profile are suspended, return null.
5814 for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5815 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5816 & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5817 return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5825 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5826 int sourceUserId, int targetUserId) {
5827 ResolveInfo forwardingResolveInfo = new ResolveInfo();
5828 long ident = Binder.clearCallingIdentity();
5829 boolean targetIsProfile;
5831 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5833 Binder.restoreCallingIdentity(ident);
5836 if (targetIsProfile) {
5837 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5839 className = FORWARD_INTENT_TO_PARENT;
5841 ComponentName forwardingActivityComponentName = new ComponentName(
5842 mAndroidApplication.packageName, className);
5843 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5845 if (!targetIsProfile) {
5846 forwardingActivityInfo.showUserIcon = targetUserId;
5847 forwardingResolveInfo.noResourceId = true;
5849 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5850 forwardingResolveInfo.priority = 0;
5851 forwardingResolveInfo.preferredOrder = 0;
5852 forwardingResolveInfo.match = 0;
5853 forwardingResolveInfo.isDefault = true;
5854 forwardingResolveInfo.filter = filter;
5855 forwardingResolveInfo.targetUserId = targetUserId;
5856 return forwardingResolveInfo;
5860 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5861 Intent[] specifics, String[] specificTypes, Intent intent,
5862 String resolvedType, int flags, int userId) {
5863 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5864 specificTypes, intent, resolvedType, flags, userId));
5867 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5868 Intent[] specifics, String[] specificTypes, Intent intent,
5869 String resolvedType, int flags, int userId) {
5870 if (!sUserManager.exists(userId)) return Collections.emptyList();
5871 flags = updateFlagsForResolve(flags, userId, intent);
5872 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5873 false /* requireFullPermission */, false /* checkShell */,
5874 "query intent activity options");
5875 final String resultsAction = intent.getAction();
5877 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5878 | PackageManager.GET_RESOLVED_FILTER, userId);
5880 if (DEBUG_INTENT_MATCHING) {
5881 Log.v(TAG, "Query " + intent + ": " + results);
5884 int specificsPos = 0;
5887 // todo: note that the algorithm used here is O(N^2). This
5888 // isn't a problem in our current environment, but if we start running
5889 // into situations where we have more than 5 or 10 matches then this
5890 // should probably be changed to something smarter...
5892 // First we go through and resolve each of the specific items
5893 // that were supplied, taking care of removing any corresponding
5894 // duplicate items in the generic resolve list.
5895 if (specifics != null) {
5896 for (int i=0; i<specifics.length; i++) {
5897 final Intent sintent = specifics[i];
5898 if (sintent == null) {
5902 if (DEBUG_INTENT_MATCHING) {
5903 Log.v(TAG, "Specific #" + i + ": " + sintent);
5906 String action = sintent.getAction();
5907 if (resultsAction != null && resultsAction.equals(action)) {
5908 // If this action was explicitly requested, then don't
5909 // remove things that have it.
5913 ResolveInfo ri = null;
5914 ActivityInfo ai = null;
5916 ComponentName comp = sintent.getComponent();
5920 specificTypes != null ? specificTypes[i] : null,
5925 if (ri == mResolveInfo) {
5926 // ACK! Must do something better with this.
5928 ai = ri.activityInfo;
5929 comp = new ComponentName(ai.applicationInfo.packageName,
5932 ai = getActivityInfo(comp, flags, userId);
5938 // Look for any generic query activities that are duplicates
5939 // of this specific one, and remove them from the results.
5940 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5943 for (j=specificsPos; j<N; j++) {
5944 ResolveInfo sri = results.get(j);
5945 if ((sri.activityInfo.name.equals(comp.getClassName())
5946 && sri.activityInfo.applicationInfo.packageName.equals(
5947 comp.getPackageName()))
5948 || (action != null && sri.filter.matchAction(action))) {
5950 if (DEBUG_INTENT_MATCHING) Log.v(
5951 TAG, "Removing duplicate item from " + j
5952 + " due to specific " + specificsPos);
5961 // Add this specific item to its proper place.
5963 ri = new ResolveInfo();
5964 ri.activityInfo = ai;
5966 results.add(specificsPos, ri);
5967 ri.specificIndex = i;
5972 // Now we go through the remaining generic results and remove any
5973 // duplicate actions that are found here.
5975 for (int i=specificsPos; i<N-1; i++) {
5976 final ResolveInfo rii = results.get(i);
5977 if (rii.filter == null) {
5981 // Iterate over all of the actions of this result's intent
5982 // filter... typically this should be just one.
5983 final Iterator<String> it = rii.filter.actionsIterator();
5987 while (it.hasNext()) {
5988 final String action = it.next();
5989 if (resultsAction != null && resultsAction.equals(action)) {
5990 // If this action was explicitly requested, then don't
5991 // remove things that have it.
5994 for (int j=i+1; j<N; j++) {
5995 final ResolveInfo rij = results.get(j);
5996 if (rij.filter != null && rij.filter.hasAction(action)) {
5998 if (DEBUG_INTENT_MATCHING) Log.v(
5999 TAG, "Removing duplicate item from " + j
6000 + " due to action " + action + " at " + i);
6007 // If the caller didn't request filter information, drop it now
6008 // so we don't have to marshall/unmarshall it.
6009 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6014 // Filter out the caller activity if so requested.
6015 if (caller != null) {
6017 for (int i=0; i<N; i++) {
6018 ActivityInfo ainfo = results.get(i).activityInfo;
6019 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6020 && caller.getClassName().equals(ainfo.name)) {
6027 // If the caller didn't request filter information,
6028 // drop them now so we don't have to
6029 // marshall/unmarshall it.
6030 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6032 for (int i=0; i<N; i++) {
6033 results.get(i).filter = null;
6037 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6042 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6043 String resolvedType, int flags, int userId) {
6044 return new ParceledListSlice<>(
6045 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6048 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6049 String resolvedType, int flags, int userId) {
6050 if (!sUserManager.exists(userId)) return Collections.emptyList();
6051 flags = updateFlagsForResolve(flags, userId, intent);
6052 ComponentName comp = intent.getComponent();
6054 if (intent.getSelector() != null) {
6055 intent = intent.getSelector();
6056 comp = intent.getComponent();
6060 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6061 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6063 ResolveInfo ri = new ResolveInfo();
6064 ri.activityInfo = ai;
6071 synchronized (mPackages) {
6072 String pkgName = intent.getPackage();
6073 if (pkgName == null) {
6074 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6076 final PackageParser.Package pkg = mPackages.get(pkgName);
6078 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6081 return Collections.emptyList();
6086 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6087 if (!sUserManager.exists(userId)) return null;
6088 flags = updateFlagsForResolve(flags, userId, intent);
6089 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6090 if (query != null) {
6091 if (query.size() >= 1) {
6092 // If there is more than one service with the same priority,
6093 // just arbitrarily pick the first one.
6094 return query.get(0);
6101 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6102 String resolvedType, int flags, int userId) {
6103 return new ParceledListSlice<>(
6104 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6107 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6108 String resolvedType, int flags, int userId) {
6109 if (!sUserManager.exists(userId)) return Collections.emptyList();
6110 flags = updateFlagsForResolve(flags, userId, intent);
6111 ComponentName comp = intent.getComponent();
6113 if (intent.getSelector() != null) {
6114 intent = intent.getSelector();
6115 comp = intent.getComponent();
6119 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6120 final ServiceInfo si = getServiceInfo(comp, flags, userId);
6122 final ResolveInfo ri = new ResolveInfo();
6123 ri.serviceInfo = si;
6130 synchronized (mPackages) {
6131 String pkgName = intent.getPackage();
6132 if (pkgName == null) {
6133 return mServices.queryIntent(intent, resolvedType, flags, userId);
6135 final PackageParser.Package pkg = mPackages.get(pkgName);
6137 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6140 return Collections.emptyList();
6145 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6146 String resolvedType, int flags, int userId) {
6147 return new ParceledListSlice<>(
6148 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6151 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6152 Intent intent, String resolvedType, int flags, int userId) {
6153 if (!sUserManager.exists(userId)) return Collections.emptyList();
6154 flags = updateFlagsForResolve(flags, userId, intent);
6155 ComponentName comp = intent.getComponent();
6157 if (intent.getSelector() != null) {
6158 intent = intent.getSelector();
6159 comp = intent.getComponent();
6163 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6164 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6166 final ResolveInfo ri = new ResolveInfo();
6167 ri.providerInfo = pi;
6174 synchronized (mPackages) {
6175 String pkgName = intent.getPackage();
6176 if (pkgName == null) {
6177 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6179 final PackageParser.Package pkg = mPackages.get(pkgName);
6181 return mProviders.queryIntentForPackage(
6182 intent, resolvedType, flags, pkg.providers, userId);
6184 return Collections.emptyList();
6189 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6190 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6191 flags = updateFlagsForPackage(flags, userId, null);
6192 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6193 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6194 true /* requireFullPermission */, false /* checkShell */,
6195 "get installed packages");
6198 synchronized (mPackages) {
6199 ArrayList<PackageInfo> list;
6200 if (listUninstalled) {
6201 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6202 for (PackageSetting ps : mSettings.mPackages.values()) {
6203 final PackageInfo pi;
6204 if (ps.pkg != null) {
6205 pi = generatePackageInfo(ps, flags, userId);
6207 pi = generatePackageInfo(ps, flags, userId);
6214 list = new ArrayList<PackageInfo>(mPackages.size());
6215 for (PackageParser.Package p : mPackages.values()) {
6216 final PackageInfo pi =
6217 generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6224 return new ParceledListSlice<PackageInfo>(list);
6228 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6229 String[] permissions, boolean[] tmp, int flags, int userId) {
6231 final PermissionsState permissionsState = ps.getPermissionsState();
6232 for (int i=0; i<permissions.length; i++) {
6233 final String permission = permissions[i];
6234 if (permissionsState.hasPermission(permission, userId)) {
6241 if (numMatch == 0) {
6244 final PackageInfo pi;
6245 if (ps.pkg != null) {
6246 pi = generatePackageInfo(ps, flags, userId);
6248 pi = generatePackageInfo(ps, flags, userId);
6250 // The above might return null in cases of uninstalled apps or install-state
6251 // skew across users/profiles.
6253 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6254 if (numMatch == permissions.length) {
6255 pi.requestedPermissions = permissions;
6257 pi.requestedPermissions = new String[numMatch];
6259 for (int i=0; i<permissions.length; i++) {
6261 pi.requestedPermissions[numMatch] = permissions[i];
6272 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6273 String[] permissions, int flags, int userId) {
6274 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6275 flags = updateFlagsForPackage(flags, userId, permissions);
6276 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6279 synchronized (mPackages) {
6280 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6281 boolean[] tmpBools = new boolean[permissions.length];
6282 if (listUninstalled) {
6283 for (PackageSetting ps : mSettings.mPackages.values()) {
6284 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6287 for (PackageParser.Package pkg : mPackages.values()) {
6288 PackageSetting ps = (PackageSetting)pkg.mExtras;
6290 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6296 return new ParceledListSlice<PackageInfo>(list);
6301 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6302 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6303 flags = updateFlagsForApplication(flags, userId, null);
6304 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6307 synchronized (mPackages) {
6308 ArrayList<ApplicationInfo> list;
6309 if (listUninstalled) {
6310 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6311 for (PackageSetting ps : mSettings.mPackages.values()) {
6313 if (ps.pkg != null) {
6314 ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6315 ps.readUserState(userId), userId);
6317 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6324 list = new ArrayList<ApplicationInfo>(mPackages.size());
6325 for (PackageParser.Package p : mPackages.values()) {
6326 if (p.mExtras != null) {
6327 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6328 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6336 return new ParceledListSlice<ApplicationInfo>(list);
6341 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6342 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6346 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6347 "getEphemeralApplications");
6348 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6349 true /* requireFullPermission */, false /* checkShell */,
6350 "getEphemeralApplications");
6351 synchronized (mPackages) {
6352 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6353 .getEphemeralApplicationsLPw(userId);
6354 if (ephemeralApps != null) {
6355 return new ParceledListSlice<>(ephemeralApps);
6362 public boolean isEphemeralApplication(String packageName, int userId) {
6363 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6364 true /* requireFullPermission */, false /* checkShell */,
6366 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6370 if (!isCallerSameApp(packageName)) {
6373 synchronized (mPackages) {
6374 PackageParser.Package pkg = mPackages.get(packageName);
6376 return pkg.applicationInfo.isEphemeralApp();
6383 public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6384 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6388 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6389 true /* requireFullPermission */, false /* checkShell */,
6391 if (!isCallerSameApp(packageName)) {
6394 synchronized (mPackages) {
6395 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6396 packageName, userId);
6401 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6402 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6406 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6407 true /* requireFullPermission */, true /* checkShell */,
6409 if (!isCallerSameApp(packageName)) {
6412 synchronized (mPackages) {
6413 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6414 packageName, cookie, userId);
6419 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6420 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6424 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6425 "getEphemeralApplicationIcon");
6426 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6427 true /* requireFullPermission */, false /* checkShell */,
6428 "getEphemeralApplicationIcon");
6429 synchronized (mPackages) {
6430 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6431 packageName, userId);
6435 private boolean isCallerSameApp(String packageName) {
6436 PackageParser.Package pkg = mPackages.get(packageName);
6438 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6442 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6443 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6446 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6447 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6450 synchronized (mPackages) {
6451 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6452 final int userId = UserHandle.getCallingUserId();
6453 while (i.hasNext()) {
6454 final PackageParser.Package p = i.next();
6455 if (p.applicationInfo == null) continue;
6457 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6458 && !p.applicationInfo.isDirectBootAware();
6459 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6460 && p.applicationInfo.isDirectBootAware();
6462 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6463 && (!mSafeMode || isSystemApp(p))
6464 && (matchesUnaware || matchesAware)) {
6465 PackageSetting ps = mSettings.mPackages.get(p.packageName);
6467 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6468 ps.readUserState(userId), userId);
6481 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6482 if (!sUserManager.exists(userId)) return null;
6483 flags = updateFlagsForComponent(flags, userId, name);
6485 synchronized (mPackages) {
6486 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6487 PackageSetting ps = provider != null
6488 ? mSettings.mPackages.get(provider.owner.packageName)
6491 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6492 ? PackageParser.generateProviderInfo(provider, flags,
6493 ps.readUserState(userId), userId)
6502 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6504 synchronized (mPackages) {
6505 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6506 .entrySet().iterator();
6507 final int userId = UserHandle.getCallingUserId();
6508 while (i.hasNext()) {
6509 Map.Entry<String, PackageParser.Provider> entry = i.next();
6510 PackageParser.Provider p = entry.getValue();
6511 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6513 if (ps != null && p.syncable
6514 && (!mSafeMode || (p.info.applicationInfo.flags
6515 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6516 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6517 ps.readUserState(userId), userId);
6519 outNames.add(entry.getKey());
6528 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6529 int uid, int flags) {
6530 final int userId = processName != null ? UserHandle.getUserId(uid)
6531 : UserHandle.getCallingUserId();
6532 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6533 flags = updateFlagsForComponent(flags, userId, processName);
6535 ArrayList<ProviderInfo> finalList = null;
6537 synchronized (mPackages) {
6538 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6539 while (i.hasNext()) {
6540 final PackageParser.Provider p = i.next();
6541 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6542 if (ps != null && p.info.authority != null
6543 && (processName == null
6544 || (p.info.processName.equals(processName)
6545 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6546 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6547 if (finalList == null) {
6548 finalList = new ArrayList<ProviderInfo>(3);
6550 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6551 ps.readUserState(userId), userId);
6553 finalList.add(info);
6559 if (finalList != null) {
6560 Collections.sort(finalList, mProviderInitOrderSorter);
6561 return new ParceledListSlice<ProviderInfo>(finalList);
6564 return ParceledListSlice.emptyList();
6568 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6570 synchronized (mPackages) {
6571 final PackageParser.Instrumentation i = mInstrumentation.get(name);
6572 return PackageParser.generateInstrumentationInfo(i, flags);
6577 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6578 String targetPackage, int flags) {
6579 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6582 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6584 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6587 synchronized (mPackages) {
6588 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6589 while (i.hasNext()) {
6590 final PackageParser.Instrumentation p = i.next();
6591 if (targetPackage == null
6592 || targetPackage.equals(p.info.targetPackage)) {
6593 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6605 private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6606 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6607 if (overlays == null) {
6608 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6611 for (PackageParser.Package opkg : overlays.values()) {
6612 // Not much to do if idmap fails: we already logged the error
6613 // and we certainly don't want to abort installation of pkg simply
6614 // because an overlay didn't fit properly. For these reasons,
6615 // ignore the return value of createIdmapForPackagePairLI.
6616 createIdmapForPackagePairLI(pkg, opkg);
6620 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6621 PackageParser.Package opkg) {
6622 if (!opkg.mTrustedOverlay) {
6623 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6624 opkg.baseCodePath + ": overlay not trusted");
6627 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6628 if (overlaySet == null) {
6629 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6630 opkg.baseCodePath + " but target package has no known overlays");
6633 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6634 // TODO: generate idmap for split APKs
6636 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6637 } catch (InstallerException e) {
6638 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6639 + opkg.baseCodePath);
6642 PackageParser.Package[] overlayArray =
6643 overlaySet.values().toArray(new PackageParser.Package[0]);
6644 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6645 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6646 return p1.mOverlayPriority - p2.mOverlayPriority;
6649 Arrays.sort(overlayArray, cmp);
6651 pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6653 for (PackageParser.Package p : overlayArray) {
6654 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6659 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6662 scanDirLI(dir, parseFlags, scanFlags, currentTime);
6664 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6668 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6669 final File[] files = dir.listFiles();
6670 if (ArrayUtils.isEmpty(files)) {
6671 Log.d(TAG, "No files in app dir " + dir);
6675 if (DEBUG_PACKAGE_SCANNING) {
6676 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6677 + " flags=0x" + Integer.toHexString(parseFlags));
6680 for (File file : files) {
6681 final boolean isPackage = (isApkFile(file) || file.isDirectory())
6682 && !PackageInstallerService.isStageName(file.getName());
6684 // Ignore entries which are not packages
6688 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6689 scanFlags, currentTime, null);
6690 } catch (PackageManagerException e) {
6691 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6693 // Delete invalid userdata apps
6694 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6695 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6696 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6697 removeCodePathLI(file);
6703 private static File getSettingsProblemFile() {
6704 File dataDir = Environment.getDataDirectory();
6705 File systemDir = new File(dataDir, "system");
6706 File fname = new File(systemDir, "uiderrors.txt");
6710 static void reportSettingsProblem(int priority, String msg) {
6711 logCriticalInfo(priority, msg);
6714 static void logCriticalInfo(int priority, String msg) {
6715 Slog.println(priority, TAG, msg);
6716 EventLogTags.writePmCriticalInfo(msg);
6718 File fname = getSettingsProblemFile();
6719 FileOutputStream out = new FileOutputStream(fname, true);
6720 PrintWriter pw = new FastPrintWriter(out);
6721 SimpleDateFormat formatter = new SimpleDateFormat();
6722 String dateString = formatter.format(new Date(System.currentTimeMillis()));
6723 pw.println(dateString + ": " + msg);
6725 FileUtils.setPermissions(
6727 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6729 } catch (java.io.IOException e) {
6733 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6734 if (srcFile.isDirectory()) {
6735 final File baseFile = new File(pkg.baseCodePath);
6736 long maxModifiedTime = baseFile.lastModified();
6737 if (pkg.splitCodePaths != null) {
6738 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6739 final File splitFile = new File(pkg.splitCodePaths[i]);
6740 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6743 return maxModifiedTime;
6745 return srcFile.lastModified();
6748 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6749 final int policyFlags) throws PackageManagerException {
6750 // When upgrading from pre-N MR1, verify the package time stamp using the package
6751 // directory and not the APK file.
6752 final long lastModifiedTime = mIsPreNMR1Upgrade
6753 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6755 && ps.codePath.equals(srcFile)
6756 && ps.timeStamp == lastModifiedTime
6757 && !isCompatSignatureUpdateNeeded(pkg)
6758 && !isRecoverSignatureUpdateNeeded(pkg)) {
6759 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6760 KeySetManagerService ksms = mSettings.mKeySetManagerService;
6761 ArraySet<PublicKey> signingKs;
6762 synchronized (mPackages) {
6763 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6765 if (ps.signatures.mSignatures != null
6766 && ps.signatures.mSignatures.length != 0
6767 && signingKs != null) {
6768 // Optimization: reuse the existing cached certificates
6769 // if the package appears to be unchanged.
6770 pkg.mSignatures = ps.signatures.mSignatures;
6771 pkg.mSigningKeys = signingKs;
6775 Slog.w(TAG, "PackageSetting for " + ps.name
6776 + " is missing signatures. Collecting certs again to recover them.");
6778 Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6782 PackageParser.collectCertificates(pkg, policyFlags);
6783 } catch (PackageParserException e) {
6784 throw PackageManagerException.from(e);
6789 * Traces a package scan.
6790 * @see #scanPackageLI(File, int, int, long, UserHandle)
6792 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6793 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6794 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6796 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6798 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6803 * Scans a package and returns the newly parsed package.
6804 * Returns {@code null} in case of errors and the error code is stored in mLastScanError
6806 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6807 long currentTime, UserHandle user) throws PackageManagerException {
6808 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6809 PackageParser pp = new PackageParser();
6810 pp.setSeparateProcesses(mSeparateProcesses);
6811 pp.setOnlyCoreApps(mOnlyCore);
6812 pp.setDisplayMetrics(mMetrics);
6814 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6815 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6819 final PackageParser.Package pkg;
6821 pkg = pp.parsePackage(scanFile, parseFlags);
6822 } catch (PackageParserException e) {
6823 throw PackageManagerException.from(e);
6825 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6828 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6832 * Scans a package and returns the newly parsed package.
6833 * @throws PackageManagerException on a parse error.
6835 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6836 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6837 throws PackageManagerException {
6838 // If the package has children and this is the first dive in the function
6839 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6840 // packages (parent and children) would be successfully scanned before the
6841 // actual scan since scanning mutates internal state and we want to atomically
6842 // install the package and its children.
6843 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6844 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6845 scanFlags |= SCAN_CHECK_ONLY;
6848 scanFlags &= ~SCAN_CHECK_ONLY;
6852 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6853 scanFlags, currentTime, user);
6855 // Scan the children
6856 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6857 for (int i = 0; i < childCount; i++) {
6858 PackageParser.Package childPackage = pkg.childPackages.get(i);
6859 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6864 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6865 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6872 * Scans a package and returns the newly parsed package.
6873 * @throws PackageManagerException on a parse error.
6875 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6876 int policyFlags, int scanFlags, long currentTime, UserHandle user)
6877 throws PackageManagerException {
6878 PackageSetting ps = null;
6879 PackageSetting updatedPkg;
6881 synchronized (mPackages) {
6882 // Look to see if we already know about this package.
6883 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6884 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6885 // This package has been renamed to its original name. Let's
6887 ps = mSettings.peekPackageLPr(oldName);
6889 // If there was no original package, see one for the real package name.
6891 ps = mSettings.peekPackageLPr(pkg.packageName);
6893 // Check to see if this package could be hiding/updating a system
6894 // package. Must look for it either under the original or real
6895 // package name depending on our state.
6896 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6897 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6899 // If this is a package we don't know about on the system partition, we
6900 // may need to remove disabled child packages on the system partition
6901 // or may need to not add child packages if the parent apk is updated
6902 // on the data partition and no longer defines this child package.
6903 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6904 // If this is a parent package for an updated system app and this system
6905 // app got an OTA update which no longer defines some of the child packages
6906 // we have to prune them from the disabled system packages.
6907 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6908 if (disabledPs != null) {
6909 final int scannedChildCount = (pkg.childPackages != null)
6910 ? pkg.childPackages.size() : 0;
6911 final int disabledChildCount = disabledPs.childPackageNames != null
6912 ? disabledPs.childPackageNames.size() : 0;
6913 for (int i = 0; i < disabledChildCount; i++) {
6914 String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6915 boolean disabledPackageAvailable = false;
6916 for (int j = 0; j < scannedChildCount; j++) {
6917 PackageParser.Package childPkg = pkg.childPackages.get(j);
6918 if (childPkg.packageName.equals(disabledChildPackageName)) {
6919 disabledPackageAvailable = true;
6923 if (!disabledPackageAvailable) {
6924 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6931 boolean updatedPkgBetter = false;
6932 // First check if this is a system package that may involve an update
6933 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6934 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6935 // it needs to drop FLAG_PRIVILEGED.
6936 if (locationIsPrivileged(scanFile)) {
6937 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6939 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6942 if (ps != null && !ps.codePath.equals(scanFile)) {
6943 // The path has changed from what was last scanned... check the
6944 // version of the new path against what we have stored to determine
6946 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6947 if (pkg.mVersionCode <= ps.versionCode) {
6948 // The system package has been updated and the code path does not match
6949 // Ignore entry. Skip it.
6950 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6951 + " ignored: updated version " + ps.versionCode
6952 + " better than this " + pkg.mVersionCode);
6953 if (!updatedPkg.codePath.equals(scanFile)) {
6954 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6955 + ps.name + " changing from " + updatedPkg.codePathString
6956 + " to " + scanFile);
6957 updatedPkg.codePath = scanFile;
6958 updatedPkg.codePathString = scanFile.toString();
6959 updatedPkg.resourcePath = scanFile;
6960 updatedPkg.resourcePathString = scanFile.toString();
6962 updatedPkg.pkg = pkg;
6963 updatedPkg.versionCode = pkg.mVersionCode;
6965 // Update the disabled system child packages to point to the package too.
6966 final int childCount = updatedPkg.childPackageNames != null
6967 ? updatedPkg.childPackageNames.size() : 0;
6968 for (int i = 0; i < childCount; i++) {
6969 String childPackageName = updatedPkg.childPackageNames.get(i);
6970 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6972 if (updatedChildPkg != null) {
6973 updatedChildPkg.pkg = pkg;
6974 updatedChildPkg.versionCode = pkg.mVersionCode;
6978 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6979 + scanFile + " ignored: updated version " + ps.versionCode
6980 + " better than this " + pkg.mVersionCode);
6982 // The current app on the system partition is better than
6983 // what we have updated to on the data partition; switch
6984 // back to the system partition version.
6985 // At this point, its safely assumed that package installation for
6986 // apps in system partition will go through. If not there won't be a working
6987 // version of the app
6989 synchronized (mPackages) {
6990 // Just remove the loaded entries from package lists.
6991 mPackages.remove(ps.name);
6994 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6995 + " reverting from " + ps.codePathString
6996 + ": new version " + pkg.mVersionCode
6997 + " better than installed " + ps.versionCode);
6999 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7000 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7001 synchronized (mInstallLock) {
7002 args.cleanUpResourcesLI();
7004 synchronized (mPackages) {
7005 mSettings.enableSystemPackageLPw(ps.name);
7007 updatedPkgBetter = true;
7012 if (updatedPkg != null) {
7013 // An updated system app will not have the PARSE_IS_SYSTEM flag set
7015 policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7017 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7018 // flag set initially
7019 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7020 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7024 // Verify certificates against what was last scanned
7025 collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7028 * A new system app appeared, but we already had a non-system one of the
7029 * same name installed earlier.
7031 boolean shouldHideSystemApp = false;
7032 if (updatedPkg == null && ps != null
7033 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7035 * Check to make sure the signatures match first. If they don't,
7036 * wipe the installed application and its data.
7038 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7039 != PackageManager.SIGNATURE_MATCH) {
7040 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7041 + " signatures don't match existing userdata copy; removing");
7042 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7043 "scanPackageInternalLI")) {
7044 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7049 * If the newly-added system app is an older version than the
7050 * already installed version, hide it. It will be scanned later
7051 * and re-added like an update.
7053 if (pkg.mVersionCode <= ps.versionCode) {
7054 shouldHideSystemApp = true;
7055 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7056 + " but new version " + pkg.mVersionCode + " better than installed "
7057 + ps.versionCode + "; hiding system");
7060 * The newly found system app is a newer version that the
7061 * one previously installed. Simply remove the
7062 * already-installed application and replace it with our own
7063 * while keeping the application data.
7065 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7066 + " reverting from " + ps.codePathString + ": new version "
7067 + pkg.mVersionCode + " better than installed " + ps.versionCode);
7068 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7069 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7070 synchronized (mInstallLock) {
7071 args.cleanUpResourcesLI();
7077 // The apk is forward locked (not public) if its code and resources
7078 // are kept in different files. (except for app in either system or
7080 // TODO grab this value from PackageSettings
7081 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7082 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7083 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7087 // TODO: extend to support forward-locked splits
7088 String resourcePath = null;
7089 String baseResourcePath = null;
7090 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7091 if (ps != null && ps.resourcePathString != null) {
7092 resourcePath = ps.resourcePathString;
7093 baseResourcePath = ps.resourcePathString;
7095 // Should not happen at all. Just log an error.
7096 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7099 resourcePath = pkg.codePath;
7100 baseResourcePath = pkg.baseCodePath;
7103 // Set application objects path explicitly.
7104 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7105 pkg.setApplicationInfoCodePath(pkg.codePath);
7106 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7107 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7108 pkg.setApplicationInfoResourcePath(resourcePath);
7109 pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7110 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7112 // Note that we invoke the following method only if we are about to unpack an application
7113 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7114 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7117 * If the system app should be overridden by a previously installed
7118 * data, hide the system app now and let the /data/app scan pick it up
7121 if (shouldHideSystemApp) {
7122 synchronized (mPackages) {
7123 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7130 private static String fixProcessName(String defProcessName,
7131 String processName, int uid) {
7132 if (processName == null) {
7133 return defProcessName;
7138 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7139 throws PackageManagerException {
7140 if (pkgSetting.signatures.mSignatures != null) {
7141 // Already existing package. Make sure signatures match
7142 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7143 == PackageManager.SIGNATURE_MATCH;
7145 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7146 == PackageManager.SIGNATURE_MATCH;
7149 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7150 == PackageManager.SIGNATURE_MATCH;
7153 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7154 + pkg.packageName + " signatures do not match the "
7155 + "previously installed version; ignoring!");
7159 // Check for shared user signatures
7160 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7161 // Already existing package. Make sure signatures match
7162 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7163 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7165 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7166 == PackageManager.SIGNATURE_MATCH;
7169 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7170 == PackageManager.SIGNATURE_MATCH;
7173 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7174 "Package " + pkg.packageName
7175 + " has no signatures that match those in shared user "
7176 + pkgSetting.sharedUser.name + "; ignoring!");
7182 * Enforces that only the system UID or root's UID can call a method exposed
7185 * @param message used as message if SecurityException is thrown
7186 * @throws SecurityException if the caller is not system or root
7188 private static final void enforceSystemOrRoot(String message) {
7189 final int uid = Binder.getCallingUid();
7190 if (uid != Process.SYSTEM_UID && uid != 0) {
7191 throw new SecurityException(message);
7196 public void performFstrimIfNeeded() {
7197 enforceSystemOrRoot("Only the system can request fstrim");
7199 // Before everything else, see whether we need to fstrim.
7201 IMountService ms = PackageHelper.getMountService();
7203 boolean doTrim = false;
7204 final long interval = android.provider.Settings.Global.getLong(
7205 mContext.getContentResolver(),
7206 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7207 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7209 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7210 if (timeSinceLast > interval) {
7212 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7213 + "; running immediately");
7217 final boolean dexOptDialogShown;
7218 synchronized (mPackages) {
7219 dexOptDialogShown = mDexOptDialogShown;
7221 if (!isFirstBoot() && dexOptDialogShown) {
7223 ActivityManagerNative.getDefault().showBootMessage(
7224 mContext.getResources().getString(
7225 R.string.android_upgrading_fstrim), true);
7226 } catch (RemoteException e) {
7229 ms.runMaintenance();
7232 Slog.e(TAG, "Mount service unavailable!");
7234 } catch (RemoteException e) {
7235 // Can't happen; MountService is local
7240 public void updatePackagesIfNeeded() {
7241 enforceSystemOrRoot("Only the system can request package update");
7243 // We need to re-extract after an OTA.
7244 boolean causeUpgrade = isUpgrade();
7246 // First boot or factory reset.
7247 // Note: we also handle devices that are upgrading to N right now as if it is their
7248 // first boot, as they do not have profile data.
7249 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7251 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7252 boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7254 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7258 List<PackageParser.Package> pkgs;
7259 synchronized (mPackages) {
7260 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7263 final long startTime = System.nanoTime();
7264 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7265 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7267 final int elapsedTimeSeconds =
7268 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7270 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7271 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7272 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7273 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7274 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7278 * Performs dexopt on the set of packages in {@code packages} and returns an int array
7279 * containing statistics about the invocation. The array consists of three elements,
7280 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7281 * and {@code numberOfPackagesFailed}.
7283 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7284 String compilerFilter) {
7286 int numberOfPackagesVisited = 0;
7287 int numberOfPackagesOptimized = 0;
7288 int numberOfPackagesSkipped = 0;
7289 int numberOfPackagesFailed = 0;
7290 final int numberOfPackagesToDexopt = pkgs.size();
7292 for (PackageParser.Package pkg : pkgs) {
7293 numberOfPackagesVisited++;
7295 if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7297 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7299 numberOfPackagesSkipped++;
7304 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7305 numberOfPackagesToDexopt + ": " + pkg.packageName);
7310 ActivityManagerNative.getDefault().showBootMessage(
7311 mContext.getResources().getString(R.string.android_upgrading_apk,
7312 numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7313 } catch (RemoteException e) {
7315 synchronized (mPackages) {
7316 mDexOptDialogShown = true;
7320 // If the OTA updates a system app which was previously preopted to a non-preopted state
7321 // the app might end up being verified at runtime. That's because by default the apps
7322 // are verify-profile but for preopted apps there's no profile.
7323 // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7324 // that before the OTA the app was preopted) the app gets compiled with a non-profile
7325 // filter (by default interpret-only).
7326 // Note that at this stage unused apps are already filtered.
7327 if (isSystemApp(pkg) &&
7328 DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7329 !Environment.getReferenceProfile(pkg.packageName).exists()) {
7330 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7333 // checkProfiles is false to avoid merging profiles during boot which
7334 // might interfere with background compilation (b/28612421).
7335 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7336 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7337 // trade-off worth doing to save boot time work.
7338 int dexOptStatus = performDexOptTraced(pkg.packageName,
7339 false /* checkProfiles */,
7342 switch (dexOptStatus) {
7343 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7344 numberOfPackagesOptimized++;
7346 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7347 numberOfPackagesSkipped++;
7349 case PackageDexOptimizer.DEX_OPT_FAILED:
7350 numberOfPackagesFailed++;
7353 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7358 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7359 numberOfPackagesFailed };
7363 public void notifyPackageUse(String packageName, int reason) {
7364 synchronized (mPackages) {
7365 PackageParser.Package p = mPackages.get(packageName);
7369 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7373 // TODO: this is not used nor needed. Delete it.
7375 public boolean performDexOptIfNeeded(String packageName) {
7376 int dexOptStatus = performDexOptTraced(packageName,
7377 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7378 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7382 public boolean performDexOpt(String packageName,
7383 boolean checkProfiles, int compileReason, boolean force) {
7384 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7385 getCompilerFilterForReason(compileReason), force);
7386 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7390 public boolean performDexOptMode(String packageName,
7391 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7392 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7393 targetCompilerFilter, force);
7394 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7397 private int performDexOptTraced(String packageName,
7398 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7399 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7401 return performDexOptInternal(packageName, checkProfiles,
7402 targetCompilerFilter, force);
7404 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7408 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7409 // if the package can now be considered up to date for the given filter.
7410 private int performDexOptInternal(String packageName,
7411 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7412 PackageParser.Package p;
7413 synchronized (mPackages) {
7414 p = mPackages.get(packageName);
7416 // Package could not be found. Report failure.
7417 return PackageDexOptimizer.DEX_OPT_FAILED;
7419 mPackageUsage.maybeWriteAsync(mPackages);
7420 mCompilerStats.maybeWriteAsync();
7422 long callingId = Binder.clearCallingIdentity();
7424 synchronized (mInstallLock) {
7425 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7426 targetCompilerFilter, force);
7429 Binder.restoreCallingIdentity(callingId);
7433 public ArraySet<String> getOptimizablePackages() {
7434 ArraySet<String> pkgs = new ArraySet<String>();
7435 synchronized (mPackages) {
7436 for (PackageParser.Package p : mPackages.values()) {
7437 if (PackageDexOptimizer.canOptimizePackage(p)) {
7438 pkgs.add(p.packageName);
7445 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7446 boolean checkProfiles, String targetCompilerFilter,
7448 // Select the dex optimizer based on the force parameter.
7449 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7450 // allocate an object here.
7451 PackageDexOptimizer pdo = force
7452 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7453 : mPackageDexOptimizer;
7455 // Optimize all dependencies first. Note: we ignore the return value and march on
7457 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7458 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7459 if (!deps.isEmpty()) {
7460 for (PackageParser.Package depPackage : deps) {
7461 // TODO: Analyze and investigate if we (should) profile libraries.
7462 // Currently this will do a full compilation of the library by default.
7463 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7464 false /* checkProfiles */,
7465 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7466 getOrCreateCompilerPackageStats(depPackage));
7469 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7470 targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7473 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7474 if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7475 ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7476 Set<String> collectedNames = new HashSet<>();
7477 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7483 return Collections.emptyList();
7487 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7488 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7489 if (!collectedNames.contains(p.packageName)) {
7490 collectedNames.add(p.packageName);
7493 if (p.usesLibraries != null) {
7494 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7496 if (p.usesOptionalLibraries != null) {
7497 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7503 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7504 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7505 for (String libName : libs) {
7506 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7507 if (libPkg != null) {
7508 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7513 private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7514 synchronized (mPackages) {
7515 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7516 if (lib != null && lib.apk != null) {
7517 return mPackages.get(lib.apk);
7523 public void shutdown() {
7524 mPackageUsage.writeNow(mPackages);
7525 mCompilerStats.writeNow();
7529 public void dumpProfiles(String packageName) {
7530 PackageParser.Package pkg;
7531 synchronized (mPackages) {
7532 pkg = mPackages.get(packageName);
7534 throw new IllegalArgumentException("Unknown package: " + packageName);
7537 /* Only the shell, root, or the app user should be able to dump profiles. */
7538 int callingUid = Binder.getCallingUid();
7539 if (callingUid != Process.SHELL_UID &&
7540 callingUid != Process.ROOT_UID &&
7541 callingUid != pkg.applicationInfo.uid) {
7542 throw new SecurityException("dumpProfiles");
7545 synchronized (mInstallLock) {
7546 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7547 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7549 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7550 String gid = Integer.toString(sharedGid);
7551 String codePaths = TextUtils.join(";", allCodePaths);
7552 mInstaller.dumpProfiles(gid, packageName, codePaths);
7553 } catch (InstallerException e) {
7554 Slog.w(TAG, "Failed to dump profiles", e);
7556 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7561 public void forceDexOpt(String packageName) {
7562 enforceSystemOrRoot("forceDexOpt");
7564 PackageParser.Package pkg;
7565 synchronized (mPackages) {
7566 pkg = mPackages.get(packageName);
7568 throw new IllegalArgumentException("Unknown package: " + packageName);
7572 synchronized (mInstallLock) {
7573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7575 // Whoever is calling forceDexOpt wants a fully compiled package.
7576 // Don't use profiles since that may cause compilation to be skipped.
7577 final int res = performDexOptInternalWithDependenciesLI(pkg,
7578 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7581 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7582 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7583 throw new IllegalStateException("Failed to dexopt: " + res);
7588 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7589 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7590 Slog.w(TAG, "Unable to update from " + oldPkg.name
7591 + " to " + newPkg.packageName
7592 + ": old package not in system partition");
7594 } else if (mPackages.get(oldPkg.name) != null) {
7595 Slog.w(TAG, "Unable to update from " + oldPkg.name
7596 + " to " + newPkg.packageName
7597 + ": old package still exists");
7603 void removeCodePathLI(File codePath) {
7604 if (codePath.isDirectory()) {
7606 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7607 } catch (InstallerException e) {
7608 Slog.w(TAG, "Failed to remove code path", e);
7615 private int[] resolveUserIds(int userId) {
7616 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7619 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7621 Slog.wtf(TAG, "Package was null!", new Throwable());
7624 clearAppDataLeafLIF(pkg, userId, flags);
7625 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7626 for (int i = 0; i < childCount; i++) {
7627 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7631 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7632 final PackageSetting ps;
7633 synchronized (mPackages) {
7634 ps = mSettings.mPackages.get(pkg.packageName);
7636 for (int realUserId : resolveUserIds(userId)) {
7637 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7639 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7641 } catch (InstallerException e) {
7642 Slog.w(TAG, String.valueOf(e));
7647 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7649 Slog.wtf(TAG, "Package was null!", new Throwable());
7652 destroyAppDataLeafLIF(pkg, userId, flags);
7653 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7654 for (int i = 0; i < childCount; i++) {
7655 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7659 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7660 final PackageSetting ps;
7661 synchronized (mPackages) {
7662 ps = mSettings.mPackages.get(pkg.packageName);
7664 for (int realUserId : resolveUserIds(userId)) {
7665 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7667 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7669 } catch (InstallerException e) {
7670 Slog.w(TAG, String.valueOf(e));
7675 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7677 Slog.wtf(TAG, "Package was null!", new Throwable());
7680 destroyAppProfilesLeafLIF(pkg);
7681 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7682 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7683 for (int i = 0; i < childCount; i++) {
7684 destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7685 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7686 true /* removeBaseMarker */);
7690 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7691 boolean removeBaseMarker) {
7692 if (pkg.isForwardLocked()) {
7696 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7698 path = PackageManagerServiceUtils.realpath(new File(path));
7699 } catch (IOException e) {
7700 // TODO: Should we return early here ?
7701 Slog.w(TAG, "Failed to get canonical path", e);
7705 final String useMarker = path.replace('/', '@');
7706 for (int realUserId : resolveUserIds(userId)) {
7707 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7708 if (removeBaseMarker) {
7709 File foreignUseMark = new File(profileDir, useMarker);
7710 if (foreignUseMark.exists()) {
7711 if (!foreignUseMark.delete()) {
7712 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7718 File[] markers = profileDir.listFiles();
7719 if (markers != null) {
7720 final String searchString = "@" + pkg.packageName + "@";
7721 // We also delete all markers that contain the package name we're
7722 // uninstalling. These are associated with secondary dex-files belonging
7723 // to the package. Reconstructing the path of these dex files is messy
7725 for (File marker : markers) {
7726 if (marker.getName().indexOf(searchString) > 0) {
7727 if (!marker.delete()) {
7728 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7738 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7740 mInstaller.destroyAppProfiles(pkg.packageName);
7741 } catch (InstallerException e) {
7742 Slog.w(TAG, String.valueOf(e));
7746 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7748 Slog.wtf(TAG, "Package was null!", new Throwable());
7751 clearAppProfilesLeafLIF(pkg);
7752 // We don't remove the base foreign use marker when clearing profiles because
7753 // we will rename it when the app is updated. Unlike the actual profile contents,
7754 // the foreign use marker is good across installs.
7755 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7756 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7757 for (int i = 0; i < childCount; i++) {
7758 clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7762 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7764 mInstaller.clearAppProfiles(pkg.packageName);
7765 } catch (InstallerException e) {
7766 Slog.w(TAG, String.valueOf(e));
7770 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7771 long lastUpdateTime) {
7772 // Set parent install/update time
7773 PackageSetting ps = (PackageSetting) pkg.mExtras;
7775 ps.firstInstallTime = firstInstallTime;
7776 ps.lastUpdateTime = lastUpdateTime;
7778 // Set children install/update time
7779 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7780 for (int i = 0; i < childCount; i++) {
7781 PackageParser.Package childPkg = pkg.childPackages.get(i);
7782 ps = (PackageSetting) childPkg.mExtras;
7784 ps.firstInstallTime = firstInstallTime;
7785 ps.lastUpdateTime = lastUpdateTime;
7790 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7791 PackageParser.Package changingLib) {
7792 if (file.path != null) {
7793 usesLibraryFiles.add(file.path);
7796 PackageParser.Package p = mPackages.get(file.apk);
7797 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7798 // If we are doing this while in the middle of updating a library apk,
7799 // then we need to make sure to use that new apk for determining the
7800 // dependencies here. (We haven't yet finished committing the new apk
7801 // to the package manager state.)
7802 if (p == null || p.packageName.equals(changingLib.packageName)) {
7807 usesLibraryFiles.addAll(p.getAllCodePaths());
7811 private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7812 PackageParser.Package changingLib) throws PackageManagerException {
7813 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7814 final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7815 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7816 for (int i=0; i<N; i++) {
7817 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7819 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7820 "Package " + pkg.packageName + " requires unavailable shared library "
7821 + pkg.usesLibraries.get(i) + "; failing!");
7823 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7825 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7826 for (int i=0; i<N; i++) {
7827 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7829 Slog.w(TAG, "Package " + pkg.packageName
7830 + " desires unavailable shared library "
7831 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7833 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7836 N = usesLibraryFiles.size();
7838 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7840 pkg.usesLibraryFiles = null;
7845 private static boolean hasString(List<String> list, List<String> which) {
7849 for (int i=list.size()-1; i>=0; i--) {
7850 for (int j=which.size()-1; j>=0; j--) {
7851 if (which.get(j).equals(list.get(i))) {
7859 private void updateAllSharedLibrariesLPw() {
7860 for (PackageParser.Package pkg : mPackages.values()) {
7862 updateSharedLibrariesLPw(pkg, null);
7863 } catch (PackageManagerException e) {
7864 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7869 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7870 PackageParser.Package changingPkg) {
7871 ArrayList<PackageParser.Package> res = null;
7872 for (PackageParser.Package pkg : mPackages.values()) {
7873 if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7874 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7876 res = new ArrayList<PackageParser.Package>();
7880 updateSharedLibrariesLPw(pkg, changingPkg);
7881 } catch (PackageManagerException e) {
7882 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7890 * Derive the value of the {@code cpuAbiOverride} based on the provided
7891 * value and an optional stored value from the package settings.
7893 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7894 String cpuAbiOverride = null;
7896 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7897 cpuAbiOverride = null;
7898 } else if (abiOverride != null) {
7899 cpuAbiOverride = abiOverride;
7900 } else if (settings != null) {
7901 cpuAbiOverride = settings.cpuAbiOverrideString;
7904 return cpuAbiOverride;
7907 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7908 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7909 throws PackageManagerException {
7910 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7911 // If the package has children and this is the first dive in the function
7912 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7913 // whether all packages (parent and children) would be successfully scanned
7914 // before the actual scan since scanning mutates internal state and we want
7915 // to atomically install the package and its children.
7916 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7917 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7918 scanFlags |= SCAN_CHECK_ONLY;
7921 scanFlags &= ~SCAN_CHECK_ONLY;
7924 final PackageParser.Package scannedPkg;
7927 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7928 // Scan the children
7929 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7930 for (int i = 0; i < childCount; i++) {
7931 PackageParser.Package childPkg = pkg.childPackages.get(i);
7932 scanPackageLI(childPkg, policyFlags,
7933 scanFlags, currentTime, user);
7936 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7939 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7940 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7946 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7947 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7948 boolean success = false;
7950 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7955 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7956 // DELETE_DATA_ON_FAILURES is only used by frozen paths
7957 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7958 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7959 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7965 * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7967 private static boolean apkHasCode(String fileName) {
7968 StrictJarFile jarFile = null;
7970 jarFile = new StrictJarFile(fileName,
7971 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7972 return jarFile.findEntry("classes.dex") != null;
7973 } catch (IOException ignore) {
7976 if (jarFile != null) {
7979 } catch (IOException ignore) {}
7985 * Enforces code policy for the package. This ensures that if an APK has
7986 * declared hasCode="true" in its manifest that the APK actually contains
7989 * @throws PackageManagerException If bytecode could not be found when it should exist
7991 private static void enforceCodePolicy(PackageParser.Package pkg)
7992 throws PackageManagerException {
7993 final boolean shouldHaveCode =
7994 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7995 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7996 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7997 "Package " + pkg.baseCodePath + " code is missing");
8000 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8001 for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8002 final boolean splitShouldHaveCode =
8003 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8004 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8005 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8006 "Package " + pkg.splitCodePaths[i] + " code is missing");
8012 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8013 final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8014 throws PackageManagerException {
8015 final File scanFile = new File(pkg.codePath);
8016 if (pkg.applicationInfo.getCodePath() == null ||
8017 pkg.applicationInfo.getResourcePath() == null) {
8018 // Bail out. The resource and code paths haven't been set.
8019 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8020 "Code and resource paths haven't been set correctly");
8024 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8025 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8026 if (pkg.applicationInfo.isDirectBootAware()) {
8027 // we're direct boot aware; set for all components
8028 for (PackageParser.Service s : pkg.services) {
8029 s.info.encryptionAware = s.info.directBootAware = true;
8031 for (PackageParser.Provider p : pkg.providers) {
8032 p.info.encryptionAware = p.info.directBootAware = true;
8034 for (PackageParser.Activity a : pkg.activities) {
8035 a.info.encryptionAware = a.info.directBootAware = true;
8037 for (PackageParser.Activity r : pkg.receivers) {
8038 r.info.encryptionAware = r.info.directBootAware = true;
8042 // Only allow system apps to be flagged as core apps.
8043 pkg.coreApp = false;
8044 // clear flags not applicable to regular apps
8045 pkg.applicationInfo.privateFlags &=
8046 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8047 pkg.applicationInfo.privateFlags &=
8048 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8050 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8052 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8053 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8056 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8057 enforceCodePolicy(pkg);
8060 if (mCustomResolverComponentName != null &&
8061 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8062 setUpCustomResolverActivity(pkg);
8065 if (pkg.packageName.equals("android")) {
8066 synchronized (mPackages) {
8067 if (mAndroidApplication != null) {
8068 Slog.w(TAG, "*************************************************");
8069 Slog.w(TAG, "Core android package being redefined. Skipping.");
8070 Slog.w(TAG, " file=" + scanFile);
8071 Slog.w(TAG, "*************************************************");
8072 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8073 "Core android package being redefined. Skipping.");
8076 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8077 // Set up information for our fall-back user intent resolution activity.
8078 mPlatformPackage = pkg;
8079 pkg.mVersionCode = mSdkVersion;
8080 mAndroidApplication = pkg.applicationInfo;
8082 if (!mResolverReplaced) {
8083 mResolveActivity.applicationInfo = mAndroidApplication;
8084 mResolveActivity.name = ResolverActivity.class.getName();
8085 mResolveActivity.packageName = mAndroidApplication.packageName;
8086 mResolveActivity.processName = "system:ui";
8087 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8088 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8089 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8090 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8091 mResolveActivity.exported = true;
8092 mResolveActivity.enabled = true;
8093 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8094 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8095 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8096 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8097 | ActivityInfo.CONFIG_ORIENTATION
8098 | ActivityInfo.CONFIG_KEYBOARD
8099 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8100 mResolveInfo.activityInfo = mResolveActivity;
8101 mResolveInfo.priority = 0;
8102 mResolveInfo.preferredOrder = 0;
8103 mResolveInfo.match = 0;
8104 mResolveComponentName = new ComponentName(
8105 mAndroidApplication.packageName, mResolveActivity.name);
8111 if (DEBUG_PACKAGE_SCANNING) {
8112 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8113 Log.d(TAG, "Scanning package " + pkg.packageName);
8116 synchronized (mPackages) {
8117 if (mPackages.containsKey(pkg.packageName)
8118 || mSharedLibraries.containsKey(pkg.packageName)) {
8119 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8120 "Application package " + pkg.packageName
8121 + " already installed. Skipping duplicate.");
8124 // If we're only installing presumed-existing packages, require that the
8125 // scanned APK is both already known and at the path previously established
8126 // for it. Previously unknown packages we pick up normally, but if we have an
8127 // a priori expectation about this package's install presence, enforce it.
8128 // With a singular exception for new system packages. When an OTA contains
8129 // a new system package, we allow the codepath to change from a system location
8130 // to the user-installed location. If we don't allow this change, any newer,
8131 // user-installed version of the application will be ignored.
8132 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8133 if (mExpectingBetter.containsKey(pkg.packageName)) {
8134 logCriticalInfo(Log.WARN,
8135 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8137 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8138 if (known != null) {
8139 if (DEBUG_PACKAGE_SCANNING) {
8140 Log.d(TAG, "Examining " + pkg.codePath
8141 + " and requiring known paths " + known.codePathString
8142 + " & " + known.resourcePathString);
8144 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8145 || !pkg.applicationInfo.getResourcePath().equals(
8146 known.resourcePathString)) {
8147 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8148 "Application package " + pkg.packageName
8149 + " found at " + pkg.applicationInfo.getCodePath()
8150 + " but expected at " + known.codePathString
8158 // Initialize package source and resource directories
8159 File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8160 File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8162 SharedUserSetting suid = null;
8163 PackageSetting pkgSetting = null;
8165 if (!isSystemApp(pkg)) {
8166 // Only system apps can use these features.
8167 pkg.mOriginalPackages = null;
8168 pkg.mRealPackage = null;
8169 pkg.mAdoptPermissions = null;
8172 // Getting the package setting may have a side-effect, so if we
8173 // are only checking if scan would succeed, stash a copy of the
8174 // old setting to restore at the end.
8175 PackageSetting nonMutatedPs = null;
8178 synchronized (mPackages) {
8179 if (pkg.mSharedUserId != null) {
8180 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8182 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8183 "Creating application package " + pkg.packageName
8184 + " for shared user failed");
8186 if (DEBUG_PACKAGE_SCANNING) {
8187 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8188 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8189 + "): packages=" + suid.packages);
8193 // Check if we are renaming from an original package name.
8194 PackageSetting origPackage = null;
8195 String realName = null;
8196 if (pkg.mOriginalPackages != null) {
8197 // This package may need to be renamed to a previously
8198 // installed name. Let's check on that...
8199 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8200 if (pkg.mOriginalPackages.contains(renamed)) {
8201 // This package had originally been installed as the
8202 // original name, and we have already taken care of
8203 // transitioning to the new one. Just update the new
8204 // one to continue using the old name.
8205 realName = pkg.mRealPackage;
8206 if (!pkg.packageName.equals(renamed)) {
8207 // Callers into this function may have already taken
8208 // care of renaming the package; only do it here if
8209 // it is not already done.
8210 pkg.setPackageName(renamed);
8214 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8215 if ((origPackage = mSettings.peekPackageLPr(
8216 pkg.mOriginalPackages.get(i))) != null) {
8217 // We do have the package already installed under its
8218 // original name... should we use it?
8219 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8220 // New package is not compatible with original.
8223 } else if (origPackage.sharedUser != null) {
8224 // Make sure uid is compatible between packages.
8225 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8226 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8227 + " to " + pkg.packageName + ": old uid "
8228 + origPackage.sharedUser.name
8229 + " differs from " + pkg.mSharedUserId);
8233 // TODO: Add case when shared user id is added [b/28144775]
8235 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8236 + pkg.packageName + " to old name " + origPackage.name);
8244 if (mTransferedPackages.contains(pkg.packageName)) {
8245 Slog.w(TAG, "Package " + pkg.packageName
8246 + " was transferred to another, but its .apk remains");
8249 // See comments in nonMutatedPs declaration
8250 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8251 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8252 if (foundPs != null) {
8253 nonMutatedPs = new PackageSetting(foundPs);
8257 // Just create the setting, don't add it yet. For already existing packages
8258 // the PkgSetting exists already and doesn't have to be created.
8259 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8260 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8261 pkg.applicationInfo.primaryCpuAbi,
8262 pkg.applicationInfo.secondaryCpuAbi,
8263 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8265 if (pkgSetting == null) {
8266 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8267 "Creating application package " + pkg.packageName + " failed");
8270 if (pkgSetting.origPackage != null) {
8271 // If we are first transitioning from an original package,
8272 // fix up the new package's name now. We need to do this after
8273 // looking up the package under its new name, so getPackageLP
8274 // can take care of fiddling things correctly.
8275 pkg.setPackageName(origPackage.name);
8277 // File a report about this.
8278 String msg = "New package " + pkgSetting.realName
8279 + " renamed to replace old package " + pkgSetting.name;
8280 reportSettingsProblem(Log.WARN, msg);
8282 // Make a note of it.
8283 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8284 mTransferedPackages.add(origPackage.name);
8287 // No longer need to retain this.
8288 pkgSetting.origPackage = null;
8291 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8292 // Make a note of it.
8293 mTransferedPackages.add(pkg.packageName);
8296 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8297 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8300 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8301 // Check all shared libraries and map to their actual file path.
8302 // We only do this here for apps not on a system dir, because those
8303 // are the only ones that can fail an install due to this. We
8304 // will take care of the system apps by updating all of their
8305 // library paths after the scan is done.
8306 updateSharedLibrariesLPw(pkg, null);
8309 if (mFoundPolicyFile) {
8310 SELinuxMMAC.assignSeinfoValue(pkg);
8313 pkg.applicationInfo.uid = pkgSetting.appId;
8314 pkg.mExtras = pkgSetting;
8315 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8316 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8317 // We just determined the app is signed correctly, so bring
8318 // over the latest parsed certs.
8319 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8321 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8322 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8323 "Package " + pkg.packageName + " upgrade keys do not match the "
8324 + "previously installed version");
8326 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8327 String msg = "System package " + pkg.packageName
8328 + " signature changed; retaining data.";
8329 reportSettingsProblem(Log.WARN, msg);
8334 verifySignaturesLP(pkgSetting, pkg);
8335 // We just determined the app is signed correctly, so bring
8336 // over the latest parsed certs.
8337 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8338 } catch (PackageManagerException e) {
8339 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8342 // The signature has changed, but this package is in the system
8343 // image... let's recover!
8344 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8345 // However... if this package is part of a shared user, but it
8346 // doesn't match the signature of the shared user, let's fail.
8347 // What this means is that you can't change the signatures
8348 // associated with an overall shared user, which doesn't seem all
8349 // that unreasonable.
8350 if (pkgSetting.sharedUser != null) {
8351 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8352 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8353 throw new PackageManagerException(
8354 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8355 "Signature mismatch for shared user: "
8356 + pkgSetting.sharedUser);
8359 // File a report about this.
8360 String msg = "System package " + pkg.packageName
8361 + " signature changed; retaining data.";
8362 reportSettingsProblem(Log.WARN, msg);
8365 // Verify that this new package doesn't have any content providers
8366 // that conflict with existing packages. Only do this if the
8367 // package isn't already installed, since we don't want to break
8368 // things that are installed.
8369 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8370 final int N = pkg.providers.size();
8372 for (i=0; i<N; i++) {
8373 PackageParser.Provider p = pkg.providers.get(i);
8374 if (p.info.authority != null) {
8375 String names[] = p.info.authority.split(";");
8376 for (int j = 0; j < names.length; j++) {
8377 if (mProvidersByAuthority.containsKey(names[j])) {
8378 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8379 final String otherPackageName =
8380 ((other != null && other.getComponentName() != null) ?
8381 other.getComponentName().getPackageName() : "?");
8382 throw new PackageManagerException(
8383 INSTALL_FAILED_CONFLICTING_PROVIDER,
8384 "Can't install because provider name " + names[j]
8385 + " (in package " + pkg.applicationInfo.packageName
8386 + ") is already used by " + otherPackageName);
8393 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8394 // This package wants to adopt ownership of permissions from
8396 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8397 final String origName = pkg.mAdoptPermissions.get(i);
8398 final PackageSetting orig = mSettings.peekPackageLPr(origName);
8400 if (verifyPackageUpdateLPr(orig, pkg)) {
8401 Slog.i(TAG, "Adopting permissions from " + origName + " to "
8403 mSettings.transferPermissionsLPw(origName, pkg.packageName);
8410 final String pkgName = pkg.packageName;
8412 final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8413 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8414 pkg.applicationInfo.processName = fixProcessName(
8415 pkg.applicationInfo.packageName,
8416 pkg.applicationInfo.processName,
8417 pkg.applicationInfo.uid);
8419 if (pkg != mPlatformPackage) {
8420 // Get all of our default paths setup
8421 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8424 final String path = scanFile.getPath();
8425 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8427 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8428 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8430 // Some system apps still use directory structure for native libraries
8431 // in which case we might end up not detecting abi solely based on apk
8432 // structure. Try to detect abi based on directory structure.
8433 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8434 pkg.applicationInfo.primaryCpuAbi == null) {
8435 setBundledAppAbisAndRoots(pkg, pkgSetting);
8436 setNativeLibraryPaths(pkg);
8440 if ((scanFlags & SCAN_MOVE) != 0) {
8441 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8442 // but we already have this packages package info in the PackageSetting. We just
8443 // use that and derive the native library path based on the new codepath.
8444 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8445 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8448 // Set native library paths again. For moves, the path will be updated based on the
8449 // ABIs we've determined above. For non-moves, the path will be updated based on the
8450 // ABIs we determined during compilation, but the path will depend on the final
8451 // package path (after the rename away from the stage path).
8452 setNativeLibraryPaths(pkg);
8455 // This is a special case for the "system" package, where the ABI is
8456 // dictated by the zygote configuration (and init.rc). We should keep track
8457 // of this ABI so that we can deal with "normal" applications that run under
8458 // the same UID correctly.
8459 if (mPlatformPackage == pkg) {
8460 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8461 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8464 // If there's a mismatch between the abi-override in the package setting
8465 // and the abiOverride specified for the install. Warn about this because we
8466 // would've already compiled the app without taking the package setting into
8468 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8469 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8470 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8471 " for package " + pkg.packageName);
8475 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8476 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8477 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8479 // Copy the derived override back to the parsed package, so that we can
8480 // update the package settings accordingly.
8481 pkg.cpuAbiOverride = cpuAbiOverride;
8483 if (DEBUG_ABI_SELECTION) {
8484 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8485 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8486 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8489 // Push the derived path down into PackageSettings so we know what to
8490 // clean up at uninstall time.
8491 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8493 if (DEBUG_ABI_SELECTION) {
8494 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8495 " primary=" + pkg.applicationInfo.primaryCpuAbi +
8496 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8499 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8500 // We don't do this here during boot because we can do it all
8501 // at once after scanning all existing packages.
8503 // We also do this *before* we perform dexopt on this package, so that
8504 // we can avoid redundant dexopts, and also to make sure we've got the
8505 // code and package path correct.
8506 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8507 pkg, true /* boot complete */);
8510 if (mFactoryTest && pkg.requestedPermissions.contains(
8511 android.Manifest.permission.FACTORY_TEST)) {
8512 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8515 if (isSystemApp(pkg)) {
8516 pkgSetting.isOrphaned = true;
8519 ArrayList<PackageParser.Package> clientLibPkgs = null;
8521 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8522 if (nonMutatedPs != null) {
8523 synchronized (mPackages) {
8524 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8530 // Only privileged apps and updated privileged apps can add child packages.
8531 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8532 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8533 throw new PackageManagerException("Only privileged apps and updated "
8534 + "privileged apps can add child packages. Ignoring package "
8537 final int childCount = pkg.childPackages.size();
8538 for (int i = 0; i < childCount; i++) {
8539 PackageParser.Package childPkg = pkg.childPackages.get(i);
8540 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8541 childPkg.packageName)) {
8542 throw new PackageManagerException("Cannot override a child package of "
8543 + "another disabled system app. Ignoring package " + pkg.packageName);
8549 synchronized (mPackages) {
8550 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8551 // Only system apps can add new shared libraries.
8552 if (pkg.libraryNames != null) {
8553 for (int i=0; i<pkg.libraryNames.size(); i++) {
8554 String name = pkg.libraryNames.get(i);
8555 boolean allowed = false;
8556 if (pkg.isUpdatedSystemApp()) {
8557 // New library entries can only be added through the
8558 // system image. This is important to get rid of a lot
8559 // of nasty edge cases: for example if we allowed a non-
8560 // system update of the app to add a library, then uninstalling
8561 // the update would make the library go away, and assumptions
8562 // we made such as through app install filtering would now
8563 // have allowed apps on the device which aren't compatible
8564 // with it. Better to just have the restriction here, be
8565 // conservative, and create many fewer cases that can negatively
8566 // impact the user experience.
8567 final PackageSetting sysPs = mSettings
8568 .getDisabledSystemPkgLPr(pkg.packageName);
8569 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8570 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8571 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8581 if (!mSharedLibraries.containsKey(name)) {
8582 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8583 } else if (!name.equals(pkg.packageName)) {
8584 Slog.w(TAG, "Package " + pkg.packageName + " library "
8585 + name + " already exists; skipping");
8588 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8589 + name + " that is not declared on system image; skipping");
8592 if ((scanFlags & SCAN_BOOTING) == 0) {
8593 // If we are not booting, we need to update any applications
8594 // that are clients of our shared library. If we are booting,
8595 // this will all be done once the scan is complete.
8596 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8602 if ((scanFlags & SCAN_BOOTING) != 0) {
8603 // No apps can run during boot scan, so they don't need to be frozen
8604 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8605 // Caller asked to not kill app, so it's probably not frozen
8606 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8607 // Caller asked us to ignore frozen check for some reason; they
8608 // probably didn't know the package name
8610 // We're doing major surgery on this package, so it better be frozen
8611 // right now to keep it from launching
8612 checkPackageFrozen(pkgName);
8615 // Also need to kill any apps that are dependent on the library.
8616 if (clientLibPkgs != null) {
8617 for (int i=0; i<clientLibPkgs.size(); i++) {
8618 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8619 killApplication(clientPkg.applicationInfo.packageName,
8620 clientPkg.applicationInfo.uid, "update lib");
8624 // Make sure we're not adding any bogus keyset info
8625 KeySetManagerService ksms = mSettings.mKeySetManagerService;
8626 ksms.assertScannedPackageValid(pkg);
8629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8631 boolean createIdmapFailed = false;
8632 synchronized (mPackages) {
8633 // We don't expect installation to fail beyond this point
8635 if (pkgSetting.pkg != null) {
8636 // Note that |user| might be null during the initial boot scan. If a codePath
8637 // for an app has changed during a boot scan, it's due to an app update that's
8638 // part of the system partition and marker changes must be applied to all users.
8639 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8640 (user != null) ? user : UserHandle.ALL);
8643 // Add the new setting to mSettings
8644 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8645 // Add the new setting to mPackages
8646 mPackages.put(pkg.applicationInfo.packageName, pkg);
8647 // Make sure we don't accidentally delete its data.
8648 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8649 while (iter.hasNext()) {
8650 PackageCleanItem item = iter.next();
8651 if (pkgName.equals(item.packageName)) {
8656 // Take care of first install / last update times.
8657 if (currentTime != 0) {
8658 if (pkgSetting.firstInstallTime == 0) {
8659 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8660 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8661 pkgSetting.lastUpdateTime = currentTime;
8663 } else if (pkgSetting.firstInstallTime == 0) {
8664 // We need *something*. Take time time stamp of the file.
8665 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8666 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8667 if (scanFileTime != pkgSetting.timeStamp) {
8668 // A package on the system image has changed; consider this
8670 pkgSetting.lastUpdateTime = scanFileTime;
8674 // Add the package's KeySets to the global KeySetManagerService
8675 ksms.addScannedPackageLPw(pkg);
8677 int N = pkg.providers.size();
8678 StringBuilder r = null;
8680 for (i=0; i<N; i++) {
8681 PackageParser.Provider p = pkg.providers.get(i);
8682 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8683 p.info.processName, pkg.applicationInfo.uid);
8684 mProviders.addProvider(p);
8685 p.syncable = p.info.isSyncable;
8686 if (p.info.authority != null) {
8687 String names[] = p.info.authority.split(";");
8688 p.info.authority = null;
8689 for (int j = 0; j < names.length; j++) {
8690 if (j == 1 && p.syncable) {
8691 // We only want the first authority for a provider to possibly be
8692 // syncable, so if we already added this provider using a different
8693 // authority clear the syncable flag. We copy the provider before
8694 // changing it because the mProviders object contains a reference
8695 // to a provider that we don't want to change.
8696 // Only do this for the second authority since the resulting provider
8697 // object can be the same for all future authorities for this provider.
8698 p = new PackageParser.Provider(p);
8701 if (!mProvidersByAuthority.containsKey(names[j])) {
8702 mProvidersByAuthority.put(names[j], p);
8703 if (p.info.authority == null) {
8704 p.info.authority = names[j];
8706 p.info.authority = p.info.authority + ";" + names[j];
8708 if (DEBUG_PACKAGE_SCANNING) {
8709 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8710 Log.d(TAG, "Registered content provider: " + names[j]
8711 + ", className = " + p.info.name + ", isSyncable = "
8712 + p.info.isSyncable);
8715 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8716 Slog.w(TAG, "Skipping provider name " + names[j] +
8717 " (in package " + pkg.applicationInfo.packageName +
8718 "): name already used by "
8719 + ((other != null && other.getComponentName() != null)
8720 ? other.getComponentName().getPackageName() : "?"));
8724 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8726 r = new StringBuilder(256);
8730 r.append(p.info.name);
8734 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
8737 N = pkg.services.size();
8739 for (i=0; i<N; i++) {
8740 PackageParser.Service s = pkg.services.get(i);
8741 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8742 s.info.processName, pkg.applicationInfo.uid);
8743 mServices.addService(s);
8744 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8746 r = new StringBuilder(256);
8750 r.append(s.info.name);
8754 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
8757 N = pkg.receivers.size();
8759 for (i=0; i<N; i++) {
8760 PackageParser.Activity a = pkg.receivers.get(i);
8761 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8762 a.info.processName, pkg.applicationInfo.uid);
8763 mReceivers.addActivity(a, "receiver");
8764 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8766 r = new StringBuilder(256);
8770 r.append(a.info.name);
8774 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
8777 N = pkg.activities.size();
8779 for (i=0; i<N; i++) {
8780 PackageParser.Activity a = pkg.activities.get(i);
8781 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8782 a.info.processName, pkg.applicationInfo.uid);
8783 mActivities.addActivity(a, "activity");
8784 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8786 r = new StringBuilder(256);
8790 r.append(a.info.name);
8794 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
8797 N = pkg.permissionGroups.size();
8799 for (i=0; i<N; i++) {
8800 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8801 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8802 final String curPackageName = cur == null ? null : cur.info.packageName;
8803 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8804 if (cur == null || isPackageUpdate) {
8805 mPermissionGroups.put(pg.info.name, pg);
8806 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8808 r = new StringBuilder(256);
8812 if (isPackageUpdate) {
8815 r.append(pg.info.name);
8818 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8819 + pg.info.packageName + " ignored: original from "
8820 + cur.info.packageName);
8821 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8823 r = new StringBuilder(256);
8828 r.append(pg.info.name);
8833 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
8836 N = pkg.permissions.size();
8838 for (i=0; i<N; i++) {
8839 PackageParser.Permission p = pkg.permissions.get(i);
8841 // Assume by default that we did not install this permission into the system.
8842 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8844 // Now that permission groups have a special meaning, we ignore permission
8845 // groups for legacy apps to prevent unexpected behavior. In particular,
8846 // permissions for one app being granted to someone just becase they happen
8847 // to be in a group defined by another app (before this had no implications).
8848 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8849 p.group = mPermissionGroups.get(p.info.group);
8850 // Warn for a permission in an unknown group.
8851 if (p.info.group != null && p.group == null) {
8852 Slog.w(TAG, "Permission " + p.info.name + " from package "
8853 + p.info.packageName + " in an unknown group " + p.info.group);
8857 ArrayMap<String, BasePermission> permissionMap =
8858 p.tree ? mSettings.mPermissionTrees
8859 : mSettings.mPermissions;
8860 BasePermission bp = permissionMap.get(p.info.name);
8862 // Allow system apps to redefine non-system permissions
8863 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8864 final boolean currentOwnerIsSystem = (bp.perm != null
8865 && isSystemApp(bp.perm.owner));
8866 if (isSystemApp(p.owner)) {
8867 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8868 // It's a built-in permission and no owner, take ownership now
8869 bp.packageSetting = pkgSetting;
8871 bp.uid = pkg.applicationInfo.uid;
8872 bp.sourcePackage = p.info.packageName;
8873 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8874 } else if (!currentOwnerIsSystem) {
8875 String msg = "New decl " + p.owner + " of permission "
8876 + p.info.name + " is system; overriding " + bp.sourcePackage;
8877 reportSettingsProblem(Log.WARN, msg);
8884 bp = new BasePermission(p.info.name, p.info.packageName,
8885 BasePermission.TYPE_NORMAL);
8886 permissionMap.put(p.info.name, bp);
8889 if (bp.perm == null) {
8890 if (bp.sourcePackage == null
8891 || bp.sourcePackage.equals(p.info.packageName)) {
8892 BasePermission tree = findPermissionTreeLP(p.info.name);
8894 || tree.sourcePackage.equals(p.info.packageName)) {
8895 bp.packageSetting = pkgSetting;
8897 bp.uid = pkg.applicationInfo.uid;
8898 bp.sourcePackage = p.info.packageName;
8899 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8900 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8902 r = new StringBuilder(256);
8906 r.append(p.info.name);
8909 Slog.w(TAG, "Permission " + p.info.name + " from package "
8910 + p.info.packageName + " ignored: base tree "
8911 + tree.name + " is from package "
8912 + tree.sourcePackage);
8915 Slog.w(TAG, "Permission " + p.info.name + " from package "
8916 + p.info.packageName + " ignored: original from "
8917 + bp.sourcePackage);
8919 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8921 r = new StringBuilder(256);
8926 r.append(p.info.name);
8929 bp.protectionLevel = p.info.protectionLevel;
8934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
8937 N = pkg.instrumentation.size();
8939 for (i=0; i<N; i++) {
8940 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8941 a.info.packageName = pkg.applicationInfo.packageName;
8942 a.info.sourceDir = pkg.applicationInfo.sourceDir;
8943 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8944 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8945 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8946 a.info.dataDir = pkg.applicationInfo.dataDir;
8947 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8948 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8950 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8951 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8952 mInstrumentation.put(a.getComponentName(), a);
8953 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8955 r = new StringBuilder(256);
8959 r.append(a.info.name);
8963 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
8966 if (pkg.protectedBroadcasts != null) {
8967 N = pkg.protectedBroadcasts.size();
8968 for (i=0; i<N; i++) {
8969 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8973 pkgSetting.setTimeStamp(scanFileTime);
8975 // Create idmap files for pairs of (packages, overlay packages).
8976 // Note: "android", ie framework-res.apk, is handled by native layers.
8977 if (pkg.mOverlayTarget != null) {
8978 // This is an overlay package.
8979 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8980 if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8981 mOverlays.put(pkg.mOverlayTarget,
8982 new ArrayMap<String, PackageParser.Package>());
8984 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8985 map.put(pkg.packageName, pkg);
8986 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8987 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8988 createIdmapFailed = true;
8991 } else if (mOverlays.containsKey(pkg.packageName) &&
8992 !pkg.packageName.equals("android")) {
8993 // This is a regular package, with one or more known overlay packages.
8994 createIdmapsForPackageLI(pkg);
8998 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9000 if (createIdmapFailed) {
9001 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9002 "scanPackageLI failed to createIdmap");
9007 private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9008 PackageParser.Package update, UserHandle user) {
9009 if (existing.applicationInfo == null || update.applicationInfo == null) {
9010 // This isn't due to an app installation.
9014 final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9015 final File newCodePath = new File(update.applicationInfo.getCodePath());
9017 // The codePath hasn't changed, so there's nothing for us to do.
9018 if (Objects.equals(oldCodePath, newCodePath)) {
9022 File canonicalNewCodePath;
9024 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9025 } catch (IOException e) {
9026 Slog.w(TAG, "Failed to get canonical path.", e);
9030 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9031 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9032 // that the last component of the path (i.e, the name) doesn't need canonicalization
9033 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9034 // but may change in the future. Hopefully this function won't exist at that point.
9035 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9036 oldCodePath.getName());
9038 // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9040 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9041 if (!oldMarkerPrefix.endsWith("@")) {
9042 oldMarkerPrefix += "@";
9044 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9045 if (!newMarkerPrefix.endsWith("@")) {
9046 newMarkerPrefix += "@";
9049 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9050 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9051 for (String updatedPath : updatedPaths) {
9052 String updatedPathName = new File(updatedPath).getName();
9053 markerSuffixes.add(updatedPathName.replace('/', '@'));
9056 for (int userId : resolveUserIds(user.getIdentifier())) {
9057 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9059 for (String markerSuffix : markerSuffixes) {
9060 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9061 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9062 if (oldForeignUseMark.exists()) {
9064 Os.rename(oldForeignUseMark.getAbsolutePath(),
9065 newForeignUseMark.getAbsolutePath());
9066 } catch (ErrnoException e) {
9067 Slog.w(TAG, "Failed to rename foreign use marker", e);
9068 oldForeignUseMark.delete();
9076 * Derive the ABI of a non-system package located at {@code scanFile}. This information
9077 * is derived purely on the basis of the contents of {@code scanFile} and
9078 * {@code cpuAbiOverride}.
9080 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9082 private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9083 String cpuAbiOverride, boolean extractLibs)
9084 throws PackageManagerException {
9085 // TODO: We can probably be smarter about this stuff. For installed apps,
9086 // we can calculate this information at install time once and for all. For
9087 // system apps, we can probably assume that this information doesn't change
9088 // after the first boot scan. As things stand, we do lots of unnecessary work.
9090 // Give ourselves some initial paths; we'll come back for another
9091 // pass once we've determined ABI below.
9092 setNativeLibraryPaths(pkg);
9094 // We would never need to extract libs for forward-locked and external packages,
9095 // since the container service will do it for us. We shouldn't attempt to
9096 // extract libs from system app when it was not updated.
9097 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9098 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9099 extractLibs = false;
9102 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9103 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9105 NativeLibraryHelper.Handle handle = null;
9107 handle = NativeLibraryHelper.Handle.create(pkg);
9108 // TODO(multiArch): This can be null for apps that didn't go through the
9109 // usual installation process. We can calculate it again, like we
9110 // do during install time.
9112 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9114 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9116 // Null out the abis so that they can be recalculated.
9117 pkg.applicationInfo.primaryCpuAbi = null;
9118 pkg.applicationInfo.secondaryCpuAbi = null;
9119 if (isMultiArch(pkg.applicationInfo)) {
9120 // Warn if we've set an abiOverride for multi-lib packages..
9121 // By definition, we need to copy both 32 and 64 bit libraries for
9123 if (pkg.cpuAbiOverride != null
9124 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9125 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9128 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9129 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9130 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9132 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9133 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9134 useIsaSpecificSubdirs);
9136 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9140 maybeThrowExceptionForMultiArchCopy(
9141 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9143 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9145 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9146 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9147 useIsaSpecificSubdirs);
9149 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9153 maybeThrowExceptionForMultiArchCopy(
9154 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9157 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9161 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9163 if (pkg.use32bitAbi) {
9164 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9165 pkg.applicationInfo.primaryCpuAbi = abi;
9167 pkg.applicationInfo.secondaryCpuAbi = abi;
9170 pkg.applicationInfo.primaryCpuAbi = abi;
9175 String[] abiList = (cpuAbiOverride != null) ?
9176 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9178 // Enable gross and lame hacks for apps that are built with old
9179 // SDK tools. We must scan their APKs for renderscript bitcode and
9180 // not launch them if it's present. Don't bother checking on devices
9181 // that don't have 64 bit support.
9182 boolean needsRenderScriptOverride = false;
9183 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9184 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9185 abiList = Build.SUPPORTED_32_BIT_ABIS;
9186 needsRenderScriptOverride = true;
9191 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9192 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9194 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9197 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9198 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9199 "Error unpackaging native libs for app, errorCode=" + copyRet);
9203 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9204 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9205 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9206 } else if (needsRenderScriptOverride) {
9207 pkg.applicationInfo.primaryCpuAbi = abiList[0];
9210 } catch (IOException ioe) {
9211 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9213 IoUtils.closeQuietly(handle);
9216 // Now that we've calculated the ABIs and determined if it's an internal app,
9217 // we will go ahead and populate the nativeLibraryPath.
9218 setNativeLibraryPaths(pkg);
9222 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9223 * i.e, so that all packages can be run inside a single process if required.
9225 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9226 * this function will either try and make the ABI for all packages in {@code packagesForUser}
9227 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9228 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9229 * updating a package that belongs to a shared user.
9231 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9232 * adds unnecessary complexity.
9234 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9235 PackageParser.Package scannedPackage, boolean bootComplete) {
9236 String requiredInstructionSet = null;
9237 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9238 requiredInstructionSet = VMRuntime.getInstructionSet(
9239 scannedPackage.applicationInfo.primaryCpuAbi);
9242 PackageSetting requirer = null;
9243 for (PackageSetting ps : packagesForUser) {
9244 // If packagesForUser contains scannedPackage, we skip it. This will happen
9245 // when scannedPackage is an update of an existing package. Without this check,
9246 // we will never be able to change the ABI of any package belonging to a shared
9247 // user, even if it's compatible with other packages.
9248 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9249 if (ps.primaryCpuAbiString == null) {
9253 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9254 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9255 // We have a mismatch between instruction sets (say arm vs arm64) warn about
9256 // this but there's not much we can do.
9257 String errorMessage = "Instruction set mismatch, "
9258 + ((requirer == null) ? "[caller]" : requirer)
9259 + " requires " + requiredInstructionSet + " whereas " + ps
9260 + " requires " + instructionSet;
9261 Slog.w(TAG, errorMessage);
9264 if (requiredInstructionSet == null) {
9265 requiredInstructionSet = instructionSet;
9271 if (requiredInstructionSet != null) {
9273 if (requirer != null) {
9274 // requirer != null implies that either scannedPackage was null or that scannedPackage
9275 // did not require an ABI, in which case we have to adjust scannedPackage to match
9276 // the ABI of the set (which is the same as requirer's ABI)
9277 adjustedAbi = requirer.primaryCpuAbiString;
9278 if (scannedPackage != null) {
9279 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9282 // requirer == null implies that we're updating all ABIs in the set to
9283 // match scannedPackage.
9284 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
9287 for (PackageSetting ps : packagesForUser) {
9288 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9289 if (ps.primaryCpuAbiString != null) {
9293 ps.primaryCpuAbiString = adjustedAbi;
9294 if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9295 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9296 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9297 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9299 + (requirer == null ? "null" : requirer.pkg.packageName)
9300 + ", scannedPackage="
9301 + (scannedPackage != null ? scannedPackage.packageName : "null")
9304 mInstaller.rmdex(ps.codePathString,
9305 getDexCodeInstructionSet(getPreferredInstructionSet()));
9306 } catch (InstallerException ignored) {
9314 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9315 synchronized (mPackages) {
9316 mResolverReplaced = true;
9317 // Set up information for custom user intent resolution activity.
9318 mResolveActivity.applicationInfo = pkg.applicationInfo;
9319 mResolveActivity.name = mCustomResolverComponentName.getClassName();
9320 mResolveActivity.packageName = pkg.applicationInfo.packageName;
9321 mResolveActivity.processName = pkg.applicationInfo.packageName;
9322 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9323 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9324 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9325 mResolveActivity.theme = 0;
9326 mResolveActivity.exported = true;
9327 mResolveActivity.enabled = true;
9328 mResolveInfo.activityInfo = mResolveActivity;
9329 mResolveInfo.priority = 0;
9330 mResolveInfo.preferredOrder = 0;
9331 mResolveInfo.match = 0;
9332 mResolveComponentName = mCustomResolverComponentName;
9333 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9334 mResolveComponentName);
9338 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9339 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9341 // Set up information for ephemeral installer activity
9342 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9343 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9344 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9345 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9346 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9347 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9348 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9349 mEphemeralInstallerActivity.theme = 0;
9350 mEphemeralInstallerActivity.exported = true;
9351 mEphemeralInstallerActivity.enabled = true;
9352 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9353 mEphemeralInstallerInfo.priority = 0;
9354 mEphemeralInstallerInfo.preferredOrder = 1;
9355 mEphemeralInstallerInfo.isDefault = true;
9356 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9357 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9359 if (DEBUG_EPHEMERAL) {
9360 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9364 private static String calculateBundledApkRoot(final String codePathString) {
9365 final File codePath = new File(codePathString);
9366 final File codeRoot;
9367 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9368 codeRoot = Environment.getRootDirectory();
9369 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9370 codeRoot = Environment.getOemDirectory();
9371 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9372 codeRoot = Environment.getVendorDirectory();
9374 // Unrecognized code path; take its top real segment as the apk root:
9375 // e.g. /something/app/blah.apk => /something
9377 File f = codePath.getCanonicalFile();
9378 File parent = f.getParentFile(); // non-null because codePath is a file
9380 while ((tmp = parent.getParentFile()) != null) {
9385 Slog.w(TAG, "Unrecognized code path "
9386 + codePath + " - using " + codeRoot);
9387 } catch (IOException e) {
9388 // Can't canonicalize the code path -- shenanigans?
9389 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9390 return Environment.getRootDirectory().getPath();
9393 return codeRoot.getPath();
9397 * Derive and set the location of native libraries for the given package,
9398 * which varies depending on where and how the package was installed.
9400 private void setNativeLibraryPaths(PackageParser.Package pkg) {
9401 final ApplicationInfo info = pkg.applicationInfo;
9402 final String codePath = pkg.codePath;
9403 final File codeFile = new File(codePath);
9404 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9405 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9407 info.nativeLibraryRootDir = null;
9408 info.nativeLibraryRootRequiresIsa = false;
9409 info.nativeLibraryDir = null;
9410 info.secondaryNativeLibraryDir = null;
9412 if (isApkFile(codeFile)) {
9413 // Monolithic install
9415 // If "/system/lib64/apkname" exists, assume that is the per-package
9416 // native library directory to use; otherwise use "/system/lib/apkname".
9417 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9418 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9419 getPrimaryInstructionSet(info));
9421 // This is a bundled system app so choose the path based on the ABI.
9422 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9423 // is just the default path.
9424 final String apkName = deriveCodePathName(codePath);
9425 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9426 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9427 apkName).getAbsolutePath();
9429 if (info.secondaryCpuAbi != null) {
9430 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9431 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9432 secondaryLibDir, apkName).getAbsolutePath();
9434 } else if (asecApp) {
9435 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9438 final String apkName = deriveCodePathName(codePath);
9439 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9443 info.nativeLibraryRootRequiresIsa = false;
9444 info.nativeLibraryDir = info.nativeLibraryRootDir;
9447 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9448 info.nativeLibraryRootRequiresIsa = true;
9450 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9451 getPrimaryInstructionSet(info)).getAbsolutePath();
9453 if (info.secondaryCpuAbi != null) {
9454 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9455 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9461 * Calculate the abis and roots for a bundled app. These can uniquely
9462 * be determined from the contents of the system partition, i.e whether
9463 * it contains 64 or 32 bit shared libraries etc. We do not validate any
9464 * of this information, and instead assume that the system was built
9467 private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9468 PackageSetting pkgSetting) {
9469 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9471 // If "/system/lib64/apkname" exists, assume that is the per-package
9472 // native library directory to use; otherwise use "/system/lib/apkname".
9473 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9474 setBundledAppAbi(pkg, apkRoot, apkName);
9475 // pkgSetting might be null during rescan following uninstall of updates
9476 // to a bundled app, so accommodate that possibility. The settings in
9477 // that case will be established later from the parsed package.
9479 // If the settings aren't null, sync them up with what we've just derived.
9480 // note that apkRoot isn't stored in the package settings.
9481 if (pkgSetting != null) {
9482 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9483 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9488 * Deduces the ABI of a bundled app and sets the relevant fields on the
9489 * parsed pkg object.
9491 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9492 * under which system libraries are installed.
9493 * @param apkName the name of the installed package.
9495 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9496 final File codeFile = new File(pkg.codePath);
9498 final boolean has64BitLibs;
9499 final boolean has32BitLibs;
9500 if (isApkFile(codeFile)) {
9501 // Monolithic install
9502 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9503 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9506 final File rootDir = new File(codeFile, LIB_DIR_NAME);
9507 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9508 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9509 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9510 has64BitLibs = (new File(rootDir, isa)).exists();
9512 has64BitLibs = false;
9514 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9515 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9516 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9517 has32BitLibs = (new File(rootDir, isa)).exists();
9519 has32BitLibs = false;
9523 if (has64BitLibs && !has32BitLibs) {
9524 // The package has 64 bit libs, but not 32 bit libs. Its primary
9525 // ABI should be 64 bit. We can safely assume here that the bundled
9526 // native libraries correspond to the most preferred ABI in the list.
9528 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9529 pkg.applicationInfo.secondaryCpuAbi = null;
9530 } else if (has32BitLibs && !has64BitLibs) {
9531 // The package has 32 bit libs but not 64 bit libs. Its primary
9532 // ABI should be 32 bit.
9534 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9535 pkg.applicationInfo.secondaryCpuAbi = null;
9536 } else if (has32BitLibs && has64BitLibs) {
9537 // The application has both 64 and 32 bit bundled libraries. We check
9538 // here that the app declares multiArch support, and warn if it doesn't.
9540 // We will be lenient here and record both ABIs. The primary will be the
9541 // ABI that's higher on the list, i.e, a device that's configured to prefer
9542 // 64 bit apps will see a 64 bit primary ABI,
9544 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9545 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9548 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9549 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9550 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9552 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9553 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9556 pkg.applicationInfo.primaryCpuAbi = null;
9557 pkg.applicationInfo.secondaryCpuAbi = null;
9561 private void killApplication(String pkgName, int appId, String reason) {
9562 killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9565 private void killApplication(String pkgName, int appId, int userId, String reason) {
9566 // Request the ActivityManager to kill the process(only for existing packages)
9567 // so that we do not end up in a confused state while the user is still using the older
9568 // version of the application while the new one gets installed.
9569 final long token = Binder.clearCallingIdentity();
9571 IActivityManager am = ActivityManagerNative.getDefault();
9574 am.killApplication(pkgName, appId, userId, reason);
9575 } catch (RemoteException e) {
9579 Binder.restoreCallingIdentity(token);
9583 private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9584 // Remove the parent package setting
9585 PackageSetting ps = (PackageSetting) pkg.mExtras;
9587 removePackageLI(ps, chatty);
9589 // Remove the child package setting
9590 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9591 for (int i = 0; i < childCount; i++) {
9592 PackageParser.Package childPkg = pkg.childPackages.get(i);
9593 ps = (PackageSetting) childPkg.mExtras;
9595 removePackageLI(ps, chatty);
9600 void removePackageLI(PackageSetting ps, boolean chatty) {
9601 if (DEBUG_INSTALL) {
9603 Log.d(TAG, "Removing package " + ps.name);
9607 synchronized (mPackages) {
9608 mPackages.remove(ps.name);
9609 final PackageParser.Package pkg = ps.pkg;
9611 cleanPackageDataStructuresLILPw(pkg, chatty);
9616 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9617 if (DEBUG_INSTALL) {
9619 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9623 synchronized (mPackages) {
9624 // Remove the parent package
9625 mPackages.remove(pkg.applicationInfo.packageName);
9626 cleanPackageDataStructuresLILPw(pkg, chatty);
9628 // Remove the child packages
9629 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9630 for (int i = 0; i < childCount; i++) {
9631 PackageParser.Package childPkg = pkg.childPackages.get(i);
9632 mPackages.remove(childPkg.applicationInfo.packageName);
9633 cleanPackageDataStructuresLILPw(childPkg, chatty);
9638 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9639 int N = pkg.providers.size();
9640 StringBuilder r = null;
9642 for (i=0; i<N; i++) {
9643 PackageParser.Provider p = pkg.providers.get(i);
9644 mProviders.removeProvider(p);
9645 if (p.info.authority == null) {
9647 /* There was another ContentProvider with this authority when
9648 * this app was installed so this authority is null,
9649 * Ignore it as we don't have to unregister the provider.
9653 String names[] = p.info.authority.split(";");
9654 for (int j = 0; j < names.length; j++) {
9655 if (mProvidersByAuthority.get(names[j]) == p) {
9656 mProvidersByAuthority.remove(names[j]);
9659 Log.d(TAG, "Unregistered content provider: " + names[j]
9660 + ", className = " + p.info.name + ", isSyncable = "
9661 + p.info.isSyncable);
9665 if (DEBUG_REMOVE && chatty) {
9667 r = new StringBuilder(256);
9671 r.append(p.info.name);
9675 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
9678 N = pkg.services.size();
9680 for (i=0; i<N; i++) {
9681 PackageParser.Service s = pkg.services.get(i);
9682 mServices.removeService(s);
9685 r = new StringBuilder(256);
9689 r.append(s.info.name);
9693 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
9696 N = pkg.receivers.size();
9698 for (i=0; i<N; i++) {
9699 PackageParser.Activity a = pkg.receivers.get(i);
9700 mReceivers.removeActivity(a, "receiver");
9701 if (DEBUG_REMOVE && chatty) {
9703 r = new StringBuilder(256);
9707 r.append(a.info.name);
9711 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
9714 N = pkg.activities.size();
9716 for (i=0; i<N; i++) {
9717 PackageParser.Activity a = pkg.activities.get(i);
9718 mActivities.removeActivity(a, "activity");
9719 if (DEBUG_REMOVE && chatty) {
9721 r = new StringBuilder(256);
9725 r.append(a.info.name);
9729 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
9732 N = pkg.permissions.size();
9734 for (i=0; i<N; i++) {
9735 PackageParser.Permission p = pkg.permissions.get(i);
9736 BasePermission bp = mSettings.mPermissions.get(p.info.name);
9738 bp = mSettings.mPermissionTrees.get(p.info.name);
9740 if (bp != null && bp.perm == p) {
9742 if (DEBUG_REMOVE && chatty) {
9744 r = new StringBuilder(256);
9748 r.append(p.info.name);
9751 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9752 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9753 if (appOpPkgs != null) {
9754 appOpPkgs.remove(pkg.packageName);
9759 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9762 N = pkg.requestedPermissions.size();
9764 for (i=0; i<N; i++) {
9765 String perm = pkg.requestedPermissions.get(i);
9766 BasePermission bp = mSettings.mPermissions.get(perm);
9767 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9768 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9769 if (appOpPkgs != null) {
9770 appOpPkgs.remove(pkg.packageName);
9771 if (appOpPkgs.isEmpty()) {
9772 mAppOpPermissionPackages.remove(perm);
9778 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9781 N = pkg.instrumentation.size();
9783 for (i=0; i<N; i++) {
9784 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9785 mInstrumentation.remove(a.getComponentName());
9786 if (DEBUG_REMOVE && chatty) {
9788 r = new StringBuilder(256);
9792 r.append(a.info.name);
9796 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
9800 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9801 // Only system apps can hold shared libraries.
9802 if (pkg.libraryNames != null) {
9803 for (i=0; i<pkg.libraryNames.size(); i++) {
9804 String name = pkg.libraryNames.get(i);
9805 SharedLibraryEntry cur = mSharedLibraries.get(name);
9806 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9807 mSharedLibraries.remove(name);
9808 if (DEBUG_REMOVE && chatty) {
9810 r = new StringBuilder(256);
9821 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
9825 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9826 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9827 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9834 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9835 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9836 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9838 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9839 // Update the parent permissions
9840 updatePermissionsLPw(pkg.packageName, pkg, flags);
9841 // Update the child permissions
9842 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9843 for (int i = 0; i < childCount; i++) {
9844 PackageParser.Package childPkg = pkg.childPackages.get(i);
9845 updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9849 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9851 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9852 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9855 private void updatePermissionsLPw(String changingPkg,
9856 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9857 // Make sure there are no dangling permission trees.
9858 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9859 while (it.hasNext()) {
9860 final BasePermission bp = it.next();
9861 if (bp.packageSetting == null) {
9862 // We may not yet have parsed the package, so just see if
9863 // we still know about its settings.
9864 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9866 if (bp.packageSetting == null) {
9867 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9868 + " from package " + bp.sourcePackage);
9870 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9871 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9872 Slog.i(TAG, "Removing old permission tree: " + bp.name
9873 + " from package " + bp.sourcePackage);
9874 flags |= UPDATE_PERMISSIONS_ALL;
9880 // Make sure all dynamic permissions have been assigned to a package,
9881 // and make sure there are no dangling permissions.
9882 it = mSettings.mPermissions.values().iterator();
9883 while (it.hasNext()) {
9884 final BasePermission bp = it.next();
9885 if (bp.type == BasePermission.TYPE_DYNAMIC) {
9886 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9887 + bp.name + " pkg=" + bp.sourcePackage
9888 + " info=" + bp.pendingInfo);
9889 if (bp.packageSetting == null && bp.pendingInfo != null) {
9890 final BasePermission tree = findPermissionTreeLP(bp.name);
9891 if (tree != null && tree.perm != null) {
9892 bp.packageSetting = tree.packageSetting;
9893 bp.perm = new PackageParser.Permission(tree.perm.owner,
9894 new PermissionInfo(bp.pendingInfo));
9895 bp.perm.info.packageName = tree.perm.info.packageName;
9896 bp.perm.info.name = bp.name;
9901 if (bp.packageSetting == null) {
9902 // We may not yet have parsed the package, so just see if
9903 // we still know about its settings.
9904 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9906 if (bp.packageSetting == null) {
9907 Slog.w(TAG, "Removing dangling permission: " + bp.name
9908 + " from package " + bp.sourcePackage);
9910 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9911 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9912 Slog.i(TAG, "Removing old permission: " + bp.name
9913 + " from package " + bp.sourcePackage);
9914 flags |= UPDATE_PERMISSIONS_ALL;
9920 // Now update the permissions for all packages, in particular
9921 // replace the granted permissions of the system packages.
9922 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9923 for (PackageParser.Package pkg : mPackages.values()) {
9924 if (pkg != pkgInfo) {
9925 // Only replace for packages on requested volume
9926 final String volumeUuid = getVolumeUuidForPackage(pkg);
9927 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9928 && Objects.equals(replaceVolumeUuid, volumeUuid);
9929 grantPermissionsLPw(pkg, replace, changingPkg);
9934 if (pkgInfo != null) {
9935 // Only replace for packages on requested volume
9936 final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9937 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9938 && Objects.equals(replaceVolumeUuid, volumeUuid);
9939 grantPermissionsLPw(pkgInfo, replace, changingPkg);
9943 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9944 String packageOfInterest) {
9945 // IMPORTANT: There are two types of permissions: install and runtime.
9946 // Install time permissions are granted when the app is installed to
9947 // all device users and users added in the future. Runtime permissions
9948 // are granted at runtime explicitly to specific users. Normal and signature
9949 // protected permissions are install time permissions. Dangerous permissions
9950 // are install permissions if the app's target SDK is Lollipop MR1 or older,
9951 // otherwise they are runtime permissions. This function does not manage
9952 // runtime permissions except for the case an app targeting Lollipop MR1
9953 // being upgraded to target a newer SDK, in which case dangerous permissions
9954 // are transformed from install time to runtime ones.
9956 final PackageSetting ps = (PackageSetting) pkg.mExtras;
9961 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9963 PermissionsState permissionsState = ps.getPermissionsState();
9964 PermissionsState origPermissions = permissionsState;
9966 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9968 boolean runtimePermissionsRevoked = false;
9969 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9971 boolean changedInstallPermission = false;
9974 ps.installPermissionsFixed = false;
9975 if (!ps.isSharedUser()) {
9976 origPermissions = new PermissionsState(permissionsState);
9977 permissionsState.reset();
9979 // We need to know only about runtime permission changes since the
9980 // calling code always writes the install permissions state but
9981 // the runtime ones are written only if changed. The only cases of
9982 // changed runtime permissions here are promotion of an install to
9983 // runtime and revocation of a runtime from a shared user.
9984 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9985 ps.sharedUser, UserManagerService.getInstance().getUserIds());
9986 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9987 runtimePermissionsRevoked = true;
9992 permissionsState.setGlobalGids(mGlobalGids);
9994 final int N = pkg.requestedPermissions.size();
9995 for (int i=0; i<N; i++) {
9996 final String name = pkg.requestedPermissions.get(i);
9997 final BasePermission bp = mSettings.mPermissions.get(name);
9999 if (DEBUG_INSTALL) {
10000 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10003 if (bp == null || bp.packageSetting == null) {
10004 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10005 Slog.w(TAG, "Unknown permission " + name
10006 + " in package " + pkg.packageName);
10011 final String perm = bp.name;
10012 boolean allowedSig = false;
10013 int grant = GRANT_DENIED;
10015 // Keep track of app op permissions.
10016 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10017 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10018 if (pkgs == null) {
10019 pkgs = new ArraySet<>();
10020 mAppOpPermissionPackages.put(bp.name, pkgs);
10022 pkgs.add(pkg.packageName);
10025 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10026 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10027 >= Build.VERSION_CODES.M;
10029 case PermissionInfo.PROTECTION_NORMAL: {
10030 // For all apps normal permissions are install time ones.
10031 grant = GRANT_INSTALL;
10034 case PermissionInfo.PROTECTION_DANGEROUS: {
10035 // If a permission review is required for legacy apps we represent
10036 // their permissions as always granted runtime ones since we need
10037 // to keep the review required permission flag per user while an
10038 // install permission's state is shared across all users.
10039 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10040 && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10041 // For legacy apps dangerous permissions are install time ones.
10042 grant = GRANT_INSTALL;
10043 } else if (origPermissions.hasInstallPermission(bp.name)) {
10044 // For legacy apps that became modern, install becomes runtime.
10045 grant = GRANT_UPGRADE;
10046 } else if (mPromoteSystemApps
10048 && mExistingSystemPackages.contains(ps.name)) {
10049 // For legacy system apps, install becomes runtime.
10050 // We cannot check hasInstallPermission() for system apps since those
10051 // permissions were granted implicitly and not persisted pre-M.
10052 grant = GRANT_UPGRADE;
10054 // For modern apps keep runtime permissions unchanged.
10055 grant = GRANT_RUNTIME;
10059 case PermissionInfo.PROTECTION_SIGNATURE: {
10060 // For all apps signature permissions are install time ones.
10061 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10063 grant = GRANT_INSTALL;
10068 if (DEBUG_INSTALL) {
10069 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10072 if (grant != GRANT_DENIED) {
10073 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10074 // If this is an existing, non-system package, then
10075 // we can't add any new permissions to it.
10076 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10077 // Except... if this is a permission that was added
10078 // to the platform (note: need to only do this when
10079 // updating the platform).
10080 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10081 grant = GRANT_DENIED;
10087 case GRANT_INSTALL: {
10088 // Revoke this as runtime permission to handle the case of
10089 // a runtime permission being downgraded to an install one.
10090 // Also in permission review mode we keep dangerous permissions
10092 for (int userId : UserManagerService.getInstance().getUserIds()) {
10093 if (origPermissions.getRuntimePermissionState(
10094 bp.name, userId) != null) {
10095 // Revoke the runtime permission and clear the flags.
10096 origPermissions.revokeRuntimePermission(bp, userId);
10097 origPermissions.updatePermissionFlags(bp, userId,
10098 PackageManager.MASK_PERMISSION_FLAGS, 0);
10099 // If we revoked a permission permission, we have to write.
10100 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10101 changedRuntimePermissionUserIds, userId);
10104 // Grant an install permission.
10105 if (permissionsState.grantInstallPermission(bp) !=
10106 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10107 changedInstallPermission = true;
10111 case GRANT_RUNTIME: {
10112 // Grant previously granted runtime permissions.
10113 for (int userId : UserManagerService.getInstance().getUserIds()) {
10114 PermissionState permissionState = origPermissions
10115 .getRuntimePermissionState(bp.name, userId);
10116 int flags = permissionState != null
10117 ? permissionState.getFlags() : 0;
10118 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10119 // Don't propagate the permission in a permission review mode if
10120 // the former was revoked, i.e. marked to not propagate on upgrade.
10121 // Note that in a permission review mode install permissions are
10122 // represented as constantly granted runtime ones since we need to
10123 // keep a per user state associated with the permission. Also the
10124 // revoke on upgrade flag is no longer applicable and is reset.
10125 final boolean revokeOnUpgrade = (flags & PackageManager
10126 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10127 if (revokeOnUpgrade) {
10128 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10129 // Since we changed the flags, we have to write.
10130 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10131 changedRuntimePermissionUserIds, userId);
10133 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10134 if (permissionsState.grantRuntimePermission(bp, userId) ==
10135 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10136 // If we cannot put the permission as it was,
10137 // we have to write.
10138 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10139 changedRuntimePermissionUserIds, userId);
10143 // If the app supports runtime permissions no need for a review.
10144 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10145 && appSupportsRuntimePermissions
10146 && (flags & PackageManager
10147 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10148 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10149 // Since we changed the flags, we have to write.
10150 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10151 changedRuntimePermissionUserIds, userId);
10153 } else if ((mPermissionReviewRequired
10154 || Build.PERMISSIONS_REVIEW_REQUIRED)
10155 && !appSupportsRuntimePermissions) {
10156 // For legacy apps that need a permission review, every new
10157 // runtime permission is granted but it is pending a review.
10158 // We also need to review only platform defined runtime
10159 // permissions as these are the only ones the platform knows
10160 // how to disable the API to simulate revocation as legacy
10161 // apps don't expect to run with revoked permissions.
10162 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10163 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10164 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10165 // We changed the flags, hence have to write.
10166 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10167 changedRuntimePermissionUserIds, userId);
10170 if (permissionsState.grantRuntimePermission(bp, userId)
10171 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10172 // We changed the permission, hence have to write.
10173 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10174 changedRuntimePermissionUserIds, userId);
10177 // Propagate the permission flags.
10178 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10182 case GRANT_UPGRADE: {
10183 // Grant runtime permissions for a previously held install permission.
10184 PermissionState permissionState = origPermissions
10185 .getInstallPermissionState(bp.name);
10186 final int flags = permissionState != null ? permissionState.getFlags() : 0;
10188 if (origPermissions.revokeInstallPermission(bp)
10189 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10190 // We will be transferring the permission flags, so clear them.
10191 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10192 PackageManager.MASK_PERMISSION_FLAGS, 0);
10193 changedInstallPermission = true;
10196 // If the permission is not to be promoted to runtime we ignore it and
10197 // also its other flags as they are not applicable to install permissions.
10198 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10199 for (int userId : currentUserIds) {
10200 if (permissionsState.grantRuntimePermission(bp, userId) !=
10201 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10202 // Transfer the permission flags.
10203 permissionsState.updatePermissionFlags(bp, userId,
10205 // If we granted the permission, we have to write.
10206 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10207 changedRuntimePermissionUserIds, userId);
10214 if (packageOfInterest == null
10215 || packageOfInterest.equals(pkg.packageName)) {
10216 Slog.w(TAG, "Not granting permission " + perm
10217 + " to package " + pkg.packageName
10218 + " because it was previously installed without");
10223 if (permissionsState.revokeInstallPermission(bp) !=
10224 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10225 // Also drop the permission flags.
10226 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10227 PackageManager.MASK_PERMISSION_FLAGS, 0);
10228 changedInstallPermission = true;
10229 Slog.i(TAG, "Un-granting permission " + perm
10230 + " from package " + pkg.packageName
10231 + " (protectionLevel=" + bp.protectionLevel
10232 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10234 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10235 // Don't print warning for app op permissions, since it is fine for them
10236 // not to be granted, there is a UI for the user to decide.
10237 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10238 Slog.w(TAG, "Not granting permission " + perm
10239 + " to package " + pkg.packageName
10240 + " (protectionLevel=" + bp.protectionLevel
10241 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10248 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10249 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10250 // This is the first that we have heard about this package, so the
10251 // permissions we have now selected are fixed until explicitly
10253 ps.installPermissionsFixed = true;
10256 // Persist the runtime permissions state for users with changes. If permissions
10257 // were revoked because no app in the shared user declares them we have to
10258 // write synchronously to avoid losing runtime permissions state.
10259 for (int userId : changedRuntimePermissionUserIds) {
10260 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10263 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10266 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10267 boolean allowed = false;
10268 final int NP = PackageParser.NEW_PERMISSIONS.length;
10269 for (int ip=0; ip<NP; ip++) {
10270 final PackageParser.NewPermissionInfo npi
10271 = PackageParser.NEW_PERMISSIONS[ip];
10272 if (npi.name.equals(perm)
10273 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10275 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10276 + pkg.packageName);
10283 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10284 BasePermission bp, PermissionsState origPermissions) {
10286 allowed = (compareSignatures(
10287 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10288 == PackageManager.SIGNATURE_MATCH)
10289 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10290 == PackageManager.SIGNATURE_MATCH);
10291 if (!allowed && (bp.protectionLevel
10292 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10293 if (isSystemApp(pkg)) {
10294 // For updated system applications, a system permission
10295 // is granted only if it had been defined by the original application.
10296 if (pkg.isUpdatedSystemApp()) {
10297 final PackageSetting sysPs = mSettings
10298 .getDisabledSystemPkgLPr(pkg.packageName);
10299 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10300 // If the original was granted this permission, we take
10301 // that grant decision as read and propagate it to the
10303 if (sysPs.isPrivileged()) {
10307 // The system apk may have been updated with an older
10308 // version of the one on the data partition, but which
10309 // granted a new system permission that it didn't have
10310 // before. In this case we do want to allow the app to
10311 // now get the new permission if the ancestral apk is
10312 // privileged to get it.
10313 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10314 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10315 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10321 // Also if a privileged parent package on the system image or any of
10322 // its children requested a privileged permission, the updated child
10323 // packages can also get the permission.
10324 if (pkg.parentPackage != null) {
10325 final PackageSetting disabledSysParentPs = mSettings
10326 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10327 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10328 && disabledSysParentPs.isPrivileged()) {
10329 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10331 } else if (disabledSysParentPs.pkg.childPackages != null) {
10332 final int count = disabledSysParentPs.pkg.childPackages.size();
10333 for (int i = 0; i < count; i++) {
10334 PackageParser.Package disabledSysChildPkg =
10335 disabledSysParentPs.pkg.childPackages.get(i);
10336 if (isPackageRequestingPermission(disabledSysChildPkg,
10347 allowed = isPrivilegedApp(pkg);
10352 if (!allowed && (bp.protectionLevel
10353 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10354 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10355 // If this was a previously normal/dangerous permission that got moved
10356 // to a system permission as part of the runtime permission redesign, then
10357 // we still want to blindly grant it to old apps.
10360 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10361 && pkg.packageName.equals(mRequiredInstallerPackage)) {
10362 // If this permission is to be granted to the system installer and
10363 // this app is an installer, then it gets the permission.
10366 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10367 && pkg.packageName.equals(mRequiredVerifierPackage)) {
10368 // If this permission is to be granted to the system verifier and
10369 // this app is a verifier, then it gets the permission.
10372 if (!allowed && (bp.protectionLevel
10373 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10374 && isSystemApp(pkg)) {
10375 // Any pre-installed system app is allowed to get this permission.
10378 if (!allowed && (bp.protectionLevel
10379 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10380 // For development permissions, a development permission
10381 // is granted only if it was already granted.
10382 allowed = origPermissions.hasInstallPermission(perm);
10384 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10385 && pkg.packageName.equals(mSetupWizardPackage)) {
10386 // If this permission is to be granted to the system setup wizard and
10387 // this app is a setup wizard, then it gets the permission.
10394 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10395 final int permCount = pkg.requestedPermissions.size();
10396 for (int j = 0; j < permCount; j++) {
10397 String requestedPermission = pkg.requestedPermissions.get(j);
10398 if (permission.equals(requestedPermission)) {
10405 final class ActivityIntentResolver
10406 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10407 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10408 boolean defaultOnly, int userId) {
10409 if (!sUserManager.exists(userId)) return null;
10410 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10411 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10414 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10416 if (!sUserManager.exists(userId)) return null;
10418 return super.queryIntent(intent, resolvedType,
10419 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10422 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10423 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10424 if (!sUserManager.exists(userId)) return null;
10425 if (packageActivities == null) {
10429 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10430 final int N = packageActivities.size();
10431 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10432 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10434 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10435 for (int i = 0; i < N; ++i) {
10436 intentFilters = packageActivities.get(i).intents;
10437 if (intentFilters != null && intentFilters.size() > 0) {
10438 PackageParser.ActivityIntentInfo[] array =
10439 new PackageParser.ActivityIntentInfo[intentFilters.size()];
10440 intentFilters.toArray(array);
10441 listCut.add(array);
10444 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10448 * Finds a privileged activity that matches the specified activity names.
10450 private PackageParser.Activity findMatchingActivity(
10451 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10452 for (PackageParser.Activity sysActivity : activityList) {
10453 if (sysActivity.info.name.equals(activityInfo.name)) {
10454 return sysActivity;
10456 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10457 return sysActivity;
10459 if (sysActivity.info.targetActivity != null) {
10460 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10461 return sysActivity;
10463 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10464 return sysActivity;
10471 public class IterGenerator<E> {
10472 public Iterator<E> generate(ActivityIntentInfo info) {
10477 public class ActionIterGenerator extends IterGenerator<String> {
10479 public Iterator<String> generate(ActivityIntentInfo info) {
10480 return info.actionsIterator();
10484 public class CategoriesIterGenerator extends IterGenerator<String> {
10486 public Iterator<String> generate(ActivityIntentInfo info) {
10487 return info.categoriesIterator();
10491 public class SchemesIterGenerator extends IterGenerator<String> {
10493 public Iterator<String> generate(ActivityIntentInfo info) {
10494 return info.schemesIterator();
10498 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10500 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10501 return info.authoritiesIterator();
10506 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10507 * MODIFIED. Do not pass in a list that should not be changed.
10509 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10510 IterGenerator<T> generator, Iterator<T> searchIterator) {
10511 // loop through the set of actions; every one must be found in the intent filter
10512 while (searchIterator.hasNext()) {
10513 // we must have at least one filter in the list to consider a match
10514 if (intentList.size() == 0) {
10518 final T searchAction = searchIterator.next();
10520 // loop through the set of intent filters
10521 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10522 while (intentIter.hasNext()) {
10523 final ActivityIntentInfo intentInfo = intentIter.next();
10524 boolean selectionFound = false;
10526 // loop through the intent filter's selection criteria; at least one
10527 // of them must match the searched criteria
10528 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10529 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10530 final T intentSelection = intentSelectionIter.next();
10531 if (intentSelection != null && intentSelection.equals(searchAction)) {
10532 selectionFound = true;
10537 // the selection criteria wasn't found in this filter's set; this filter
10538 // is not a potential match
10539 if (!selectionFound) {
10540 intentIter.remove();
10546 private boolean isProtectedAction(ActivityIntentInfo filter) {
10547 final Iterator<String> actionsIter = filter.actionsIterator();
10548 while (actionsIter != null && actionsIter.hasNext()) {
10549 final String filterAction = actionsIter.next();
10550 if (PROTECTED_ACTIONS.contains(filterAction)) {
10558 * Adjusts the priority of the given intent filter according to policy.
10561 * <li>The priority for non privileged applications is capped to '0'</li>
10562 * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10563 * <li>The priority for unbundled updates to privileged applications is capped to the
10564 * priority defined on the system partition</li>
10567 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10568 * allowed to obtain any priority on any action.
10570 private void adjustPriority(
10571 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10572 // nothing to do; priority is fine as-is
10573 if (intent.getPriority() <= 0) {
10577 final ActivityInfo activityInfo = intent.activity.info;
10578 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10580 final boolean privilegedApp =
10581 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10582 if (!privilegedApp) {
10583 // non-privileged applications can never define a priority >0
10584 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10585 + " package: " + applicationInfo.packageName
10586 + " activity: " + intent.activity.className
10587 + " origPrio: " + intent.getPriority());
10588 intent.setPriority(0);
10592 if (systemActivities == null) {
10593 // the system package is not disabled; we're parsing the system partition
10594 if (isProtectedAction(intent)) {
10595 if (mDeferProtectedFilters) {
10596 // We can't deal with these just yet. No component should ever obtain a
10597 // >0 priority for a protected actions, with ONE exception -- the setup
10598 // wizard. The setup wizard, however, cannot be known until we're able to
10599 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10600 // until all intent filters have been processed. Chicken, meet egg.
10601 // Let the filter temporarily have a high priority and rectify the
10602 // priorities after all system packages have been scanned.
10603 mProtectedFilters.add(intent);
10604 if (DEBUG_FILTERS) {
10605 Slog.i(TAG, "Protected action; save for later;"
10606 + " package: " + applicationInfo.packageName
10607 + " activity: " + intent.activity.className
10608 + " origPrio: " + intent.getPriority());
10612 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10613 Slog.i(TAG, "No setup wizard;"
10614 + " All protected intents capped to priority 0");
10616 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10617 if (DEBUG_FILTERS) {
10618 Slog.i(TAG, "Found setup wizard;"
10619 + " allow priority " + intent.getPriority() + ";"
10620 + " package: " + intent.activity.info.packageName
10621 + " activity: " + intent.activity.className
10622 + " priority: " + intent.getPriority());
10624 // setup wizard gets whatever it wants
10627 Slog.w(TAG, "Protected action; cap priority to 0;"
10628 + " package: " + intent.activity.info.packageName
10629 + " activity: " + intent.activity.className
10630 + " origPrio: " + intent.getPriority());
10631 intent.setPriority(0);
10635 // privileged apps on the system image get whatever priority they request
10639 // privileged app unbundled update ... try to find the same activity
10640 final PackageParser.Activity foundActivity =
10641 findMatchingActivity(systemActivities, activityInfo);
10642 if (foundActivity == null) {
10643 // this is a new activity; it cannot obtain >0 priority
10644 if (DEBUG_FILTERS) {
10645 Slog.i(TAG, "New activity; cap priority to 0;"
10646 + " package: " + applicationInfo.packageName
10647 + " activity: " + intent.activity.className
10648 + " origPrio: " + intent.getPriority());
10650 intent.setPriority(0);
10654 // found activity, now check for filter equivalence
10656 // a shallow copy is enough; we modify the list, not its contents
10657 final List<ActivityIntentInfo> intentListCopy =
10658 new ArrayList<>(foundActivity.intents);
10659 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10661 // find matching action subsets
10662 final Iterator<String> actionsIterator = intent.actionsIterator();
10663 if (actionsIterator != null) {
10664 getIntentListSubset(
10665 intentListCopy, new ActionIterGenerator(), actionsIterator);
10666 if (intentListCopy.size() == 0) {
10667 // no more intents to match; we're not equivalent
10668 if (DEBUG_FILTERS) {
10669 Slog.i(TAG, "Mismatched action; cap priority to 0;"
10670 + " package: " + applicationInfo.packageName
10671 + " activity: " + intent.activity.className
10672 + " origPrio: " + intent.getPriority());
10674 intent.setPriority(0);
10679 // find matching category subsets
10680 final Iterator<String> categoriesIterator = intent.categoriesIterator();
10681 if (categoriesIterator != null) {
10682 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10683 categoriesIterator);
10684 if (intentListCopy.size() == 0) {
10685 // no more intents to match; we're not equivalent
10686 if (DEBUG_FILTERS) {
10687 Slog.i(TAG, "Mismatched category; cap priority to 0;"
10688 + " package: " + applicationInfo.packageName
10689 + " activity: " + intent.activity.className
10690 + " origPrio: " + intent.getPriority());
10692 intent.setPriority(0);
10697 // find matching schemes subsets
10698 final Iterator<String> schemesIterator = intent.schemesIterator();
10699 if (schemesIterator != null) {
10700 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10702 if (intentListCopy.size() == 0) {
10703 // no more intents to match; we're not equivalent
10704 if (DEBUG_FILTERS) {
10705 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10706 + " package: " + applicationInfo.packageName
10707 + " activity: " + intent.activity.className
10708 + " origPrio: " + intent.getPriority());
10710 intent.setPriority(0);
10715 // find matching authorities subsets
10716 final Iterator<IntentFilter.AuthorityEntry>
10717 authoritiesIterator = intent.authoritiesIterator();
10718 if (authoritiesIterator != null) {
10719 getIntentListSubset(intentListCopy,
10720 new AuthoritiesIterGenerator(),
10721 authoritiesIterator);
10722 if (intentListCopy.size() == 0) {
10723 // no more intents to match; we're not equivalent
10724 if (DEBUG_FILTERS) {
10725 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10726 + " package: " + applicationInfo.packageName
10727 + " activity: " + intent.activity.className
10728 + " origPrio: " + intent.getPriority());
10730 intent.setPriority(0);
10735 // we found matching filter(s); app gets the max priority of all intents
10736 int cappedPriority = 0;
10737 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10738 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10740 if (intent.getPriority() > cappedPriority) {
10741 if (DEBUG_FILTERS) {
10742 Slog.i(TAG, "Found matching filter(s);"
10743 + " cap priority to " + cappedPriority + ";"
10744 + " package: " + applicationInfo.packageName
10745 + " activity: " + intent.activity.className
10746 + " origPrio: " + intent.getPriority());
10748 intent.setPriority(cappedPriority);
10751 // all this for nothing; the requested priority was <= what was on the system
10754 public final void addActivity(PackageParser.Activity a, String type) {
10755 mActivities.put(a.getComponentName(), a);
10756 if (DEBUG_SHOW_INFO)
10758 TAG, " " + type + " " +
10759 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10760 if (DEBUG_SHOW_INFO)
10761 Log.v(TAG, " Class=" + a.info.name);
10762 final int NI = a.intents.size();
10763 for (int j=0; j<NI; j++) {
10764 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10765 if ("activity".equals(type)) {
10766 final PackageSetting ps =
10767 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10768 final List<PackageParser.Activity> systemActivities =
10769 ps != null && ps.pkg != null ? ps.pkg.activities : null;
10770 adjustPriority(systemActivities, intent);
10772 if (DEBUG_SHOW_INFO) {
10773 Log.v(TAG, " IntentFilter:");
10774 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10776 if (!intent.debugCheck()) {
10777 Log.w(TAG, "==> For Activity " + a.info.name);
10783 public final void removeActivity(PackageParser.Activity a, String type) {
10784 mActivities.remove(a.getComponentName());
10785 if (DEBUG_SHOW_INFO) {
10786 Log.v(TAG, " " + type + " "
10787 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10788 : a.info.name) + ":");
10789 Log.v(TAG, " Class=" + a.info.name);
10791 final int NI = a.intents.size();
10792 for (int j=0; j<NI; j++) {
10793 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10794 if (DEBUG_SHOW_INFO) {
10795 Log.v(TAG, " IntentFilter:");
10796 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10798 removeFilter(intent);
10803 protected boolean allowFilterResult(
10804 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10805 ActivityInfo filterAi = filter.activity.info;
10806 for (int i=dest.size()-1; i>=0; i--) {
10807 ActivityInfo destAi = dest.get(i).activityInfo;
10808 if (destAi.name == filterAi.name
10809 && destAi.packageName == filterAi.packageName) {
10817 protected ActivityIntentInfo[] newArray(int size) {
10818 return new ActivityIntentInfo[size];
10822 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10823 if (!sUserManager.exists(userId)) return true;
10824 PackageParser.Package p = filter.activity.owner;
10826 PackageSetting ps = (PackageSetting)p.mExtras;
10828 // System apps are never considered stopped for purposes of
10829 // filtering, because there may be no way for the user to
10830 // actually re-launch them.
10831 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10832 && ps.getStopped(userId);
10839 protected boolean isPackageForFilter(String packageName,
10840 PackageParser.ActivityIntentInfo info) {
10841 return packageName.equals(info.activity.owner.packageName);
10845 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10846 int match, int userId) {
10847 if (!sUserManager.exists(userId)) return null;
10848 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10851 final PackageParser.Activity activity = info.activity;
10852 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10856 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10857 ps.readUserState(userId), userId);
10861 final ResolveInfo res = new ResolveInfo();
10862 res.activityInfo = ai;
10863 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10866 if (info != null) {
10867 res.handleAllWebDataURI = info.handleAllWebDataURI();
10869 res.priority = info.getPriority();
10870 res.preferredOrder = activity.owner.mPreferredOrder;
10871 //System.out.println("Result: " + res.activityInfo.className +
10872 // " = " + res.priority);
10874 res.isDefault = info.hasDefault;
10875 res.labelRes = info.labelRes;
10876 res.nonLocalizedLabel = info.nonLocalizedLabel;
10877 if (userNeedsBadging(userId)) {
10878 res.noResourceId = true;
10880 res.icon = info.icon;
10882 res.iconResourceId = info.icon;
10883 res.system = res.activityInfo.applicationInfo.isSystemApp();
10888 protected void sortResults(List<ResolveInfo> results) {
10889 Collections.sort(results, mResolvePrioritySorter);
10893 protected void dumpFilter(PrintWriter out, String prefix,
10894 PackageParser.ActivityIntentInfo filter) {
10895 out.print(prefix); out.print(
10896 Integer.toHexString(System.identityHashCode(filter.activity)));
10898 filter.activity.printComponentShortName(out);
10899 out.print(" filter ");
10900 out.println(Integer.toHexString(System.identityHashCode(filter)));
10904 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10905 return filter.activity;
10908 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10909 PackageParser.Activity activity = (PackageParser.Activity)label;
10910 out.print(prefix); out.print(
10911 Integer.toHexString(System.identityHashCode(activity)));
10913 activity.printComponentShortName(out);
10915 out.print(" ("); out.print(count); out.print(" filters)");
10920 // Keys are String (activity class name), values are Activity.
10921 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10922 = new ArrayMap<ComponentName, PackageParser.Activity>();
10923 private int mFlags;
10926 private final class ServiceIntentResolver
10927 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10928 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10929 boolean defaultOnly, int userId) {
10930 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10931 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10934 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10936 if (!sUserManager.exists(userId)) return null;
10938 return super.queryIntent(intent, resolvedType,
10939 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10942 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10943 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10944 if (!sUserManager.exists(userId)) return null;
10945 if (packageServices == null) {
10949 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10950 final int N = packageServices.size();
10951 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10952 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10954 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10955 for (int i = 0; i < N; ++i) {
10956 intentFilters = packageServices.get(i).intents;
10957 if (intentFilters != null && intentFilters.size() > 0) {
10958 PackageParser.ServiceIntentInfo[] array =
10959 new PackageParser.ServiceIntentInfo[intentFilters.size()];
10960 intentFilters.toArray(array);
10961 listCut.add(array);
10964 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10967 public final void addService(PackageParser.Service s) {
10968 mServices.put(s.getComponentName(), s);
10969 if (DEBUG_SHOW_INFO) {
10971 + (s.info.nonLocalizedLabel != null
10972 ? s.info.nonLocalizedLabel : s.info.name) + ":");
10973 Log.v(TAG, " Class=" + s.info.name);
10975 final int NI = s.intents.size();
10977 for (j=0; j<NI; j++) {
10978 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10979 if (DEBUG_SHOW_INFO) {
10980 Log.v(TAG, " IntentFilter:");
10981 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10983 if (!intent.debugCheck()) {
10984 Log.w(TAG, "==> For Service " + s.info.name);
10990 public final void removeService(PackageParser.Service s) {
10991 mServices.remove(s.getComponentName());
10992 if (DEBUG_SHOW_INFO) {
10993 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
10994 ? s.info.nonLocalizedLabel : s.info.name) + ":");
10995 Log.v(TAG, " Class=" + s.info.name);
10997 final int NI = s.intents.size();
10999 for (j=0; j<NI; j++) {
11000 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11001 if (DEBUG_SHOW_INFO) {
11002 Log.v(TAG, " IntentFilter:");
11003 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11005 removeFilter(intent);
11010 protected boolean allowFilterResult(
11011 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11012 ServiceInfo filterSi = filter.service.info;
11013 for (int i=dest.size()-1; i>=0; i--) {
11014 ServiceInfo destAi = dest.get(i).serviceInfo;
11015 if (destAi.name == filterSi.name
11016 && destAi.packageName == filterSi.packageName) {
11024 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11025 return new PackageParser.ServiceIntentInfo[size];
11029 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11030 if (!sUserManager.exists(userId)) return true;
11031 PackageParser.Package p = filter.service.owner;
11033 PackageSetting ps = (PackageSetting)p.mExtras;
11035 // System apps are never considered stopped for purposes of
11036 // filtering, because there may be no way for the user to
11037 // actually re-launch them.
11038 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11039 && ps.getStopped(userId);
11046 protected boolean isPackageForFilter(String packageName,
11047 PackageParser.ServiceIntentInfo info) {
11048 return packageName.equals(info.service.owner.packageName);
11052 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11053 int match, int userId) {
11054 if (!sUserManager.exists(userId)) return null;
11055 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11056 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11059 final PackageParser.Service service = info.service;
11060 PackageSetting ps = (PackageSetting) service.owner.mExtras;
11064 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11065 ps.readUserState(userId), userId);
11069 final ResolveInfo res = new ResolveInfo();
11070 res.serviceInfo = si;
11071 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11072 res.filter = filter;
11074 res.priority = info.getPriority();
11075 res.preferredOrder = service.owner.mPreferredOrder;
11077 res.isDefault = info.hasDefault;
11078 res.labelRes = info.labelRes;
11079 res.nonLocalizedLabel = info.nonLocalizedLabel;
11080 res.icon = info.icon;
11081 res.system = res.serviceInfo.applicationInfo.isSystemApp();
11086 protected void sortResults(List<ResolveInfo> results) {
11087 Collections.sort(results, mResolvePrioritySorter);
11091 protected void dumpFilter(PrintWriter out, String prefix,
11092 PackageParser.ServiceIntentInfo filter) {
11093 out.print(prefix); out.print(
11094 Integer.toHexString(System.identityHashCode(filter.service)));
11096 filter.service.printComponentShortName(out);
11097 out.print(" filter ");
11098 out.println(Integer.toHexString(System.identityHashCode(filter)));
11102 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11103 return filter.service;
11106 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11107 PackageParser.Service service = (PackageParser.Service)label;
11108 out.print(prefix); out.print(
11109 Integer.toHexString(System.identityHashCode(service)));
11111 service.printComponentShortName(out);
11113 out.print(" ("); out.print(count); out.print(" filters)");
11118 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11119 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11120 // final List<ResolveInfo> retList = Lists.newArrayList();
11121 // while (i.hasNext()) {
11122 // final ResolveInfo resolveInfo = (ResolveInfo) i;
11123 // if (isEnabledLP(resolveInfo.serviceInfo)) {
11124 // retList.add(resolveInfo);
11130 // Keys are String (activity class name), values are Activity.
11131 private final ArrayMap<ComponentName, PackageParser.Service> mServices
11132 = new ArrayMap<ComponentName, PackageParser.Service>();
11133 private int mFlags;
11136 private final class ProviderIntentResolver
11137 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11138 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11139 boolean defaultOnly, int userId) {
11140 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11141 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11144 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11146 if (!sUserManager.exists(userId))
11149 return super.queryIntent(intent, resolvedType,
11150 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11153 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11154 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11155 if (!sUserManager.exists(userId))
11157 if (packageProviders == null) {
11161 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11162 final int N = packageProviders.size();
11163 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11164 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11166 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11167 for (int i = 0; i < N; ++i) {
11168 intentFilters = packageProviders.get(i).intents;
11169 if (intentFilters != null && intentFilters.size() > 0) {
11170 PackageParser.ProviderIntentInfo[] array =
11171 new PackageParser.ProviderIntentInfo[intentFilters.size()];
11172 intentFilters.toArray(array);
11173 listCut.add(array);
11176 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11179 public final void addProvider(PackageParser.Provider p) {
11180 if (mProviders.containsKey(p.getComponentName())) {
11181 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11185 mProviders.put(p.getComponentName(), p);
11186 if (DEBUG_SHOW_INFO) {
11188 + (p.info.nonLocalizedLabel != null
11189 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11190 Log.v(TAG, " Class=" + p.info.name);
11192 final int NI = p.intents.size();
11194 for (j = 0; j < NI; j++) {
11195 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11196 if (DEBUG_SHOW_INFO) {
11197 Log.v(TAG, " IntentFilter:");
11198 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11200 if (!intent.debugCheck()) {
11201 Log.w(TAG, "==> For Provider " + p.info.name);
11207 public final void removeProvider(PackageParser.Provider p) {
11208 mProviders.remove(p.getComponentName());
11209 if (DEBUG_SHOW_INFO) {
11210 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
11211 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11212 Log.v(TAG, " Class=" + p.info.name);
11214 final int NI = p.intents.size();
11216 for (j = 0; j < NI; j++) {
11217 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11218 if (DEBUG_SHOW_INFO) {
11219 Log.v(TAG, " IntentFilter:");
11220 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11222 removeFilter(intent);
11227 protected boolean allowFilterResult(
11228 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11229 ProviderInfo filterPi = filter.provider.info;
11230 for (int i = dest.size() - 1; i >= 0; i--) {
11231 ProviderInfo destPi = dest.get(i).providerInfo;
11232 if (destPi.name == filterPi.name
11233 && destPi.packageName == filterPi.packageName) {
11241 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11242 return new PackageParser.ProviderIntentInfo[size];
11246 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11247 if (!sUserManager.exists(userId))
11249 PackageParser.Package p = filter.provider.owner;
11251 PackageSetting ps = (PackageSetting) p.mExtras;
11253 // System apps are never considered stopped for purposes of
11254 // filtering, because there may be no way for the user to
11255 // actually re-launch them.
11256 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11257 && ps.getStopped(userId);
11264 protected boolean isPackageForFilter(String packageName,
11265 PackageParser.ProviderIntentInfo info) {
11266 return packageName.equals(info.provider.owner.packageName);
11270 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11271 int match, int userId) {
11272 if (!sUserManager.exists(userId))
11274 final PackageParser.ProviderIntentInfo info = filter;
11275 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11278 final PackageParser.Provider provider = info.provider;
11279 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11283 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11284 ps.readUserState(userId), userId);
11288 final ResolveInfo res = new ResolveInfo();
11289 res.providerInfo = pi;
11290 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11291 res.filter = filter;
11293 res.priority = info.getPriority();
11294 res.preferredOrder = provider.owner.mPreferredOrder;
11296 res.isDefault = info.hasDefault;
11297 res.labelRes = info.labelRes;
11298 res.nonLocalizedLabel = info.nonLocalizedLabel;
11299 res.icon = info.icon;
11300 res.system = res.providerInfo.applicationInfo.isSystemApp();
11305 protected void sortResults(List<ResolveInfo> results) {
11306 Collections.sort(results, mResolvePrioritySorter);
11310 protected void dumpFilter(PrintWriter out, String prefix,
11311 PackageParser.ProviderIntentInfo filter) {
11314 Integer.toHexString(System.identityHashCode(filter.provider)));
11316 filter.provider.printComponentShortName(out);
11317 out.print(" filter ");
11318 out.println(Integer.toHexString(System.identityHashCode(filter)));
11322 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11323 return filter.provider;
11326 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11327 PackageParser.Provider provider = (PackageParser.Provider)label;
11328 out.print(prefix); out.print(
11329 Integer.toHexString(System.identityHashCode(provider)));
11331 provider.printComponentShortName(out);
11333 out.print(" ("); out.print(count); out.print(" filters)");
11338 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11339 = new ArrayMap<ComponentName, PackageParser.Provider>();
11340 private int mFlags;
11343 private static final class EphemeralIntentResolver
11344 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11346 * The result that has the highest defined order. Ordering applies on a
11347 * per-package basis. Mapping is from package name to Pair of order and
11348 * EphemeralResolveInfo.
11350 * NOTE: This is implemented as a field variable for convenience and efficiency.
11351 * By having a field variable, we're able to track filter ordering as soon as
11352 * a non-zero order is defined. Otherwise, multiple loops across the result set
11353 * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11354 * this needs to be contained entirely within {@link #filterResults()}.
11356 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11359 protected EphemeralResolveIntentInfo[] newArray(int size) {
11360 return new EphemeralResolveIntentInfo[size];
11364 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11369 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11371 if (!sUserManager.exists(userId)) {
11374 final String packageName = info.getEphemeralResolveInfo().getPackageName();
11375 final Integer order = info.getOrder();
11376 final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11377 mOrderResult.get(packageName);
11378 // ordering is enabled and this item's order isn't high enough
11379 if (lastOrderResult != null && lastOrderResult.first >= order) {
11382 final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11384 // non-zero order, enable ordering
11385 mOrderResult.put(packageName, new Pair<>(order, res));
11391 protected void filterResults(List<EphemeralResolveInfo> results) {
11392 // only do work if ordering is enabled [most of the time it won't be]
11393 if (mOrderResult.size() == 0) {
11396 int resultSize = results.size();
11397 for (int i = 0; i < resultSize; i++) {
11398 final EphemeralResolveInfo info = results.get(i);
11399 final String packageName = info.getPackageName();
11400 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11401 if (savedInfo == null) {
11402 // package doesn't having ordering
11405 if (savedInfo.second == info) {
11406 // circled back to the highest ordered item; remove from order list
11407 mOrderResult.remove(savedInfo);
11408 if (mOrderResult.size() == 0) {
11409 // no more ordered items
11414 // item has a worse order, remove it from the result list
11422 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11423 new Comparator<ResolveInfo>() {
11424 public int compare(ResolveInfo r1, ResolveInfo r2) {
11425 int v1 = r1.priority;
11426 int v2 = r2.priority;
11427 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11429 return (v1 > v2) ? -1 : 1;
11431 v1 = r1.preferredOrder;
11432 v2 = r2.preferredOrder;
11434 return (v1 > v2) ? -1 : 1;
11436 if (r1.isDefault != r2.isDefault) {
11437 return r1.isDefault ? -1 : 1;
11441 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11443 return (v1 > v2) ? -1 : 1;
11445 if (r1.system != r2.system) {
11446 return r1.system ? -1 : 1;
11448 if (r1.activityInfo != null) {
11449 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11451 if (r1.serviceInfo != null) {
11452 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11454 if (r1.providerInfo != null) {
11455 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11461 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11462 new Comparator<ProviderInfo>() {
11463 public int compare(ProviderInfo p1, ProviderInfo p2) {
11464 final int v1 = p1.initOrder;
11465 final int v2 = p2.initOrder;
11466 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11470 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11471 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11472 final int[] userIds) {
11473 mHandler.post(new Runnable() {
11475 public void run() {
11477 final IActivityManager am = ActivityManagerNative.getDefault();
11478 if (am == null) return;
11479 final int[] resolvedUserIds;
11480 if (userIds == null) {
11481 resolvedUserIds = am.getRunningUserIds();
11483 resolvedUserIds = userIds;
11485 for (int id : resolvedUserIds) {
11486 final Intent intent = new Intent(action,
11487 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11488 if (extras != null) {
11489 intent.putExtras(extras);
11491 if (targetPkg != null) {
11492 intent.setPackage(targetPkg);
11494 // Modify the UID when posting to other users
11495 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11496 if (uid > 0 && UserHandle.getUserId(uid) != id) {
11497 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11498 intent.putExtra(Intent.EXTRA_UID, uid);
11500 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11501 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11502 if (DEBUG_BROADCASTS) {
11503 RuntimeException here = new RuntimeException("here");
11504 here.fillInStackTrace();
11505 Slog.d(TAG, "Sending to user " + id + ": "
11506 + intent.toShortString(false, true, false, false)
11507 + " " + intent.getExtras(), here);
11509 am.broadcastIntent(null, intent, null, finishedReceiver,
11510 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11511 null, finishedReceiver != null, false, id);
11513 } catch (RemoteException ex) {
11520 * Check if the external storage media is available. This is true if there
11521 * is a mounted external storage medium or if the external storage is
11524 private boolean isExternalMediaAvailable() {
11525 return mMediaMounted || Environment.isExternalStorageEmulated();
11529 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11531 synchronized (mPackages) {
11532 if (!isExternalMediaAvailable()) {
11533 // If the external storage is no longer mounted at this point,
11534 // the caller may not have been able to delete all of this
11535 // packages files and can not delete any more. Bail.
11538 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11539 if (lastPackage != null) {
11540 pkgs.remove(lastPackage);
11542 if (pkgs.size() > 0) {
11543 return pkgs.get(0);
11549 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11550 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11551 userId, andCode ? 1 : 0, packageName);
11552 if (mSystemReady) {
11553 msg.sendToTarget();
11555 if (mPostSystemReadyMessages == null) {
11556 mPostSystemReadyMessages = new ArrayList<>();
11558 mPostSystemReadyMessages.add(msg);
11562 void startCleaningPackages() {
11564 if (!isExternalMediaAvailable()) {
11567 synchronized (mPackages) {
11568 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11572 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11573 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11574 IActivityManager am = ActivityManagerNative.getDefault();
11577 am.startService(null, intent, null, mContext.getOpPackageName(),
11578 UserHandle.USER_SYSTEM);
11579 } catch (RemoteException e) {
11585 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11586 int installFlags, String installerPackageName, int userId) {
11587 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11589 final int callingUid = Binder.getCallingUid();
11590 enforceCrossUserPermission(callingUid, userId,
11591 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11593 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11595 if (observer != null) {
11596 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11598 } catch (RemoteException re) {
11603 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11604 installFlags |= PackageManager.INSTALL_FROM_ADB;
11607 // Caller holds INSTALL_PACKAGES permission, so we're less strict
11608 // about installerPackageName.
11610 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11611 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11615 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11616 user = UserHandle.ALL;
11618 user = new UserHandle(userId);
11621 // Only system components can circumvent runtime permissions when installing.
11622 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11623 && mContext.checkCallingOrSelfPermission(Manifest.permission
11624 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11625 throw new SecurityException("You need the "
11626 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11627 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11630 final File originFile = new File(originPath);
11631 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11633 final Message msg = mHandler.obtainMessage(INIT_COPY);
11634 final VerificationInfo verificationInfo = new VerificationInfo(
11635 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11636 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11637 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11638 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11639 null /*certificates*/);
11640 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11643 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11644 System.identityHashCode(msg.obj));
11645 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11646 System.identityHashCode(msg.obj));
11648 mHandler.sendMessage(msg);
11651 void installStage(String packageName, File stagedDir, String stagedCid,
11652 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11653 String installerPackageName, int installerUid, UserHandle user,
11654 Certificate[][] certificates) {
11655 if (DEBUG_EPHEMERAL) {
11656 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11657 Slog.d(TAG, "Ephemeral install of " + packageName);
11660 final VerificationInfo verificationInfo = new VerificationInfo(
11661 sessionParams.originatingUri, sessionParams.referrerUri,
11662 sessionParams.originatingUid, installerUid);
11664 final OriginInfo origin;
11665 if (stagedDir != null) {
11666 origin = OriginInfo.fromStagedFile(stagedDir);
11668 origin = OriginInfo.fromStagedContainer(stagedCid);
11671 final Message msg = mHandler.obtainMessage(INIT_COPY);
11672 final InstallParams params = new InstallParams(origin, null, observer,
11673 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11674 verificationInfo, user, sessionParams.abiOverride,
11675 sessionParams.grantedRuntimePermissions, certificates);
11676 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11679 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11680 System.identityHashCode(msg.obj));
11681 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11682 System.identityHashCode(msg.obj));
11684 mHandler.sendMessage(msg);
11687 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11689 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11690 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11693 private void sendPackageAddedForUser(String packageName, boolean isSystem,
11694 int appId, int userId) {
11695 Bundle extras = new Bundle(1);
11696 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11698 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11699 packageName, extras, 0, null, null, new int[] {userId});
11701 IActivityManager am = ActivityManagerNative.getDefault();
11702 if (isSystem && am.isUserRunning(userId, 0)) {
11703 // The just-installed/enabled app is bundled on the system, so presumed
11704 // to be able to run automatically without needing an explicit launch.
11705 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11706 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11707 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11708 .setPackage(packageName);
11709 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11710 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11712 } catch (RemoteException e) {
11713 // shouldn't happen
11714 Slog.w(TAG, "Unable to bootstrap installed package", e);
11719 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11722 PackageSetting pkgSetting;
11723 final int uid = Binder.getCallingUid();
11724 enforceCrossUserPermission(uid, userId,
11725 true /* requireFullPermission */, true /* checkShell */,
11726 "setApplicationHiddenSetting for user " + userId);
11728 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11729 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11733 long callingId = Binder.clearCallingIdentity();
11735 boolean sendAdded = false;
11736 boolean sendRemoved = false;
11738 synchronized (mPackages) {
11739 pkgSetting = mSettings.mPackages.get(packageName);
11740 if (pkgSetting == null) {
11743 // Do not allow "android" is being disabled
11744 if ("android".equals(packageName)) {
11745 Slog.w(TAG, "Cannot hide package: android");
11748 // Only allow protected packages to hide themselves.
11749 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11750 && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11751 Slog.w(TAG, "Not hiding protected package: " + packageName);
11755 if (pkgSetting.getHidden(userId) != hidden) {
11756 pkgSetting.setHidden(hidden, userId);
11757 mSettings.writePackageRestrictionsLPr(userId);
11759 sendRemoved = true;
11766 sendPackageAddedForUser(packageName, pkgSetting, userId);
11770 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11772 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11776 Binder.restoreCallingIdentity(callingId);
11781 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11783 final PackageRemovedInfo info = new PackageRemovedInfo();
11784 info.removedPackage = packageName;
11785 info.removedUsers = new int[] {userId};
11786 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11787 info.sendPackageRemovedBroadcasts(true /*killApp*/);
11790 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11791 if (pkgList.length > 0) {
11792 Bundle extras = new Bundle(1);
11793 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11795 sendPackageBroadcast(
11796 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11797 : Intent.ACTION_PACKAGES_UNSUSPENDED,
11798 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11799 new int[] {userId});
11804 * Returns true if application is not found or there was an error. Otherwise it returns
11805 * the hidden state of the package for the given user.
11808 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11809 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11810 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11811 true /* requireFullPermission */, false /* checkShell */,
11812 "getApplicationHidden for user " + userId);
11813 PackageSetting pkgSetting;
11814 long callingId = Binder.clearCallingIdentity();
11817 synchronized (mPackages) {
11818 pkgSetting = mSettings.mPackages.get(packageName);
11819 if (pkgSetting == null) {
11822 return pkgSetting.getHidden(userId);
11825 Binder.restoreCallingIdentity(callingId);
11833 public int installExistingPackageAsUser(String packageName, int userId) {
11834 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11836 PackageSetting pkgSetting;
11837 final int uid = Binder.getCallingUid();
11838 enforceCrossUserPermission(uid, userId,
11839 true /* requireFullPermission */, true /* checkShell */,
11840 "installExistingPackage for user " + userId);
11841 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11842 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11845 long callingId = Binder.clearCallingIdentity();
11847 boolean installed = false;
11850 synchronized (mPackages) {
11851 pkgSetting = mSettings.mPackages.get(packageName);
11852 if (pkgSetting == null) {
11853 return PackageManager.INSTALL_FAILED_INVALID_URI;
11855 if (!pkgSetting.getInstalled(userId)) {
11856 pkgSetting.setInstalled(true, userId);
11857 pkgSetting.setHidden(false, userId);
11858 mSettings.writePackageRestrictionsLPr(userId);
11864 if (pkgSetting.pkg != null) {
11865 synchronized (mInstallLock) {
11866 // We don't need to freeze for a brand new install
11867 prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11870 sendPackageAddedForUser(packageName, pkgSetting, userId);
11873 Binder.restoreCallingIdentity(callingId);
11876 return PackageManager.INSTALL_SUCCEEDED;
11879 boolean isUserRestricted(int userId, String restrictionKey) {
11880 Bundle restrictions = sUserManager.getUserRestrictions(userId);
11881 if (restrictions.getBoolean(restrictionKey, false)) {
11882 Log.w(TAG, "User is restricted: " + restrictionKey);
11889 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11891 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11892 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11893 true /* requireFullPermission */, true /* checkShell */,
11894 "setPackagesSuspended for user " + userId);
11896 if (ArrayUtils.isEmpty(packageNames)) {
11897 return packageNames;
11900 // List of package names for whom the suspended state has changed.
11901 List<String> changedPackages = new ArrayList<>(packageNames.length);
11902 // List of package names for whom the suspended state is not set as requested in this
11904 List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11905 long callingId = Binder.clearCallingIdentity();
11907 for (int i = 0; i < packageNames.length; i++) {
11908 String packageName = packageNames[i];
11909 boolean changed = false;
11911 synchronized (mPackages) {
11912 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11913 if (pkgSetting == null) {
11914 Slog.w(TAG, "Could not find package setting for package \"" + packageName
11915 + "\". Skipping suspending/un-suspending.");
11916 unactionedPackages.add(packageName);
11919 appId = pkgSetting.appId;
11920 if (pkgSetting.getSuspended(userId) != suspended) {
11921 if (!canSuspendPackageForUserLocked(packageName, userId)) {
11922 unactionedPackages.add(packageName);
11925 pkgSetting.setSuspended(suspended, userId);
11926 mSettings.writePackageRestrictionsLPr(userId);
11928 changedPackages.add(packageName);
11932 if (changed && suspended) {
11933 killApplication(packageName, UserHandle.getUid(userId, appId),
11934 "suspending package");
11938 Binder.restoreCallingIdentity(callingId);
11941 if (!changedPackages.isEmpty()) {
11942 sendPackagesSuspendedForUser(changedPackages.toArray(
11943 new String[changedPackages.size()]), userId, suspended);
11946 return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11950 public boolean isPackageSuspendedForUser(String packageName, int userId) {
11951 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11952 true /* requireFullPermission */, false /* checkShell */,
11953 "isPackageSuspendedForUser for user " + userId);
11954 synchronized (mPackages) {
11955 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11956 if (pkgSetting == null) {
11957 throw new IllegalArgumentException("Unknown target package: " + packageName);
11959 return pkgSetting.getSuspended(userId);
11963 private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11964 if (isPackageDeviceAdmin(packageName, userId)) {
11965 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11966 + "\": has an active device admin");
11970 String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11971 if (packageName.equals(activeLauncherPackageName)) {
11972 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11973 + "\": contains the active launcher");
11977 if (packageName.equals(mRequiredInstallerPackage)) {
11978 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11979 + "\": required for package installation");
11983 if (packageName.equals(mRequiredUninstallerPackage)) {
11984 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11985 + "\": required for package uninstallation");
11989 if (packageName.equals(mRequiredVerifierPackage)) {
11990 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11991 + "\": required for package verification");
11995 if (packageName.equals(getDefaultDialerPackageName(userId))) {
11996 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11997 + "\": is the default dialer");
12001 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12002 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12003 + "\": protected package");
12010 private String getActiveLauncherPackageName(int userId) {
12011 Intent intent = new Intent(Intent.ACTION_MAIN);
12012 intent.addCategory(Intent.CATEGORY_HOME);
12013 ResolveInfo resolveInfo = resolveIntent(
12015 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12016 PackageManager.MATCH_DEFAULT_ONLY,
12019 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12022 private String getDefaultDialerPackageName(int userId) {
12023 synchronized (mPackages) {
12024 return mSettings.getDefaultDialerPackageNameLPw(userId);
12029 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12030 mContext.enforceCallingOrSelfPermission(
12031 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12032 "Only package verification agents can verify applications");
12034 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12035 final PackageVerificationResponse response = new PackageVerificationResponse(
12036 verificationCode, Binder.getCallingUid());
12038 msg.obj = response;
12039 mHandler.sendMessage(msg);
12043 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12044 long millisecondsToDelay) {
12045 mContext.enforceCallingOrSelfPermission(
12046 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12047 "Only package verification agents can extend verification timeouts");
12049 final PackageVerificationState state = mPendingVerification.get(id);
12050 final PackageVerificationResponse response = new PackageVerificationResponse(
12051 verificationCodeAtTimeout, Binder.getCallingUid());
12053 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12054 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12056 if (millisecondsToDelay < 0) {
12057 millisecondsToDelay = 0;
12059 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12060 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12061 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12064 if ((state != null) && !state.timeoutExtended()) {
12065 state.extendTimeout();
12067 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12069 msg.obj = response;
12070 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12074 private void broadcastPackageVerified(int verificationId, Uri packageUri,
12075 int verificationCode, UserHandle user) {
12076 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12077 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12078 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12079 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12080 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12082 mContext.sendBroadcastAsUser(intent, user,
12083 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12086 private ComponentName matchComponentForVerifier(String packageName,
12087 List<ResolveInfo> receivers) {
12088 ActivityInfo targetReceiver = null;
12090 final int NR = receivers.size();
12091 for (int i = 0; i < NR; i++) {
12092 final ResolveInfo info = receivers.get(i);
12093 if (info.activityInfo == null) {
12097 if (packageName.equals(info.activityInfo.packageName)) {
12098 targetReceiver = info.activityInfo;
12103 if (targetReceiver == null) {
12107 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12110 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12111 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12112 if (pkgInfo.verifiers.length == 0) {
12116 final int N = pkgInfo.verifiers.length;
12117 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12118 for (int i = 0; i < N; i++) {
12119 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12121 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12123 if (comp == null) {
12127 final int verifierUid = getUidForVerifier(verifierInfo);
12128 if (verifierUid == -1) {
12132 if (DEBUG_VERIFY) {
12133 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12134 + " with the correct signature");
12136 sufficientVerifiers.add(comp);
12137 verificationState.addSufficientVerifier(verifierUid);
12140 return sufficientVerifiers;
12143 private int getUidForVerifier(VerifierInfo verifierInfo) {
12144 synchronized (mPackages) {
12145 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12148 } else if (pkg.mSignatures.length != 1) {
12149 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12150 + " has more than one signature; ignoring");
12155 * If the public key of the package's signature does not match
12156 * our expected public key, then this is a different package and
12160 final byte[] expectedPublicKey;
12162 final Signature verifierSig = pkg.mSignatures[0];
12163 final PublicKey publicKey = verifierSig.getPublicKey();
12164 expectedPublicKey = publicKey.getEncoded();
12165 } catch (CertificateException e) {
12169 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12171 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12172 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12173 + " does not have the expected public key; ignoring");
12177 return pkg.applicationInfo.uid;
12182 public void finishPackageInstall(int token, boolean didLaunch) {
12183 enforceSystemOrRoot("Only the system is allowed to finish installs");
12185 if (DEBUG_INSTALL) {
12186 Slog.v(TAG, "BM finishing package install for " + token);
12188 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12190 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12191 mHandler.sendMessage(msg);
12195 * Get the verification agent timeout.
12197 * @return verification timeout in milliseconds
12199 private long getVerificationTimeout() {
12200 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12201 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12202 DEFAULT_VERIFICATION_TIMEOUT);
12206 * Get the default verification agent response code.
12208 * @return default verification response code
12210 private int getDefaultVerificationResponse() {
12211 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12212 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12213 DEFAULT_VERIFICATION_RESPONSE);
12217 * Check whether or not package verification has been enabled.
12219 * @return true if verification should be performed
12221 private boolean isVerificationEnabled(int userId, int installFlags) {
12222 if (!DEFAULT_VERIFY_ENABLE) {
12225 // Ephemeral apps don't get the full verification treatment
12226 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12227 if (DEBUG_EPHEMERAL) {
12228 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12233 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12235 // Check if installing from ADB
12236 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12237 // Do not run verification in a test harness environment
12238 if (ActivityManager.isRunningInTestHarness()) {
12241 if (ensureVerifyAppsEnabled) {
12244 // Check if the developer does not want package verification for ADB installs
12245 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12246 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12251 if (ensureVerifyAppsEnabled) {
12255 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12256 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12260 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12261 throws RemoteException {
12262 mContext.enforceCallingOrSelfPermission(
12263 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12264 "Only intentfilter verification agents can verify applications");
12266 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12267 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12268 Binder.getCallingUid(), verificationCode, failedDomains);
12270 msg.obj = response;
12271 mHandler.sendMessage(msg);
12275 public int getIntentVerificationStatus(String packageName, int userId) {
12276 synchronized (mPackages) {
12277 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12282 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12283 mContext.enforceCallingOrSelfPermission(
12284 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12286 boolean result = false;
12287 synchronized (mPackages) {
12288 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12291 scheduleWritePackageRestrictionsLocked(userId);
12297 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12298 String packageName) {
12299 synchronized (mPackages) {
12300 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12305 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12306 if (TextUtils.isEmpty(packageName)) {
12307 return ParceledListSlice.emptyList();
12309 synchronized (mPackages) {
12310 PackageParser.Package pkg = mPackages.get(packageName);
12311 if (pkg == null || pkg.activities == null) {
12312 return ParceledListSlice.emptyList();
12314 final int count = pkg.activities.size();
12315 ArrayList<IntentFilter> result = new ArrayList<>();
12316 for (int n=0; n<count; n++) {
12317 PackageParser.Activity activity = pkg.activities.get(n);
12318 if (activity.intents != null && activity.intents.size() > 0) {
12319 result.addAll(activity.intents);
12322 return new ParceledListSlice<>(result);
12327 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12328 mContext.enforceCallingOrSelfPermission(
12329 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12331 synchronized (mPackages) {
12332 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12333 if (packageName != null) {
12334 result |= updateIntentVerificationStatus(packageName,
12335 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12337 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12338 packageName, userId);
12345 public String getDefaultBrowserPackageName(int userId) {
12346 synchronized (mPackages) {
12347 return mSettings.getDefaultBrowserPackageNameLPw(userId);
12352 * Get the "allow unknown sources" setting.
12354 * @return the current "allow unknown sources" setting
12356 private int getUnknownSourcesSettings() {
12357 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12358 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12363 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12364 final int uid = Binder.getCallingUid();
12366 synchronized (mPackages) {
12367 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12368 if (targetPackageSetting == null) {
12369 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12372 PackageSetting installerPackageSetting;
12373 if (installerPackageName != null) {
12374 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12375 if (installerPackageSetting == null) {
12376 throw new IllegalArgumentException("Unknown installer package: "
12377 + installerPackageName);
12380 installerPackageSetting = null;
12383 Signature[] callerSignature;
12384 Object obj = mSettings.getUserIdLPr(uid);
12386 if (obj instanceof SharedUserSetting) {
12387 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12388 } else if (obj instanceof PackageSetting) {
12389 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12391 throw new SecurityException("Bad object " + obj + " for uid " + uid);
12394 throw new SecurityException("Unknown calling UID: " + uid);
12397 // Verify: can't set installerPackageName to a package that is
12398 // not signed with the same cert as the caller.
12399 if (installerPackageSetting != null) {
12400 if (compareSignatures(callerSignature,
12401 installerPackageSetting.signatures.mSignatures)
12402 != PackageManager.SIGNATURE_MATCH) {
12403 throw new SecurityException(
12404 "Caller does not have same cert as new installer package "
12405 + installerPackageName);
12409 // Verify: if target already has an installer package, it must
12410 // be signed with the same cert as the caller.
12411 if (targetPackageSetting.installerPackageName != null) {
12412 PackageSetting setting = mSettings.mPackages.get(
12413 targetPackageSetting.installerPackageName);
12414 // If the currently set package isn't valid, then it's always
12415 // okay to change it.
12416 if (setting != null) {
12417 if (compareSignatures(callerSignature,
12418 setting.signatures.mSignatures)
12419 != PackageManager.SIGNATURE_MATCH) {
12420 throw new SecurityException(
12421 "Caller does not have same cert as old installer package "
12422 + targetPackageSetting.installerPackageName);
12428 targetPackageSetting.installerPackageName = installerPackageName;
12429 if (installerPackageName != null) {
12430 mSettings.mInstallerPackages.add(installerPackageName);
12432 scheduleWriteSettingsLocked();
12436 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12437 // Queue up an async operation since the package installation may take a little while.
12438 mHandler.post(new Runnable() {
12439 public void run() {
12440 mHandler.removeCallbacks(this);
12441 // Result object to be returned
12442 PackageInstalledInfo res = new PackageInstalledInfo();
12443 res.setReturnCode(currentStatus);
12446 res.removedInfo = null;
12447 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12448 args.doPreInstall(res.returnCode);
12449 synchronized (mInstallLock) {
12450 installPackageTracedLI(args, res);
12452 args.doPostInstall(res.returnCode, res.uid);
12455 // A restore should be performed at this point if (a) the install
12456 // succeeded, (b) the operation is not an update, and (c) the new
12457 // package has not opted out of backup participation.
12458 final boolean update = res.removedInfo != null
12459 && res.removedInfo.removedPackage != null;
12460 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12461 boolean doRestore = !update
12462 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12464 // Set up the post-install work request bookkeeping. This will be used
12465 // and cleaned up by the post-install event handling regardless of whether
12466 // there's a restore pass performed. Token values are >= 1.
12468 if (mNextInstallToken < 0) mNextInstallToken = 1;
12469 token = mNextInstallToken++;
12471 PostInstallData data = new PostInstallData(args, res);
12472 mRunningInstalls.put(token, data);
12473 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12475 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12476 // Pass responsibility to the Backup Manager. It will perform a
12477 // restore if appropriate, then pass responsibility back to the
12478 // Package Manager to run the post-install observer callbacks
12480 IBackupManager bm = IBackupManager.Stub.asInterface(
12481 ServiceManager.getService(Context.BACKUP_SERVICE));
12483 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12484 + " to BM for possible restore");
12485 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12487 // TODO: http://b/22388012
12488 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12489 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12493 } catch (RemoteException e) {
12494 // can't happen; the backup manager is local
12495 } catch (Exception e) {
12496 Slog.e(TAG, "Exception trying to enqueue restore", e);
12500 Slog.e(TAG, "Backup Manager not found!");
12506 // No restore possible, or the Backup Manager was mysteriously not
12507 // available -- just fire the post-install work request directly.
12508 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12510 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12512 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12513 mHandler.sendMessage(msg);
12520 * Callback from PackageSettings whenever an app is first transitioned out of the
12521 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if
12522 * the app was "launched" for a restoreAtInstall operation. Therefore we check
12523 * here whether the app is the target of an ongoing install, and only send the
12524 * broadcast immediately if it is not in that state. If it *is* undergoing a restore,
12525 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12528 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12529 // Serialize this with the rest of the install-process message chain. In the
12530 // restore-at-install case, this Runnable will necessarily run before the
12531 // POST_INSTALL message is processed, so the contents of mRunningInstalls
12532 // are coherent. In the non-restore case, the app has already completed install
12533 // and been launched through some other means, so it is not in a problematic
12534 // state for observers to see the FIRST_LAUNCH signal.
12535 mHandler.post(new Runnable() {
12537 public void run() {
12538 for (int i = 0; i < mRunningInstalls.size(); i++) {
12539 final PostInstallData data = mRunningInstalls.valueAt(i);
12540 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12543 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12544 // right package; but is it for the right user?
12545 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12546 if (userId == data.res.newUsers[uIndex]) {
12547 if (DEBUG_BACKUP) {
12548 Slog.i(TAG, "Package " + pkgName
12549 + " being restored so deferring FIRST_LAUNCH");
12556 // didn't find it, so not being restored
12557 if (DEBUG_BACKUP) {
12558 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12560 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12565 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12566 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12567 installerPkg, null, userIds);
12570 private abstract class HandlerParams {
12571 private static final int MAX_RETRIES = 4;
12574 * Number of times startCopy() has been attempted and had a non-fatal
12577 private int mRetries = 0;
12579 /** User handle for the user requesting the information or installation. */
12580 private final UserHandle mUser;
12581 String traceMethod;
12584 HandlerParams(UserHandle user) {
12588 UserHandle getUser() {
12592 HandlerParams setTraceMethod(String traceMethod) {
12593 this.traceMethod = traceMethod;
12597 HandlerParams setTraceCookie(int traceCookie) {
12598 this.traceCookie = traceCookie;
12602 final boolean startCopy() {
12605 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12607 if (++mRetries > MAX_RETRIES) {
12608 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12609 mHandler.sendEmptyMessage(MCS_GIVE_UP);
12610 handleServiceError();
12616 } catch (RemoteException e) {
12617 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12618 mHandler.sendEmptyMessage(MCS_RECONNECT);
12621 handleReturnCode();
12625 final void serviceError() {
12626 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12627 handleServiceError();
12628 handleReturnCode();
12631 abstract void handleStartCopy() throws RemoteException;
12632 abstract void handleServiceError();
12633 abstract void handleReturnCode();
12636 class MeasureParams extends HandlerParams {
12637 private final PackageStats mStats;
12638 private boolean mSuccess;
12640 private final IPackageStatsObserver mObserver;
12642 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12643 super(new UserHandle(stats.userHandle));
12644 mObserver = observer;
12649 public String toString() {
12650 return "MeasureParams{"
12651 + Integer.toHexString(System.identityHashCode(this))
12652 + " " + mStats.packageName + "}";
12656 void handleStartCopy() throws RemoteException {
12657 synchronized (mInstallLock) {
12658 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12662 boolean mounted = false;
12664 final String status = Environment.getExternalStorageState();
12665 mounted = (Environment.MEDIA_MOUNTED.equals(status)
12666 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12667 } catch (Exception e) {
12671 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12673 mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12674 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12676 mStats.externalDataSize = calculateDirectorySize(mContainerService,
12677 userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12679 // Always subtract cache size, since it's a subdirectory
12680 mStats.externalDataSize -= mStats.externalCacheSize;
12682 mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12683 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12685 mStats.externalObbSize = calculateDirectorySize(mContainerService,
12686 userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12692 void handleReturnCode() {
12693 if (mObserver != null) {
12695 mObserver.onGetStatsCompleted(mStats, mSuccess);
12696 } catch (RemoteException e) {
12697 Slog.i(TAG, "Observer no longer exists.");
12703 void handleServiceError() {
12704 Slog.e(TAG, "Could not measure application " + mStats.packageName
12705 + " external storage");
12709 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12710 throws RemoteException {
12712 for (File path : paths) {
12713 result += mcs.calculateDirectorySize(path.getAbsolutePath());
12718 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12719 for (File path : paths) {
12721 mcs.clearDirectory(path.getAbsolutePath());
12722 } catch (RemoteException e) {
12727 static class OriginInfo {
12729 * Location where install is coming from, before it has been
12730 * copied/renamed into place. This could be a single monolithic APK
12731 * file, or a cluster directory. This location may be untrusted.
12737 * Flag indicating that {@link #file} or {@link #cid} has already been
12738 * staged, meaning downstream users don't need to defensively copy the
12741 final boolean staged;
12744 * Flag indicating that {@link #file} or {@link #cid} is an already
12745 * installed app that is being moved.
12747 final boolean existing;
12749 final String resolvedPath;
12750 final File resolvedFile;
12752 static OriginInfo fromNothing() {
12753 return new OriginInfo(null, null, false, false);
12756 static OriginInfo fromUntrustedFile(File file) {
12757 return new OriginInfo(file, null, false, false);
12760 static OriginInfo fromExistingFile(File file) {
12761 return new OriginInfo(file, null, false, true);
12764 static OriginInfo fromStagedFile(File file) {
12765 return new OriginInfo(file, null, true, false);
12768 static OriginInfo fromStagedContainer(String cid) {
12769 return new OriginInfo(null, cid, true, false);
12772 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12775 this.staged = staged;
12776 this.existing = existing;
12779 resolvedPath = PackageHelper.getSdDir(cid);
12780 resolvedFile = new File(resolvedPath);
12781 } else if (file != null) {
12782 resolvedPath = file.getAbsolutePath();
12783 resolvedFile = file;
12785 resolvedPath = null;
12786 resolvedFile = null;
12791 static class MoveInfo {
12793 final String fromUuid;
12794 final String toUuid;
12795 final String packageName;
12796 final String dataAppName;
12798 final String seinfo;
12799 final int targetSdkVersion;
12801 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12802 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12803 this.moveId = moveId;
12804 this.fromUuid = fromUuid;
12805 this.toUuid = toUuid;
12806 this.packageName = packageName;
12807 this.dataAppName = dataAppName;
12808 this.appId = appId;
12809 this.seinfo = seinfo;
12810 this.targetSdkVersion = targetSdkVersion;
12814 static class VerificationInfo {
12815 /** A constant used to indicate that a uid value is not present. */
12816 public static final int NO_UID = -1;
12818 /** URI referencing where the package was downloaded from. */
12819 final Uri originatingUri;
12821 /** HTTP referrer URI associated with the originatingURI. */
12822 final Uri referrer;
12824 /** UID of the application that the install request originated from. */
12825 final int originatingUid;
12827 /** UID of application requesting the install */
12828 final int installerUid;
12830 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12831 this.originatingUri = originatingUri;
12832 this.referrer = referrer;
12833 this.originatingUid = originatingUid;
12834 this.installerUid = installerUid;
12838 class InstallParams extends HandlerParams {
12839 final OriginInfo origin;
12840 final MoveInfo move;
12841 final IPackageInstallObserver2 observer;
12843 final String installerPackageName;
12844 final String volumeUuid;
12845 private InstallArgs mArgs;
12847 final String packageAbiOverride;
12848 final String[] grantedRuntimePermissions;
12849 final VerificationInfo verificationInfo;
12850 final Certificate[][] certificates;
12852 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12853 int installFlags, String installerPackageName, String volumeUuid,
12854 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12855 String[] grantedPermissions, Certificate[][] certificates) {
12857 this.origin = origin;
12859 this.observer = observer;
12860 this.installFlags = installFlags;
12861 this.installerPackageName = installerPackageName;
12862 this.volumeUuid = volumeUuid;
12863 this.verificationInfo = verificationInfo;
12864 this.packageAbiOverride = packageAbiOverride;
12865 this.grantedRuntimePermissions = grantedPermissions;
12866 this.certificates = certificates;
12870 public String toString() {
12871 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12872 + " file=" + origin.file + " cid=" + origin.cid + "}";
12875 private int installLocationPolicy(PackageInfoLite pkgLite) {
12876 String packageName = pkgLite.packageName;
12877 int installLocation = pkgLite.installLocation;
12878 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12880 synchronized (mPackages) {
12881 // Currently installed package which the new package is attempting to replace or
12882 // null if no such package is installed.
12883 PackageParser.Package installedPkg = mPackages.get(packageName);
12884 // Package which currently owns the data which the new package will own if installed.
12885 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12886 // will be null whereas dataOwnerPkg will contain information about the package
12887 // which was uninstalled while keeping its data.
12888 PackageParser.Package dataOwnerPkg = installedPkg;
12889 if (dataOwnerPkg == null) {
12890 PackageSetting ps = mSettings.mPackages.get(packageName);
12892 dataOwnerPkg = ps.pkg;
12896 if (dataOwnerPkg != null) {
12897 // If installed, the package will get access to data left on the device by its
12898 // predecessor. As a security measure, this is permited only if this is not a
12899 // version downgrade or if the predecessor package is marked as debuggable and
12900 // a downgrade is explicitly requested.
12902 // On debuggable platform builds, downgrades are permitted even for
12903 // non-debuggable packages to make testing easier. Debuggable platform builds do
12904 // not offer security guarantees and thus it's OK to disable some security
12905 // mechanisms to make debugging/testing easier on those builds. However, even on
12906 // debuggable builds downgrades of packages are permitted only if requested via
12907 // installFlags. This is because we aim to keep the behavior of debuggable
12908 // platform builds as close as possible to the behavior of non-debuggable
12909 // platform builds.
12910 final boolean downgradeRequested =
12911 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12912 final boolean packageDebuggable =
12913 (dataOwnerPkg.applicationInfo.flags
12914 & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12915 final boolean downgradePermitted =
12916 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12917 if (!downgradePermitted) {
12919 checkDowngrade(dataOwnerPkg, pkgLite);
12920 } catch (PackageManagerException e) {
12921 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12922 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12927 if (installedPkg != null) {
12928 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12929 // Check for updated system application.
12930 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12932 Slog.w(TAG, "Cannot install update to system app on sdcard");
12933 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12935 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12938 // Install flag overrides everything.
12939 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12941 // If current upgrade specifies particular preference
12942 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12943 // Application explicitly specified internal.
12944 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12945 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12946 // App explictly prefers external. Let policy decide
12948 // Prefer previous location
12949 if (isExternal(installedPkg)) {
12950 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12952 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12956 // Invalid install. Return error code
12957 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12961 // All the special cases have been taken care of.
12962 // Return result based on recommended install location.
12964 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12966 return pkgLite.recommendedInstallLocation;
12970 * Invoke remote method to get package information and install
12971 * location values. Override install location based on default
12972 * policy if needed and then create install arguments based
12973 * on the install location.
12975 public void handleStartCopy() throws RemoteException {
12976 int ret = PackageManager.INSTALL_SUCCEEDED;
12978 // If we're already staged, we've firmly committed to an install location
12979 if (origin.staged) {
12980 if (origin.file != null) {
12981 installFlags |= PackageManager.INSTALL_INTERNAL;
12982 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12983 } else if (origin.cid != null) {
12984 installFlags |= PackageManager.INSTALL_EXTERNAL;
12985 installFlags &= ~PackageManager.INSTALL_INTERNAL;
12987 throw new IllegalStateException("Invalid stage location");
12991 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12992 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12993 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12994 PackageInfoLite pkgLite = null;
12996 if (onInt && onSd) {
12997 // Check if both bits are set.
12998 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12999 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13000 } else if (onSd && ephemeral) {
13001 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external");
13002 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13004 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13005 packageAbiOverride);
13007 if (DEBUG_EPHEMERAL && ephemeral) {
13008 Slog.v(TAG, "pkgLite for install: " + pkgLite);
13012 * If we have too little free space, try to free cache
13013 * before giving up.
13015 if (!origin.staged && pkgLite.recommendedInstallLocation
13016 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13017 // TODO: focus freeing disk space on the target device
13018 final StorageManager storage = StorageManager.from(mContext);
13019 final long lowThreshold = storage.getStorageLowBytes(
13020 Environment.getDataDirectory());
13022 final long sizeBytes = mContainerService.calculateInstalledSize(
13023 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13026 mInstaller.freeCache(null, sizeBytes + lowThreshold);
13027 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13028 installFlags, packageAbiOverride);
13029 } catch (InstallerException e) {
13030 Slog.w(TAG, "Failed to free cache", e);
13034 * The cache free must have deleted the file we
13035 * downloaded to install.
13037 * TODO: fix the "freeCache" call to not delete
13038 * the file we care about.
13040 if (pkgLite.recommendedInstallLocation
13041 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13042 pkgLite.recommendedInstallLocation
13043 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13048 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13049 int loc = pkgLite.recommendedInstallLocation;
13050 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13051 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13052 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13053 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13054 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13055 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13056 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13057 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13058 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13059 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13060 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13061 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13063 // Override with defaults if needed.
13064 loc = installLocationPolicy(pkgLite);
13065 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13066 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13067 } else if (!onSd && !onInt) {
13068 // Override install location with flags
13069 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13070 // Set the flag to install on external media.
13071 installFlags |= PackageManager.INSTALL_EXTERNAL;
13072 installFlags &= ~PackageManager.INSTALL_INTERNAL;
13073 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13074 if (DEBUG_EPHEMERAL) {
13075 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13077 installFlags |= PackageManager.INSTALL_EPHEMERAL;
13078 installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13079 |PackageManager.INSTALL_INTERNAL);
13081 // Make sure the flag for installing on external
13083 installFlags |= PackageManager.INSTALL_INTERNAL;
13084 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13090 final InstallArgs args = createInstallArgs(this);
13093 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13094 // TODO: http://b/22976637
13095 // Apps installed for "all" users use the device owner to verify the app
13096 UserHandle verifierUser = getUser();
13097 if (verifierUser == UserHandle.ALL) {
13098 verifierUser = UserHandle.SYSTEM;
13102 * Determine if we have any installed package verifiers. If we
13103 * do, then we'll defer to them to verify the packages.
13105 final int requiredUid = mRequiredVerifierPackage == null ? -1
13106 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13107 verifierUser.getIdentifier());
13108 if (!origin.existing && requiredUid != -1
13109 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13110 final Intent verification = new Intent(
13111 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13112 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13113 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13114 PACKAGE_MIME_TYPE);
13115 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13117 // Query all live verifiers based on current user state
13118 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13119 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13121 if (DEBUG_VERIFY) {
13122 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13123 + verification.toString() + " with " + pkgLite.verifiers.length
13124 + " optional verifiers");
13127 final int verificationId = mPendingVerificationToken++;
13129 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13131 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13132 installerPackageName);
13134 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13137 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13138 pkgLite.packageName);
13140 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13141 pkgLite.versionCode);
13143 if (verificationInfo != null) {
13144 if (verificationInfo.originatingUri != null) {
13145 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13146 verificationInfo.originatingUri);
13148 if (verificationInfo.referrer != null) {
13149 verification.putExtra(Intent.EXTRA_REFERRER,
13150 verificationInfo.referrer);
13152 if (verificationInfo.originatingUid >= 0) {
13153 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13154 verificationInfo.originatingUid);
13156 if (verificationInfo.installerUid >= 0) {
13157 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13158 verificationInfo.installerUid);
13162 final PackageVerificationState verificationState = new PackageVerificationState(
13163 requiredUid, args);
13165 mPendingVerification.append(verificationId, verificationState);
13167 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13168 receivers, verificationState);
13171 * If any sufficient verifiers were listed in the package
13172 * manifest, attempt to ask them.
13174 if (sufficientVerifiers != null) {
13175 final int N = sufficientVerifiers.size();
13177 Slog.i(TAG, "Additional verifiers required, but none installed.");
13178 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13180 for (int i = 0; i < N; i++) {
13181 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13183 final Intent sufficientIntent = new Intent(verification);
13184 sufficientIntent.setComponent(verifierComponent);
13185 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13190 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13191 mRequiredVerifierPackage, receivers);
13192 if (ret == PackageManager.INSTALL_SUCCEEDED
13193 && mRequiredVerifierPackage != null) {
13194 Trace.asyncTraceBegin(
13195 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13197 * Send the intent to the required verification agent,
13198 * but only start the verification timeout after the
13199 * target BroadcastReceivers have run.
13201 verification.setComponent(requiredVerifierComponent);
13202 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13203 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13204 new BroadcastReceiver() {
13206 public void onReceive(Context context, Intent intent) {
13207 final Message msg = mHandler
13208 .obtainMessage(CHECK_PENDING_VERIFICATION);
13209 msg.arg1 = verificationId;
13210 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13212 }, null, 0, null, null);
13215 * We don't want the copy to proceed until verification
13216 * succeeds, so null out this field.
13222 * No package verification is enabled, so immediately start
13223 * the remote call to initiate copy using temporary file.
13225 ret = args.copyApk(mContainerService, true);
13233 void handleReturnCode() {
13234 // If mArgs is null, then MCS couldn't be reached. When it
13235 // reconnects, it will try again to install. At that point, this
13237 if (mArgs != null) {
13238 processPendingInstall(mArgs, mRet);
13243 void handleServiceError() {
13244 mArgs = createInstallArgs(this);
13245 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13248 public boolean isForwardLocked() {
13249 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13254 * Used during creation of InstallArgs
13256 * @param installFlags package installation flags
13257 * @return true if should be installed on external storage
13259 private static boolean installOnExternalAsec(int installFlags) {
13260 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13263 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13270 * Used during creation of InstallArgs
13272 * @param installFlags package installation flags
13273 * @return true if should be installed as forward locked
13275 private static boolean installForwardLocked(int installFlags) {
13276 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13279 private InstallArgs createInstallArgs(InstallParams params) {
13280 if (params.move != null) {
13281 return new MoveInstallArgs(params);
13282 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13283 return new AsecInstallArgs(params);
13285 return new FileInstallArgs(params);
13290 * Create args that describe an existing installed package. Typically used
13291 * when cleaning up old installs, or used as a move source.
13293 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13294 String resourcePath, String[] instructionSets) {
13295 final boolean isInAsec;
13296 if (installOnExternalAsec(installFlags)) {
13297 /* Apps on SD card are always in ASEC containers. */
13299 } else if (installForwardLocked(installFlags)
13300 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13302 * Forward-locked apps are only in ASEC containers if they're the
13311 return new AsecInstallArgs(codePath, instructionSets,
13312 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13314 return new FileInstallArgs(codePath, resourcePath, instructionSets);
13318 static abstract class InstallArgs {
13319 /** @see InstallParams#origin */
13320 final OriginInfo origin;
13321 /** @see InstallParams#move */
13322 final MoveInfo move;
13324 final IPackageInstallObserver2 observer;
13325 // Always refers to PackageManager flags only
13326 final int installFlags;
13327 final String installerPackageName;
13328 final String volumeUuid;
13329 final UserHandle user;
13330 final String abiOverride;
13331 final String[] installGrantPermissions;
13332 /** If non-null, drop an async trace when the install completes */
13333 final String traceMethod;
13334 final int traceCookie;
13335 final Certificate[][] certificates;
13337 // The list of instruction sets supported by this app. This is currently
13338 // only used during the rmdex() phase to clean up resources. We can get rid of this
13339 // if we move dex files under the common app path.
13340 /* nullable */ String[] instructionSets;
13342 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13343 int installFlags, String installerPackageName, String volumeUuid,
13344 UserHandle user, String[] instructionSets,
13345 String abiOverride, String[] installGrantPermissions,
13346 String traceMethod, int traceCookie, Certificate[][] certificates) {
13347 this.origin = origin;
13349 this.installFlags = installFlags;
13350 this.observer = observer;
13351 this.installerPackageName = installerPackageName;
13352 this.volumeUuid = volumeUuid;
13354 this.instructionSets = instructionSets;
13355 this.abiOverride = abiOverride;
13356 this.installGrantPermissions = installGrantPermissions;
13357 this.traceMethod = traceMethod;
13358 this.traceCookie = traceCookie;
13359 this.certificates = certificates;
13362 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13363 abstract int doPreInstall(int status);
13366 * Rename package into final resting place. All paths on the given
13367 * scanned package should be updated to reflect the rename.
13369 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13370 abstract int doPostInstall(int status, int uid);
13372 /** @see PackageSettingBase#codePathString */
13373 abstract String getCodePath();
13374 /** @see PackageSettingBase#resourcePathString */
13375 abstract String getResourcePath();
13377 // Need installer lock especially for dex file removal.
13378 abstract void cleanUpResourcesLI();
13379 abstract boolean doPostDeleteLI(boolean delete);
13382 * Called before the source arguments are copied. This is used mostly
13383 * for MoveParams when it needs to read the source file to put it in the
13387 return PackageManager.INSTALL_SUCCEEDED;
13391 * Called after the source arguments are copied. This is used mostly for
13392 * MoveParams when it needs to read the source file to put it in the
13395 int doPostCopy(int uid) {
13396 return PackageManager.INSTALL_SUCCEEDED;
13399 protected boolean isFwdLocked() {
13400 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13403 protected boolean isExternalAsec() {
13404 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13407 protected boolean isEphemeral() {
13408 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13411 UserHandle getUser() {
13416 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13417 if (!allCodePaths.isEmpty()) {
13418 if (instructionSets == null) {
13419 throw new IllegalStateException("instructionSet == null");
13421 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13422 for (String codePath : allCodePaths) {
13423 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13425 mInstaller.rmdex(codePath, dexCodeInstructionSet);
13426 } catch (InstallerException ignored) {
13434 * Logic to handle installation of non-ASEC applications, including copying
13435 * and renaming logic.
13437 class FileInstallArgs extends InstallArgs {
13438 private File codeFile;
13439 private File resourceFile;
13441 // Example topology:
13442 // /data/app/com.example/base.apk
13443 // /data/app/com.example/split_foo.apk
13444 // /data/app/com.example/lib/arm/libfoo.so
13445 // /data/app/com.example/lib/arm64/libfoo.so
13446 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13449 FileInstallArgs(InstallParams params) {
13450 super(params.origin, params.move, params.observer, params.installFlags,
13451 params.installerPackageName, params.volumeUuid,
13452 params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13453 params.grantedRuntimePermissions,
13454 params.traceMethod, params.traceCookie, params.certificates);
13455 if (isFwdLocked()) {
13456 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13460 /** Existing install */
13461 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13462 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13463 null, null, null, 0, null /*certificates*/);
13464 this.codeFile = (codePath != null) ? new File(codePath) : null;
13465 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13468 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13469 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13471 return doCopyApk(imcs, temp);
13473 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13477 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13478 if (origin.staged) {
13479 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13480 codeFile = origin.file;
13481 resourceFile = origin.file;
13482 return PackageManager.INSTALL_SUCCEEDED;
13486 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13487 final File tempDir =
13488 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13489 codeFile = tempDir;
13490 resourceFile = tempDir;
13491 } catch (IOException e) {
13492 Slog.w(TAG, "Failed to create copy file: " + e);
13493 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13496 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13498 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13499 if (!FileUtils.isValidExtFilename(name)) {
13500 throw new IllegalArgumentException("Invalid filename: " + name);
13503 final File file = new File(codeFile, name);
13504 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13505 O_RDWR | O_CREAT, 0644);
13506 Os.chmod(file.getAbsolutePath(), 0644);
13507 return new ParcelFileDescriptor(fd);
13508 } catch (ErrnoException e) {
13509 throw new RemoteException("Failed to open: " + e.getMessage());
13514 int ret = PackageManager.INSTALL_SUCCEEDED;
13515 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13516 if (ret != PackageManager.INSTALL_SUCCEEDED) {
13517 Slog.e(TAG, "Failed to copy package");
13521 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13522 NativeLibraryHelper.Handle handle = null;
13524 handle = NativeLibraryHelper.Handle.create(codeFile);
13525 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13527 } catch (IOException e) {
13528 Slog.e(TAG, "Copying native libraries failed", e);
13529 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13531 IoUtils.closeQuietly(handle);
13537 int doPreInstall(int status) {
13538 if (status != PackageManager.INSTALL_SUCCEEDED) {
13544 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13545 if (status != PackageManager.INSTALL_SUCCEEDED) {
13550 final File targetDir = codeFile.getParentFile();
13551 final File beforeCodeFile = codeFile;
13552 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13554 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13556 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13557 } catch (ErrnoException e) {
13558 Slog.w(TAG, "Failed to rename", e);
13562 if (!SELinux.restoreconRecursive(afterCodeFile)) {
13563 Slog.w(TAG, "Failed to restorecon");
13567 // Reflect the rename internally
13568 codeFile = afterCodeFile;
13569 resourceFile = afterCodeFile;
13571 // Reflect the rename in scanned details
13572 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13573 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13574 afterCodeFile, pkg.baseCodePath));
13575 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13576 afterCodeFile, pkg.splitCodePaths));
13578 // Reflect the rename in app info
13579 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13580 pkg.setApplicationInfoCodePath(pkg.codePath);
13581 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13582 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13583 pkg.setApplicationInfoResourcePath(pkg.codePath);
13584 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13585 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13590 int doPostInstall(int status, int uid) {
13591 if (status != PackageManager.INSTALL_SUCCEEDED) {
13598 String getCodePath() {
13599 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13603 String getResourcePath() {
13604 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13607 private boolean cleanUp() {
13608 if (codeFile == null || !codeFile.exists()) {
13612 removeCodePathLI(codeFile);
13614 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13615 resourceFile.delete();
13621 void cleanUpResourcesLI() {
13622 // Try enumerating all code paths before deleting
13623 List<String> allCodePaths = Collections.EMPTY_LIST;
13624 if (codeFile != null && codeFile.exists()) {
13626 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13627 allCodePaths = pkg.getAllCodePaths();
13628 } catch (PackageParserException e) {
13629 // Ignored; we tried our best
13634 removeDexFiles(allCodePaths, instructionSets);
13637 boolean doPostDeleteLI(boolean delete) {
13638 // XXX err, shouldn't we respect the delete flag?
13639 cleanUpResourcesLI();
13644 private boolean isAsecExternal(String cid) {
13645 final String asecPath = PackageHelper.getSdFilesystem(cid);
13646 return !asecPath.startsWith(mAsecInternalPath);
13649 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13650 PackageManagerException {
13652 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13653 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13654 throw new PackageManagerException(copyRet, message);
13660 * Extract the MountService "container ID" from the full code path of an
13663 static String cidFromCodePath(String fullCodePath) {
13664 int eidx = fullCodePath.lastIndexOf("/");
13665 String subStr1 = fullCodePath.substring(0, eidx);
13666 int sidx = subStr1.lastIndexOf("/");
13667 return subStr1.substring(sidx+1, eidx);
13671 * Logic to handle installation of ASEC applications, including copying and
13674 class AsecInstallArgs extends InstallArgs {
13675 static final String RES_FILE_NAME = "pkg.apk";
13676 static final String PUBLIC_RES_FILE_NAME = "res.zip";
13679 String packagePath;
13680 String resourcePath;
13683 AsecInstallArgs(InstallParams params) {
13684 super(params.origin, params.move, params.observer, params.installFlags,
13685 params.installerPackageName, params.volumeUuid,
13686 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13687 params.grantedRuntimePermissions,
13688 params.traceMethod, params.traceCookie, params.certificates);
13691 /** Existing install */
13692 AsecInstallArgs(String fullCodePath, String[] instructionSets,
13693 boolean isExternal, boolean isForwardLocked) {
13694 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13695 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13696 instructionSets, null, null, null, 0, null /*certificates*/);
13697 // Hackily pretend we're still looking at a full code path
13698 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13699 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13702 // Extract cid from fullCodePath
13703 int eidx = fullCodePath.lastIndexOf("/");
13704 String subStr1 = fullCodePath.substring(0, eidx);
13705 int sidx = subStr1.lastIndexOf("/");
13706 cid = subStr1.substring(sidx+1, eidx);
13707 setMountPath(subStr1);
13710 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13711 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13712 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13713 instructionSets, null, null, null, 0, null /*certificates*/);
13715 setMountPath(PackageHelper.getSdDir(cid));
13718 void createCopyFile() {
13719 cid = mInstallerService.allocateExternalStageCidLegacy();
13722 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13723 if (origin.staged && origin.cid != null) {
13724 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13726 setMountPath(PackageHelper.getSdDir(cid));
13727 return PackageManager.INSTALL_SUCCEEDED;
13734 * Pre-emptively destroy the container since it's destroyed if
13735 * copying fails due to it existing anyway.
13737 PackageHelper.destroySdDir(cid);
13740 final String newMountPath = imcs.copyPackageToContainer(
13741 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13742 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13744 if (newMountPath != null) {
13745 setMountPath(newMountPath);
13746 return PackageManager.INSTALL_SUCCEEDED;
13748 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13753 String getCodePath() {
13754 return packagePath;
13758 String getResourcePath() {
13759 return resourcePath;
13762 int doPreInstall(int status) {
13763 if (status != PackageManager.INSTALL_SUCCEEDED) {
13764 // Destroy container
13765 PackageHelper.destroySdDir(cid);
13767 boolean mounted = PackageHelper.isContainerMounted(cid);
13769 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13770 Process.SYSTEM_UID);
13771 if (newMountPath != null) {
13772 setMountPath(newMountPath);
13774 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13781 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13782 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13783 String newMountPath = null;
13784 if (PackageHelper.isContainerMounted(cid)) {
13785 // Unmount the container
13786 if (!PackageHelper.unMountSdDir(cid)) {
13787 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13791 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13792 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13793 " which might be stale. Will try to clean up.");
13794 // Clean up the stale container and proceed to recreate.
13795 if (!PackageHelper.destroySdDir(newCacheId)) {
13796 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13799 // Successfully cleaned up stale container. Try to rename again.
13800 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13801 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13802 + " inspite of cleaning it up.");
13806 if (!PackageHelper.isContainerMounted(newCacheId)) {
13807 Slog.w(TAG, "Mounting container " + newCacheId);
13808 newMountPath = PackageHelper.mountSdDir(newCacheId,
13809 getEncryptKey(), Process.SYSTEM_UID);
13811 newMountPath = PackageHelper.getSdDir(newCacheId);
13813 if (newMountPath == null) {
13814 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
13817 Log.i(TAG, "Succesfully renamed " + cid +
13818 " to " + newCacheId +
13819 " at new path: " + newMountPath);
13822 final File beforeCodeFile = new File(packagePath);
13823 setMountPath(newMountPath);
13824 final File afterCodeFile = new File(packagePath);
13826 // Reflect the rename in scanned details
13827 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13828 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13829 afterCodeFile, pkg.baseCodePath));
13830 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13831 afterCodeFile, pkg.splitCodePaths));
13833 // Reflect the rename in app info
13834 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13835 pkg.setApplicationInfoCodePath(pkg.codePath);
13836 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13837 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13838 pkg.setApplicationInfoResourcePath(pkg.codePath);
13839 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13840 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13845 private void setMountPath(String mountPath) {
13846 final File mountFile = new File(mountPath);
13848 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13849 if (monolithicFile.exists()) {
13850 packagePath = monolithicFile.getAbsolutePath();
13851 if (isFwdLocked()) {
13852 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13854 resourcePath = packagePath;
13857 packagePath = mountFile.getAbsolutePath();
13858 resourcePath = packagePath;
13862 int doPostInstall(int status, int uid) {
13863 if (status != PackageManager.INSTALL_SUCCEEDED) {
13866 final int groupOwner;
13867 final String protectedFile;
13868 if (isFwdLocked()) {
13869 groupOwner = UserHandle.getSharedAppGid(uid);
13870 protectedFile = RES_FILE_NAME;
13873 protectedFile = null;
13876 if (uid < Process.FIRST_APPLICATION_UID
13877 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13878 Slog.e(TAG, "Failed to finalize " + cid);
13879 PackageHelper.destroySdDir(cid);
13880 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13883 boolean mounted = PackageHelper.isContainerMounted(cid);
13885 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13891 private void cleanUp() {
13892 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13894 // Destroy secure container
13895 PackageHelper.destroySdDir(cid);
13898 private List<String> getAllCodePaths() {
13899 final File codeFile = new File(getCodePath());
13900 if (codeFile != null && codeFile.exists()) {
13902 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13903 return pkg.getAllCodePaths();
13904 } catch (PackageParserException e) {
13905 // Ignored; we tried our best
13908 return Collections.EMPTY_LIST;
13911 void cleanUpResourcesLI() {
13912 // Enumerate all code paths before deleting
13913 cleanUpResourcesLI(getAllCodePaths());
13916 private void cleanUpResourcesLI(List<String> allCodePaths) {
13918 removeDexFiles(allCodePaths, instructionSets);
13921 String getPackageName() {
13922 return getAsecPackageName(cid);
13925 boolean doPostDeleteLI(boolean delete) {
13926 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13927 final List<String> allCodePaths = getAllCodePaths();
13928 boolean mounted = PackageHelper.isContainerMounted(cid);
13931 if (PackageHelper.unMountSdDir(cid)) {
13935 if (!mounted && delete) {
13936 cleanUpResourcesLI(allCodePaths);
13943 if (isFwdLocked()) {
13944 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13945 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13946 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13950 return PackageManager.INSTALL_SUCCEEDED;
13954 int doPostCopy(int uid) {
13955 if (isFwdLocked()) {
13956 if (uid < Process.FIRST_APPLICATION_UID
13957 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13959 Slog.e(TAG, "Failed to finalize " + cid);
13960 PackageHelper.destroySdDir(cid);
13961 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13965 return PackageManager.INSTALL_SUCCEEDED;
13970 * Logic to handle movement of existing installed applications.
13972 class MoveInstallArgs extends InstallArgs {
13973 private File codeFile;
13974 private File resourceFile;
13977 MoveInstallArgs(InstallParams params) {
13978 super(params.origin, params.move, params.observer, params.installFlags,
13979 params.installerPackageName, params.volumeUuid,
13980 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13981 params.grantedRuntimePermissions,
13982 params.traceMethod, params.traceCookie, params.certificates);
13985 int copyApk(IMediaContainerService imcs, boolean temp) {
13986 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13987 + move.fromUuid + " to " + move.toUuid);
13988 synchronized (mInstaller) {
13990 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13991 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13992 } catch (InstallerException e) {
13993 Slog.w(TAG, "Failed to move app", e);
13994 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13998 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13999 resourceFile = codeFile;
14000 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14002 return PackageManager.INSTALL_SUCCEEDED;
14005 int doPreInstall(int status) {
14006 if (status != PackageManager.INSTALL_SUCCEEDED) {
14007 cleanUp(move.toUuid);
14012 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14013 if (status != PackageManager.INSTALL_SUCCEEDED) {
14014 cleanUp(move.toUuid);
14018 // Reflect the move in app info
14019 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14020 pkg.setApplicationInfoCodePath(pkg.codePath);
14021 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14022 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14023 pkg.setApplicationInfoResourcePath(pkg.codePath);
14024 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14025 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14030 int doPostInstall(int status, int uid) {
14031 if (status == PackageManager.INSTALL_SUCCEEDED) {
14032 cleanUp(move.fromUuid);
14034 cleanUp(move.toUuid);
14040 String getCodePath() {
14041 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14045 String getResourcePath() {
14046 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14049 private boolean cleanUp(String volumeUuid) {
14050 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14052 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14053 final int[] userIds = sUserManager.getUserIds();
14054 synchronized (mInstallLock) {
14055 // Clean up both app data and code
14056 // All package moves are frozen until finished
14057 for (int userId : userIds) {
14059 mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14060 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14061 } catch (InstallerException e) {
14062 Slog.w(TAG, String.valueOf(e));
14065 removeCodePathLI(codeFile);
14070 void cleanUpResourcesLI() {
14071 throw new UnsupportedOperationException();
14074 boolean doPostDeleteLI(boolean delete) {
14075 throw new UnsupportedOperationException();
14079 static String getAsecPackageName(String packageCid) {
14080 int idx = packageCid.lastIndexOf("-");
14084 return packageCid.substring(0, idx);
14087 // Utility method used to create code paths based on package name and available index.
14088 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14089 String idxStr = "";
14091 // Fall back to default value of idx=1 if prefix is not
14092 // part of oldCodePath
14093 if (oldCodePath != null) {
14094 String subStr = oldCodePath;
14095 // Drop the suffix right away
14096 if (suffix != null && subStr.endsWith(suffix)) {
14097 subStr = subStr.substring(0, subStr.length() - suffix.length());
14099 // If oldCodePath already contains prefix find out the
14100 // ending index to either increment or decrement.
14101 int sidx = subStr.lastIndexOf(prefix);
14103 subStr = subStr.substring(sidx + prefix.length());
14104 if (subStr != null) {
14105 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14106 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14109 idx = Integer.parseInt(subStr);
14115 } catch(NumberFormatException e) {
14120 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14121 return prefix + idxStr;
14124 private File getNextCodePath(File targetDir, String packageName) {
14128 result = new File(targetDir, packageName + "-" + suffix);
14130 } while (result.exists());
14134 // Utility method that returns the relative package path with respect
14135 // to the installation directory. Like say for /data/data/com.test-1.apk
14136 // string com.test-1 is returned.
14137 static String deriveCodePathName(String codePath) {
14138 if (codePath == null) {
14141 final File codeFile = new File(codePath);
14142 final String name = codeFile.getName();
14143 if (codeFile.isDirectory()) {
14145 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14146 final int lastDot = name.lastIndexOf('.');
14147 return name.substring(0, lastDot);
14149 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14154 static class PackageInstalledInfo {
14157 // The set of users that originally had this package installed.
14159 // The set of users that now have this package installed.
14161 PackageParser.Package pkg;
14164 PackageRemovedInfo removedInfo;
14165 ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14167 public void setError(int code, String msg) {
14168 setReturnCode(code);
14169 setReturnMessage(msg);
14173 public void setError(String msg, PackageParserException e) {
14174 setReturnCode(e.error);
14175 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14176 Slog.w(TAG, msg, e);
14179 public void setError(String msg, PackageManagerException e) {
14180 returnCode = e.error;
14181 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14182 Slog.w(TAG, msg, e);
14185 public void setReturnCode(int returnCode) {
14186 this.returnCode = returnCode;
14187 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14188 for (int i = 0; i < childCount; i++) {
14189 addedChildPackages.valueAt(i).returnCode = returnCode;
14193 private void setReturnMessage(String returnMsg) {
14194 this.returnMsg = returnMsg;
14195 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14196 for (int i = 0; i < childCount; i++) {
14197 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14201 // In some error cases we want to convey more info back to the observer
14202 String origPackage;
14203 String origPermission;
14207 * Install a non-existing package.
14209 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14210 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14211 PackageInstalledInfo res) {
14212 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14214 // Remember this for later, in case we need to rollback this install
14215 String pkgName = pkg.packageName;
14217 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14219 synchronized(mPackages) {
14220 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14221 // A package with the same name is already installed, though
14222 // it has been renamed to an older name. The package we
14223 // are trying to install should be installed as an update to
14224 // the existing one, but that has not been requested, so bail.
14225 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14226 + " without first uninstalling package running as "
14227 + mSettings.mRenamedPackages.get(pkgName));
14230 if (mPackages.containsKey(pkgName)) {
14231 // Don't allow installation over an existing package with the same name.
14232 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14233 + " without first uninstalling.");
14239 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14240 System.currentTimeMillis(), user);
14242 updateSettingsLI(newPackage, installerPackageName, null, res, user);
14244 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14245 prepareAppDataAfterInstallLIF(newPackage);
14248 // Remove package from internal structures, but keep around any
14249 // data that might have already existed
14250 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14251 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14253 } catch (PackageManagerException e) {
14254 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14257 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14260 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14261 // Can't rotate keys during boot or if sharedUser.
14262 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14263 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14266 // app is using upgradeKeySets; make sure all are valid
14267 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14268 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14269 for (int i = 0; i < upgradeKeySets.length; i++) {
14270 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14271 Slog.wtf(TAG, "Package "
14272 + (oldPs.name != null ? oldPs.name : "<null>")
14273 + " contains upgrade-key-set reference to unknown key-set: "
14274 + upgradeKeySets[i]
14275 + " reverting to signatures check.");
14282 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14283 // Upgrade keysets are being used. Determine if new package has a superset of the
14285 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14286 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14287 for (int i = 0; i < upgradeKeySets.length; i++) {
14288 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14289 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14296 private static void updateDigest(MessageDigest digest, File file) throws IOException {
14297 try (DigestInputStream digestStream =
14298 new DigestInputStream(new FileInputStream(file), digest)) {
14299 while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14303 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14304 UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14305 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14307 final PackageParser.Package oldPackage;
14308 final String pkgName = pkg.packageName;
14309 final int[] allUsers;
14310 final int[] installedUsers;
14312 synchronized(mPackages) {
14313 oldPackage = mPackages.get(pkgName);
14314 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14316 // don't allow upgrade to target a release SDK from a pre-release SDK
14317 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14318 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14319 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14320 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14321 if (oldTargetsPreRelease
14322 && !newTargetsPreRelease
14323 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14324 Slog.w(TAG, "Can't install package targeting released sdk");
14325 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14329 // don't allow an upgrade from full to ephemeral
14330 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14331 if (isEphemeral && !oldIsEphemeral) {
14332 // can't downgrade from full to ephemeral
14333 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14334 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14338 // verify signatures are valid
14339 final PackageSetting ps = mSettings.mPackages.get(pkgName);
14340 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14341 if (!checkUpgradeKeySetLP(ps, pkg)) {
14342 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14343 "New package not signed by keys specified by upgrade-keysets: "
14348 // default to original signature matching
14349 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14350 != PackageManager.SIGNATURE_MATCH) {
14351 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14352 "New package has a different signature: " + pkgName);
14357 // don't allow a system upgrade unless the upgrade hash matches
14358 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14359 byte[] digestBytes = null;
14361 final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14362 updateDigest(digest, new File(pkg.baseCodePath));
14363 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14364 for (String path : pkg.splitCodePaths) {
14365 updateDigest(digest, new File(path));
14368 digestBytes = digest.digest();
14369 } catch (NoSuchAlgorithmException | IOException e) {
14370 res.setError(INSTALL_FAILED_INVALID_APK,
14371 "Could not compute hash: " + pkgName);
14374 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14375 res.setError(INSTALL_FAILED_INVALID_APK,
14376 "New package fails restrict-update check: " + pkgName);
14379 // retain upgrade restriction
14380 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14383 // Check for shared user id changes
14384 String invalidPackageName =
14385 getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14386 if (invalidPackageName != null) {
14387 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14388 "Package " + invalidPackageName + " tried to change user "
14389 + oldPackage.mSharedUserId);
14393 // In case of rollback, remember per-user/profile install state
14394 allUsers = sUserManager.getUserIds();
14395 installedUsers = ps.queryInstalledUsers(allUsers, true);
14398 // Update what is removed
14399 res.removedInfo = new PackageRemovedInfo();
14400 res.removedInfo.uid = oldPackage.applicationInfo.uid;
14401 res.removedInfo.removedPackage = oldPackage.packageName;
14402 res.removedInfo.isUpdate = true;
14403 res.removedInfo.origUsers = installedUsers;
14404 final int childCount = (oldPackage.childPackages != null)
14405 ? oldPackage.childPackages.size() : 0;
14406 for (int i = 0; i < childCount; i++) {
14407 boolean childPackageUpdated = false;
14408 PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14409 if (res.addedChildPackages != null) {
14410 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14411 if (childRes != null) {
14412 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14413 childRes.removedInfo.removedPackage = childPkg.packageName;
14414 childRes.removedInfo.isUpdate = true;
14415 childPackageUpdated = true;
14418 if (!childPackageUpdated) {
14419 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14420 childRemovedRes.removedPackage = childPkg.packageName;
14421 childRemovedRes.isUpdate = false;
14422 childRemovedRes.dataRemoved = true;
14423 synchronized (mPackages) {
14424 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14425 if (childPs != null) {
14426 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14429 if (res.removedInfo.removedChildPackages == null) {
14430 res.removedInfo.removedChildPackages = new ArrayMap<>();
14432 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14436 boolean sysPkg = (isSystemApp(oldPackage));
14438 // Set the system/privileged flags as needed
14439 final boolean privileged =
14440 (oldPackage.applicationInfo.privateFlags
14441 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14442 final int systemPolicyFlags = policyFlags
14443 | PackageParser.PARSE_IS_SYSTEM
14444 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14446 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14447 user, allUsers, installerPackageName, res);
14449 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14450 user, allUsers, installerPackageName, res);
14454 public List<String> getPreviousCodePaths(String packageName) {
14455 final PackageSetting ps = mSettings.mPackages.get(packageName);
14456 final List<String> result = new ArrayList<String>();
14457 if (ps != null && ps.oldCodePaths != null) {
14458 result.addAll(ps.oldCodePaths);
14463 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14464 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14465 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14466 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14469 String pkgName = deletedPackage.packageName;
14470 boolean deletedPkg = true;
14471 boolean addedPkg = false;
14472 boolean updatedSettings = false;
14473 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14474 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14475 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14477 final long origUpdateTime = (pkg.mExtras != null)
14478 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14480 // First delete the existing package while retaining the data directory
14481 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14482 res.removedInfo, true, pkg)) {
14483 // If the existing package wasn't successfully deleted
14484 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14485 deletedPkg = false;
14487 // Successfully deleted the old package; proceed with replace.
14489 // If deleted package lived in a container, give users a chance to
14490 // relinquish resources before killing.
14491 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14492 if (DEBUG_INSTALL) {
14493 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14495 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14496 final ArrayList<String> pkgList = new ArrayList<String>(1);
14497 pkgList.add(deletedPackage.applicationInfo.packageName);
14498 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14501 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14502 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14503 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14506 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14507 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14508 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14510 // Update the in-memory copy of the previous code paths.
14511 PackageSetting ps = mSettings.mPackages.get(pkgName);
14513 if (ps.oldCodePaths == null) {
14514 ps.oldCodePaths = new ArraySet<>();
14516 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14517 if (deletedPackage.splitCodePaths != null) {
14518 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14521 ps.oldCodePaths = null;
14523 if (ps.childPackageNames != null) {
14524 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14525 final String childPkgName = ps.childPackageNames.get(i);
14526 final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14527 childPs.oldCodePaths = ps.oldCodePaths;
14530 prepareAppDataAfterInstallLIF(newPackage);
14532 } catch (PackageManagerException e) {
14533 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14537 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14538 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14540 // Revert all internal state mutations and added folders for the failed install
14542 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14543 res.removedInfo, true, null);
14546 // Restore the old package
14548 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14549 File restoreFile = new File(deletedPackage.codePath);
14550 // Parse old package
14551 boolean oldExternal = isExternal(deletedPackage);
14552 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
14553 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14554 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14555 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14557 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14559 } catch (PackageManagerException e) {
14560 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14565 synchronized (mPackages) {
14566 // Ensure the installer package name up to date
14567 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14569 // Update permissions for restored package
14570 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14572 mSettings.writeLPr();
14575 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14578 synchronized (mPackages) {
14579 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14581 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14582 if (res.removedInfo.removedChildPackages != null) {
14583 final int childCount = res.removedInfo.removedChildPackages.size();
14584 // Iterate in reverse as we may modify the collection
14585 for (int i = childCount - 1; i >= 0; i--) {
14586 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14587 if (res.addedChildPackages.containsKey(childPackageName)) {
14588 res.removedInfo.removedChildPackages.removeAt(i);
14590 PackageRemovedInfo childInfo = res.removedInfo
14591 .removedChildPackages.valueAt(i);
14592 childInfo.removedForAllUsers = mPackages.get(
14593 childInfo.removedPackage) == null;
14602 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14603 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14604 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14605 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14606 + ", old=" + deletedPackage);
14608 final boolean disabledSystem;
14610 // Remove existing system package
14611 removePackageLI(deletedPackage, true);
14613 synchronized (mPackages) {
14614 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14616 if (!disabledSystem) {
14617 // We didn't need to disable the .apk as a current system package,
14618 // which means we are replacing another update that is already
14619 // installed. We need to make sure to delete the older one's .apk.
14620 res.removedInfo.args = createInstallArgsForExisting(0,
14621 deletedPackage.applicationInfo.getCodePath(),
14622 deletedPackage.applicationInfo.getResourcePath(),
14623 getAppDexInstructionSets(deletedPackage.applicationInfo));
14625 res.removedInfo.args = null;
14628 // Successfully disabled the old package. Now proceed with re-installation
14629 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14630 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14631 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14633 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14634 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14635 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14637 PackageParser.Package newPackage = null;
14639 // Add the package to the internal data structures
14640 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14642 // Set the update and install times
14643 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14644 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14645 System.currentTimeMillis());
14647 // Update the package dynamic state if succeeded
14648 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14649 // Now that the install succeeded make sure we remove data
14650 // directories for any child package the update removed.
14651 final int deletedChildCount = (deletedPackage.childPackages != null)
14652 ? deletedPackage.childPackages.size() : 0;
14653 final int newChildCount = (newPackage.childPackages != null)
14654 ? newPackage.childPackages.size() : 0;
14655 for (int i = 0; i < deletedChildCount; i++) {
14656 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14657 boolean childPackageDeleted = true;
14658 for (int j = 0; j < newChildCount; j++) {
14659 PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14660 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14661 childPackageDeleted = false;
14665 if (childPackageDeleted) {
14666 PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14667 deletedChildPkg.packageName);
14668 if (ps != null && res.removedInfo.removedChildPackages != null) {
14669 PackageRemovedInfo removedChildRes = res.removedInfo
14670 .removedChildPackages.get(deletedChildPkg.packageName);
14671 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14672 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14677 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14678 prepareAppDataAfterInstallLIF(newPackage);
14680 } catch (PackageManagerException e) {
14681 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14682 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14685 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14686 // Re installation failed. Restore old information
14687 // Remove new pkg information
14688 if (newPackage != null) {
14689 removeInstalledPackageLI(newPackage, true);
14691 // Add back the old system package
14693 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14694 } catch (PackageManagerException e) {
14695 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14698 synchronized (mPackages) {
14699 if (disabledSystem) {
14700 enableSystemPackageLPw(deletedPackage);
14703 // Ensure the installer package name up to date
14704 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14706 // Update permissions for restored package
14707 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14709 mSettings.writeLPr();
14712 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14713 + " after failed upgrade");
14718 * Checks whether the parent or any of the child packages have a change shared
14719 * user. For a package to be a valid update the shred users of the parent and
14720 * the children should match. We may later support changing child shared users.
14721 * @param oldPkg The updated package.
14722 * @param newPkg The update package.
14723 * @return The shared user that change between the versions.
14725 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14726 PackageParser.Package newPkg) {
14727 // Check parent shared user
14728 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14729 return newPkg.packageName;
14731 // Check child shared users
14732 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14733 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14734 for (int i = 0; i < newChildCount; i++) {
14735 PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14736 // If this child was present, did it have the same shared user?
14737 for (int j = 0; j < oldChildCount; j++) {
14738 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14739 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14740 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14741 return newChildPkg.packageName;
14748 private void removeNativeBinariesLI(PackageSetting ps) {
14749 // Remove the lib path for the parent package
14751 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14752 // Remove the lib path for the child packages
14753 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14754 for (int i = 0; i < childCount; i++) {
14755 PackageSetting childPs = null;
14756 synchronized (mPackages) {
14757 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14759 if (childPs != null) {
14760 NativeLibraryHelper.removeNativeBinariesLI(childPs
14761 .legacyNativeLibraryPathString);
14767 private void enableSystemPackageLPw(PackageParser.Package pkg) {
14768 // Enable the parent package
14769 mSettings.enableSystemPackageLPw(pkg.packageName);
14770 // Enable the child packages
14771 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14772 for (int i = 0; i < childCount; i++) {
14773 PackageParser.Package childPkg = pkg.childPackages.get(i);
14774 mSettings.enableSystemPackageLPw(childPkg.packageName);
14778 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14779 PackageParser.Package newPkg) {
14780 // Disable the parent package (parent always replaced)
14781 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14782 // Disable the child packages
14783 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14784 for (int i = 0; i < childCount; i++) {
14785 PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14786 final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14787 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14792 private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14793 String installerPackageName) {
14794 // Enable the parent package
14795 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14796 // Enable the child packages
14797 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14798 for (int i = 0; i < childCount; i++) {
14799 PackageParser.Package childPkg = pkg.childPackages.get(i);
14800 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14804 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14805 // Collect all used permissions in the UID
14806 ArraySet<String> usedPermissions = new ArraySet<>();
14807 final int packageCount = su.packages.size();
14808 for (int i = 0; i < packageCount; i++) {
14809 PackageSetting ps = su.packages.valueAt(i);
14810 if (ps.pkg == null) {
14813 final int requestedPermCount = ps.pkg.requestedPermissions.size();
14814 for (int j = 0; j < requestedPermCount; j++) {
14815 String permission = ps.pkg.requestedPermissions.get(j);
14816 BasePermission bp = mSettings.mPermissions.get(permission);
14818 usedPermissions.add(permission);
14823 PermissionsState permissionsState = su.getPermissionsState();
14824 // Prune install permissions
14825 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14826 final int installPermCount = installPermStates.size();
14827 for (int i = installPermCount - 1; i >= 0; i--) {
14828 PermissionState permissionState = installPermStates.get(i);
14829 if (!usedPermissions.contains(permissionState.getName())) {
14830 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14832 permissionsState.revokeInstallPermission(bp);
14833 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14834 PackageManager.MASK_PERMISSION_FLAGS, 0);
14839 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14841 // Prune runtime permissions
14842 for (int userId : allUserIds) {
14843 List<PermissionState> runtimePermStates = permissionsState
14844 .getRuntimePermissionStates(userId);
14845 final int runtimePermCount = runtimePermStates.size();
14846 for (int i = runtimePermCount - 1; i >= 0; i--) {
14847 PermissionState permissionState = runtimePermStates.get(i);
14848 if (!usedPermissions.contains(permissionState.getName())) {
14849 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14851 permissionsState.revokeRuntimePermission(bp, userId);
14852 permissionsState.updatePermissionFlags(bp, userId,
14853 PackageManager.MASK_PERMISSION_FLAGS, 0);
14854 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14855 runtimePermissionChangedUserIds, userId);
14861 return runtimePermissionChangedUserIds;
14864 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14865 int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14866 // Update the parent package setting
14867 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14869 // Update the child packages setting
14870 final int childCount = (newPackage.childPackages != null)
14871 ? newPackage.childPackages.size() : 0;
14872 for (int i = 0; i < childCount; i++) {
14873 PackageParser.Package childPackage = newPackage.childPackages.get(i);
14874 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14875 updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14876 childRes.origUsers, childRes, user);
14880 private void updateSettingsInternalLI(PackageParser.Package newPackage,
14881 String installerPackageName, int[] allUsers, int[] installedForUsers,
14882 PackageInstalledInfo res, UserHandle user) {
14883 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14885 String pkgName = newPackage.packageName;
14886 synchronized (mPackages) {
14887 //write settings. the installStatus will be incomplete at this stage.
14888 //note that the new package setting would have already been
14889 //added to mPackages. It hasn't been persisted yet.
14890 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14891 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14892 mSettings.writeLPr();
14893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14896 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14897 synchronized (mPackages) {
14898 updatePermissionsLPw(newPackage.packageName, newPackage,
14899 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14900 ? UPDATE_PERMISSIONS_ALL : 0));
14901 // For system-bundled packages, we assume that installing an upgraded version
14902 // of the package implies that the user actually wants to run that new code,
14903 // so we enable the package.
14904 PackageSetting ps = mSettings.mPackages.get(pkgName);
14905 final int userId = user.getIdentifier();
14907 if (isSystemApp(newPackage)) {
14908 if (DEBUG_INSTALL) {
14909 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14911 // Enable system package for requested users
14912 if (res.origUsers != null) {
14913 for (int origUserId : res.origUsers) {
14914 if (userId == UserHandle.USER_ALL || userId == origUserId) {
14915 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14916 origUserId, installerPackageName);
14920 // Also convey the prior install/uninstall state
14921 if (allUsers != null && installedForUsers != null) {
14922 for (int currentUserId : allUsers) {
14923 final boolean installed = ArrayUtils.contains(
14924 installedForUsers, currentUserId);
14925 if (DEBUG_INSTALL) {
14926 Slog.d(TAG, " user " + currentUserId + " => " + installed);
14928 ps.setInstalled(installed, currentUserId);
14930 // these install state changes will be persisted in the
14931 // upcoming call to mSettings.writeLPr().
14934 // It's implied that when a user requests installation, they want the app to be
14935 // installed and enabled.
14936 if (userId != UserHandle.USER_ALL) {
14937 ps.setInstalled(true, userId);
14938 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14941 res.name = pkgName;
14942 res.uid = newPackage.applicationInfo.uid;
14943 res.pkg = newPackage;
14944 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14945 mSettings.setInstallerPackageName(pkgName, installerPackageName);
14946 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14947 //to update install status
14948 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14949 mSettings.writeLPr();
14950 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14953 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14956 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14959 installPackageLI(args, res);
14961 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14965 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14966 final int installFlags = args.installFlags;
14967 final String installerPackageName = args.installerPackageName;
14968 final String volumeUuid = args.volumeUuid;
14969 final File tmpPackageFile = new File(args.getCodePath());
14970 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14971 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14972 || (args.volumeUuid != null));
14973 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14974 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14975 boolean replace = false;
14976 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14977 if (args.move != null) {
14978 // moving a complete application; perform an initial scan on the new install location
14979 scanFlags |= SCAN_INITIAL;
14981 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14982 scanFlags |= SCAN_DONT_KILL_APP;
14985 // Result object to be returned
14986 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14988 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14991 if (ephemeral && (forwardLocked || onExternal)) {
14992 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14993 + " external=" + onExternal);
14994 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14998 // Retrieve PackageSettings and parse package
14999 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15000 | PackageParser.PARSE_ENFORCE_CODE
15001 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15002 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15003 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15004 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15005 PackageParser pp = new PackageParser();
15006 pp.setSeparateProcesses(mSeparateProcesses);
15007 pp.setDisplayMetrics(mMetrics);
15009 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15010 final PackageParser.Package pkg;
15012 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15013 } catch (PackageParserException e) {
15014 res.setError("Failed parse during installPackageLI", e);
15017 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15020 // If we are installing a clustered package add results for the children
15021 if (pkg.childPackages != null) {
15022 synchronized (mPackages) {
15023 final int childCount = pkg.childPackages.size();
15024 for (int i = 0; i < childCount; i++) {
15025 PackageParser.Package childPkg = pkg.childPackages.get(i);
15026 PackageInstalledInfo childRes = new PackageInstalledInfo();
15027 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15028 childRes.pkg = childPkg;
15029 childRes.name = childPkg.packageName;
15030 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15031 if (childPs != null) {
15032 childRes.origUsers = childPs.queryInstalledUsers(
15033 sUserManager.getUserIds(), true);
15035 if ((mPackages.containsKey(childPkg.packageName))) {
15036 childRes.removedInfo = new PackageRemovedInfo();
15037 childRes.removedInfo.removedPackage = childPkg.packageName;
15039 if (res.addedChildPackages == null) {
15040 res.addedChildPackages = new ArrayMap<>();
15042 res.addedChildPackages.put(childPkg.packageName, childRes);
15047 // If package doesn't declare API override, mark that we have an install
15048 // time CPU ABI override.
15049 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15050 pkg.cpuAbiOverride = args.abiOverride;
15053 String pkgName = res.name = pkg.packageName;
15054 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15055 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15056 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15062 // either use what we've been given or parse directly from the APK
15063 if (args.certificates != null) {
15065 PackageParser.populateCertificates(pkg, args.certificates);
15066 } catch (PackageParserException e) {
15067 // there was something wrong with the certificates we were given;
15068 // try to pull them from the APK
15069 PackageParser.collectCertificates(pkg, parseFlags);
15072 PackageParser.collectCertificates(pkg, parseFlags);
15074 } catch (PackageParserException e) {
15075 res.setError("Failed collect during installPackageLI", e);
15079 // Get rid of all references to package scan path via parser.
15081 String oldCodePath = null;
15082 boolean systemApp = false;
15083 synchronized (mPackages) {
15084 // Check if installing already existing package
15085 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15086 String oldName = mSettings.mRenamedPackages.get(pkgName);
15087 if (pkg.mOriginalPackages != null
15088 && pkg.mOriginalPackages.contains(oldName)
15089 && mPackages.containsKey(oldName)) {
15090 // This package is derived from an original package,
15091 // and this device has been updating from that original
15092 // name. We must continue using the original name, so
15093 // rename the new package here.
15094 pkg.setPackageName(oldName);
15095 pkgName = pkg.packageName;
15097 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15098 + oldName + " pkgName=" + pkgName);
15099 } else if (mPackages.containsKey(pkgName)) {
15100 // This package, under its official name, already exists
15101 // on the device; we should replace it.
15103 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15106 // Child packages are installed through the parent package
15107 if (pkg.parentPackage != null) {
15108 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15109 "Package " + pkg.packageName + " is child of package "
15110 + pkg.parentPackage.parentPackage + ". Child packages "
15111 + "can be updated only through the parent package.");
15116 // Prevent apps opting out from runtime permissions
15117 PackageParser.Package oldPackage = mPackages.get(pkgName);
15118 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15119 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15120 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15121 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15122 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15123 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15124 + " doesn't support runtime permissions but the old"
15125 + " target SDK " + oldTargetSdk + " does.");
15129 // Prevent installing of child packages
15130 if (oldPackage.parentPackage != null) {
15131 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15132 "Package " + pkg.packageName + " is child of package "
15133 + oldPackage.parentPackage + ". Child packages "
15134 + "can be updated only through the parent package.");
15140 PackageSetting ps = mSettings.mPackages.get(pkgName);
15142 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15144 // Quick sanity check that we're signed correctly if updating;
15145 // we'll check this again later when scanning, but we want to
15146 // bail early here before tripping over redefined permissions.
15147 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15148 if (!checkUpgradeKeySetLP(ps, pkg)) {
15149 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15150 + pkg.packageName + " upgrade keys do not match the "
15151 + "previously installed version");
15156 verifySignaturesLP(ps, pkg);
15157 } catch (PackageManagerException e) {
15158 res.setError(e.error, e.getMessage());
15163 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15164 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15165 systemApp = (ps.pkg.applicationInfo.flags &
15166 ApplicationInfo.FLAG_SYSTEM) != 0;
15168 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15171 // Check whether the newly-scanned package wants to define an already-defined perm
15172 int N = pkg.permissions.size();
15173 for (int i = N-1; i >= 0; i--) {
15174 PackageParser.Permission perm = pkg.permissions.get(i);
15175 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15177 // If the defining package is signed with our cert, it's okay. This
15178 // also includes the "updating the same package" case, of course.
15179 // "updating same package" could also involve key-rotation.
15180 final boolean sigsOk;
15181 if (bp.sourcePackage.equals(pkg.packageName)
15182 && (bp.packageSetting instanceof PackageSetting)
15183 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15185 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15187 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15188 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15191 // If the owning package is the system itself, we log but allow
15192 // install to proceed; we fail the install on all other permission
15194 if (!bp.sourcePackage.equals("android")) {
15195 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15196 + pkg.packageName + " attempting to redeclare permission "
15197 + perm.info.name + " already owned by " + bp.sourcePackage);
15198 res.origPermission = perm.info.name;
15199 res.origPackage = bp.sourcePackage;
15202 Slog.w(TAG, "Package " + pkg.packageName
15203 + " attempting to redeclare system permission "
15204 + perm.info.name + "; ignoring new declaration");
15205 pkg.permissions.remove(i);
15214 // Abort update; system app can't be replaced with app on sdcard
15215 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15216 "Cannot install updates to system apps on sdcard");
15218 } else if (ephemeral) {
15219 // Abort update; system app can't be replaced with an ephemeral app
15220 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15221 "Cannot update a system app with an ephemeral app");
15226 if (args.move != null) {
15227 // We did an in-place move, so dex is ready to roll
15228 scanFlags |= SCAN_NO_DEX;
15229 scanFlags |= SCAN_MOVE;
15231 synchronized (mPackages) {
15232 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15234 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15235 "Missing settings for moved package " + pkgName);
15238 // We moved the entire application as-is, so bring over the
15239 // previously derived ABI information.
15240 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15241 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15244 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15245 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15246 scanFlags |= SCAN_NO_DEX;
15249 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15250 args.abiOverride : pkg.cpuAbiOverride);
15251 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15252 true /* extract libs */);
15253 } catch (PackageManagerException pme) {
15254 Slog.e(TAG, "Error deriving application ABI", pme);
15255 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15259 // Shared libraries for the package need to be updated.
15260 synchronized (mPackages) {
15262 updateSharedLibrariesLPw(pkg, null);
15263 } catch (PackageManagerException e) {
15264 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15267 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15268 // Do not run PackageDexOptimizer through the local performDexOpt
15269 // method because `pkg` may not be in `mPackages` yet.
15271 // Also, don't fail application installs if the dexopt step fails.
15272 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15273 null /* instructionSets */, false /* checkProfiles */,
15274 getCompilerFilterForReason(REASON_INSTALL),
15275 getOrCreateCompilerPackageStats(pkg));
15276 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15278 // Notify BackgroundDexOptService that the package has been changed.
15279 // If this is an update of a package which used to fail to compile,
15280 // BDOS will remove it from its blacklist.
15281 BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15284 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15285 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15289 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15291 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15292 "installPackageLI")) {
15294 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15295 installerPackageName, res);
15297 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15298 args.user, installerPackageName, volumeUuid, res);
15301 synchronized (mPackages) {
15302 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15304 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15307 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15308 for (int i = 0; i < childCount; i++) {
15309 PackageParser.Package childPkg = pkg.childPackages.get(i);
15310 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15311 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15312 if (childPs != null) {
15313 childRes.newUsers = childPs.queryInstalledUsers(
15314 sUserManager.getUserIds(), true);
15320 private void startIntentFilterVerifications(int userId, boolean replacing,
15321 PackageParser.Package pkg) {
15322 if (mIntentFilterVerifierComponent == null) {
15323 Slog.w(TAG, "No IntentFilter verification will not be done as "
15324 + "there is no IntentFilterVerifier available!");
15328 final int verifierUid = getPackageUid(
15329 mIntentFilterVerifierComponent.getPackageName(),
15330 MATCH_DEBUG_TRIAGED_MISSING,
15331 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15333 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15334 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15335 mHandler.sendMessage(msg);
15337 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15338 for (int i = 0; i < childCount; i++) {
15339 PackageParser.Package childPkg = pkg.childPackages.get(i);
15340 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15341 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15342 mHandler.sendMessage(msg);
15346 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15347 PackageParser.Package pkg) {
15348 int size = pkg.activities.size();
15350 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15351 "No activity, so no need to verify any IntentFilter!");
15355 final boolean hasDomainURLs = hasDomainURLs(pkg);
15356 if (!hasDomainURLs) {
15357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15358 "No domain URLs, so no need to verify any IntentFilter!");
15362 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15363 + " if any IntentFilter from the " + size
15364 + " Activities needs verification ...");
15367 final String packageName = pkg.packageName;
15369 synchronized (mPackages) {
15370 // If this is a new install and we see that we've already run verification for this
15371 // package, we have nothing to do: it means the state was restored from backup.
15373 IntentFilterVerificationInfo ivi =
15374 mSettings.getIntentFilterVerificationLPr(packageName);
15376 if (DEBUG_DOMAIN_VERIFICATION) {
15377 Slog.i(TAG, "Package " + packageName+ " already verified: status="
15378 + ivi.getStatusString());
15384 // If any filters need to be verified, then all need to be.
15385 boolean needToVerify = false;
15386 for (PackageParser.Activity a : pkg.activities) {
15387 for (ActivityIntentInfo filter : a.intents) {
15388 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15389 if (DEBUG_DOMAIN_VERIFICATION) {
15390 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15392 needToVerify = true;
15398 if (needToVerify) {
15399 final int verificationId = mIntentFilterVerificationToken++;
15400 for (PackageParser.Activity a : pkg.activities) {
15401 for (ActivityIntentInfo filter : a.intents) {
15402 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15403 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15404 "Verification needed for IntentFilter:" + filter.toString());
15405 mIntentFilterVerifier.addOneIntentFilterVerification(
15406 verifierUid, userId, verificationId, filter, packageName);
15415 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15416 + " IntentFilter verification" + (count > 1 ? "s" : "")
15417 + " for userId:" + userId);
15418 mIntentFilterVerifier.startVerifications(userId);
15420 if (DEBUG_DOMAIN_VERIFICATION) {
15421 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15426 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15427 final ComponentName cn = filter.activity.getComponentName();
15428 final String packageName = cn.getPackageName();
15430 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15435 int status = ivi.getStatus();
15437 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15438 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15447 private static boolean isMultiArch(ApplicationInfo info) {
15448 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15451 private static boolean isExternal(PackageParser.Package pkg) {
15452 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15455 private static boolean isExternal(PackageSetting ps) {
15456 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15459 private static boolean isEphemeral(PackageParser.Package pkg) {
15460 return pkg.applicationInfo.isEphemeralApp();
15463 private static boolean isEphemeral(PackageSetting ps) {
15464 return ps.pkg != null && isEphemeral(ps.pkg);
15467 private static boolean isSystemApp(PackageParser.Package pkg) {
15468 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15471 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15472 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15475 private static boolean hasDomainURLs(PackageParser.Package pkg) {
15476 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15479 private static boolean isSystemApp(PackageSetting ps) {
15480 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15483 private static boolean isUpdatedSystemApp(PackageSetting ps) {
15484 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15487 private int packageFlagsToInstallFlags(PackageSetting ps) {
15488 int installFlags = 0;
15489 if (isEphemeral(ps)) {
15490 installFlags |= PackageManager.INSTALL_EPHEMERAL;
15492 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15493 // This existing package was an external ASEC install when we have
15494 // the external flag without a UUID
15495 installFlags |= PackageManager.INSTALL_EXTERNAL;
15497 if (ps.isForwardLocked()) {
15498 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15500 return installFlags;
15503 private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15504 if (isExternal(pkg)) {
15505 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15506 return StorageManager.UUID_PRIMARY_PHYSICAL;
15508 return pkg.volumeUuid;
15511 return StorageManager.UUID_PRIVATE_INTERNAL;
15515 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15516 if (isExternal(pkg)) {
15517 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15518 return mSettings.getExternalVersion();
15520 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15523 return mSettings.getInternalVersion();
15527 private void deleteTempPackageFiles() {
15528 final FilenameFilter filter = new FilenameFilter() {
15529 public boolean accept(File dir, String name) {
15530 return name.startsWith("vmdl") && name.endsWith(".tmp");
15533 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15539 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15541 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15546 public void deletePackage(final String packageName,
15547 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15548 mContext.enforceCallingOrSelfPermission(
15549 android.Manifest.permission.DELETE_PACKAGES, null);
15550 Preconditions.checkNotNull(packageName);
15551 Preconditions.checkNotNull(observer);
15552 final int uid = Binder.getCallingUid();
15553 if (!isOrphaned(packageName)
15554 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15556 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15557 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15558 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15559 observer.onUserActionRequired(intent);
15560 } catch (RemoteException re) {
15564 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15565 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15566 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15567 mContext.enforceCallingOrSelfPermission(
15568 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15569 "deletePackage for user " + userId);
15572 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15574 observer.onPackageDeleted(packageName,
15575 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15576 } catch (RemoteException re) {
15581 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15583 observer.onPackageDeleted(packageName,
15584 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15585 } catch (RemoteException re) {
15590 if (DEBUG_REMOVE) {
15591 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15592 + " deleteAllUsers: " + deleteAllUsers );
15594 // Queue up an async operation since the package deletion may take a little while.
15595 mHandler.post(new Runnable() {
15596 public void run() {
15597 mHandler.removeCallbacks(this);
15599 if (!deleteAllUsers) {
15600 returnCode = deletePackageX(packageName, userId, deleteFlags);
15602 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15603 // If nobody is blocking uninstall, proceed with delete for all users
15604 if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15605 returnCode = deletePackageX(packageName, userId, deleteFlags);
15607 // Otherwise uninstall individually for users with blockUninstalls=false
15608 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15609 for (int userId : users) {
15610 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15611 returnCode = deletePackageX(packageName, userId, userFlags);
15612 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15613 Slog.w(TAG, "Package delete failed for user " + userId
15614 + ", returnCode " + returnCode);
15618 // The app has only been marked uninstalled for certain users.
15619 // We still need to report that delete was blocked
15620 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15624 observer.onPackageDeleted(packageName, returnCode, null);
15625 } catch (RemoteException e) {
15626 Log.i(TAG, "Observer no longer exists.");
15632 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15633 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15634 || callingUid == Process.SYSTEM_UID) {
15637 final int callingUserId = UserHandle.getUserId(callingUid);
15638 // If the caller installed the pkgName, then allow it to silently uninstall.
15639 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15643 // Allow package verifier to silently uninstall.
15644 if (mRequiredVerifierPackage != null &&
15645 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15649 // Allow package uninstaller to silently uninstall.
15650 if (mRequiredUninstallerPackage != null &&
15651 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15655 // Allow storage manager to silently uninstall.
15656 if (mStorageManagerPackage != null &&
15657 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15663 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15664 int[] result = EMPTY_INT_ARRAY;
15665 for (int userId : userIds) {
15666 if (getBlockUninstallForUser(packageName, userId)) {
15667 result = ArrayUtils.appendInt(result, userId);
15674 public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15675 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15678 private boolean isPackageDeviceAdmin(String packageName, int userId) {
15679 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15680 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15683 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15684 /* callingUserOnly =*/ false);
15685 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15686 : deviceOwnerComponentName.getPackageName();
15687 // Does the package contains the device owner?
15688 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise,
15689 // this check is probably not needed, since DO should be registered as a device
15690 // admin on some user too. (Original bug for this: b/17657954)
15691 if (packageName.equals(deviceOwnerPackageName)) {
15694 // Does it contain a device admin for any user?
15696 if (userId == UserHandle.USER_ALL) {
15697 users = sUserManager.getUserIds();
15699 users = new int[]{userId};
15701 for (int i = 0; i < users.length; ++i) {
15702 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15707 } catch (RemoteException e) {
15712 private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15713 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15717 * This method is an internal method that could be get invoked either
15718 * to delete an installed package or to clean up a failed installation.
15719 * After deleting an installed package, a broadcast is sent to notify any
15720 * listeners that the package has been removed. For cleaning up a failed
15721 * installation, the broadcast is not necessary since the package's
15722 * installation wouldn't have sent the initial broadcast either
15723 * The key steps in deleting a package are
15724 * deleting the package information in internal structures like mPackages,
15725 * deleting the packages base directories through installd
15726 * updating mSettings to reflect current status
15727 * persisting settings for later use
15728 * sending a broadcast if necessary
15730 private int deletePackageX(String packageName, int userId, int deleteFlags) {
15731 final PackageRemovedInfo info = new PackageRemovedInfo();
15734 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15735 ? UserHandle.USER_ALL : userId;
15737 if (isPackageDeviceAdmin(packageName, removeUser)) {
15738 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15739 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15742 PackageSetting uninstalledPs = null;
15744 // for the uninstall-updates case and restricted profiles, remember the per-
15745 // user handle installed state
15747 synchronized (mPackages) {
15748 uninstalledPs = mSettings.mPackages.get(packageName);
15749 if (uninstalledPs == null) {
15750 Slog.w(TAG, "Not removing non-existent package " + packageName);
15751 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15753 allUsers = sUserManager.getUserIds();
15754 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15757 final int freezeUser;
15758 if (isUpdatedSystemApp(uninstalledPs)
15759 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15760 // We're downgrading a system app, which will apply to all users, so
15761 // freeze them all during the downgrade
15762 freezeUser = UserHandle.USER_ALL;
15764 freezeUser = removeUser;
15767 synchronized (mInstallLock) {
15768 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15769 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15770 deleteFlags, "deletePackageX")) {
15771 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15772 deleteFlags | REMOVE_CHATTY, info, true, null);
15774 synchronized (mPackages) {
15776 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15782 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15783 info.sendPackageRemovedBroadcasts(killApp);
15784 info.sendSystemPackageUpdatedBroadcasts();
15785 info.sendSystemPackageAppearedBroadcasts();
15787 // Force a gc here.
15788 Runtime.getRuntime().gc();
15789 // Delete the resources here after sending the broadcast to let
15790 // other processes clean up before deleting resources.
15791 if (info.args != null) {
15792 synchronized (mInstallLock) {
15793 info.args.doPostDeleteLI(true);
15797 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15800 class PackageRemovedInfo {
15801 String removedPackage;
15803 int removedAppId = -1;
15805 int[] removedUsers = null;
15806 boolean isRemovedPackageSystemUpdate = false;
15808 boolean dataRemoved;
15809 boolean removedForAllUsers;
15810 // Clean up resources deleted packages.
15811 InstallArgs args = null;
15812 ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15813 ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15815 void sendPackageRemovedBroadcasts(boolean killApp) {
15816 sendPackageRemovedBroadcastInternal(killApp);
15817 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15818 for (int i = 0; i < childCount; i++) {
15819 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15820 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15824 void sendSystemPackageUpdatedBroadcasts() {
15825 if (isRemovedPackageSystemUpdate) {
15826 sendSystemPackageUpdatedBroadcastsInternal();
15827 final int childCount = (removedChildPackages != null)
15828 ? removedChildPackages.size() : 0;
15829 for (int i = 0; i < childCount; i++) {
15830 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15831 if (childInfo.isRemovedPackageSystemUpdate) {
15832 childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15838 void sendSystemPackageAppearedBroadcasts() {
15839 final int packageCount = (appearedChildPackages != null)
15840 ? appearedChildPackages.size() : 0;
15841 for (int i = 0; i < packageCount; i++) {
15842 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15843 for (int userId : installedInfo.newUsers) {
15844 sendPackageAddedForUser(installedInfo.name, true,
15845 UserHandle.getAppId(installedInfo.uid), userId);
15850 private void sendSystemPackageUpdatedBroadcastsInternal() {
15851 Bundle extras = new Bundle(2);
15852 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15853 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15854 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15855 extras, 0, null, null, null);
15856 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15857 extras, 0, null, null, null);
15858 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15859 null, 0, removedPackage, null, null);
15862 private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15863 Bundle extras = new Bundle(2);
15864 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15865 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15866 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15867 if (isUpdate || isRemovedPackageSystemUpdate) {
15868 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15870 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15871 if (removedPackage != null) {
15872 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15873 extras, 0, null, null, removedUsers);
15874 if (dataRemoved && !isRemovedPackageSystemUpdate) {
15875 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15876 removedPackage, extras, 0, null, null, removedUsers);
15879 if (removedAppId >= 0) {
15880 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15887 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15888 * flag is not set, the data directory is removed as well.
15889 * make sure this flag is set for partially installed apps. If not its meaningless to
15890 * delete a partially installed application.
15892 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15893 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15894 String packageName = ps.name;
15895 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15896 // Retrieve object to delete permissions for shared user later on
15897 final PackageParser.Package deletedPkg;
15898 final PackageSetting deletedPs;
15900 synchronized (mPackages) {
15901 deletedPkg = mPackages.get(packageName);
15902 deletedPs = mSettings.mPackages.get(packageName);
15903 if (outInfo != null) {
15904 outInfo.removedPackage = packageName;
15905 outInfo.removedUsers = deletedPs != null
15906 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15911 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15913 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15914 final PackageParser.Package resolvedPkg;
15915 if (deletedPkg != null) {
15916 resolvedPkg = deletedPkg;
15918 // We don't have a parsed package when it lives on an ejected
15919 // adopted storage device, so fake something together
15920 resolvedPkg = new PackageParser.Package(ps.name);
15921 resolvedPkg.setVolumeUuid(ps.volumeUuid);
15923 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15924 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15925 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15926 if (outInfo != null) {
15927 outInfo.dataRemoved = true;
15929 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15933 synchronized (mPackages) {
15934 if (deletedPs != null) {
15935 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15936 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15937 clearDefaultBrowserIfNeeded(packageName);
15938 if (outInfo != null) {
15939 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15940 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15942 updatePermissionsLPw(deletedPs.name, null, 0);
15943 if (deletedPs.sharedUser != null) {
15944 // Remove permissions associated with package. Since runtime
15945 // permissions are per user we have to kill the removed package
15946 // or packages running under the shared user of the removed
15947 // package if revoking the permissions requested only by the removed
15948 // package is successful and this causes a change in gids.
15949 for (int userId : UserManagerService.getInstance().getUserIds()) {
15950 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15952 if (userIdToKill == UserHandle.USER_ALL
15953 || userIdToKill >= UserHandle.USER_SYSTEM) {
15954 // If gids changed for this user, kill all affected packages.
15955 mHandler.post(new Runnable() {
15957 public void run() {
15958 // This has to happen with no lock held.
15959 killApplication(deletedPs.name, deletedPs.appId,
15960 KILL_APP_REASON_GIDS_CHANGED);
15967 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15969 // make sure to preserve per-user disabled state if this removal was just
15970 // a downgrade of a system app to the factory package
15971 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15972 if (DEBUG_REMOVE) {
15973 Slog.d(TAG, "Propagating install state across downgrade");
15975 for (int userId : allUserHandles) {
15976 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15977 if (DEBUG_REMOVE) {
15978 Slog.d(TAG, " user " + userId + " => " + installed);
15980 ps.setInstalled(installed, userId);
15984 // can downgrade to reader
15985 if (writeSettings) {
15986 // Save settings now
15987 mSettings.writeLPr();
15990 if (outInfo != null) {
15991 // A user ID was deleted here. Go through all users and remove it
15993 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15997 static boolean locationIsPrivileged(File path) {
15999 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16000 .getCanonicalPath();
16001 return path.getCanonicalPath().startsWith(privilegedAppDir);
16002 } catch (IOException e) {
16003 Slog.e(TAG, "Unable to access code path " + path);
16009 * Tries to delete system package.
16011 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16012 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16013 boolean writeSettings) {
16014 if (deletedPs.parentPackageName != null) {
16015 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16019 final boolean applyUserRestrictions
16020 = (allUserHandles != null) && (outInfo.origUsers != null);
16021 final PackageSetting disabledPs;
16022 // Confirm if the system package has been updated
16023 // An updated system app can be deleted. This will also have to restore
16024 // the system pkg from system partition
16026 synchronized (mPackages) {
16027 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16030 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16031 + " disabledPs=" + disabledPs);
16033 if (disabledPs == null) {
16034 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16036 } else if (DEBUG_REMOVE) {
16037 Slog.d(TAG, "Deleting system pkg from data partition");
16040 if (DEBUG_REMOVE) {
16041 if (applyUserRestrictions) {
16042 Slog.d(TAG, "Remembering install states:");
16043 for (int userId : allUserHandles) {
16044 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16045 Slog.d(TAG, " u=" + userId + " inst=" + finstalled);
16050 // Delete the updated package
16051 outInfo.isRemovedPackageSystemUpdate = true;
16052 if (outInfo.removedChildPackages != null) {
16053 final int childCount = (deletedPs.childPackageNames != null)
16054 ? deletedPs.childPackageNames.size() : 0;
16055 for (int i = 0; i < childCount; i++) {
16056 String childPackageName = deletedPs.childPackageNames.get(i);
16057 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16058 .contains(childPackageName)) {
16059 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16061 if (childInfo != null) {
16062 childInfo.isRemovedPackageSystemUpdate = true;
16068 if (disabledPs.versionCode < deletedPs.versionCode) {
16069 // Delete data for downgrades
16070 flags &= ~PackageManager.DELETE_KEEP_DATA;
16072 // Preserve data by setting flag
16073 flags |= PackageManager.DELETE_KEEP_DATA;
16076 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16077 outInfo, writeSettings, disabledPs.pkg);
16083 synchronized (mPackages) {
16084 // Reinstate the old system package
16085 enableSystemPackageLPw(disabledPs.pkg);
16086 // Remove any native libraries from the upgraded package.
16087 removeNativeBinariesLI(deletedPs);
16090 // Install the system package
16091 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16092 int parseFlags = mDefParseFlags
16093 | PackageParser.PARSE_MUST_BE_APK
16094 | PackageParser.PARSE_IS_SYSTEM
16095 | PackageParser.PARSE_IS_SYSTEM_DIR;
16096 if (locationIsPrivileged(disabledPs.codePath)) {
16097 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16100 final PackageParser.Package newPkg;
16102 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16103 } catch (PackageManagerException e) {
16104 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16109 // update shared libraries for the newly re-installed system package
16110 updateSharedLibrariesLPw(newPkg, null);
16111 } catch (PackageManagerException e) {
16112 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16115 prepareAppDataAfterInstallLIF(newPkg);
16118 synchronized (mPackages) {
16119 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16121 // Propagate the permissions state as we do not want to drop on the floor
16122 // runtime permissions. The update permissions method below will take
16123 // care of removing obsolete permissions and grant install permissions.
16124 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16125 updatePermissionsLPw(newPkg.packageName, newPkg,
16126 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16128 if (applyUserRestrictions) {
16129 if (DEBUG_REMOVE) {
16130 Slog.d(TAG, "Propagating install state across reinstall");
16132 for (int userId : allUserHandles) {
16133 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16134 if (DEBUG_REMOVE) {
16135 Slog.d(TAG, " user " + userId + " => " + installed);
16137 ps.setInstalled(installed, userId);
16139 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16141 // Regardless of writeSettings we need to ensure that this restriction
16142 // state propagation is persisted
16143 mSettings.writeAllUsersPackageRestrictionsLPr();
16145 // can downgrade to reader here
16146 if (writeSettings) {
16147 mSettings.writeLPr();
16153 private boolean deleteInstalledPackageLIF(PackageSetting ps,
16154 boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16155 PackageRemovedInfo outInfo, boolean writeSettings,
16156 PackageParser.Package replacingPackage) {
16157 synchronized (mPackages) {
16158 if (outInfo != null) {
16159 outInfo.uid = ps.appId;
16162 if (outInfo != null && outInfo.removedChildPackages != null) {
16163 final int childCount = (ps.childPackageNames != null)
16164 ? ps.childPackageNames.size() : 0;
16165 for (int i = 0; i < childCount; i++) {
16166 String childPackageName = ps.childPackageNames.get(i);
16167 PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16168 if (childPs == null) {
16171 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16173 if (childInfo != null) {
16174 childInfo.uid = childPs.appId;
16180 // Delete package data from internal structures and also remove data if flag is set
16181 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16183 // Delete the child packages data
16184 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16185 for (int i = 0; i < childCount; i++) {
16186 PackageSetting childPs;
16187 synchronized (mPackages) {
16188 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16190 if (childPs != null) {
16191 PackageRemovedInfo childOutInfo = (outInfo != null
16192 && outInfo.removedChildPackages != null)
16193 ? outInfo.removedChildPackages.get(childPs.name) : null;
16194 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16195 && (replacingPackage != null
16196 && !replacingPackage.hasChildPackage(childPs.name))
16197 ? flags & ~DELETE_KEEP_DATA : flags;
16198 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16199 deleteFlags, writeSettings);
16203 // Delete application code and resources only for parent packages
16204 if (ps.parentPackageName == null) {
16205 if (deleteCodeAndResources && (outInfo != null)) {
16206 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16207 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16208 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16216 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16218 mContext.enforceCallingOrSelfPermission(
16219 android.Manifest.permission.DELETE_PACKAGES, null);
16220 synchronized (mPackages) {
16221 PackageSetting ps = mSettings.mPackages.get(packageName);
16223 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16226 if (!ps.getInstalled(userId)) {
16227 // Can't block uninstall for an app that is not installed or enabled.
16228 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16231 ps.setBlockUninstall(blockUninstall, userId);
16232 mSettings.writePackageRestrictionsLPr(userId);
16238 public boolean getBlockUninstallForUser(String packageName, int userId) {
16239 synchronized (mPackages) {
16240 PackageSetting ps = mSettings.mPackages.get(packageName);
16242 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16245 return ps.getBlockUninstall(userId);
16250 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16251 int callingUid = Binder.getCallingUid();
16252 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16253 throw new SecurityException(
16254 "setRequiredForSystemUser can only be run by the system or root");
16256 synchronized (mPackages) {
16257 PackageSetting ps = mSettings.mPackages.get(packageName);
16259 Log.w(TAG, "Package doesn't exist: " + packageName);
16262 if (systemUserApp) {
16263 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16265 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16267 mSettings.writeLPr();
16273 * This method handles package deletion in general
16275 private boolean deletePackageLIF(String packageName, UserHandle user,
16276 boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16277 PackageRemovedInfo outInfo, boolean writeSettings,
16278 PackageParser.Package replacingPackage) {
16279 if (packageName == null) {
16280 Slog.w(TAG, "Attempt to delete null packageName.");
16284 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16288 synchronized (mPackages) {
16289 ps = mSettings.mPackages.get(packageName);
16291 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16295 if (ps.parentPackageName != null && (!isSystemApp(ps)
16296 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16297 if (DEBUG_REMOVE) {
16298 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16299 + ((user == null) ? UserHandle.USER_ALL : user));
16301 final int removedUserId = (user != null) ? user.getIdentifier()
16302 : UserHandle.USER_ALL;
16303 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16306 markPackageUninstalledForUserLPw(ps, user);
16307 scheduleWritePackageRestrictionsLocked(user);
16312 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16313 && user.getIdentifier() != UserHandle.USER_ALL)) {
16314 // The caller is asking that the package only be deleted for a single
16315 // user. To do this, we just mark its uninstalled state and delete
16316 // its data. If this is a system app, we only allow this to happen if
16317 // they have set the special DELETE_SYSTEM_APP which requests different
16318 // semantics than normal for uninstalling system apps.
16319 markPackageUninstalledForUserLPw(ps, user);
16321 if (!isSystemApp(ps)) {
16322 // Do not uninstall the APK if an app should be cached
16323 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16324 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16325 // Other user still have this package installed, so all
16326 // we need to do is clear this user's data and save that
16327 // it is uninstalled.
16328 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16329 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16332 scheduleWritePackageRestrictionsLocked(user);
16335 // We need to set it back to 'installed' so the uninstall
16336 // broadcasts will be sent correctly.
16337 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16338 ps.setInstalled(true, user.getIdentifier());
16341 // This is a system app, so we assume that the
16342 // other users still have this package installed, so all
16343 // we need to do is clear this user's data and save that
16344 // it is uninstalled.
16345 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16346 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16349 scheduleWritePackageRestrictionsLocked(user);
16354 // If we are deleting a composite package for all users, keep track
16355 // of result for each child.
16356 if (ps.childPackageNames != null && outInfo != null) {
16357 synchronized (mPackages) {
16358 final int childCount = ps.childPackageNames.size();
16359 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16360 for (int i = 0; i < childCount; i++) {
16361 String childPackageName = ps.childPackageNames.get(i);
16362 PackageRemovedInfo childInfo = new PackageRemovedInfo();
16363 childInfo.removedPackage = childPackageName;
16364 outInfo.removedChildPackages.put(childPackageName, childInfo);
16365 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16366 if (childPs != null) {
16367 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16373 boolean ret = false;
16374 if (isSystemApp(ps)) {
16375 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16376 // When an updated system application is deleted we delete the existing resources
16377 // as well and fall back to existing code in system partition
16378 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16380 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16381 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16382 outInfo, writeSettings, replacingPackage);
16385 // Take a note whether we deleted the package for all users
16386 if (outInfo != null) {
16387 outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16388 if (outInfo.removedChildPackages != null) {
16389 synchronized (mPackages) {
16390 final int childCount = outInfo.removedChildPackages.size();
16391 for (int i = 0; i < childCount; i++) {
16392 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16393 if (childInfo != null) {
16394 childInfo.removedForAllUsers = mPackages.get(
16395 childInfo.removedPackage) == null;
16400 // If we uninstalled an update to a system app there may be some
16401 // child packages that appeared as they are declared in the system
16402 // app but were not declared in the update.
16403 if (isSystemApp(ps)) {
16404 synchronized (mPackages) {
16405 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16406 final int childCount = (updatedPs.childPackageNames != null)
16407 ? updatedPs.childPackageNames.size() : 0;
16408 for (int i = 0; i < childCount; i++) {
16409 String childPackageName = updatedPs.childPackageNames.get(i);
16410 if (outInfo.removedChildPackages == null
16411 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16412 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16413 if (childPs == null) {
16416 PackageInstalledInfo installRes = new PackageInstalledInfo();
16417 installRes.name = childPackageName;
16418 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16419 installRes.pkg = mPackages.get(childPackageName);
16420 installRes.uid = childPs.pkg.applicationInfo.uid;
16421 if (outInfo.appearedChildPackages == null) {
16422 outInfo.appearedChildPackages = new ArrayMap<>();
16424 outInfo.appearedChildPackages.put(childPackageName, installRes);
16434 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16435 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16436 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16437 for (int nextUserId : userIds) {
16438 if (DEBUG_REMOVE) {
16439 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16441 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16442 false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16443 false /*hidden*/, false /*suspended*/, null, null, null,
16444 false /*blockUninstall*/,
16445 ps.readUserState(nextUserId).domainVerificationStatus, 0);
16449 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16450 PackageRemovedInfo outInfo) {
16451 final PackageParser.Package pkg;
16452 synchronized (mPackages) {
16453 pkg = mPackages.get(ps.name);
16456 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16457 : new int[] {userId};
16458 for (int nextUserId : userIds) {
16459 if (DEBUG_REMOVE) {
16460 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16464 destroyAppDataLIF(pkg, userId,
16465 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16466 destroyAppProfilesLIF(pkg, userId);
16467 removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16468 schedulePackageCleaning(ps.name, nextUserId, false);
16469 synchronized (mPackages) {
16470 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16471 scheduleWritePackageRestrictionsLocked(nextUserId);
16473 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16477 if (outInfo != null) {
16478 outInfo.removedPackage = ps.name;
16479 outInfo.removedAppId = ps.appId;
16480 outInfo.removedUsers = userIds;
16486 private final class ClearStorageConnection implements ServiceConnection {
16487 IMediaContainerService mContainerService;
16490 public void onServiceConnected(ComponentName name, IBinder service) {
16491 synchronized (this) {
16492 mContainerService = IMediaContainerService.Stub.asInterface(service);
16498 public void onServiceDisconnected(ComponentName name) {
16502 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16503 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16505 final boolean mounted;
16506 if (Environment.isExternalStorageEmulated()) {
16509 final String status = Environment.getExternalStorageState();
16511 mounted = status.equals(Environment.MEDIA_MOUNTED)
16512 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16519 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16521 if (userId == UserHandle.USER_ALL) {
16522 users = sUserManager.getUserIds();
16524 users = new int[] { userId };
16526 final ClearStorageConnection conn = new ClearStorageConnection();
16527 if (mContext.bindServiceAsUser(
16528 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16530 for (int curUser : users) {
16531 long timeout = SystemClock.uptimeMillis() + 5000;
16532 synchronized (conn) {
16534 while (conn.mContainerService == null &&
16535 (now = SystemClock.uptimeMillis()) < timeout) {
16537 conn.wait(timeout - now);
16538 } catch (InterruptedException e) {
16542 if (conn.mContainerService == null) {
16546 final UserEnvironment userEnv = new UserEnvironment(curUser);
16547 clearDirectory(conn.mContainerService,
16548 userEnv.buildExternalStorageAppCacheDirs(packageName));
16550 clearDirectory(conn.mContainerService,
16551 userEnv.buildExternalStorageAppDataDirs(packageName));
16552 clearDirectory(conn.mContainerService,
16553 userEnv.buildExternalStorageAppMediaDirs(packageName));
16557 mContext.unbindService(conn);
16563 public void clearApplicationProfileData(String packageName) {
16564 enforceSystemOrRoot("Only the system can clear all profile data");
16566 final PackageParser.Package pkg;
16567 synchronized (mPackages) {
16568 pkg = mPackages.get(packageName);
16571 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16572 synchronized (mInstallLock) {
16573 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16574 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16575 true /* removeBaseMarker */);
16581 public void clearApplicationUserData(final String packageName,
16582 final IPackageDataObserver observer, final int userId) {
16583 mContext.enforceCallingOrSelfPermission(
16584 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16586 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16587 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16589 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16590 throw new SecurityException("Cannot clear data for a protected package: "
16593 // Queue up an async operation since the package deletion may take a little while.
16594 mHandler.post(new Runnable() {
16595 public void run() {
16596 mHandler.removeCallbacks(this);
16597 final boolean succeeded;
16598 try (PackageFreezer freezer = freezePackage(packageName,
16599 "clearApplicationUserData")) {
16600 synchronized (mInstallLock) {
16601 succeeded = clearApplicationUserDataLIF(packageName, userId);
16603 clearExternalStorageDataSync(packageName, userId, true);
16606 // invoke DeviceStorageMonitor's update method to clear any notifications
16607 DeviceStorageMonitorInternal dsm = LocalServices
16608 .getService(DeviceStorageMonitorInternal.class);
16613 if(observer != null) {
16615 observer.onRemoveCompleted(packageName, succeeded);
16616 } catch (RemoteException e) {
16617 Log.i(TAG, "Observer no longer exists.");
16619 } //end if observer
16624 private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16625 if (packageName == null) {
16626 Slog.w(TAG, "Attempt to delete null packageName.");
16630 // Try finding details about the requested package
16631 PackageParser.Package pkg;
16632 synchronized (mPackages) {
16633 pkg = mPackages.get(packageName);
16635 final PackageSetting ps = mSettings.mPackages.get(packageName);
16642 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16646 PackageSetting ps = (PackageSetting) pkg.mExtras;
16647 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16650 clearAppDataLIF(pkg, userId,
16651 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16653 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16654 removeKeystoreDataIfNeeded(userId, appId);
16656 UserManagerInternal umInternal = getUserManagerInternal();
16658 if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16659 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16660 } else if (umInternal.isUserRunning(userId)) {
16661 flags = StorageManager.FLAG_STORAGE_DE;
16665 prepareAppDataContentsLIF(pkg, userId, flags);
16671 * Reverts user permission state changes (permissions and flags) in
16672 * all packages for a given user.
16674 * @param userId The device user for which to do a reset.
16676 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16677 final int packageCount = mPackages.size();
16678 for (int i = 0; i < packageCount; i++) {
16679 PackageParser.Package pkg = mPackages.valueAt(i);
16680 PackageSetting ps = (PackageSetting) pkg.mExtras;
16681 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16685 private void resetNetworkPolicies(int userId) {
16686 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16690 * Reverts user permission state changes (permissions and flags).
16692 * @param ps The package for which to reset.
16693 * @param userId The device user for which to do a reset.
16695 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16696 final PackageSetting ps, final int userId) {
16697 if (ps.pkg == null) {
16701 // These are flags that can change base on user actions.
16702 final int userSettableMask = FLAG_PERMISSION_USER_SET
16703 | FLAG_PERMISSION_USER_FIXED
16704 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16705 | FLAG_PERMISSION_REVIEW_REQUIRED;
16707 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16708 | FLAG_PERMISSION_POLICY_FIXED;
16710 boolean writeInstallPermissions = false;
16711 boolean writeRuntimePermissions = false;
16713 final int permissionCount = ps.pkg.requestedPermissions.size();
16714 for (int i = 0; i < permissionCount; i++) {
16715 String permission = ps.pkg.requestedPermissions.get(i);
16717 BasePermission bp = mSettings.mPermissions.get(permission);
16722 // If shared user we just reset the state to which only this app contributed.
16723 if (ps.sharedUser != null) {
16724 boolean used = false;
16725 final int packageCount = ps.sharedUser.packages.size();
16726 for (int j = 0; j < packageCount; j++) {
16727 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16728 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16729 && pkg.pkg.requestedPermissions.contains(permission)) {
16739 PermissionsState permissionsState = ps.getPermissionsState();
16741 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16743 // Always clear the user settable flags.
16744 final boolean hasInstallState = permissionsState.getInstallPermissionState(
16746 // If permission review is enabled and this is a legacy app, mark the
16747 // permission as requiring a review as this is the initial state.
16749 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16750 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16751 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16753 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16754 if (hasInstallState) {
16755 writeInstallPermissions = true;
16757 writeRuntimePermissions = true;
16761 // Below is only runtime permission handling.
16762 if (!bp.isRuntime()) {
16766 // Never clobber system or policy.
16767 if ((oldFlags & policyOrSystemFlags) != 0) {
16771 // If this permission was granted by default, make sure it is.
16772 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16773 if (permissionsState.grantRuntimePermission(bp, userId)
16774 != PERMISSION_OPERATION_FAILURE) {
16775 writeRuntimePermissions = true;
16777 // If permission review is enabled the permissions for a legacy apps
16778 // are represented as constantly granted runtime ones, so don't revoke.
16779 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16780 // Otherwise, reset the permission.
16781 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16782 switch (revokeResult) {
16783 case PERMISSION_OPERATION_SUCCESS:
16784 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16785 writeRuntimePermissions = true;
16786 final int appId = ps.appId;
16787 mHandler.post(new Runnable() {
16789 public void run() {
16790 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16798 // Synchronously write as we are taking permissions away.
16799 if (writeRuntimePermissions) {
16800 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16803 // Synchronously write as we are taking permissions away.
16804 if (writeInstallPermissions) {
16805 mSettings.writeLPr();
16810 * Remove entries from the keystore daemon. Will only remove it if the
16811 * {@code appId} is valid.
16813 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16818 final KeyStore keyStore = KeyStore.getInstance();
16819 if (keyStore != null) {
16820 if (userId == UserHandle.USER_ALL) {
16821 for (final int individual : sUserManager.getUserIds()) {
16822 keyStore.clearUid(UserHandle.getUid(individual, appId));
16825 keyStore.clearUid(UserHandle.getUid(userId, appId));
16828 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16833 public void deleteApplicationCacheFiles(final String packageName,
16834 final IPackageDataObserver observer) {
16835 final int userId = UserHandle.getCallingUserId();
16836 deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16840 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16841 final IPackageDataObserver observer) {
16842 mContext.enforceCallingOrSelfPermission(
16843 android.Manifest.permission.DELETE_CACHE_FILES, null);
16844 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16845 /* requireFullPermission= */ true, /* checkShell= */ false,
16846 "delete application cache files");
16848 final PackageParser.Package pkg;
16849 synchronized (mPackages) {
16850 pkg = mPackages.get(packageName);
16853 // Queue up an async operation since the package deletion may take a little while.
16854 mHandler.post(new Runnable() {
16855 public void run() {
16856 synchronized (mInstallLock) {
16857 final int flags = StorageManager.FLAG_STORAGE_DE
16858 | StorageManager.FLAG_STORAGE_CE;
16859 // We're only clearing cache files, so we don't care if the
16860 // app is unfrozen and still able to run
16861 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16862 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16864 clearExternalStorageDataSync(packageName, userId, false);
16865 if (observer != null) {
16867 observer.onRemoveCompleted(packageName, true);
16868 } catch (RemoteException e) {
16869 Log.i(TAG, "Observer no longer exists.");
16877 public void getPackageSizeInfo(final String packageName, int userHandle,
16878 final IPackageStatsObserver observer) {
16879 mContext.enforceCallingOrSelfPermission(
16880 android.Manifest.permission.GET_PACKAGE_SIZE, null);
16881 if (packageName == null) {
16882 throw new IllegalArgumentException("Attempt to get size of null packageName");
16885 PackageStats stats = new PackageStats(packageName, userHandle);
16888 * Queue up an async operation since the package measurement may take a
16891 Message msg = mHandler.obtainMessage(INIT_COPY);
16892 msg.obj = new MeasureParams(stats, observer);
16893 mHandler.sendMessage(msg);
16896 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16897 final PackageSetting ps;
16898 synchronized (mPackages) {
16899 ps = mSettings.mPackages.get(packageName);
16901 Slog.w(TAG, "Failed to find settings for " + packageName);
16906 mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16907 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16908 ps.getCeDataInode(userId), ps.codePathString, stats);
16909 } catch (InstallerException e) {
16910 Slog.w(TAG, String.valueOf(e));
16914 // For now, ignore code size of packages on system partition
16915 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16916 stats.codeSize = 0;
16922 private int getUidTargetSdkVersionLockedLPr(int uid) {
16923 Object obj = mSettings.getUserIdLPr(uid);
16924 if (obj instanceof SharedUserSetting) {
16925 final SharedUserSetting sus = (SharedUserSetting) obj;
16926 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16927 final Iterator<PackageSetting> it = sus.packages.iterator();
16928 while (it.hasNext()) {
16929 final PackageSetting ps = it.next();
16930 if (ps.pkg != null) {
16931 int v = ps.pkg.applicationInfo.targetSdkVersion;
16932 if (v < vers) vers = v;
16936 } else if (obj instanceof PackageSetting) {
16937 final PackageSetting ps = (PackageSetting) obj;
16938 if (ps.pkg != null) {
16939 return ps.pkg.applicationInfo.targetSdkVersion;
16942 return Build.VERSION_CODES.CUR_DEVELOPMENT;
16946 public void addPreferredActivity(IntentFilter filter, int match,
16947 ComponentName[] set, ComponentName activity, int userId) {
16948 addPreferredActivityInternal(filter, match, set, activity, true, userId,
16949 "Adding preferred");
16952 private void addPreferredActivityInternal(IntentFilter filter, int match,
16953 ComponentName[] set, ComponentName activity, boolean always, int userId,
16956 int callingUid = Binder.getCallingUid();
16957 enforceCrossUserPermission(callingUid, userId,
16958 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16959 if (filter.countActions() == 0) {
16960 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16963 synchronized (mPackages) {
16964 if (mContext.checkCallingOrSelfPermission(
16965 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16966 != PackageManager.PERMISSION_GRANTED) {
16967 if (getUidTargetSdkVersionLockedLPr(callingUid)
16968 < Build.VERSION_CODES.FROYO) {
16969 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16973 mContext.enforceCallingOrSelfPermission(
16974 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16977 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16978 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16980 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
16981 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16982 scheduleWritePackageRestrictionsLocked(userId);
16983 postPreferredActivityChangedBroadcast(userId);
16987 private void postPreferredActivityChangedBroadcast(int userId) {
16988 mHandler.post(() -> {
16989 final IActivityManager am = ActivityManagerNative.getDefault();
16994 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16995 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16997 am.broadcastIntent(null, intent, null, null,
16998 0, null, null, null, android.app.AppOpsManager.OP_NONE,
16999 null, false, false, userId);
17000 } catch (RemoteException e) {
17006 public void replacePreferredActivity(IntentFilter filter, int match,
17007 ComponentName[] set, ComponentName activity, int userId) {
17008 if (filter.countActions() != 1) {
17009 throw new IllegalArgumentException(
17010 "replacePreferredActivity expects filter to have only 1 action.");
17012 if (filter.countDataAuthorities() != 0
17013 || filter.countDataPaths() != 0
17014 || filter.countDataSchemes() > 1
17015 || filter.countDataTypes() != 0) {
17016 throw new IllegalArgumentException(
17017 "replacePreferredActivity expects filter to have no data authorities, " +
17018 "paths, or types; and at most one scheme.");
17021 final int callingUid = Binder.getCallingUid();
17022 enforceCrossUserPermission(callingUid, userId,
17023 true /* requireFullPermission */, false /* checkShell */,
17024 "replace preferred activity");
17025 synchronized (mPackages) {
17026 if (mContext.checkCallingOrSelfPermission(
17027 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17028 != PackageManager.PERMISSION_GRANTED) {
17029 if (getUidTargetSdkVersionLockedLPr(callingUid)
17030 < Build.VERSION_CODES.FROYO) {
17031 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17032 + Binder.getCallingUid());
17035 mContext.enforceCallingOrSelfPermission(
17036 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17039 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17041 // Get all of the existing entries that exactly match this filter.
17042 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17043 if (existing != null && existing.size() == 1) {
17044 PreferredActivity cur = existing.get(0);
17045 if (DEBUG_PREFERRED) {
17046 Slog.i(TAG, "Checking replace of preferred:");
17047 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17048 if (!cur.mPref.mAlways) {
17049 Slog.i(TAG, " -- CUR; not mAlways!");
17051 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
17052 Slog.i(TAG, " -- CUR: mSet="
17053 + Arrays.toString(cur.mPref.mSetComponents));
17054 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
17055 Slog.i(TAG, " -- NEW: mMatch="
17056 + (match&IntentFilter.MATCH_CATEGORY_MASK));
17057 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
17058 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
17061 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17062 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17063 && cur.mPref.sameSet(set)) {
17064 // Setting the preferred activity to what it happens to be already
17065 if (DEBUG_PREFERRED) {
17066 Slog.i(TAG, "Replacing with same preferred activity "
17067 + cur.mPref.mShortComponent + " for user "
17069 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17075 if (existing != null) {
17076 if (DEBUG_PREFERRED) {
17077 Slog.i(TAG, existing.size() + " existing preferred matches for:");
17078 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17080 for (int i = 0; i < existing.size(); i++) {
17081 PreferredActivity pa = existing.get(i);
17082 if (DEBUG_PREFERRED) {
17083 Slog.i(TAG, "Removing existing preferred activity "
17084 + pa.mPref.mComponent + ":");
17085 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
17087 pir.removeFilter(pa);
17091 addPreferredActivityInternal(filter, match, set, activity, true, userId,
17092 "Replacing preferred");
17097 public void clearPackagePreferredActivities(String packageName) {
17098 final int uid = Binder.getCallingUid();
17100 synchronized (mPackages) {
17101 PackageParser.Package pkg = mPackages.get(packageName);
17102 if (pkg == null || pkg.applicationInfo.uid != uid) {
17103 if (mContext.checkCallingOrSelfPermission(
17104 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17105 != PackageManager.PERMISSION_GRANTED) {
17106 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17107 < Build.VERSION_CODES.FROYO) {
17108 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17109 + Binder.getCallingUid());
17112 mContext.enforceCallingOrSelfPermission(
17113 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17117 int user = UserHandle.getCallingUserId();
17118 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17119 scheduleWritePackageRestrictionsLocked(user);
17124 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17125 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17126 ArrayList<PreferredActivity> removed = null;
17127 boolean changed = false;
17128 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17129 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17130 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17131 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17134 Iterator<PreferredActivity> it = pir.filterIterator();
17135 while (it.hasNext()) {
17136 PreferredActivity pa = it.next();
17137 // Mark entry for removal only if it matches the package name
17138 // and the entry is of type "always".
17139 if (packageName == null ||
17140 (pa.mPref.mComponent.getPackageName().equals(packageName)
17141 && pa.mPref.mAlways)) {
17142 if (removed == null) {
17143 removed = new ArrayList<PreferredActivity>();
17148 if (removed != null) {
17149 for (int j=0; j<removed.size(); j++) {
17150 PreferredActivity pa = removed.get(j);
17151 pir.removeFilter(pa);
17157 postPreferredActivityChangedBroadcast(userId);
17162 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17163 private void clearIntentFilterVerificationsLPw(int userId) {
17164 final int packageCount = mPackages.size();
17165 for (int i = 0; i < packageCount; i++) {
17166 PackageParser.Package pkg = mPackages.valueAt(i);
17167 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17171 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17172 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17173 if (userId == UserHandle.USER_ALL) {
17174 if (mSettings.removeIntentFilterVerificationLPw(packageName,
17175 sUserManager.getUserIds())) {
17176 for (int oneUserId : sUserManager.getUserIds()) {
17177 scheduleWritePackageRestrictionsLocked(oneUserId);
17181 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17182 scheduleWritePackageRestrictionsLocked(userId);
17187 void clearDefaultBrowserIfNeeded(String packageName) {
17188 for (int oneUserId : sUserManager.getUserIds()) {
17189 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17190 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17191 if (packageName.equals(defaultBrowserPackageName)) {
17192 setDefaultBrowserPackageName(null, oneUserId);
17198 public void resetApplicationPreferences(int userId) {
17199 mContext.enforceCallingOrSelfPermission(
17200 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17201 final long identity = Binder.clearCallingIdentity();
17204 synchronized (mPackages) {
17205 clearPackagePreferredActivitiesLPw(null, userId);
17206 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17207 // TODO: We have to reset the default SMS and Phone. This requires
17208 // significant refactoring to keep all default apps in the package
17209 // manager (cleaner but more work) or have the services provide
17210 // callbacks to the package manager to request a default app reset.
17211 applyFactoryDefaultBrowserLPw(userId);
17212 clearIntentFilterVerificationsLPw(userId);
17213 primeDomainVerificationsLPw(userId);
17214 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17215 scheduleWritePackageRestrictionsLocked(userId);
17217 resetNetworkPolicies(userId);
17219 Binder.restoreCallingIdentity(identity);
17224 public int getPreferredActivities(List<IntentFilter> outFilters,
17225 List<ComponentName> outActivities, String packageName) {
17228 final int userId = UserHandle.getCallingUserId();
17230 synchronized (mPackages) {
17231 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17233 final Iterator<PreferredActivity> it = pir.filterIterator();
17234 while (it.hasNext()) {
17235 final PreferredActivity pa = it.next();
17236 if (packageName == null
17237 || (pa.mPref.mComponent.getPackageName().equals(packageName)
17238 && pa.mPref.mAlways)) {
17239 if (outFilters != null) {
17240 outFilters.add(new IntentFilter(pa));
17242 if (outActivities != null) {
17243 outActivities.add(pa.mPref.mComponent);
17254 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17256 int callingUid = Binder.getCallingUid();
17257 if (callingUid != Process.SYSTEM_UID) {
17258 throw new SecurityException(
17259 "addPersistentPreferredActivity can only be run by the system");
17261 if (filter.countActions() == 0) {
17262 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17265 synchronized (mPackages) {
17266 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17268 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17269 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17270 new PersistentPreferredActivity(filter, activity));
17271 scheduleWritePackageRestrictionsLocked(userId);
17272 postPreferredActivityChangedBroadcast(userId);
17277 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17278 int callingUid = Binder.getCallingUid();
17279 if (callingUid != Process.SYSTEM_UID) {
17280 throw new SecurityException(
17281 "clearPackagePersistentPreferredActivities can only be run by the system");
17283 ArrayList<PersistentPreferredActivity> removed = null;
17284 boolean changed = false;
17285 synchronized (mPackages) {
17286 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17287 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17288 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17290 if (userId != thisUserId) {
17293 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17294 while (it.hasNext()) {
17295 PersistentPreferredActivity ppa = it.next();
17296 // Mark entry for removal only if it matches the package name.
17297 if (ppa.mComponent.getPackageName().equals(packageName)) {
17298 if (removed == null) {
17299 removed = new ArrayList<PersistentPreferredActivity>();
17304 if (removed != null) {
17305 for (int j=0; j<removed.size(); j++) {
17306 PersistentPreferredActivity ppa = removed.get(j);
17307 ppir.removeFilter(ppa);
17314 scheduleWritePackageRestrictionsLocked(userId);
17315 postPreferredActivityChangedBroadcast(userId);
17321 * Common machinery for picking apart a restored XML blob and passing
17322 * it to a caller-supplied functor to be applied to the running system.
17324 private void restoreFromXml(XmlPullParser parser, int userId,
17325 String expectedStartTag, BlobXmlRestorer functor)
17326 throws IOException, XmlPullParserException {
17328 while ((type = parser.next()) != XmlPullParser.START_TAG
17329 && type != XmlPullParser.END_DOCUMENT) {
17331 if (type != XmlPullParser.START_TAG) {
17332 // oops didn't find a start tag?!
17333 if (DEBUG_BACKUP) {
17334 Slog.e(TAG, "Didn't find start tag during restore");
17338 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17339 // this is supposed to be TAG_PREFERRED_BACKUP
17340 if (!expectedStartTag.equals(parser.getName())) {
17341 if (DEBUG_BACKUP) {
17342 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17347 // skip interfering stuff, then we're aligned with the backing implementation
17348 while ((type = parser.next()) == XmlPullParser.TEXT) { }
17349 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17350 functor.apply(parser, userId);
17353 private interface BlobXmlRestorer {
17354 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17358 * Non-Binder method, support for the backup/restore mechanism: write the
17359 * full set of preferred activities in its canonical XML format. Returns the
17360 * XML output as a byte array, or null if there is none.
17363 public byte[] getPreferredActivityBackup(int userId) {
17364 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17365 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17368 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17370 final XmlSerializer serializer = new FastXmlSerializer();
17371 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17372 serializer.startDocument(null, true);
17373 serializer.startTag(null, TAG_PREFERRED_BACKUP);
17375 synchronized (mPackages) {
17376 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17379 serializer.endTag(null, TAG_PREFERRED_BACKUP);
17380 serializer.endDocument();
17381 serializer.flush();
17382 } catch (Exception e) {
17383 if (DEBUG_BACKUP) {
17384 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17389 return dataStream.toByteArray();
17393 public void restorePreferredActivities(byte[] backup, int userId) {
17394 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17395 throw new SecurityException("Only the system may call restorePreferredActivities()");
17399 final XmlPullParser parser = Xml.newPullParser();
17400 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17401 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17402 new BlobXmlRestorer() {
17404 public void apply(XmlPullParser parser, int userId)
17405 throws XmlPullParserException, IOException {
17406 synchronized (mPackages) {
17407 mSettings.readPreferredActivitiesLPw(parser, userId);
17411 } catch (Exception e) {
17412 if (DEBUG_BACKUP) {
17413 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17419 * Non-Binder method, support for the backup/restore mechanism: write the
17420 * default browser (etc) settings in its canonical XML format. Returns the default
17421 * browser XML representation as a byte array, or null if there is none.
17424 public byte[] getDefaultAppsBackup(int userId) {
17425 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17426 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17429 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17431 final XmlSerializer serializer = new FastXmlSerializer();
17432 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17433 serializer.startDocument(null, true);
17434 serializer.startTag(null, TAG_DEFAULT_APPS);
17436 synchronized (mPackages) {
17437 mSettings.writeDefaultAppsLPr(serializer, userId);
17440 serializer.endTag(null, TAG_DEFAULT_APPS);
17441 serializer.endDocument();
17442 serializer.flush();
17443 } catch (Exception e) {
17444 if (DEBUG_BACKUP) {
17445 Slog.e(TAG, "Unable to write default apps for backup", e);
17450 return dataStream.toByteArray();
17454 public void restoreDefaultApps(byte[] backup, int userId) {
17455 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17456 throw new SecurityException("Only the system may call restoreDefaultApps()");
17460 final XmlPullParser parser = Xml.newPullParser();
17461 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17462 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17463 new BlobXmlRestorer() {
17465 public void apply(XmlPullParser parser, int userId)
17466 throws XmlPullParserException, IOException {
17467 synchronized (mPackages) {
17468 mSettings.readDefaultAppsLPw(parser, userId);
17472 } catch (Exception e) {
17473 if (DEBUG_BACKUP) {
17474 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17480 public byte[] getIntentFilterVerificationBackup(int userId) {
17481 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17482 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17485 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17487 final XmlSerializer serializer = new FastXmlSerializer();
17488 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17489 serializer.startDocument(null, true);
17490 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17492 synchronized (mPackages) {
17493 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17496 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17497 serializer.endDocument();
17498 serializer.flush();
17499 } catch (Exception e) {
17500 if (DEBUG_BACKUP) {
17501 Slog.e(TAG, "Unable to write default apps for backup", e);
17506 return dataStream.toByteArray();
17510 public void restoreIntentFilterVerification(byte[] backup, int userId) {
17511 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17512 throw new SecurityException("Only the system may call restorePreferredActivities()");
17516 final XmlPullParser parser = Xml.newPullParser();
17517 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17518 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17519 new BlobXmlRestorer() {
17521 public void apply(XmlPullParser parser, int userId)
17522 throws XmlPullParserException, IOException {
17523 synchronized (mPackages) {
17524 mSettings.readAllDomainVerificationsLPr(parser, userId);
17525 mSettings.writeLPr();
17529 } catch (Exception e) {
17530 if (DEBUG_BACKUP) {
17531 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17537 public byte[] getPermissionGrantBackup(int userId) {
17538 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17539 throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17542 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17544 final XmlSerializer serializer = new FastXmlSerializer();
17545 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17546 serializer.startDocument(null, true);
17547 serializer.startTag(null, TAG_PERMISSION_BACKUP);
17549 synchronized (mPackages) {
17550 serializeRuntimePermissionGrantsLPr(serializer, userId);
17553 serializer.endTag(null, TAG_PERMISSION_BACKUP);
17554 serializer.endDocument();
17555 serializer.flush();
17556 } catch (Exception e) {
17557 if (DEBUG_BACKUP) {
17558 Slog.e(TAG, "Unable to write default apps for backup", e);
17563 return dataStream.toByteArray();
17567 public void restorePermissionGrants(byte[] backup, int userId) {
17568 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17569 throw new SecurityException("Only the system may call restorePermissionGrants()");
17573 final XmlPullParser parser = Xml.newPullParser();
17574 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17575 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17576 new BlobXmlRestorer() {
17578 public void apply(XmlPullParser parser, int userId)
17579 throws XmlPullParserException, IOException {
17580 synchronized (mPackages) {
17581 processRestoredPermissionGrantsLPr(parser, userId);
17585 } catch (Exception e) {
17586 if (DEBUG_BACKUP) {
17587 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17592 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17593 throws IOException {
17594 serializer.startTag(null, TAG_ALL_GRANTS);
17596 final int N = mSettings.mPackages.size();
17597 for (int i = 0; i < N; i++) {
17598 final PackageSetting ps = mSettings.mPackages.valueAt(i);
17599 boolean pkgGrantsKnown = false;
17601 PermissionsState packagePerms = ps.getPermissionsState();
17603 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17604 final int grantFlags = state.getFlags();
17605 // only look at grants that are not system/policy fixed
17606 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17607 final boolean isGranted = state.isGranted();
17608 // And only back up the user-twiddled state bits
17609 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17610 final String packageName = mSettings.mPackages.keyAt(i);
17611 if (!pkgGrantsKnown) {
17612 serializer.startTag(null, TAG_GRANT);
17613 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17614 pkgGrantsKnown = true;
17617 final boolean userSet =
17618 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17619 final boolean userFixed =
17620 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17621 final boolean revoke =
17622 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17624 serializer.startTag(null, TAG_PERMISSION);
17625 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17627 serializer.attribute(null, ATTR_IS_GRANTED, "true");
17630 serializer.attribute(null, ATTR_USER_SET, "true");
17633 serializer.attribute(null, ATTR_USER_FIXED, "true");
17636 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17638 serializer.endTag(null, TAG_PERMISSION);
17643 if (pkgGrantsKnown) {
17644 serializer.endTag(null, TAG_GRANT);
17648 serializer.endTag(null, TAG_ALL_GRANTS);
17651 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17652 throws XmlPullParserException, IOException {
17653 String pkgName = null;
17654 int outerDepth = parser.getDepth();
17656 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17657 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17658 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17662 final String tagName = parser.getName();
17663 if (tagName.equals(TAG_GRANT)) {
17664 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17665 if (DEBUG_BACKUP) {
17666 Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17668 } else if (tagName.equals(TAG_PERMISSION)) {
17670 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17671 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17673 int newFlagSet = 0;
17674 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17675 newFlagSet |= FLAG_PERMISSION_USER_SET;
17677 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17678 newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17680 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17681 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17683 if (DEBUG_BACKUP) {
17684 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName
17685 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17687 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17689 // Already installed so we apply the grant immediately
17690 if (DEBUG_BACKUP) {
17691 Slog.v(TAG, " + already installed; applying");
17693 PermissionsState perms = ps.getPermissionsState();
17694 BasePermission bp = mSettings.mPermissions.get(permName);
17697 perms.grantRuntimePermission(bp, userId);
17699 if (newFlagSet != 0) {
17700 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17704 // Need to wait for post-restore install to apply the grant
17705 if (DEBUG_BACKUP) {
17706 Slog.v(TAG, " - not yet installed; saving for later");
17708 mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17709 isGranted, newFlagSet, userId);
17712 PackageManagerService.reportSettingsProblem(Log.WARN,
17713 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17714 XmlUtils.skipCurrentTag(parser);
17718 scheduleWriteSettingsLocked();
17719 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17723 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17724 int sourceUserId, int targetUserId, int flags) {
17725 mContext.enforceCallingOrSelfPermission(
17726 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17727 int callingUid = Binder.getCallingUid();
17728 enforceOwnerRights(ownerPackage, callingUid);
17729 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17730 if (intentFilter.countActions() == 0) {
17731 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17734 synchronized (mPackages) {
17735 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17736 ownerPackage, targetUserId, flags);
17737 CrossProfileIntentResolver resolver =
17738 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17739 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17740 // We have all those whose filter is equal. Now checking if the rest is equal as well.
17741 if (existing != null) {
17742 int size = existing.size();
17743 for (int i = 0; i < size; i++) {
17744 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17749 resolver.addFilter(newFilter);
17750 scheduleWritePackageRestrictionsLocked(sourceUserId);
17755 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17756 mContext.enforceCallingOrSelfPermission(
17757 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17758 int callingUid = Binder.getCallingUid();
17759 enforceOwnerRights(ownerPackage, callingUid);
17760 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17761 synchronized (mPackages) {
17762 CrossProfileIntentResolver resolver =
17763 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17764 ArraySet<CrossProfileIntentFilter> set =
17765 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17766 for (CrossProfileIntentFilter filter : set) {
17767 if (filter.getOwnerPackage().equals(ownerPackage)) {
17768 resolver.removeFilter(filter);
17771 scheduleWritePackageRestrictionsLocked(sourceUserId);
17775 // Enforcing that callingUid is owning pkg on userId
17776 private void enforceOwnerRights(String pkg, int callingUid) {
17777 // The system owns everything.
17778 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17781 int callingUserId = UserHandle.getUserId(callingUid);
17782 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17784 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17787 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17788 throw new SecurityException("Calling uid " + callingUid
17789 + " does not own package " + pkg);
17794 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17795 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17798 private Intent getHomeIntent() {
17799 Intent intent = new Intent(Intent.ACTION_MAIN);
17800 intent.addCategory(Intent.CATEGORY_HOME);
17801 intent.addCategory(Intent.CATEGORY_DEFAULT);
17805 private IntentFilter getHomeFilter() {
17806 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17807 filter.addCategory(Intent.CATEGORY_HOME);
17808 filter.addCategory(Intent.CATEGORY_DEFAULT);
17812 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17814 Intent intent = getHomeIntent();
17815 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17816 PackageManager.GET_META_DATA, userId);
17817 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17818 true, false, false, userId);
17820 allHomeCandidates.clear();
17821 if (list != null) {
17822 for (ResolveInfo ri : list) {
17823 allHomeCandidates.add(ri);
17826 return (preferred == null || preferred.activityInfo == null)
17828 : new ComponentName(preferred.activityInfo.packageName,
17829 preferred.activityInfo.name);
17833 public void setHomeActivity(ComponentName comp, int userId) {
17834 ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17835 getHomeActivitiesAsUser(homeActivities, userId);
17837 boolean found = false;
17839 final int size = homeActivities.size();
17840 final ComponentName[] set = new ComponentName[size];
17841 for (int i = 0; i < size; i++) {
17842 final ResolveInfo candidate = homeActivities.get(i);
17843 final ActivityInfo info = candidate.activityInfo;
17844 final ComponentName activityName = new ComponentName(info.packageName, info.name);
17845 set[i] = activityName;
17846 if (!found && activityName.equals(comp)) {
17851 throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17854 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17855 set, comp, userId);
17858 private @Nullable String getSetupWizardPackageName() {
17859 final Intent intent = new Intent(Intent.ACTION_MAIN);
17860 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17862 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17863 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17864 | MATCH_DISABLED_COMPONENTS,
17865 UserHandle.myUserId());
17866 if (matches.size() == 1) {
17867 return matches.get(0).getComponentInfo().packageName;
17869 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17870 + ": matches=" + matches);
17875 private @Nullable String getStorageManagerPackageName() {
17876 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17878 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17879 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17880 | MATCH_DISABLED_COMPONENTS,
17881 UserHandle.myUserId());
17882 if (matches.size() == 1) {
17883 return matches.get(0).getComponentInfo().packageName;
17885 Slog.e(TAG, "There should probably be exactly one storage manager; found "
17886 + matches.size() + ": matches=" + matches);
17892 public void setApplicationEnabledSetting(String appPackageName,
17893 int newState, int flags, int userId, String callingPackage) {
17894 if (!sUserManager.exists(userId)) return;
17895 if (callingPackage == null) {
17896 callingPackage = Integer.toString(Binder.getCallingUid());
17898 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17902 public void setComponentEnabledSetting(ComponentName componentName,
17903 int newState, int flags, int userId) {
17904 if (!sUserManager.exists(userId)) return;
17905 setEnabledSetting(componentName.getPackageName(),
17906 componentName.getClassName(), newState, flags, userId, null);
17909 private void setEnabledSetting(final String packageName, String className, int newState,
17910 final int flags, int userId, String callingPackage) {
17911 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17912 || newState == COMPONENT_ENABLED_STATE_ENABLED
17913 || newState == COMPONENT_ENABLED_STATE_DISABLED
17914 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17915 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17916 throw new IllegalArgumentException("Invalid new component state: "
17919 PackageSetting pkgSetting;
17920 final int uid = Binder.getCallingUid();
17921 final int permission;
17922 if (uid == Process.SYSTEM_UID) {
17923 permission = PackageManager.PERMISSION_GRANTED;
17925 permission = mContext.checkCallingOrSelfPermission(
17926 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17928 enforceCrossUserPermission(uid, userId,
17929 false /* requireFullPermission */, true /* checkShell */, "set enabled");
17930 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17931 boolean sendNow = false;
17932 boolean isApp = (className == null);
17933 String componentName = isApp ? packageName : className;
17934 int packageUid = -1;
17935 ArrayList<String> components;
17938 synchronized (mPackages) {
17939 pkgSetting = mSettings.mPackages.get(packageName);
17940 if (pkgSetting == null) {
17941 if (className == null) {
17942 throw new IllegalArgumentException("Unknown package: " + packageName);
17944 throw new IllegalArgumentException(
17945 "Unknown component: " + packageName + "/" + className);
17949 // Limit who can change which apps
17950 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17951 // Don't allow apps that don't have permission to modify other apps
17952 if (!allowedByPermission) {
17953 throw new SecurityException(
17954 "Permission Denial: attempt to change component state from pid="
17955 + Binder.getCallingPid()
17956 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17958 // Don't allow changing protected packages.
17959 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17960 throw new SecurityException("Cannot disable a protected package: " + packageName);
17964 synchronized (mPackages) {
17965 if (uid == Process.SHELL_UID) {
17966 // Shell can only change whole packages between ENABLED and DISABLED_USER states
17967 int oldState = pkgSetting.getEnabled(userId);
17968 if (className == null
17970 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17971 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17972 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17974 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17975 || newState == COMPONENT_ENABLED_STATE_DEFAULT
17976 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17979 throw new SecurityException(
17980 "Shell cannot change component state for " + packageName + "/"
17981 + className + " to " + newState);
17984 if (className == null) {
17985 // We're dealing with an application/package level state change
17986 if (pkgSetting.getEnabled(userId) == newState) {
17990 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17991 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17992 // Don't care about who enables an app.
17993 callingPackage = null;
17995 pkgSetting.setEnabled(newState, userId, callingPackage);
17996 // pkgSetting.pkg.mSetEnabled = newState;
17998 // We're dealing with a component level state change
17999 // First, verify that this is a valid class name.
18000 PackageParser.Package pkg = pkgSetting.pkg;
18001 if (pkg == null || !pkg.hasComponentClassName(className)) {
18003 pkg.applicationInfo.targetSdkVersion >=
18004 Build.VERSION_CODES.JELLY_BEAN) {
18005 throw new IllegalArgumentException("Component class " + className
18006 + " does not exist in " + packageName);
18008 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18009 + className + " does not exist in " + packageName);
18012 switch (newState) {
18013 case COMPONENT_ENABLED_STATE_ENABLED:
18014 if (!pkgSetting.enableComponentLPw(className, userId)) {
18018 case COMPONENT_ENABLED_STATE_DISABLED:
18019 if (!pkgSetting.disableComponentLPw(className, userId)) {
18023 case COMPONENT_ENABLED_STATE_DEFAULT:
18024 if (!pkgSetting.restoreComponentLPw(className, userId)) {
18029 Slog.e(TAG, "Invalid new component state: " + newState);
18033 scheduleWritePackageRestrictionsLocked(userId);
18034 components = mPendingBroadcasts.get(userId, packageName);
18035 final boolean newPackage = components == null;
18037 components = new ArrayList<String>();
18039 if (!components.contains(componentName)) {
18040 components.add(componentName);
18042 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18044 // Purge entry from pending broadcast list if another one exists already
18045 // since we are sending one right away.
18046 mPendingBroadcasts.remove(userId, packageName);
18049 mPendingBroadcasts.put(userId, packageName, components);
18051 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18052 // Schedule a message
18053 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18058 long callingId = Binder.clearCallingIdentity();
18061 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18062 sendPackageChangedBroadcast(packageName,
18063 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18066 Binder.restoreCallingIdentity(callingId);
18071 public void flushPackageRestrictionsAsUser(int userId) {
18072 if (!sUserManager.exists(userId)) {
18075 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18076 false /* checkShell */, "flushPackageRestrictions");
18077 synchronized (mPackages) {
18078 mSettings.writePackageRestrictionsLPr(userId);
18079 mDirtyUsers.remove(userId);
18080 if (mDirtyUsers.isEmpty()) {
18081 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18086 private void sendPackageChangedBroadcast(String packageName,
18087 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18089 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18091 Bundle extras = new Bundle(4);
18092 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18093 String nameList[] = new String[componentNames.size()];
18094 componentNames.toArray(nameList);
18095 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18096 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18097 extras.putInt(Intent.EXTRA_UID, packageUid);
18098 // If this is not reporting a change of the overall package, then only send it
18099 // to registered receivers. We don't want to launch a swath of apps for every
18100 // little component state change.
18101 final int flags = !componentNames.contains(packageName)
18102 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18103 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null,
18104 new int[] {UserHandle.getUserId(packageUid)});
18108 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18109 if (!sUserManager.exists(userId)) return;
18110 final int uid = Binder.getCallingUid();
18111 final int permission = mContext.checkCallingOrSelfPermission(
18112 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18113 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18114 enforceCrossUserPermission(uid, userId,
18115 true /* requireFullPermission */, true /* checkShell */, "stop package");
18117 synchronized (mPackages) {
18118 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18119 allowedByPermission, uid, userId)) {
18120 scheduleWritePackageRestrictionsLocked(userId);
18126 public String getInstallerPackageName(String packageName) {
18128 synchronized (mPackages) {
18129 return mSettings.getInstallerPackageNameLPr(packageName);
18133 public boolean isOrphaned(String packageName) {
18135 synchronized (mPackages) {
18136 return mSettings.isOrphaned(packageName);
18141 public int getApplicationEnabledSetting(String packageName, int userId) {
18142 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18143 int uid = Binder.getCallingUid();
18144 enforceCrossUserPermission(uid, userId,
18145 false /* requireFullPermission */, false /* checkShell */, "get enabled");
18147 synchronized (mPackages) {
18148 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18153 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18154 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18155 int uid = Binder.getCallingUid();
18156 enforceCrossUserPermission(uid, userId,
18157 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18159 synchronized (mPackages) {
18160 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18165 public void enterSafeMode() {
18166 enforceSystemOrRoot("Only the system can request entering safe mode");
18168 if (!mSystemReady) {
18174 public void systemReady() {
18175 mSystemReady = true;
18177 // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18178 // disabled after already being started.
18179 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18180 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18182 // Read the compatibilty setting when the system is ready.
18183 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18184 mContext.getContentResolver(),
18185 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18186 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18187 if (DEBUG_SETTINGS) {
18188 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18191 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18193 synchronized (mPackages) {
18194 // Verify that all of the preferred activity components actually
18195 // exist. It is possible for applications to be updated and at
18196 // that point remove a previously declared activity component that
18197 // had been set as a preferred activity. We try to clean this up
18198 // the next time we encounter that preferred activity, but it is
18199 // possible for the user flow to never be able to return to that
18200 // situation so here we do a sanity check to make sure we haven't
18201 // left any junk around.
18202 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18203 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18204 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18206 for (PreferredActivity pa : pir.filterSet()) {
18207 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18211 if (removed.size() > 0) {
18212 for (int r=0; r<removed.size(); r++) {
18213 PreferredActivity pa = removed.get(r);
18214 Slog.w(TAG, "Removing dangling preferred activity: "
18215 + pa.mPref.mComponent);
18216 pir.removeFilter(pa);
18218 mSettings.writePackageRestrictionsLPr(
18219 mSettings.mPreferredActivities.keyAt(i));
18223 for (int userId : UserManagerService.getInstance().getUserIds()) {
18224 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18225 grantPermissionsUserIds = ArrayUtils.appendInt(
18226 grantPermissionsUserIds, userId);
18230 sUserManager.systemReady();
18232 // If we upgraded grant all default permissions before kicking off.
18233 for (int userId : grantPermissionsUserIds) {
18234 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18237 // If we did not grant default permissions, we preload from this the
18238 // default permission exceptions lazily to ensure we don't hit the
18239 // disk on a new user creation.
18240 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18241 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18244 // Kick off any messages waiting for system ready
18245 if (mPostSystemReadyMessages != null) {
18246 for (Message msg : mPostSystemReadyMessages) {
18247 msg.sendToTarget();
18249 mPostSystemReadyMessages = null;
18252 // Watch for external volumes that come and go over time
18253 final StorageManager storage = mContext.getSystemService(StorageManager.class);
18254 storage.registerListener(mStorageListener);
18256 mInstallerService.systemReady();
18257 mPackageDexOptimizer.systemReady();
18259 MountServiceInternal mountServiceInternal = LocalServices.getService(
18260 MountServiceInternal.class);
18261 mountServiceInternal.addExternalStoragePolicy(
18262 new MountServiceInternal.ExternalStorageMountPolicy() {
18264 public int getMountMode(int uid, String packageName) {
18265 if (Process.isIsolated(uid)) {
18266 return Zygote.MOUNT_EXTERNAL_NONE;
18268 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18269 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18271 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18272 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18274 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18275 return Zygote.MOUNT_EXTERNAL_READ;
18277 return Zygote.MOUNT_EXTERNAL_WRITE;
18281 public boolean hasExternalStorage(int uid, String packageName) {
18286 // Now that we're mostly running, clean up stale users and apps
18287 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18288 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18292 public boolean isSafeMode() {
18297 public boolean hasSystemUidErrors() {
18298 return mHasSystemUidErrors;
18301 static String arrayToString(int[] array) {
18302 StringBuffer buf = new StringBuffer(128);
18304 if (array != null) {
18305 for (int i=0; i<array.length; i++) {
18306 if (i > 0) buf.append(", ");
18307 buf.append(array[i]);
18311 return buf.toString();
18314 static class DumpState {
18315 public static final int DUMP_LIBS = 1 << 0;
18316 public static final int DUMP_FEATURES = 1 << 1;
18317 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18318 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18319 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18320 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18321 public static final int DUMP_PERMISSIONS = 1 << 6;
18322 public static final int DUMP_PACKAGES = 1 << 7;
18323 public static final int DUMP_SHARED_USERS = 1 << 8;
18324 public static final int DUMP_MESSAGES = 1 << 9;
18325 public static final int DUMP_PROVIDERS = 1 << 10;
18326 public static final int DUMP_VERIFIERS = 1 << 11;
18327 public static final int DUMP_PREFERRED = 1 << 12;
18328 public static final int DUMP_PREFERRED_XML = 1 << 13;
18329 public static final int DUMP_KEYSETS = 1 << 14;
18330 public static final int DUMP_VERSION = 1 << 15;
18331 public static final int DUMP_INSTALLS = 1 << 16;
18332 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18333 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18334 public static final int DUMP_FROZEN = 1 << 19;
18335 public static final int DUMP_DEXOPT = 1 << 20;
18336 public static final int DUMP_COMPILER_STATS = 1 << 21;
18338 public static final int OPTION_SHOW_FILTERS = 1 << 0;
18340 private int mTypes;
18342 private int mOptions;
18344 private boolean mTitlePrinted;
18346 private SharedUserSetting mSharedUser;
18348 public boolean isDumping(int type) {
18349 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18353 return (mTypes & type) != 0;
18356 public void setDump(int type) {
18360 public boolean isOptionEnabled(int option) {
18361 return (mOptions & option) != 0;
18364 public void setOptionEnabled(int option) {
18365 mOptions |= option;
18368 public boolean onTitlePrinted() {
18369 final boolean printed = mTitlePrinted;
18370 mTitlePrinted = true;
18374 public boolean getTitlePrinted() {
18375 return mTitlePrinted;
18378 public void setTitlePrinted(boolean enabled) {
18379 mTitlePrinted = enabled;
18382 public SharedUserSetting getSharedUser() {
18383 return mSharedUser;
18386 public void setSharedUser(SharedUserSetting user) {
18387 mSharedUser = user;
18392 public void onShellCommand(FileDescriptor in, FileDescriptor out,
18393 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18394 (new PackageManagerShellCommand(this)).exec(
18395 this, in, out, err, args, resultReceiver);
18399 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18400 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18401 != PackageManager.PERMISSION_GRANTED) {
18402 pw.println("Permission Denial: can't dump ActivityManager from from pid="
18403 + Binder.getCallingPid()
18404 + ", uid=" + Binder.getCallingUid()
18405 + " without permission "
18406 + android.Manifest.permission.DUMP);
18410 DumpState dumpState = new DumpState();
18411 boolean fullPreferred = false;
18412 boolean checkin = false;
18414 String packageName = null;
18415 ArraySet<String> permissionNames = null;
18418 while (opti < args.length) {
18419 String opt = args[opti];
18420 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18425 if ("-a".equals(opt)) {
18426 // Right now we only know how to print all.
18427 } else if ("-h".equals(opt)) {
18428 pw.println("Package manager dump options:");
18429 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
18430 pw.println(" --checkin: dump for a checkin");
18431 pw.println(" -f: print details of intent filters");
18432 pw.println(" -h: print this help");
18433 pw.println(" cmd may be one of:");
18434 pw.println(" l[ibraries]: list known shared libraries");
18435 pw.println(" f[eatures]: list device features");
18436 pw.println(" k[eysets]: print known keysets");
18437 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18438 pw.println(" perm[issions]: dump permissions");
18439 pw.println(" permission [name ...]: dump declaration and use of given permission");
18440 pw.println(" pref[erred]: print preferred package settings");
18441 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
18442 pw.println(" prov[iders]: dump content providers");
18443 pw.println(" p[ackages]: dump installed packages");
18444 pw.println(" s[hared-users]: dump shared user IDs");
18445 pw.println(" m[essages]: print collected runtime messages");
18446 pw.println(" v[erifiers]: print package verifier info");
18447 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
18448 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18449 pw.println(" version: print database version info");
18450 pw.println(" write: write current settings now");
18451 pw.println(" installs: details about install sessions");
18452 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
18453 pw.println(" dexopt: dump dexopt state");
18454 pw.println(" compiler-stats: dump compiler statistics");
18455 pw.println(" <package.name>: info about given package");
18457 } else if ("--checkin".equals(opt)) {
18459 } else if ("-f".equals(opt)) {
18460 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18462 pw.println("Unknown argument: " + opt + "; use -h for help");
18466 // Is the caller requesting to dump a particular piece of data?
18467 if (opti < args.length) {
18468 String cmd = args[opti];
18470 // Is this a package name?
18471 if ("android".equals(cmd) || cmd.contains(".")) {
18473 // When dumping a single package, we always dump all of its
18474 // filter information since the amount of data will be reasonable.
18475 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18476 } else if ("check-permission".equals(cmd)) {
18477 if (opti >= args.length) {
18478 pw.println("Error: check-permission missing permission argument");
18481 String perm = args[opti];
18483 if (opti >= args.length) {
18484 pw.println("Error: check-permission missing package argument");
18487 String pkg = args[opti];
18489 int user = UserHandle.getUserId(Binder.getCallingUid());
18490 if (opti < args.length) {
18492 user = Integer.parseInt(args[opti]);
18493 } catch (NumberFormatException e) {
18494 pw.println("Error: check-permission user argument is not a number: "
18499 pw.println(checkPermission(perm, pkg, user));
18501 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18502 dumpState.setDump(DumpState.DUMP_LIBS);
18503 } else if ("f".equals(cmd) || "features".equals(cmd)) {
18504 dumpState.setDump(DumpState.DUMP_FEATURES);
18505 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18506 if (opti >= args.length) {
18507 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18508 | DumpState.DUMP_SERVICE_RESOLVERS
18509 | DumpState.DUMP_RECEIVER_RESOLVERS
18510 | DumpState.DUMP_CONTENT_RESOLVERS);
18512 while (opti < args.length) {
18513 String name = args[opti];
18514 if ("a".equals(name) || "activity".equals(name)) {
18515 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18516 } else if ("s".equals(name) || "service".equals(name)) {
18517 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18518 } else if ("r".equals(name) || "receiver".equals(name)) {
18519 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18520 } else if ("c".equals(name) || "content".equals(name)) {
18521 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18523 pw.println("Error: unknown resolver table type: " + name);
18529 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18530 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18531 } else if ("permission".equals(cmd)) {
18532 if (opti >= args.length) {
18533 pw.println("Error: permission requires permission name");
18536 permissionNames = new ArraySet<>();
18537 while (opti < args.length) {
18538 permissionNames.add(args[opti]);
18541 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18542 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18543 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18544 dumpState.setDump(DumpState.DUMP_PREFERRED);
18545 } else if ("preferred-xml".equals(cmd)) {
18546 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18547 if (opti < args.length && "--full".equals(args[opti])) {
18548 fullPreferred = true;
18551 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18552 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18553 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18554 dumpState.setDump(DumpState.DUMP_PACKAGES);
18555 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18556 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18557 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18558 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18559 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18560 dumpState.setDump(DumpState.DUMP_MESSAGES);
18561 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18562 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18563 } else if ("i".equals(cmd) || "ifv".equals(cmd)
18564 || "intent-filter-verifiers".equals(cmd)) {
18565 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18566 } else if ("version".equals(cmd)) {
18567 dumpState.setDump(DumpState.DUMP_VERSION);
18568 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18569 dumpState.setDump(DumpState.DUMP_KEYSETS);
18570 } else if ("installs".equals(cmd)) {
18571 dumpState.setDump(DumpState.DUMP_INSTALLS);
18572 } else if ("frozen".equals(cmd)) {
18573 dumpState.setDump(DumpState.DUMP_FROZEN);
18574 } else if ("dexopt".equals(cmd)) {
18575 dumpState.setDump(DumpState.DUMP_DEXOPT);
18576 } else if ("compiler-stats".equals(cmd)) {
18577 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18578 } else if ("write".equals(cmd)) {
18579 synchronized (mPackages) {
18580 mSettings.writeLPr();
18581 pw.println("Settings written.");
18588 pw.println("vers,1");
18592 synchronized (mPackages) {
18593 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18595 if (dumpState.onTitlePrinted())
18597 pw.println("Database versions:");
18598 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
18602 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18604 if (dumpState.onTitlePrinted())
18606 pw.println("Verifiers:");
18607 pw.print(" Required: ");
18608 pw.print(mRequiredVerifierPackage);
18609 pw.print(" (uid=");
18610 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18611 UserHandle.USER_SYSTEM));
18613 } else if (mRequiredVerifierPackage != null) {
18614 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18616 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18617 UserHandle.USER_SYSTEM));
18621 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18622 packageName == null) {
18623 if (mIntentFilterVerifierComponent != null) {
18624 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18626 if (dumpState.onTitlePrinted())
18628 pw.println("Intent Filter Verifier:");
18629 pw.print(" Using: ");
18630 pw.print(verifierPackageName);
18631 pw.print(" (uid=");
18632 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18633 UserHandle.USER_SYSTEM));
18635 } else if (verifierPackageName != null) {
18636 pw.print("ifv,"); pw.print(verifierPackageName);
18638 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18639 UserHandle.USER_SYSTEM));
18643 pw.println("No Intent Filter Verifier available!");
18647 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18648 boolean printedHeader = false;
18649 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18650 while (it.hasNext()) {
18651 String name = it.next();
18652 SharedLibraryEntry ent = mSharedLibraries.get(name);
18654 if (!printedHeader) {
18655 if (dumpState.onTitlePrinted())
18657 pw.println("Libraries:");
18658 printedHeader = true;
18668 if (ent.path != null) {
18670 pw.print("(jar) ");
18671 pw.print(ent.path);
18674 pw.print(ent.path);
18678 pw.print("(apk) ");
18689 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18690 if (dumpState.onTitlePrinted())
18693 pw.println("Features:");
18696 for (FeatureInfo feat : mAvailableFeatures.values()) {
18699 pw.print(feat.name);
18701 pw.println(feat.version);
18704 pw.print(feat.name);
18705 if (feat.version > 0) {
18706 pw.print(" version=");
18707 pw.print(feat.version);
18714 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18715 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18716 : "Activity Resolver Table:", " ", packageName,
18717 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18718 dumpState.setTitlePrinted(true);
18721 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18722 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18723 : "Receiver Resolver Table:", " ", packageName,
18724 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18725 dumpState.setTitlePrinted(true);
18728 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18729 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18730 : "Service Resolver Table:", " ", packageName,
18731 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18732 dumpState.setTitlePrinted(true);
18735 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18736 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18737 : "Provider Resolver Table:", " ", packageName,
18738 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18739 dumpState.setTitlePrinted(true);
18743 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18744 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18745 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18746 int user = mSettings.mPreferredActivities.keyAt(i);
18748 dumpState.getTitlePrinted()
18749 ? "\nPreferred Activities User " + user + ":"
18750 : "Preferred Activities User " + user + ":", " ",
18751 packageName, true, false)) {
18752 dumpState.setTitlePrinted(true);
18757 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18759 FileOutputStream fout = new FileOutputStream(fd);
18760 BufferedOutputStream str = new BufferedOutputStream(fout);
18761 XmlSerializer serializer = new FastXmlSerializer();
18763 serializer.setOutput(str, StandardCharsets.UTF_8.name());
18764 serializer.startDocument(null, true);
18765 serializer.setFeature(
18766 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18767 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18768 serializer.endDocument();
18769 serializer.flush();
18770 } catch (IllegalArgumentException e) {
18771 pw.println("Failed writing: " + e);
18772 } catch (IllegalStateException e) {
18773 pw.println("Failed writing: " + e);
18774 } catch (IOException e) {
18775 pw.println("Failed writing: " + e);
18780 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18781 && packageName == null) {
18783 int count = mSettings.mPackages.size();
18785 pw.println("No applications!");
18788 final String prefix = " ";
18789 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18790 if (allPackageSettings.size() == 0) {
18791 pw.println("No domain preferred apps!");
18794 pw.println("App verification status:");
18797 for (PackageSetting ps : allPackageSettings) {
18798 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18799 if (ivi == null || ivi.getPackageName() == null) continue;
18800 pw.println(prefix + "Package: " + ivi.getPackageName());
18801 pw.println(prefix + "Domains: " + ivi.getDomainsString());
18802 pw.println(prefix + "Status: " + ivi.getStatusString());
18807 pw.println(prefix + "No app verification established.");
18810 for (int userId : sUserManager.getUserIds()) {
18811 pw.println("App linkages for user " + userId + ":");
18814 for (PackageSetting ps : allPackageSettings) {
18815 final long status = ps.getDomainVerificationStatusForUser(userId);
18816 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18819 pw.println(prefix + "Package: " + ps.name);
18820 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18821 String statusStr = IntentFilterVerificationInfo.
18822 getStatusStringFromValue(status);
18823 pw.println(prefix + "Status: " + statusStr);
18828 pw.println(prefix + "No configured app linkages.");
18836 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18837 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18838 if (packageName == null && permissionNames == null) {
18839 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18841 if (dumpState.onTitlePrinted())
18843 pw.println("AppOp Permissions:");
18845 pw.print(" AppOp Permission ");
18846 pw.print(mAppOpPermissionPackages.keyAt(iperm));
18848 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18849 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18850 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
18856 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18857 boolean printedSomething = false;
18858 for (PackageParser.Provider p : mProviders.mProviders.values()) {
18859 if (packageName != null && !packageName.equals(p.info.packageName)) {
18862 if (!printedSomething) {
18863 if (dumpState.onTitlePrinted())
18865 pw.println("Registered ContentProviders:");
18866 printedSomething = true;
18868 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
18869 pw.print(" "); pw.println(p.toString());
18871 printedSomething = false;
18872 for (Map.Entry<String, PackageParser.Provider> entry :
18873 mProvidersByAuthority.entrySet()) {
18874 PackageParser.Provider p = entry.getValue();
18875 if (packageName != null && !packageName.equals(p.info.packageName)) {
18878 if (!printedSomething) {
18879 if (dumpState.onTitlePrinted())
18881 pw.println("ContentProvider Authorities:");
18882 printedSomething = true;
18884 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
18885 pw.print(" "); pw.println(p.toString());
18886 if (p.info != null && p.info.applicationInfo != null) {
18887 final String appInfo = p.info.applicationInfo.toString();
18888 pw.print(" applicationInfo="); pw.println(appInfo);
18893 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18894 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18897 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18898 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18901 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18902 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18905 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18906 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18909 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18910 // XXX should handle packageName != null by dumping only install data that
18911 // the given package is involved with.
18912 if (dumpState.onTitlePrinted()) pw.println();
18913 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
18916 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18917 // XXX should handle packageName != null by dumping only install data that
18918 // the given package is involved with.
18919 if (dumpState.onTitlePrinted()) pw.println();
18921 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
18923 ipw.println("Frozen packages:");
18924 ipw.increaseIndent();
18925 if (mFrozenPackages.size() == 0) {
18926 ipw.println("(none)");
18928 for (int i = 0; i < mFrozenPackages.size(); i++) {
18929 ipw.println(mFrozenPackages.valueAt(i));
18932 ipw.decreaseIndent();
18935 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18936 if (dumpState.onTitlePrinted()) pw.println();
18937 dumpDexoptStateLPr(pw, packageName);
18940 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18941 if (dumpState.onTitlePrinted()) pw.println();
18942 dumpCompilerStatsLPr(pw, packageName);
18945 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18946 if (dumpState.onTitlePrinted()) pw.println();
18947 mSettings.dumpReadMessagesLPr(pw, dumpState);
18950 pw.println("Package warning messages:");
18951 BufferedReader in = null;
18952 String line = null;
18954 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18955 while ((line = in.readLine()) != null) {
18956 if (line.contains("ignored: updated version")) continue;
18959 } catch (IOException ignored) {
18961 IoUtils.closeQuietly(in);
18965 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18966 BufferedReader in = null;
18967 String line = null;
18969 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18970 while ((line = in.readLine()) != null) {
18971 if (line.contains("ignored: updated version")) continue;
18975 } catch (IOException ignored) {
18977 IoUtils.closeQuietly(in);
18983 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18984 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
18986 ipw.println("Dexopt state:");
18987 ipw.increaseIndent();
18988 Collection<PackageParser.Package> packages = null;
18989 if (packageName != null) {
18990 PackageParser.Package targetPackage = mPackages.get(packageName);
18991 if (targetPackage != null) {
18992 packages = Collections.singletonList(targetPackage);
18994 ipw.println("Unable to find package: " + packageName);
18998 packages = mPackages.values();
19001 for (PackageParser.Package pkg : packages) {
19002 ipw.println("[" + pkg.packageName + "]");
19003 ipw.increaseIndent();
19004 mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19005 ipw.decreaseIndent();
19009 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19010 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19012 ipw.println("Compiler stats:");
19013 ipw.increaseIndent();
19014 Collection<PackageParser.Package> packages = null;
19015 if (packageName != null) {
19016 PackageParser.Package targetPackage = mPackages.get(packageName);
19017 if (targetPackage != null) {
19018 packages = Collections.singletonList(targetPackage);
19020 ipw.println("Unable to find package: " + packageName);
19024 packages = mPackages.values();
19027 for (PackageParser.Package pkg : packages) {
19028 ipw.println("[" + pkg.packageName + "]");
19029 ipw.increaseIndent();
19031 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19032 if (stats == null) {
19033 ipw.println("(No recorded stats)");
19037 ipw.decreaseIndent();
19041 private String dumpDomainString(String packageName) {
19042 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19044 List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19046 ArraySet<String> result = new ArraySet<>();
19047 if (iviList.size() > 0) {
19048 for (IntentFilterVerificationInfo ivi : iviList) {
19049 for (String host : ivi.getDomains()) {
19054 if (filters != null && filters.size() > 0) {
19055 for (IntentFilter filter : filters) {
19056 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19057 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19058 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19059 result.addAll(filter.getHostsList());
19064 StringBuilder sb = new StringBuilder(result.size() * 16);
19065 for (String domain : result) {
19066 if (sb.length() > 0) sb.append(" ");
19069 return sb.toString();
19072 // ------- apps on sdcard specific code -------
19073 static final boolean DEBUG_SD_INSTALL = false;
19075 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19077 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19079 private boolean mMediaMounted = false;
19081 static String getEncryptKey() {
19083 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19084 SD_ENCRYPTION_KEYSTORE_NAME);
19085 if (sdEncKey == null) {
19086 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19087 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19088 if (sdEncKey == null) {
19089 Slog.e(TAG, "Failed to create encryption keys");
19094 } catch (NoSuchAlgorithmException nsae) {
19095 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19097 } catch (IOException ioe) {
19098 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19104 * Update media status on PackageManager.
19107 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19108 int callingUid = Binder.getCallingUid();
19109 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19110 throw new SecurityException("Media status can only be updated by the system");
19112 // reader; this apparently protects mMediaMounted, but should probably
19113 // be a different lock in that case.
19114 synchronized (mPackages) {
19115 Log.i(TAG, "Updating external media status from "
19116 + (mMediaMounted ? "mounted" : "unmounted") + " to "
19117 + (mediaStatus ? "mounted" : "unmounted"));
19118 if (DEBUG_SD_INSTALL)
19119 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19120 + ", mMediaMounted=" + mMediaMounted);
19121 if (mediaStatus == mMediaMounted) {
19122 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19124 mHandler.sendMessage(msg);
19127 mMediaMounted = mediaStatus;
19129 // Queue up an async operation since the package installation may take a
19131 mHandler.post(new Runnable() {
19132 public void run() {
19133 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19139 * Called by MountService when the initial ASECs to scan are available.
19140 * Should block until all the ASEC containers are finished being scanned.
19142 public void scanAvailableAsecs() {
19143 updateExternalMediaStatusInner(true, false, false);
19147 * Collect information of applications on external media, map them against
19148 * existing containers and update information based on current mount status.
19149 * Please note that we always have to report status if reportStatus has been
19150 * set to true especially when unloading packages.
19152 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19153 boolean externalStorage) {
19154 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19155 int[] uidArr = EmptyArray.INT;
19157 final String[] list = PackageHelper.getSecureContainerList();
19158 if (ArrayUtils.isEmpty(list)) {
19159 Log.i(TAG, "No secure containers found");
19161 // Process list of secure containers and categorize them
19162 // as active or stale based on their package internal state.
19165 synchronized (mPackages) {
19166 for (String cid : list) {
19167 // Leave stages untouched for now; installer service owns them
19168 if (PackageInstallerService.isStageName(cid)) continue;
19170 if (DEBUG_SD_INSTALL)
19171 Log.i(TAG, "Processing container " + cid);
19172 String pkgName = getAsecPackageName(cid);
19173 if (pkgName == null) {
19174 Slog.i(TAG, "Found stale container " + cid + " with no package name");
19177 if (DEBUG_SD_INSTALL)
19178 Log.i(TAG, "Looking for pkg : " + pkgName);
19180 final PackageSetting ps = mSettings.mPackages.get(pkgName);
19182 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19187 * Skip packages that are not external if we're unmounting
19188 * external storage.
19190 if (externalStorage && !isMounted && !isExternal(ps)) {
19194 final AsecInstallArgs args = new AsecInstallArgs(cid,
19195 getAppDexInstructionSets(ps), ps.isForwardLocked());
19196 // The package status is changed only if the code path
19197 // matches between settings and the container id.
19198 if (ps.codePathString != null
19199 && ps.codePathString.startsWith(args.getCodePath())) {
19200 if (DEBUG_SD_INSTALL) {
19201 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19202 + " at code path: " + ps.codePathString);
19205 // We do have a valid package installed on sdcard
19206 processCids.put(args, ps.codePathString);
19207 final int uid = ps.appId;
19209 uidArr = ArrayUtils.appendInt(uidArr, uid);
19212 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19213 + ps.codePathString);
19218 Arrays.sort(uidArr);
19221 // Process packages with valid entries.
19223 if (DEBUG_SD_INSTALL)
19224 Log.i(TAG, "Loading packages");
19225 loadMediaPackages(processCids, uidArr, externalStorage);
19226 startCleaningPackages();
19227 mInstallerService.onSecureContainersAvailable();
19229 if (DEBUG_SD_INSTALL)
19230 Log.i(TAG, "Unloading packages");
19231 unloadMediaPackages(processCids, uidArr, reportStatus);
19235 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19236 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19237 final int size = infos.size();
19238 final String[] packageNames = new String[size];
19239 final int[] packageUids = new int[size];
19240 for (int i = 0; i < size; i++) {
19241 final ApplicationInfo info = infos.get(i);
19242 packageNames[i] = info.packageName;
19243 packageUids[i] = info.uid;
19245 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19249 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19250 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19251 sendResourcesChangedBroadcast(mediaStatus, replacing,
19252 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19255 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19256 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19257 int size = pkgList.length;
19259 // Send broadcasts here
19260 Bundle extras = new Bundle();
19261 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19262 if (uidArr != null) {
19263 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19266 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19268 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19269 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19270 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19275 * Look at potentially valid container ids from processCids If package
19276 * information doesn't match the one on record or package scanning fails,
19277 * the cid is added to list of removeCids. We currently don't delete stale
19280 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19281 boolean externalStorage) {
19282 ArrayList<String> pkgList = new ArrayList<String>();
19283 Set<AsecInstallArgs> keys = processCids.keySet();
19285 for (AsecInstallArgs args : keys) {
19286 String codePath = processCids.get(args);
19287 if (DEBUG_SD_INSTALL)
19288 Log.i(TAG, "Loading container : " + args.cid);
19289 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19291 // Make sure there are no container errors first.
19292 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19293 Slog.e(TAG, "Failed to mount cid : " + args.cid
19294 + " when installing from sdcard");
19297 // Check code path here.
19298 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19299 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19300 + " does not match one in settings " + codePath);
19304 int parseFlags = mDefParseFlags;
19305 if (args.isExternalAsec()) {
19306 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19308 if (args.isFwdLocked()) {
19309 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19312 synchronized (mInstallLock) {
19313 PackageParser.Package pkg = null;
19315 // Sadly we don't know the package name yet to freeze it
19316 pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19317 SCAN_IGNORE_FROZEN, 0, null);
19318 } catch (PackageManagerException e) {
19319 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19321 // Scan the package
19324 * TODO why is the lock being held? doPostInstall is
19325 * called in other places without the lock. This needs
19326 * to be straightened out.
19329 synchronized (mPackages) {
19330 retCode = PackageManager.INSTALL_SUCCEEDED;
19331 pkgList.add(pkg.packageName);
19332 // Post process args
19333 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19334 pkg.applicationInfo.uid);
19337 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
19342 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19343 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19348 synchronized (mPackages) {
19349 // If the platform SDK has changed since the last time we booted,
19350 // we need to re-grant app permission to catch any new ones that
19351 // appear. This is really a hack, and means that apps can in some
19352 // cases get permissions that the user didn't initially explicitly
19353 // allow... it would be nice to have some better way to handle
19355 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19356 : mSettings.getInternalVersion();
19357 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19358 : StorageManager.UUID_PRIVATE_INTERNAL;
19360 int updateFlags = UPDATE_PERMISSIONS_ALL;
19361 if (ver.sdkVersion != mSdkVersion) {
19362 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19363 + mSdkVersion + "; regranting permissions for external");
19364 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19366 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19368 // Yay, everything is now upgraded
19369 ver.forceCurrent();
19371 // can downgrade to reader
19372 // Persist settings
19373 mSettings.writeLPr();
19375 // Send a broadcast to let everyone know we are done processing
19376 if (pkgList.size() > 0) {
19377 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19382 * Utility method to unload a list of specified containers
19384 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19385 // Just unmount all valid containers.
19386 for (AsecInstallArgs arg : cidArgs) {
19387 synchronized (mInstallLock) {
19388 arg.doPostDeleteLI(false);
19394 * Unload packages mounted on external media. This involves deleting package
19395 * data from internal structures, sending broadcasts about disabled packages,
19396 * gc'ing to free up references, unmounting all secure containers
19397 * corresponding to packages on external media, and posting a
19398 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19399 * that we always have to post this message if status has been requested no
19402 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19403 final boolean reportStatus) {
19404 if (DEBUG_SD_INSTALL)
19405 Log.i(TAG, "unloading media packages");
19406 ArrayList<String> pkgList = new ArrayList<String>();
19407 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19408 final Set<AsecInstallArgs> keys = processCids.keySet();
19409 for (AsecInstallArgs args : keys) {
19410 String pkgName = args.getPackageName();
19411 if (DEBUG_SD_INSTALL)
19412 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19413 // Delete package internally
19414 PackageRemovedInfo outInfo = new PackageRemovedInfo();
19415 synchronized (mInstallLock) {
19416 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19418 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19419 "unloadMediaPackages")) {
19420 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19424 pkgList.add(pkgName);
19426 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19427 failedList.add(args);
19433 synchronized (mPackages) {
19434 // We didn't update the settings after removing each package;
19435 // write them now for all packages.
19436 mSettings.writeLPr();
19439 // We have to absolutely send UPDATED_MEDIA_STATUS only
19440 // after confirming that all the receivers processed the ordered
19441 // broadcast when packages get disabled, force a gc to clean things up.
19442 // and unload all the containers.
19443 if (pkgList.size() > 0) {
19444 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19445 new IIntentReceiver.Stub() {
19446 public void performReceive(Intent intent, int resultCode, String data,
19447 Bundle extras, boolean ordered, boolean sticky,
19448 int sendingUser) throws RemoteException {
19449 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19450 reportStatus ? 1 : 0, 1, keys);
19451 mHandler.sendMessage(msg);
19455 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19457 mHandler.sendMessage(msg);
19461 private void loadPrivatePackages(final VolumeInfo vol) {
19462 mHandler.post(new Runnable() {
19464 public void run() {
19465 loadPrivatePackagesInner(vol);
19470 private void loadPrivatePackagesInner(VolumeInfo vol) {
19471 final String volumeUuid = vol.fsUuid;
19472 if (TextUtils.isEmpty(volumeUuid)) {
19473 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19477 final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19478 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19479 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19481 final VersionInfo ver;
19482 final List<PackageSetting> packages;
19483 synchronized (mPackages) {
19484 ver = mSettings.findOrCreateVersion(volumeUuid);
19485 packages = mSettings.getVolumePackagesLPr(volumeUuid);
19488 for (PackageSetting ps : packages) {
19489 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19490 synchronized (mInstallLock) {
19491 final PackageParser.Package pkg;
19493 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19494 loaded.add(pkg.applicationInfo);
19496 } catch (PackageManagerException e) {
19497 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19500 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19501 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19502 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19503 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19508 // Reconcile app data for all started/unlocked users
19509 final StorageManager sm = mContext.getSystemService(StorageManager.class);
19510 final UserManager um = mContext.getSystemService(UserManager.class);
19511 UserManagerInternal umInternal = getUserManagerInternal();
19512 for (UserInfo user : um.getUsers()) {
19514 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19515 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19516 } else if (umInternal.isUserRunning(user.id)) {
19517 flags = StorageManager.FLAG_STORAGE_DE;
19523 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19524 synchronized (mInstallLock) {
19525 reconcileAppsDataLI(volumeUuid, user.id, flags);
19527 } catch (IllegalStateException e) {
19528 // Device was probably ejected, and we'll process that event momentarily
19529 Slog.w(TAG, "Failed to prepare storage: " + e);
19533 synchronized (mPackages) {
19534 int updateFlags = UPDATE_PERMISSIONS_ALL;
19535 if (ver.sdkVersion != mSdkVersion) {
19536 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19537 + mSdkVersion + "; regranting permissions for " + volumeUuid);
19538 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19540 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19542 // Yay, everything is now upgraded
19543 ver.forceCurrent();
19545 mSettings.writeLPr();
19548 for (PackageFreezer freezer : freezers) {
19552 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19553 sendResourcesChangedBroadcast(true, false, loaded, null);
19556 private void unloadPrivatePackages(final VolumeInfo vol) {
19557 mHandler.post(new Runnable() {
19559 public void run() {
19560 unloadPrivatePackagesInner(vol);
19565 private void unloadPrivatePackagesInner(VolumeInfo vol) {
19566 final String volumeUuid = vol.fsUuid;
19567 if (TextUtils.isEmpty(volumeUuid)) {
19568 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19572 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19573 synchronized (mInstallLock) {
19574 synchronized (mPackages) {
19575 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19576 for (PackageSetting ps : packages) {
19577 if (ps.pkg == null) continue;
19579 final ApplicationInfo info = ps.pkg.applicationInfo;
19580 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19581 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19583 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19584 "unloadPrivatePackagesInner")) {
19585 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19587 unloaded.add(info);
19589 Slog.w(TAG, "Failed to unload " + ps.codePath);
19593 // Try very hard to release any references to this package
19594 // so we don't risk the system server being killed due to
19596 AttributeCache.instance().removePackage(ps.name);
19599 mSettings.writeLPr();
19603 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19604 sendResourcesChangedBroadcast(false, false, unloaded, null);
19606 // Try very hard to release any references to this path so we don't risk
19607 // the system server being killed due to open FDs
19608 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19610 for (int i = 0; i < 3; i++) {
19612 System.runFinalization();
19617 * Prepare storage areas for given user on all mounted devices.
19619 void prepareUserData(int userId, int userSerial, int flags) {
19620 synchronized (mInstallLock) {
19621 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19622 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19623 final String volumeUuid = vol.getFsUuid();
19624 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19629 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19630 boolean allowRecover) {
19631 // Prepare storage and verify that serial numbers are consistent; if
19632 // there's a mismatch we need to destroy to avoid leaking data
19633 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19635 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19637 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19638 UserManagerService.enforceSerialNumber(
19639 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19640 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19641 UserManagerService.enforceSerialNumber(
19642 Environment.getDataSystemDeDirectory(userId), userSerial);
19645 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19646 UserManagerService.enforceSerialNumber(
19647 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19648 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19649 UserManagerService.enforceSerialNumber(
19650 Environment.getDataSystemCeDirectory(userId), userSerial);
19654 synchronized (mInstallLock) {
19655 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19657 } catch (Exception e) {
19658 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19659 + " because we failed to prepare: " + e);
19660 destroyUserDataLI(volumeUuid, userId,
19661 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19663 if (allowRecover) {
19664 // Try one last time; if we fail again we're really in trouble
19665 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19671 * Destroy storage areas for given user on all mounted devices.
19673 void destroyUserData(int userId, int flags) {
19674 synchronized (mInstallLock) {
19675 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19676 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19677 final String volumeUuid = vol.getFsUuid();
19678 destroyUserDataLI(volumeUuid, userId, flags);
19683 private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19684 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19686 // Clean up app data, profile data, and media data
19687 mInstaller.destroyUserData(volumeUuid, userId, flags);
19689 // Clean up system data
19690 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19691 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19692 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19693 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19695 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19696 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19700 // Data with special labels is now gone, so finish the job
19701 storage.destroyUserStorage(volumeUuid, userId, flags);
19703 } catch (Exception e) {
19704 logCriticalInfo(Log.WARN,
19705 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19710 * Examine all users present on given mounted volume, and destroy data
19711 * belonging to users that are no longer valid, or whose user ID has been
19714 private void reconcileUsers(String volumeUuid) {
19715 final List<File> files = new ArrayList<>();
19716 Collections.addAll(files, FileUtils
19717 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19718 Collections.addAll(files, FileUtils
19719 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19720 Collections.addAll(files, FileUtils
19721 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19722 Collections.addAll(files, FileUtils
19723 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19724 for (File file : files) {
19725 if (!file.isDirectory()) continue;
19728 final UserInfo info;
19730 userId = Integer.parseInt(file.getName());
19731 info = sUserManager.getUserInfo(userId);
19732 } catch (NumberFormatException e) {
19733 Slog.w(TAG, "Invalid user directory " + file);
19737 boolean destroyUser = false;
19738 if (info == null) {
19739 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19740 + " because no matching user was found");
19741 destroyUser = true;
19742 } else if (!mOnlyCore) {
19744 UserManagerService.enforceSerialNumber(file, info.serialNumber);
19745 } catch (IOException e) {
19746 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19747 + " because we failed to enforce serial number: " + e);
19748 destroyUser = true;
19753 synchronized (mInstallLock) {
19754 destroyUserDataLI(volumeUuid, userId,
19755 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19761 private void assertPackageKnown(String volumeUuid, String packageName)
19762 throws PackageManagerException {
19763 synchronized (mPackages) {
19764 // Normalize package name to handle renamed packages
19765 packageName = normalizePackageNameLPr(packageName);
19767 final PackageSetting ps = mSettings.mPackages.get(packageName);
19769 throw new PackageManagerException("Package " + packageName + " is unknown");
19770 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19771 throw new PackageManagerException(
19772 "Package " + packageName + " found on unknown volume " + volumeUuid
19773 + "; expected volume " + ps.volumeUuid);
19778 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19779 throws PackageManagerException {
19780 synchronized (mPackages) {
19781 // Normalize package name to handle renamed packages
19782 packageName = normalizePackageNameLPr(packageName);
19784 final PackageSetting ps = mSettings.mPackages.get(packageName);
19786 throw new PackageManagerException("Package " + packageName + " is unknown");
19787 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19788 throw new PackageManagerException(
19789 "Package " + packageName + " found on unknown volume " + volumeUuid
19790 + "; expected volume " + ps.volumeUuid);
19791 } else if (!ps.getInstalled(userId)) {
19792 throw new PackageManagerException(
19793 "Package " + packageName + " not installed for user " + userId);
19799 * Examine all apps present on given mounted volume, and destroy apps that
19800 * aren't expected, either due to uninstallation or reinstallation on
19803 private void reconcileApps(String volumeUuid) {
19804 final File[] files = FileUtils
19805 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19806 for (File file : files) {
19807 final boolean isPackage = (isApkFile(file) || file.isDirectory())
19808 && !PackageInstallerService.isStageName(file.getName());
19810 // Ignore entries which are not packages
19815 final PackageLite pkg = PackageParser.parsePackageLite(file,
19816 PackageParser.PARSE_MUST_BE_APK);
19817 assertPackageKnown(volumeUuid, pkg.packageName);
19819 } catch (PackageParserException | PackageManagerException e) {
19820 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19821 synchronized (mInstallLock) {
19822 removeCodePathLI(file);
19829 * Reconcile all app data for the given user.
19831 * Verifies that directories exist and that ownership and labeling is
19832 * correct for all installed apps on all mounted volumes.
19834 void reconcileAppsData(int userId, int flags) {
19835 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19836 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19837 final String volumeUuid = vol.getFsUuid();
19838 synchronized (mInstallLock) {
19839 reconcileAppsDataLI(volumeUuid, userId, flags);
19845 * Reconcile all app data on given mounted volume.
19847 * Destroys app data that isn't expected, either due to uninstallation or
19848 * reinstallation on another volume.
19850 * Verifies that directories exist and that ownership and labeling is
19851 * correct for all installed apps.
19853 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19854 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19855 + Integer.toHexString(flags));
19857 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19858 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19860 // First look for stale data that doesn't belong, and check if things
19861 // have changed since we did our last restorecon
19862 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19863 if (StorageManager.isFileEncryptedNativeOrEmulated()
19864 && !StorageManager.isUserKeyUnlocked(userId)) {
19865 throw new RuntimeException(
19866 "Yikes, someone asked us to reconcile CE storage while " + userId
19867 + " was still locked; this would have caused massive data loss!");
19870 final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19871 for (File file : files) {
19872 final String packageName = file.getName();
19874 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19875 } catch (PackageManagerException e) {
19876 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19878 mInstaller.destroyAppData(volumeUuid, packageName, userId,
19879 StorageManager.FLAG_STORAGE_CE, 0);
19880 } catch (InstallerException e2) {
19881 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19886 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19887 final File[] files = FileUtils.listFilesOrEmpty(deDir);
19888 for (File file : files) {
19889 final String packageName = file.getName();
19891 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19892 } catch (PackageManagerException e) {
19893 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19895 mInstaller.destroyAppData(volumeUuid, packageName, userId,
19896 StorageManager.FLAG_STORAGE_DE, 0);
19897 } catch (InstallerException e2) {
19898 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19904 // Ensure that data directories are ready to roll for all packages
19905 // installed for this volume and user
19906 final List<PackageSetting> packages;
19907 synchronized (mPackages) {
19908 packages = mSettings.getVolumePackagesLPr(volumeUuid);
19910 int preparedCount = 0;
19911 for (PackageSetting ps : packages) {
19912 final String packageName = ps.name;
19913 if (ps.pkg == null) {
19914 Slog.w(TAG, "Odd, missing scanned package " + packageName);
19915 // TODO: might be due to legacy ASEC apps; we should circle back
19916 // and reconcile again once they're scanned
19920 if (ps.getInstalled(userId)) {
19921 prepareAppDataLIF(ps.pkg, userId, flags);
19923 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19924 // We may have just shuffled around app data directories, so
19925 // prepare them one more time
19926 prepareAppDataLIF(ps.pkg, userId, flags);
19933 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19937 * Prepare app data for the given app just after it was installed or
19938 * upgraded. This method carefully only touches users that it's installed
19939 * for, and it forces a restorecon to handle any seinfo changes.
19941 * Verifies that directories exist and that ownership and labeling is
19942 * correct for all installed apps. If there is an ownership mismatch, it
19943 * will try recovering system apps by wiping data; third-party app data is
19946 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19948 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19949 final PackageSetting ps;
19950 synchronized (mPackages) {
19951 ps = mSettings.mPackages.get(pkg.packageName);
19952 mSettings.writeKernelMappingLPr(ps);
19955 final UserManager um = mContext.getSystemService(UserManager.class);
19956 UserManagerInternal umInternal = getUserManagerInternal();
19957 for (UserInfo user : um.getUsers()) {
19959 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19960 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19961 } else if (umInternal.isUserRunning(user.id)) {
19962 flags = StorageManager.FLAG_STORAGE_DE;
19967 if (ps.getInstalled(user.id)) {
19968 // TODO: when user data is locked, mark that we're still dirty
19969 prepareAppDataLIF(pkg, user.id, flags);
19975 * Prepare app data for the given app.
19977 * Verifies that directories exist and that ownership and labeling is
19978 * correct for all installed apps. If there is an ownership mismatch, this
19979 * will try recovering system apps by wiping data; third-party app data is
19982 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19984 Slog.wtf(TAG, "Package was null!", new Throwable());
19987 prepareAppDataLeafLIF(pkg, userId, flags);
19988 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19989 for (int i = 0; i < childCount; i++) {
19990 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19994 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19995 if (DEBUG_APP_DATA) {
19996 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19997 + Integer.toHexString(flags));
20000 final String volumeUuid = pkg.volumeUuid;
20001 final String packageName = pkg.packageName;
20002 final ApplicationInfo app = pkg.applicationInfo;
20003 final int appId = UserHandle.getAppId(app.uid);
20005 Preconditions.checkNotNull(app.seinfo);
20008 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20009 appId, app.seinfo, app.targetSdkVersion);
20010 } catch (InstallerException e) {
20011 if (app.isSystemApp()) {
20012 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20013 + ", but trying to recover: " + e);
20014 destroyAppDataLeafLIF(pkg, userId, flags);
20016 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20017 appId, app.seinfo, app.targetSdkVersion);
20018 logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20019 } catch (InstallerException e2) {
20020 logCriticalInfo(Log.DEBUG, "Recovery failed!");
20023 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20027 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20029 // CE storage is unlocked right now, so read out the inode and
20030 // remember for use later when it's locked
20031 // TODO: mark this structure as dirty so we persist it!
20032 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20033 StorageManager.FLAG_STORAGE_CE);
20034 synchronized (mPackages) {
20035 final PackageSetting ps = mSettings.mPackages.get(packageName);
20037 ps.setCeDataInode(ceDataInode, userId);
20040 } catch (InstallerException e) {
20041 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20045 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20048 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20050 Slog.wtf(TAG, "Package was null!", new Throwable());
20053 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20054 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20055 for (int i = 0; i < childCount; i++) {
20056 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20060 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20061 final String volumeUuid = pkg.volumeUuid;
20062 final String packageName = pkg.packageName;
20063 final ApplicationInfo app = pkg.applicationInfo;
20065 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20066 // Create a native library symlink only if we have native libraries
20067 // and if the native libraries are 32 bit libraries. We do not provide
20068 // this symlink for 64 bit libraries.
20069 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20070 final String nativeLibPath = app.nativeLibraryDir;
20072 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20073 nativeLibPath, userId);
20074 } catch (InstallerException e) {
20075 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20082 * For system apps on non-FBE devices, this method migrates any existing
20083 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20084 * requested by the app.
20086 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20087 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20088 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20089 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20090 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20092 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20094 } catch (InstallerException e) {
20095 logCriticalInfo(Log.WARN,
20096 "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20104 public PackageFreezer freezePackage(String packageName, String killReason) {
20105 return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20108 public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20109 return new PackageFreezer(packageName, userId, killReason);
20112 public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20113 String killReason) {
20114 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20117 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20118 String killReason) {
20119 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20120 return new PackageFreezer();
20122 return freezePackage(packageName, userId, killReason);
20126 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20127 String killReason) {
20128 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20131 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20132 String killReason) {
20133 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20134 return new PackageFreezer();
20136 return freezePackage(packageName, userId, killReason);
20141 * Class that freezes and kills the given package upon creation, and
20142 * unfreezes it upon closing. This is typically used when doing surgery on
20143 * app code/data to prevent the app from running while you're working.
20145 private class PackageFreezer implements AutoCloseable {
20146 private final String mPackageName;
20147 private final PackageFreezer[] mChildren;
20149 private final boolean mWeFroze;
20151 private final AtomicBoolean mClosed = new AtomicBoolean();
20152 private final CloseGuard mCloseGuard = CloseGuard.get();
20155 * Create and return a stub freezer that doesn't actually do anything,
20156 * typically used when someone requested
20157 * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20158 * {@link PackageManager#DELETE_DONT_KILL_APP}.
20160 public PackageFreezer() {
20161 mPackageName = null;
20164 mCloseGuard.open("close");
20167 public PackageFreezer(String packageName, int userId, String killReason) {
20168 synchronized (mPackages) {
20169 mPackageName = packageName;
20170 mWeFroze = mFrozenPackages.add(mPackageName);
20172 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20174 killApplication(ps.name, ps.appId, userId, killReason);
20177 final PackageParser.Package p = mPackages.get(packageName);
20178 if (p != null && p.childPackages != null) {
20179 final int N = p.childPackages.size();
20180 mChildren = new PackageFreezer[N];
20181 for (int i = 0; i < N; i++) {
20182 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20183 userId, killReason);
20189 mCloseGuard.open("close");
20193 protected void finalize() throws Throwable {
20195 mCloseGuard.warnIfOpen();
20203 public void close() {
20204 mCloseGuard.close();
20205 if (mClosed.compareAndSet(false, true)) {
20206 synchronized (mPackages) {
20208 mFrozenPackages.remove(mPackageName);
20211 if (mChildren != null) {
20212 for (PackageFreezer freezer : mChildren) {
20222 * Verify that given package is currently frozen.
20224 private void checkPackageFrozen(String packageName) {
20225 synchronized (mPackages) {
20226 if (!mFrozenPackages.contains(packageName)) {
20227 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20233 public int movePackage(final String packageName, final String volumeUuid) {
20234 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20236 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20237 final int moveId = mNextMoveId.getAndIncrement();
20238 mHandler.post(new Runnable() {
20240 public void run() {
20242 movePackageInternal(packageName, volumeUuid, moveId, user);
20243 } catch (PackageManagerException e) {
20244 Slog.w(TAG, "Failed to move " + packageName, e);
20245 mMoveCallbacks.notifyStatusChanged(moveId,
20246 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20253 private void movePackageInternal(final String packageName, final String volumeUuid,
20254 final int moveId, UserHandle user) throws PackageManagerException {
20255 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20256 final PackageManager pm = mContext.getPackageManager();
20258 final boolean currentAsec;
20259 final String currentVolumeUuid;
20260 final File codeFile;
20261 final String installerPackageName;
20262 final String packageAbiOverride;
20264 final String seinfo;
20265 final String label;
20266 final int targetSdkVersion;
20267 final PackageFreezer freezer;
20268 final int[] installedUserIds;
20271 synchronized (mPackages) {
20272 final PackageParser.Package pkg = mPackages.get(packageName);
20273 final PackageSetting ps = mSettings.mPackages.get(packageName);
20274 if (pkg == null || ps == null) {
20275 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20278 if (pkg.applicationInfo.isSystemApp()) {
20279 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20280 "Cannot move system application");
20283 if (pkg.applicationInfo.isExternalAsec()) {
20284 currentAsec = true;
20285 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20286 } else if (pkg.applicationInfo.isForwardLocked()) {
20287 currentAsec = true;
20288 currentVolumeUuid = "forward_locked";
20290 currentAsec = false;
20291 currentVolumeUuid = ps.volumeUuid;
20293 final File probe = new File(pkg.codePath);
20294 final File probeOat = new File(probe, "oat");
20295 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20296 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20297 "Move only supported for modern cluster style installs");
20301 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20302 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20303 "Package already moved to " + volumeUuid);
20305 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20306 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20307 "Device admin cannot be moved");
20310 if (mFrozenPackages.contains(packageName)) {
20311 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20312 "Failed to move already frozen package");
20315 codeFile = new File(pkg.codePath);
20316 installerPackageName = ps.installerPackageName;
20317 packageAbiOverride = ps.cpuAbiOverrideString;
20318 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20319 seinfo = pkg.applicationInfo.seinfo;
20320 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20321 targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20322 freezer = freezePackage(packageName, "movePackageInternal");
20323 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20326 final Bundle extras = new Bundle();
20327 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20328 extras.putString(Intent.EXTRA_TITLE, label);
20329 mMoveCallbacks.notifyCreated(moveId, extras);
20332 final boolean moveCompleteApp;
20333 final File measurePath;
20335 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20336 installFlags = INSTALL_INTERNAL;
20337 moveCompleteApp = !currentAsec;
20338 measurePath = Environment.getDataAppDirectory(volumeUuid);
20339 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20340 installFlags = INSTALL_EXTERNAL;
20341 moveCompleteApp = false;
20342 measurePath = storage.getPrimaryPhysicalVolume().getPath();
20344 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20345 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20346 || !volume.isMountedWritable()) {
20348 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20349 "Move location not mounted private volume");
20352 Preconditions.checkState(!currentAsec);
20354 installFlags = INSTALL_INTERNAL;
20355 moveCompleteApp = true;
20356 measurePath = Environment.getDataAppDirectory(volumeUuid);
20359 final PackageStats stats = new PackageStats(null, -1);
20360 synchronized (mInstaller) {
20361 for (int userId : installedUserIds) {
20362 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20364 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20365 "Failed to measure package size");
20370 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20373 final long startFreeBytes = measurePath.getFreeSpace();
20374 final long sizeBytes;
20375 if (moveCompleteApp) {
20376 sizeBytes = stats.codeSize + stats.dataSize;
20378 sizeBytes = stats.codeSize;
20381 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20383 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20384 "Not enough free space to move");
20387 mMoveCallbacks.notifyStatusChanged(moveId, 10);
20389 final CountDownLatch installedLatch = new CountDownLatch(1);
20390 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20392 public void onUserActionRequired(Intent intent) throws RemoteException {
20393 throw new IllegalStateException();
20397 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20398 Bundle extras) throws RemoteException {
20399 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20400 + PackageManager.installStatusToString(returnCode, msg));
20402 installedLatch.countDown();
20405 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20407 case PackageInstaller.STATUS_SUCCESS:
20408 mMoveCallbacks.notifyStatusChanged(moveId,
20409 PackageManager.MOVE_SUCCEEDED);
20411 case PackageInstaller.STATUS_FAILURE_STORAGE:
20412 mMoveCallbacks.notifyStatusChanged(moveId,
20413 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20416 mMoveCallbacks.notifyStatusChanged(moveId,
20417 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20423 final MoveInfo move;
20424 if (moveCompleteApp) {
20425 // Kick off a thread to report progress estimates
20428 public void run() {
20431 if (installedLatch.await(1, TimeUnit.SECONDS)) {
20434 } catch (InterruptedException ignored) {
20437 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20438 final int progress = 10 + (int) MathUtils.constrain(
20439 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20440 mMoveCallbacks.notifyStatusChanged(moveId, progress);
20445 final String dataAppName = codeFile.getName();
20446 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20447 dataAppName, appId, seinfo, targetSdkVersion);
20452 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20454 final Message msg = mHandler.obtainMessage(INIT_COPY);
20455 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20456 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20457 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20458 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20459 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20462 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20463 System.identityHashCode(msg.obj));
20464 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20465 System.identityHashCode(msg.obj));
20467 mHandler.sendMessage(msg);
20471 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20472 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20474 final int realMoveId = mNextMoveId.getAndIncrement();
20475 final Bundle extras = new Bundle();
20476 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20477 mMoveCallbacks.notifyCreated(realMoveId, extras);
20479 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20481 public void onCreated(int moveId, Bundle extras) {
20486 public void onStatusChanged(int moveId, int status, long estMillis) {
20487 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20491 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20492 storage.setPrimaryStorageUuid(volumeUuid, callback);
20497 public int getMoveStatus(int moveId) {
20498 mContext.enforceCallingOrSelfPermission(
20499 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20500 return mMoveCallbacks.mLastStatus.get(moveId);
20504 public void registerMoveCallback(IPackageMoveObserver callback) {
20505 mContext.enforceCallingOrSelfPermission(
20506 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20507 mMoveCallbacks.register(callback);
20511 public void unregisterMoveCallback(IPackageMoveObserver callback) {
20512 mContext.enforceCallingOrSelfPermission(
20513 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20514 mMoveCallbacks.unregister(callback);
20518 public boolean setInstallLocation(int loc) {
20519 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20521 if (getInstallLocation() == loc) {
20524 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20525 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20526 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20527 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20534 public int getInstallLocation() {
20535 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20536 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20537 PackageHelper.APP_INSTALL_AUTO);
20540 /** Called by UserManagerService */
20541 void cleanUpUser(UserManagerService userManager, int userHandle) {
20542 synchronized (mPackages) {
20543 mDirtyUsers.remove(userHandle);
20544 mUserNeedsBadging.delete(userHandle);
20545 mSettings.removeUserLPw(userHandle);
20546 mPendingBroadcasts.remove(userHandle);
20547 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20548 removeUnusedPackagesLPw(userManager, userHandle);
20553 * We're removing userHandle and would like to remove any downloaded packages
20554 * that are no longer in use by any other user.
20555 * @param userHandle the user being removed
20557 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20558 final boolean DEBUG_CLEAN_APKS = false;
20559 int [] users = userManager.getUserIds();
20560 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20561 while (psit.hasNext()) {
20562 PackageSetting ps = psit.next();
20563 if (ps.pkg == null) {
20566 final String packageName = ps.pkg.packageName;
20567 // Skip over if system app
20568 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20571 if (DEBUG_CLEAN_APKS) {
20572 Slog.i(TAG, "Checking package " + packageName);
20574 boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20576 if (DEBUG_CLEAN_APKS) {
20577 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO");
20580 for (int i = 0; i < users.length; i++) {
20581 if (users[i] != userHandle && ps.getInstalled(users[i])) {
20583 if (DEBUG_CLEAN_APKS) {
20584 Slog.i(TAG, " Keeping package " + packageName + " for user "
20592 if (DEBUG_CLEAN_APKS) {
20593 Slog.i(TAG, " Removing package " + packageName);
20595 mHandler.post(new Runnable() {
20596 public void run() {
20597 deletePackageX(packageName, userHandle, 0);
20604 /** Called by UserManagerService */
20605 void createNewUser(int userId) {
20606 synchronized (mInstallLock) {
20607 mSettings.createNewUserLI(this, mInstaller, userId);
20609 synchronized (mPackages) {
20610 scheduleWritePackageRestrictionsLocked(userId);
20611 scheduleWritePackageListLocked(userId);
20612 applyFactoryDefaultBrowserLPw(userId);
20613 primeDomainVerificationsLPw(userId);
20617 void onNewUserCreated(final int userId) {
20618 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20619 // If permission review for legacy apps is required, we represent
20620 // dagerous permissions for such apps as always granted runtime
20621 // permissions to keep per user flag state whether review is needed.
20622 // Hence, if a new user is added we have to propagate dangerous
20623 // permission grants for these legacy apps.
20624 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20625 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20626 | UPDATE_PERMISSIONS_REPLACE_ALL);
20631 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20632 mContext.enforceCallingOrSelfPermission(
20633 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20634 "Only package verification agents can read the verifier device identity");
20636 synchronized (mPackages) {
20637 return mSettings.getVerifierDeviceIdentityLPw();
20642 public void setPermissionEnforced(String permission, boolean enforced) {
20643 // TODO: Now that we no longer change GID for storage, this should to away.
20644 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20645 "setPermissionEnforced");
20646 if (READ_EXTERNAL_STORAGE.equals(permission)) {
20647 synchronized (mPackages) {
20648 if (mSettings.mReadExternalStorageEnforced == null
20649 || mSettings.mReadExternalStorageEnforced != enforced) {
20650 mSettings.mReadExternalStorageEnforced = enforced;
20651 mSettings.writeLPr();
20654 // kill any non-foreground processes so we restart them and
20655 // grant/revoke the GID.
20656 final IActivityManager am = ActivityManagerNative.getDefault();
20658 final long token = Binder.clearCallingIdentity();
20660 am.killProcessesBelowForeground("setPermissionEnforcement");
20661 } catch (RemoteException e) {
20663 Binder.restoreCallingIdentity(token);
20667 throw new IllegalArgumentException("No selective enforcement for " + permission);
20673 public boolean isPermissionEnforced(String permission) {
20678 public boolean isStorageLow() {
20679 final long token = Binder.clearCallingIdentity();
20681 final DeviceStorageMonitorInternal
20682 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20684 return dsm.isMemoryLow();
20689 Binder.restoreCallingIdentity(token);
20694 public IPackageInstaller getPackageInstaller() {
20695 return mInstallerService;
20698 private boolean userNeedsBadging(int userId) {
20699 int index = mUserNeedsBadging.indexOfKey(userId);
20701 final UserInfo userInfo;
20702 final long token = Binder.clearCallingIdentity();
20704 userInfo = sUserManager.getUserInfo(userId);
20706 Binder.restoreCallingIdentity(token);
20709 if (userInfo != null && userInfo.isManagedProfile()) {
20714 mUserNeedsBadging.put(userId, b);
20717 return mUserNeedsBadging.valueAt(index);
20721 public KeySet getKeySetByAlias(String packageName, String alias) {
20722 if (packageName == null || alias == null) {
20725 synchronized(mPackages) {
20726 final PackageParser.Package pkg = mPackages.get(packageName);
20728 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20729 throw new IllegalArgumentException("Unknown package: " + packageName);
20731 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20732 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20737 public KeySet getSigningKeySet(String packageName) {
20738 if (packageName == null) {
20741 synchronized(mPackages) {
20742 final PackageParser.Package pkg = mPackages.get(packageName);
20744 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20745 throw new IllegalArgumentException("Unknown package: " + packageName);
20747 if (pkg.applicationInfo.uid != Binder.getCallingUid()
20748 && Process.SYSTEM_UID != Binder.getCallingUid()) {
20749 throw new SecurityException("May not access signing KeySet of other apps.");
20751 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20752 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20757 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20758 if (packageName == null || ks == null) {
20761 synchronized(mPackages) {
20762 final PackageParser.Package pkg = mPackages.get(packageName);
20764 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20765 throw new IllegalArgumentException("Unknown package: " + packageName);
20767 IBinder ksh = ks.getToken();
20768 if (ksh instanceof KeySetHandle) {
20769 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20770 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20777 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20778 if (packageName == null || ks == null) {
20781 synchronized(mPackages) {
20782 final PackageParser.Package pkg = mPackages.get(packageName);
20784 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20785 throw new IllegalArgumentException("Unknown package: " + packageName);
20787 IBinder ksh = ks.getToken();
20788 if (ksh instanceof KeySetHandle) {
20789 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20790 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20796 private void deletePackageIfUnusedLPr(final String packageName) {
20797 PackageSetting ps = mSettings.mPackages.get(packageName);
20801 if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20802 // TODO Implement atomic delete if package is unused
20803 // It is currently possible that the package will be deleted even if it is installed
20804 // after this method returns.
20805 mHandler.post(new Runnable() {
20806 public void run() {
20807 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20814 * Check and throw if the given before/after packages would be considered a
20817 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20818 throws PackageManagerException {
20819 if (after.versionCode < before.mVersionCode) {
20820 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20821 "Update version code " + after.versionCode + " is older than current "
20822 + before.mVersionCode);
20823 } else if (after.versionCode == before.mVersionCode) {
20824 if (after.baseRevisionCode < before.baseRevisionCode) {
20825 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20826 "Update base revision code " + after.baseRevisionCode
20827 + " is older than current " + before.baseRevisionCode);
20830 if (!ArrayUtils.isEmpty(after.splitNames)) {
20831 for (int i = 0; i < after.splitNames.length; i++) {
20832 final String splitName = after.splitNames[i];
20833 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20835 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20836 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20837 "Update split " + splitName + " revision code "
20838 + after.splitRevisionCodes[i] + " is older than current "
20839 + before.splitRevisionCodes[j]);
20847 private static class MoveCallbacks extends Handler {
20848 private static final int MSG_CREATED = 1;
20849 private static final int MSG_STATUS_CHANGED = 2;
20851 private final RemoteCallbackList<IPackageMoveObserver>
20852 mCallbacks = new RemoteCallbackList<>();
20854 private final SparseIntArray mLastStatus = new SparseIntArray();
20856 public MoveCallbacks(Looper looper) {
20860 public void register(IPackageMoveObserver callback) {
20861 mCallbacks.register(callback);
20864 public void unregister(IPackageMoveObserver callback) {
20865 mCallbacks.unregister(callback);
20869 public void handleMessage(Message msg) {
20870 final SomeArgs args = (SomeArgs) msg.obj;
20871 final int n = mCallbacks.beginBroadcast();
20872 for (int i = 0; i < n; i++) {
20873 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20875 invokeCallback(callback, msg.what, args);
20876 } catch (RemoteException ignored) {
20879 mCallbacks.finishBroadcast();
20883 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20884 throws RemoteException {
20886 case MSG_CREATED: {
20887 callback.onCreated(args.argi1, (Bundle) args.arg2);
20890 case MSG_STATUS_CHANGED: {
20891 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20897 private void notifyCreated(int moveId, Bundle extras) {
20898 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20900 final SomeArgs args = SomeArgs.obtain();
20901 args.argi1 = moveId;
20902 args.arg2 = extras;
20903 obtainMessage(MSG_CREATED, args).sendToTarget();
20906 private void notifyStatusChanged(int moveId, int status) {
20907 notifyStatusChanged(moveId, status, -1);
20910 private void notifyStatusChanged(int moveId, int status, long estMillis) {
20911 Slog.v(TAG, "Move " + moveId + " status " + status);
20913 final SomeArgs args = SomeArgs.obtain();
20914 args.argi1 = moveId;
20915 args.argi2 = status;
20916 args.arg3 = estMillis;
20917 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20919 synchronized (mLastStatus) {
20920 mLastStatus.put(moveId, status);
20925 private final static class OnPermissionChangeListeners extends Handler {
20926 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20928 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20929 new RemoteCallbackList<>();
20931 public OnPermissionChangeListeners(Looper looper) {
20936 public void handleMessage(Message msg) {
20937 switch (msg.what) {
20938 case MSG_ON_PERMISSIONS_CHANGED: {
20939 final int uid = msg.arg1;
20940 handleOnPermissionsChanged(uid);
20945 public void addListenerLocked(IOnPermissionsChangeListener listener) {
20946 mPermissionListeners.register(listener);
20950 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20951 mPermissionListeners.unregister(listener);
20954 public void onPermissionsChanged(int uid) {
20955 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20956 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20960 private void handleOnPermissionsChanged(int uid) {
20961 final int count = mPermissionListeners.beginBroadcast();
20963 for (int i = 0; i < count; i++) {
20964 IOnPermissionsChangeListener callback = mPermissionListeners
20965 .getBroadcastItem(i);
20967 callback.onPermissionsChanged(uid);
20968 } catch (RemoteException e) {
20969 Log.e(TAG, "Permission listener is dead", e);
20973 mPermissionListeners.finishBroadcast();
20978 private class PackageManagerInternalImpl extends PackageManagerInternal {
20980 public void setLocationPackagesProvider(PackagesProvider provider) {
20981 synchronized (mPackages) {
20982 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20987 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20988 synchronized (mPackages) {
20989 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20994 public void setSmsAppPackagesProvider(PackagesProvider provider) {
20995 synchronized (mPackages) {
20996 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21001 public void setDialerAppPackagesProvider(PackagesProvider provider) {
21002 synchronized (mPackages) {
21003 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21008 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21009 synchronized (mPackages) {
21010 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21015 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21016 synchronized (mPackages) {
21017 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21022 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21023 synchronized (mPackages) {
21024 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21025 packageName, userId);
21030 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21031 synchronized (mPackages) {
21032 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21033 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21034 packageName, userId);
21039 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21040 synchronized (mPackages) {
21041 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21042 packageName, userId);
21047 public void setKeepUninstalledPackages(final List<String> packageList) {
21048 Preconditions.checkNotNull(packageList);
21049 List<String> removedFromList = null;
21050 synchronized (mPackages) {
21051 if (mKeepUninstalledPackages != null) {
21052 final int packagesCount = mKeepUninstalledPackages.size();
21053 for (int i = 0; i < packagesCount; i++) {
21054 String oldPackage = mKeepUninstalledPackages.get(i);
21055 if (packageList != null && packageList.contains(oldPackage)) {
21058 if (removedFromList == null) {
21059 removedFromList = new ArrayList<>();
21061 removedFromList.add(oldPackage);
21064 mKeepUninstalledPackages = new ArrayList<>(packageList);
21065 if (removedFromList != null) {
21066 final int removedCount = removedFromList.size();
21067 for (int i = 0; i < removedCount; i++) {
21068 deletePackageIfUnusedLPr(removedFromList.get(i));
21075 public boolean isPermissionsReviewRequired(String packageName, int userId) {
21076 synchronized (mPackages) {
21077 // If we do not support permission review, done.
21078 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21082 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21083 if (packageSetting == null) {
21087 // Permission review applies only to apps not supporting the new permission model.
21088 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21092 // Legacy apps have the permission and get user consent on launch.
21093 PermissionsState permissionsState = packageSetting.getPermissionsState();
21094 return permissionsState.isPermissionReviewRequired(userId);
21099 public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21100 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21104 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21106 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21110 public void setDeviceAndProfileOwnerPackages(
21111 int deviceOwnerUserId, String deviceOwnerPackage,
21112 SparseArray<String> profileOwnerPackages) {
21113 mProtectedPackages.setDeviceAndProfileOwnerPackages(
21114 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21118 public boolean isPackageDataProtected(int userId, String packageName) {
21119 return mProtectedPackages.isPackageDataProtected(userId, packageName);
21123 public boolean wasPackageEverLaunched(String packageName, int userId) {
21124 synchronized (mPackages) {
21125 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21130 public String getNameForUid(int uid) {
21131 return PackageManagerService.this.getNameForUid(uid);
21136 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21137 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21138 synchronized (mPackages) {
21139 final long identity = Binder.clearCallingIdentity();
21141 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21142 packageNames, userId);
21144 Binder.restoreCallingIdentity(identity);
21149 private static void enforceSystemOrPhoneCaller(String tag) {
21150 int callingUid = Binder.getCallingUid();
21151 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21152 throw new SecurityException(
21153 "Cannot call " + tag + " from UID " + callingUid);
21157 boolean isHistoricalPackageUsageAvailable() {
21158 return mPackageUsage.isHistoricalPackageUsageAvailable();
21162 * Return a <b>copy</b> of the collection of packages known to the package manager.
21163 * @return A copy of the values of mPackages.
21165 Collection<PackageParser.Package> getPackages() {
21166 synchronized (mPackages) {
21167 return new ArrayList<>(mPackages.values());
21172 * Logs process start information (including base APK hash) to the security log.
21175 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21176 String apkFile, int pid) {
21177 if (!SecurityLog.isLoggingEnabled()) {
21180 Bundle data = new Bundle();
21181 data.putLong("startTimestamp", System.currentTimeMillis());
21182 data.putString("processName", processName);
21183 data.putInt("uid", uid);
21184 data.putString("seinfo", seinfo);
21185 data.putString("apkFile", apkFile);
21186 data.putInt("pid", pid);
21187 Message msg = mProcessLoggingHandler.obtainMessage(
21188 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21190 mProcessLoggingHandler.sendMessage(msg);
21193 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21194 return mCompilerStats.getPackageStats(pkgName);
21197 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21198 return getOrCreateCompilerPackageStats(pkg.packageName);
21201 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21202 return mCompilerStats.getOrCreatePackageStats(pkgName);
21205 public void deleteCompilerPackageStats(String pkgName) {
21206 mCompilerStats.deletePackageStats(pkgName);