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. Also
1650 // for legacy apps in permission review mode we clear the permission
1651 // review flag which is used to emulate runtime permissions for
1653 if (grantPermissions) {
1654 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1657 final boolean update = res.removedInfo != null
1658 && res.removedInfo.removedPackage != null;
1660 // If this is the first time we have child packages for a disabled privileged
1661 // app that had no children, we grant requested runtime permissions to the new
1662 // children if the parent on the system image had them already granted.
1663 if (res.pkg.parentPackage != null) {
1664 synchronized (mPackages) {
1665 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1669 synchronized (mPackages) {
1670 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1673 final String packageName = res.pkg.applicationInfo.packageName;
1674 Bundle extras = new Bundle(1);
1675 extras.putInt(Intent.EXTRA_UID, res.uid);
1677 // Determine the set of users who are adding this package for
1678 // the first time vs. those who are seeing an update.
1679 int[] firstUsers = EMPTY_INT_ARRAY;
1680 int[] updateUsers = EMPTY_INT_ARRAY;
1681 if (res.origUsers == null || res.origUsers.length == 0) {
1682 firstUsers = res.newUsers;
1684 for (int newUser : res.newUsers) {
1685 boolean isNew = true;
1686 for (int origUser : res.origUsers) {
1687 if (origUser == newUser) {
1693 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1695 updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1700 // Send installed broadcasts if the install/update is not ephemeral
1701 if (!isEphemeral(res.pkg)) {
1702 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1704 // Send added for users that see the package for the first time
1705 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1706 extras, 0 /*flags*/, null /*targetPackage*/,
1707 null /*finishedReceiver*/, firstUsers);
1709 // Send added for users that don't see the package for the first time
1711 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1713 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1714 extras, 0 /*flags*/, null /*targetPackage*/,
1715 null /*finishedReceiver*/, updateUsers);
1717 // Send replaced for users that don't see the package for the first time
1719 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1720 packageName, extras, 0 /*flags*/,
1721 null /*targetPackage*/, null /*finishedReceiver*/,
1723 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1724 null /*package*/, null /*extras*/, 0 /*flags*/,
1725 packageName /*targetPackage*/,
1726 null /*finishedReceiver*/, updateUsers);
1727 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1728 // First-install and we did a restore, so we're responsible for the
1729 // first-launch broadcast.
1731 Slog.i(TAG, "Post-restore of " + packageName
1732 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1734 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1737 // Send broadcast package appeared if forward locked/external for all users
1738 // treat asec-hosted packages like removable media on upgrade
1739 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1740 if (DEBUG_INSTALL) {
1741 Slog.i(TAG, "upgrading pkg " + res.pkg
1742 + " is ASEC-hosted -> AVAILABLE");
1744 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1745 ArrayList<String> pkgList = new ArrayList<>(1);
1746 pkgList.add(packageName);
1747 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1751 // Work that needs to happen on first install within each user
1752 if (firstUsers != null && firstUsers.length > 0) {
1753 synchronized (mPackages) {
1754 for (int userId : firstUsers) {
1755 // If this app is a browser and it's newly-installed for some
1756 // users, clear any default-browser state in those users. The
1757 // app's nature doesn't depend on the user, so we can just check
1758 // its browser nature in any user and generalize.
1759 if (packageIsBrowser(packageName, userId)) {
1760 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1763 // We may also need to apply pending (restored) runtime
1764 // permission grants within these users.
1765 mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1770 // Log current value of "unknown sources" setting
1771 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1772 getUnknownSourcesSettings());
1774 // Force a gc to clear up things
1775 Runtime.getRuntime().gc();
1777 // Remove the replaced package's older resources safely now
1778 // We delete after a gc for applications on sdcard.
1779 if (res.removedInfo != null && res.removedInfo.args != null) {
1780 synchronized (mInstallLock) {
1781 res.removedInfo.args.doPostDeleteLI(true);
1786 // If someone is watching installs - notify them
1787 if (installObserver != null) {
1789 Bundle extras = extrasForInstallResult(res);
1790 installObserver.onPackageInstalled(res.name, res.returnCode,
1791 res.returnMsg, extras);
1792 } catch (RemoteException e) {
1793 Slog.i(TAG, "Observer no longer exists.");
1798 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1799 PackageParser.Package pkg) {
1800 if (pkg.parentPackage == null) {
1803 if (pkg.requestedPermissions == null) {
1806 final PackageSetting disabledSysParentPs = mSettings
1807 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1808 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1809 || !disabledSysParentPs.isPrivileged()
1810 || (disabledSysParentPs.childPackageNames != null
1811 && !disabledSysParentPs.childPackageNames.isEmpty())) {
1814 final int[] allUserIds = sUserManager.getUserIds();
1815 final int permCount = pkg.requestedPermissions.size();
1816 for (int i = 0; i < permCount; i++) {
1817 String permission = pkg.requestedPermissions.get(i);
1818 BasePermission bp = mSettings.mPermissions.get(permission);
1819 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1822 for (int userId : allUserIds) {
1823 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1824 permission, userId)) {
1825 grantRuntimePermission(pkg.packageName, permission, userId);
1831 private StorageEventListener mStorageListener = new StorageEventListener() {
1833 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1834 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1835 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1836 final String volumeUuid = vol.getFsUuid();
1838 // Clean up any users or apps that were removed or recreated
1839 // while this volume was missing
1840 reconcileUsers(volumeUuid);
1841 reconcileApps(volumeUuid);
1843 // Clean up any install sessions that expired or were
1844 // cancelled while this volume was missing
1845 mInstallerService.onPrivateVolumeMounted(volumeUuid);
1847 loadPrivatePackages(vol);
1849 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1850 unloadPrivatePackages(vol);
1854 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1855 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1856 updateExternalMediaStatus(true, false);
1857 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1858 updateExternalMediaStatus(false, false);
1864 public void onVolumeForgotten(String fsUuid) {
1865 if (TextUtils.isEmpty(fsUuid)) {
1866 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1870 // Remove any apps installed on the forgotten volume
1871 synchronized (mPackages) {
1872 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1873 for (PackageSetting ps : packages) {
1874 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1875 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1876 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1879 mSettings.onVolumeForgotten(fsUuid);
1880 mSettings.writeLPr();
1885 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1886 String[] grantedPermissions) {
1887 for (int userId : userIds) {
1888 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1892 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1893 String[] grantedPermissions) {
1894 SettingBase sb = (SettingBase) pkg.mExtras;
1899 PermissionsState permissionsState = sb.getPermissionsState();
1901 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1902 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1904 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
1905 >= Build.VERSION_CODES.M;
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 if (supportsRuntimePermissions) {
1917 // Installer cannot change immutable permissions.
1918 if ((flags & immutableFlags) == 0) {
1919 grantRuntimePermission(pkg.packageName, permission, userId);
1921 } else if (mPermissionReviewRequired) {
1922 // In permission review mode we clear the review flag when we
1923 // are asked to install the app with all permissions granted.
1924 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
1925 updatePermissionFlags(permission, pkg.packageName,
1926 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0 /*value*/, userId);
1933 Bundle extrasForInstallResult(PackageInstalledInfo res) {
1934 Bundle extras = null;
1935 switch (res.returnCode) {
1936 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1937 extras = new Bundle();
1938 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1939 res.origPermission);
1940 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1944 case PackageManager.INSTALL_SUCCEEDED: {
1945 extras = new Bundle();
1946 extras.putBoolean(Intent.EXTRA_REPLACING,
1947 res.removedInfo != null && res.removedInfo.removedPackage != null);
1954 void scheduleWriteSettingsLocked() {
1955 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1956 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1960 void scheduleWritePackageListLocked(int userId) {
1961 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1962 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1964 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1968 void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1969 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1970 scheduleWritePackageRestrictionsLocked(userId);
1973 void scheduleWritePackageRestrictionsLocked(int userId) {
1974 final int[] userIds = (userId == UserHandle.USER_ALL)
1975 ? sUserManager.getUserIds() : new int[]{userId};
1976 for (int nextUserId : userIds) {
1977 if (!sUserManager.exists(nextUserId)) return;
1978 mDirtyUsers.add(nextUserId);
1979 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1980 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1985 public static PackageManagerService main(Context context, Installer installer,
1986 boolean factoryTest, boolean onlyCore) {
1987 // Self-check for initial settings.
1988 PackageManagerServiceCompilerMapping.checkProperties();
1990 PackageManagerService m = new PackageManagerService(context, installer,
1991 factoryTest, onlyCore);
1992 m.enableSystemUserPackages();
1993 ServiceManager.addService("package", m);
1997 private void enableSystemUserPackages() {
1998 if (!UserManager.isSplitSystemUser()) {
2001 // For system user, enable apps based on the following conditions:
2002 // - app is whitelisted or belong to one of these groups:
2003 // -- system app which has no launcher icons
2004 // -- system app which has INTERACT_ACROSS_USERS permission
2005 // -- system IME app
2006 // - app is not in the blacklist
2007 AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2008 Set<String> enableApps = new ArraySet<>();
2009 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2010 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2011 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2012 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2013 enableApps.addAll(wlApps);
2014 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2015 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2016 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2017 enableApps.removeAll(blApps);
2018 Log.i(TAG, "Applications installed for system user: " + enableApps);
2019 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2021 final int allAppsSize = allAps.size();
2022 synchronized (mPackages) {
2023 for (int i = 0; i < allAppsSize; i++) {
2024 String pName = allAps.get(i);
2025 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2026 // Should not happen, but we shouldn't be failing if it does
2027 if (pkgSetting == null) {
2030 boolean install = enableApps.contains(pName);
2031 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2032 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2033 + " for system user");
2034 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2040 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2041 DisplayManager displayManager = (DisplayManager) context.getSystemService(
2042 Context.DISPLAY_SERVICE);
2043 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2047 * Requests that files preopted on a secondary system partition be copied to the data partition
2048 * if possible. Note that the actual copying of the files is accomplished by init for security
2049 * reasons. This simply requests that the copy takes place and awaits confirmation of its
2050 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2052 private static void requestCopyPreoptedFiles() {
2053 final int WAIT_TIME_MS = 100;
2054 final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2055 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2056 SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2057 // We will wait for up to 100 seconds.
2058 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2059 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2061 Thread.sleep(WAIT_TIME_MS);
2062 } catch (InterruptedException e) {
2065 if (SystemClock.uptimeMillis() > timeEnd) {
2066 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2067 Slog.wtf(TAG, "cppreopt did not finish!");
2074 public PackageManagerService(Context context, Installer installer,
2075 boolean factoryTest, boolean onlyCore) {
2076 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2077 SystemClock.uptimeMillis());
2079 if (mSdkVersion <= 0) {
2080 Slog.w(TAG, "**** ro.build.version.sdk not set!");
2085 mPermissionReviewRequired = context.getResources().getBoolean(
2086 R.bool.config_permissionReviewRequired);
2088 mFactoryTest = factoryTest;
2089 mOnlyCore = onlyCore;
2090 mMetrics = new DisplayMetrics();
2091 mSettings = new Settings(mPackages);
2092 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2093 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2095 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2097 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2098 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2099 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2100 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2101 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2102 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2103 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2105 String separateProcesses = SystemProperties.get("debug.separate_processes");
2106 if (separateProcesses != null && separateProcesses.length() > 0) {
2107 if ("*".equals(separateProcesses)) {
2108 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2109 mSeparateProcesses = null;
2110 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2113 mSeparateProcesses = separateProcesses.split(",");
2114 Slog.w(TAG, "Running with debug.separate_processes: "
2115 + separateProcesses);
2119 mSeparateProcesses = null;
2122 mInstaller = installer;
2123 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2125 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2127 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2128 FgThread.get().getLooper());
2130 getDefaultDisplayMetrics(context, mMetrics);
2132 SystemConfig systemConfig = SystemConfig.getInstance();
2133 mGlobalGids = systemConfig.getGlobalGids();
2134 mSystemPermissions = systemConfig.getSystemPermissions();
2135 mAvailableFeatures = systemConfig.getAvailableFeatures();
2137 mProtectedPackages = new ProtectedPackages(mContext);
2139 synchronized (mInstallLock) {
2141 synchronized (mPackages) {
2142 mHandlerThread = new ServiceThread(TAG,
2143 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2144 mHandlerThread.start();
2145 mHandler = new PackageHandler(mHandlerThread.getLooper());
2146 mProcessLoggingHandler = new ProcessLoggingHandler();
2147 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2149 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2151 File dataDir = Environment.getDataDirectory();
2152 mAppInstallDir = new File(dataDir, "app");
2153 mAppLib32InstallDir = new File(dataDir, "app-lib");
2154 mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2155 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2156 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2158 sUserManager = new UserManagerService(context, this, mPackages);
2160 // Propagate permission configuration in to package manager.
2161 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2162 = systemConfig.getPermissions();
2163 for (int i=0; i<permConfig.size(); i++) {
2164 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2165 BasePermission bp = mSettings.mPermissions.get(perm.name);
2167 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2168 mSettings.mPermissions.put(perm.name, bp);
2170 if (perm.gids != null) {
2171 bp.setGids(perm.gids, perm.perUser);
2175 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2176 for (int i=0; i<libConfig.size(); i++) {
2177 mSharedLibraries.put(libConfig.keyAt(i),
2178 new SharedLibraryEntry(libConfig.valueAt(i), null));
2181 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2183 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2185 // Clean up orphaned packages for which the code path doesn't exist
2186 // and they are an update to a system app - caused by bug/32321269
2187 final int packageSettingCount = mSettings.mPackages.size();
2188 for (int i = packageSettingCount - 1; i >= 0; i--) {
2189 PackageSetting ps = mSettings.mPackages.valueAt(i);
2190 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2191 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2192 mSettings.mPackages.removeAt(i);
2193 mSettings.enableSystemPackageLPw(ps.name);
2198 requestCopyPreoptedFiles();
2201 String customResolverActivity = Resources.getSystem().getString(
2202 R.string.config_customResolverActivity);
2203 if (TextUtils.isEmpty(customResolverActivity)) {
2204 customResolverActivity = null;
2206 mCustomResolverComponentName = ComponentName.unflattenFromString(
2207 customResolverActivity);
2210 long startTime = SystemClock.uptimeMillis();
2212 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2215 // Set flag to monitor and not change apk file paths when
2216 // scanning install directories.
2217 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2219 final String bootClassPath = System.getenv("BOOTCLASSPATH");
2220 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2222 if (bootClassPath == null) {
2223 Slog.w(TAG, "No BOOTCLASSPATH found!");
2226 if (systemServerClassPath == null) {
2227 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2230 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2231 final String[] dexCodeInstructionSets =
2232 getDexCodeInstructionSets(
2233 allInstructionSets.toArray(new String[allInstructionSets.size()]));
2236 * Ensure all external libraries have had dexopt run on them.
2238 if (mSharedLibraries.size() > 0) {
2239 // NOTE: For now, we're compiling these system "shared libraries"
2240 // (and framework jars) into all available architectures. It's possible
2241 // to compile them only when we come across an app that uses them (there's
2242 // already logic for that in scanPackageLI) but that adds some complexity.
2243 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2244 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2245 final String lib = libEntry.path;
2251 // Shared libraries do not have profiles so we perform a full
2252 // AOT compilation (if needed).
2253 int dexoptNeeded = DexFile.getDexOptNeeded(
2254 lib, dexCodeInstructionSet,
2255 getCompilerFilterForReason(REASON_SHARED_APK),
2256 false /* newProfile */);
2257 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2258 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2259 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2260 getCompilerFilterForReason(REASON_SHARED_APK),
2261 StorageManager.UUID_PRIVATE_INTERNAL,
2262 SKIP_SHARED_LIBRARY_CHECK);
2264 } catch (FileNotFoundException e) {
2265 Slog.w(TAG, "Library not found: " + lib);
2266 } catch (IOException | InstallerException e) {
2267 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2274 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2276 final VersionInfo ver = mSettings.getInternalVersion();
2277 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2279 // when upgrading from pre-M, promote system app permissions from install to runtime
2280 mPromoteSystemApps =
2281 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2283 // When upgrading from pre-N, we need to handle package extraction like first boot,
2284 // as there is no profiling data available.
2285 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2287 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2289 // save off the names of pre-existing system packages prior to scanning; we don't
2290 // want to automatically grant runtime permissions for new system apps
2291 if (mPromoteSystemApps) {
2292 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2293 while (pkgSettingIter.hasNext()) {
2294 PackageSetting ps = pkgSettingIter.next();
2295 if (isSystemApp(ps)) {
2296 mExistingSystemPackages.add(ps.name);
2301 // Collect vendor overlay packages. (Do this before scanning any apps.)
2302 // For security and version matching reason, only consider
2303 // overlay packages if they reside in the right directory.
2304 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2305 if (!overlayThemeDir.isEmpty()) {
2306 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2307 | PackageParser.PARSE_IS_SYSTEM
2308 | PackageParser.PARSE_IS_SYSTEM_DIR
2309 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2311 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2312 | PackageParser.PARSE_IS_SYSTEM
2313 | PackageParser.PARSE_IS_SYSTEM_DIR
2314 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2316 // Find base frameworks (resource packages without code).
2317 scanDirTracedLI(frameworkDir, mDefParseFlags
2318 | PackageParser.PARSE_IS_SYSTEM
2319 | PackageParser.PARSE_IS_SYSTEM_DIR
2320 | PackageParser.PARSE_IS_PRIVILEGED,
2321 scanFlags | SCAN_NO_DEX, 0);
2323 // Collected privileged system packages.
2324 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2325 scanDirTracedLI(privilegedAppDir, mDefParseFlags
2326 | PackageParser.PARSE_IS_SYSTEM
2327 | PackageParser.PARSE_IS_SYSTEM_DIR
2328 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2330 // Collect ordinary system packages.
2331 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2332 scanDirTracedLI(systemAppDir, mDefParseFlags
2333 | PackageParser.PARSE_IS_SYSTEM
2334 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2336 // Collect all vendor packages.
2337 File vendorAppDir = new File("/vendor/app");
2339 vendorAppDir = vendorAppDir.getCanonicalFile();
2340 } catch (IOException e) {
2341 // failed to look up canonical path, continue with original one
2343 scanDirTracedLI(vendorAppDir, mDefParseFlags
2344 | PackageParser.PARSE_IS_SYSTEM
2345 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2347 // Collect all OEM packages.
2348 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2349 scanDirTracedLI(oemAppDir, mDefParseFlags
2350 | PackageParser.PARSE_IS_SYSTEM
2351 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2353 // Prune any system packages that no longer exist.
2354 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2356 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2357 while (psit.hasNext()) {
2358 PackageSetting ps = psit.next();
2361 * If this is not a system app, it can't be a
2362 * disable system app.
2364 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2369 * If the package is scanned, it's not erased.
2371 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2372 if (scannedPkg != null) {
2374 * If the system app is both scanned and in the
2375 * disabled packages list, then it must have been
2376 * added via OTA. Remove it from the currently
2377 * scanned package so the previously user-installed
2378 * application can be scanned.
2380 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2381 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2382 + ps.name + "; removing system app. Last known codePath="
2383 + ps.codePathString + ", installStatus=" + ps.installStatus
2384 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2385 + scannedPkg.mVersionCode);
2386 removePackageLI(scannedPkg, true);
2387 mExpectingBetter.put(ps.name, ps.codePath);
2393 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2395 logCriticalInfo(Log.WARN, "System package " + ps.name
2396 + " no longer exists; it's data will be wiped");
2397 // Actual deletion of code and data will be handled by later
2398 // reconciliation step
2400 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2401 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2402 possiblyDeletedUpdatedSystemApps.add(ps.name);
2408 //look for any incomplete package installations
2409 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2410 for (int i = 0; i < deletePkgsList.size(); i++) {
2411 // Actual deletion of code and data will be handled by later
2412 // reconciliation step
2413 final String packageName = deletePkgsList.get(i).name;
2414 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2415 synchronized (mPackages) {
2416 mSettings.removePackageLPw(packageName);
2421 deleteTempPackageFiles();
2423 // Remove any shared userIDs that have no associated packages
2424 mSettings.pruneSharedUsersLPw();
2427 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2428 SystemClock.uptimeMillis());
2429 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2431 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2432 | PackageParser.PARSE_FORWARD_LOCK,
2433 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2435 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2436 | PackageParser.PARSE_IS_EPHEMERAL,
2437 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2440 * Remove disable package settings for any updated system
2441 * apps that were removed via an OTA. If they're not a
2442 * previously-updated app, remove them completely.
2443 * Otherwise, just revoke their system-level permissions.
2445 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2446 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2447 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2450 if (deletedPkg == null) {
2451 msg = "Updated system package " + deletedAppName
2452 + " no longer exists; it's data will be wiped";
2453 // Actual deletion of code and data will be handled by later
2454 // reconciliation step
2456 msg = "Updated system app + " + deletedAppName
2457 + " no longer present; removing system privileges for "
2460 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2462 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2463 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2465 logCriticalInfo(Log.WARN, msg);
2469 * Make sure all system apps that we expected to appear on
2470 * the userdata partition actually showed up. If they never
2471 * appeared, crawl back and revive the system version.
2473 for (int i = 0; i < mExpectingBetter.size(); i++) {
2474 final String packageName = mExpectingBetter.keyAt(i);
2475 if (!mPackages.containsKey(packageName)) {
2476 final File scanFile = mExpectingBetter.valueAt(i);
2478 logCriticalInfo(Log.WARN, "Expected better " + packageName
2479 + " but never showed up; reverting to system");
2481 int reparseFlags = mDefParseFlags;
2482 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2483 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2484 | PackageParser.PARSE_IS_SYSTEM_DIR
2485 | PackageParser.PARSE_IS_PRIVILEGED;
2486 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2487 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2488 | PackageParser.PARSE_IS_SYSTEM_DIR;
2489 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2490 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2491 | PackageParser.PARSE_IS_SYSTEM_DIR;
2492 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2493 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2494 | PackageParser.PARSE_IS_SYSTEM_DIR;
2496 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2500 mSettings.enableSystemPackageLPw(packageName);
2503 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2504 } catch (PackageManagerException e) {
2505 Slog.e(TAG, "Failed to parse original system package: "
2511 mExpectingBetter.clear();
2513 // Resolve the storage manager.
2514 mStorageManagerPackage = getStorageManagerPackageName();
2516 // Resolve protected action filters. Only the setup wizard is allowed to
2517 // have a high priority filter for these actions.
2518 mSetupWizardPackage = getSetupWizardPackageName();
2519 if (mProtectedFilters.size() > 0) {
2520 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2521 Slog.i(TAG, "No setup wizard;"
2522 + " All protected intents capped to priority 0");
2524 for (ActivityIntentInfo filter : mProtectedFilters) {
2525 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2526 if (DEBUG_FILTERS) {
2527 Slog.i(TAG, "Found setup wizard;"
2528 + " allow priority " + filter.getPriority() + ";"
2529 + " package: " + filter.activity.info.packageName
2530 + " activity: " + filter.activity.className
2531 + " priority: " + filter.getPriority());
2533 // skip setup wizard; allow it to keep the high priority filter
2536 Slog.w(TAG, "Protected action; cap priority to 0;"
2537 + " package: " + filter.activity.info.packageName
2538 + " activity: " + filter.activity.className
2539 + " origPrio: " + filter.getPriority());
2540 filter.setPriority(0);
2543 mDeferProtectedFilters = false;
2544 mProtectedFilters.clear();
2546 // Now that we know all of the shared libraries, update all clients to have
2547 // the correct library paths.
2548 updateAllSharedLibrariesLPw();
2550 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2551 // NOTE: We ignore potential failures here during a system scan (like
2552 // the rest of the commands above) because there's precious little we
2553 // can do about it. A settings error is reported, though.
2554 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2555 false /* boot complete */);
2558 // Now that we know all the packages we are keeping,
2559 // read and update their last usage times.
2560 mPackageUsage.read(mPackages);
2561 mCompilerStats.read();
2563 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2564 SystemClock.uptimeMillis());
2565 Slog.i(TAG, "Time to scan packages: "
2566 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2569 // If the platform SDK has changed since the last time we booted,
2570 // we need to re-grant app permission to catch any new ones that
2571 // appear. This is really a hack, and means that apps can in some
2572 // cases get permissions that the user didn't initially explicitly
2573 // allow... it would be nice to have some better way to handle
2575 int updateFlags = UPDATE_PERMISSIONS_ALL;
2576 if (ver.sdkVersion != mSdkVersion) {
2577 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2578 + mSdkVersion + "; regranting permissions for internal storage");
2579 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2581 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2582 ver.sdkVersion = mSdkVersion;
2584 // If this is the first boot or an update from pre-M, and it is a normal
2585 // boot, then we need to initialize the default preferred apps across
2586 // all defined users.
2587 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2588 for (UserInfo user : sUserManager.getUsers(true)) {
2589 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2590 applyFactoryDefaultBrowserLPw(user.id);
2591 primeDomainVerificationsLPw(user.id);
2595 // Prepare storage for system user really early during boot,
2596 // since core system apps like SettingsProvider and SystemUI
2597 // can't wait for user to start
2598 final int storageFlags;
2599 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2600 storageFlags = StorageManager.FLAG_STORAGE_DE;
2602 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2604 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2607 // If this is first boot after an OTA, and a normal boot, then
2608 // we need to clear code cache directories.
2609 // Note that we do *not* clear the application profiles. These remain valid
2610 // across OTAs and are used to drive profile verification (post OTA) and
2611 // profile compilation (without waiting to collect a fresh set of profiles).
2612 if (mIsUpgrade && !onlyCore) {
2613 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2614 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2615 final PackageSetting ps = mSettings.mPackages.valueAt(i);
2616 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2617 // No apps are running this early, so no need to freeze
2618 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2619 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2620 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2623 ver.fingerprint = Build.FINGERPRINT;
2626 checkDefaultBrowser();
2628 // clear only after permissions and other defaults have been updated
2629 mExistingSystemPackages.clear();
2630 mPromoteSystemApps = false;
2632 // All the changes are done during package scanning.
2633 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2635 // can downgrade to reader
2636 mSettings.writeLPr();
2638 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2639 // early on (before the package manager declares itself as early) because other
2640 // components in the system server might ask for package contexts for these apps.
2642 // Note that "onlyCore" in this context means the system is encrypted or encrypting
2643 // (i.e, that the data partition is unavailable).
2644 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2645 long start = System.nanoTime();
2646 List<PackageParser.Package> coreApps = new ArrayList<>();
2647 for (PackageParser.Package pkg : mPackages.values()) {
2653 int[] stats = performDexOptUpgrade(coreApps, false,
2654 getCompilerFilterForReason(REASON_CORE_APP));
2656 final int elapsedTimeSeconds =
2657 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2658 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2661 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2662 stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2666 // TODO: Should we log these stats to tron too ?
2667 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2668 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2669 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2670 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2673 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2674 SystemClock.uptimeMillis());
2677 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2678 mRequiredInstallerPackage = getRequiredInstallerLPr();
2679 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2680 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2681 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2682 mIntentFilterVerifierComponent);
2683 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2684 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2685 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2686 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2688 mRequiredVerifierPackage = null;
2689 mRequiredInstallerPackage = null;
2690 mRequiredUninstallerPackage = null;
2691 mIntentFilterVerifierComponent = null;
2692 mIntentFilterVerifier = null;
2693 mServicesSystemSharedLibraryPackageName = null;
2694 mSharedSystemSharedLibraryPackageName = null;
2697 mInstallerService = new PackageInstallerService(context, this);
2699 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2700 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2701 // both the installer and resolver must be present to enable ephemeral
2702 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2703 if (DEBUG_EPHEMERAL) {
2704 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2705 + " installer:" + ephemeralInstallerComponent);
2707 mEphemeralResolverComponent = ephemeralResolverComponent;
2708 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2709 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2710 mEphemeralResolverConnection =
2711 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2713 if (DEBUG_EPHEMERAL) {
2714 final String missingComponent =
2715 (ephemeralResolverComponent == null)
2716 ? (ephemeralInstallerComponent == null)
2717 ? "resolver and installer"
2720 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2722 mEphemeralResolverComponent = null;
2723 mEphemeralInstallerComponent = null;
2724 mEphemeralResolverConnection = null;
2727 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2728 } // synchronized (mPackages)
2729 } // synchronized (mInstallLock)
2731 // Now after opening every single application zip, make sure they
2732 // are all flushed. Not really needed, but keeps things nice and
2734 Runtime.getRuntime().gc();
2736 // The initial scanning above does many calls into installd while
2737 // holding the mPackages lock, but we're mostly interested in yelling
2738 // once we have a booted system.
2739 mInstaller.setWarnIfHeld(mPackages);
2741 // Expose private service for system components to use.
2742 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2746 public boolean isFirstBoot() {
2751 public boolean isOnlyCoreApps() {
2756 public boolean isUpgrade() {
2760 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2761 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2763 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2764 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2765 UserHandle.USER_SYSTEM);
2766 if (matches.size() == 1) {
2767 return matches.get(0).getComponentInfo().packageName;
2768 } else if (matches.size() == 0) {
2769 Log.e(TAG, "There should probably be a verifier, but, none were found");
2772 throw new RuntimeException("There must be exactly one verifier; found " + matches);
2775 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2776 synchronized (mPackages) {
2777 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2778 if (libraryEntry == null) {
2779 throw new IllegalStateException("Missing required shared library:" + libraryName);
2781 return libraryEntry.apk;
2785 private @NonNull String getRequiredInstallerLPr() {
2786 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2787 intent.addCategory(Intent.CATEGORY_DEFAULT);
2788 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2790 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2791 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2792 UserHandle.USER_SYSTEM);
2793 if (matches.size() == 1) {
2794 ResolveInfo resolveInfo = matches.get(0);
2795 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2796 throw new RuntimeException("The installer must be a privileged app");
2798 return matches.get(0).getComponentInfo().packageName;
2800 throw new RuntimeException("There must be exactly one installer; found " + matches);
2804 private @NonNull String getRequiredUninstallerLPr() {
2805 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2806 intent.addCategory(Intent.CATEGORY_DEFAULT);
2807 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2809 final ResolveInfo resolveInfo = resolveIntent(intent, null,
2810 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2811 UserHandle.USER_SYSTEM);
2812 if (resolveInfo == null ||
2813 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2814 throw new RuntimeException("There must be exactly one uninstaller; found "
2817 return resolveInfo.getComponentInfo().packageName;
2820 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2821 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2823 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2824 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2825 UserHandle.USER_SYSTEM);
2826 ResolveInfo best = null;
2827 final int N = matches.size();
2828 for (int i = 0; i < N; i++) {
2829 final ResolveInfo cur = matches.get(i);
2830 final String packageName = cur.getComponentInfo().packageName;
2831 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2832 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2836 if (best == null || cur.priority > best.priority) {
2842 return best.getComponentInfo().getComponentName();
2844 throw new RuntimeException("There must be at least one intent filter verifier");
2848 private @Nullable ComponentName getEphemeralResolverLPr() {
2849 final String[] packageArray =
2850 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2851 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2852 if (DEBUG_EPHEMERAL) {
2853 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2858 final int resolveFlags =
2859 MATCH_DIRECT_BOOT_AWARE
2860 | MATCH_DIRECT_BOOT_UNAWARE
2861 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2862 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2863 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2864 resolveFlags, UserHandle.USER_SYSTEM);
2866 final int N = resolvers.size();
2868 if (DEBUG_EPHEMERAL) {
2869 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2874 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2875 for (int i = 0; i < N; i++) {
2876 final ResolveInfo info = resolvers.get(i);
2878 if (info.serviceInfo == null) {
2882 final String packageName = info.serviceInfo.packageName;
2883 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2884 if (DEBUG_EPHEMERAL) {
2885 Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2886 + " pkg: " + packageName + ", info:" + info);
2891 if (DEBUG_EPHEMERAL) {
2892 Slog.v(TAG, "Ephemeral resolver found;"
2893 + " pkg: " + packageName + ", info:" + info);
2895 return new ComponentName(packageName, info.serviceInfo.name);
2897 if (DEBUG_EPHEMERAL) {
2898 Slog.v(TAG, "Ephemeral resolver NOT found");
2903 private @Nullable ComponentName getEphemeralInstallerLPr() {
2904 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2905 intent.addCategory(Intent.CATEGORY_DEFAULT);
2906 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2908 final int resolveFlags =
2909 MATCH_DIRECT_BOOT_AWARE
2910 | MATCH_DIRECT_BOOT_UNAWARE
2911 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2912 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2913 resolveFlags, UserHandle.USER_SYSTEM);
2914 if (matches.size() == 0) {
2916 } else if (matches.size() == 1) {
2917 return matches.get(0).getComponentInfo().getComponentName();
2919 throw new RuntimeException(
2920 "There must be at most one ephemeral installer; found " + matches);
2924 private void primeDomainVerificationsLPw(int userId) {
2925 if (DEBUG_DOMAIN_VERIFICATION) {
2926 Slog.d(TAG, "Priming domain verifications in user " + userId);
2929 SystemConfig systemConfig = SystemConfig.getInstance();
2930 ArraySet<String> packages = systemConfig.getLinkedApps();
2931 ArraySet<String> domains = new ArraySet<String>();
2933 for (String packageName : packages) {
2934 PackageParser.Package pkg = mPackages.get(packageName);
2936 if (!pkg.isSystemApp()) {
2937 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2942 for (PackageParser.Activity a : pkg.activities) {
2943 for (ActivityIntentInfo filter : a.intents) {
2944 if (hasValidDomains(filter)) {
2945 domains.addAll(filter.getHostsList());
2950 if (domains.size() > 0) {
2951 if (DEBUG_DOMAIN_VERIFICATION) {
2952 Slog.v(TAG, " + " + packageName);
2954 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2955 // state w.r.t. the formal app-linkage "no verification attempted" state;
2956 // and then 'always' in the per-user state actually used for intent resolution.
2957 final IntentFilterVerificationInfo ivi;
2958 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2959 new ArrayList<String>(domains));
2960 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2961 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2962 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2964 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2965 + "' does not handle web links");
2968 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2972 scheduleWritePackageRestrictionsLocked(userId);
2973 scheduleWriteSettingsLocked();
2976 private void applyFactoryDefaultBrowserLPw(int userId) {
2977 // The default browser app's package name is stored in a string resource,
2978 // with a product-specific overlay used for vendor customization.
2979 String browserPkg = mContext.getResources().getString(
2980 com.android.internal.R.string.default_browser);
2981 if (!TextUtils.isEmpty(browserPkg)) {
2982 // non-empty string => required to be a known package
2983 PackageSetting ps = mSettings.mPackages.get(browserPkg);
2985 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2988 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2992 // Nothing valid explicitly set? Make the factory-installed browser the explicit
2993 // default. If there's more than one, just leave everything alone.
2994 if (browserPkg == null) {
2995 calculateDefaultBrowserLPw(userId);
2999 private void calculateDefaultBrowserLPw(int userId) {
3000 List<String> allBrowsers = resolveAllBrowserApps(userId);
3001 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3002 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3005 private List<String> resolveAllBrowserApps(int userId) {
3006 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3007 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3008 PackageManager.MATCH_ALL, userId);
3010 final int count = list.size();
3011 List<String> result = new ArrayList<String>(count);
3012 for (int i=0; i<count; i++) {
3013 ResolveInfo info = list.get(i);
3014 if (info.activityInfo == null
3015 || !info.handleAllWebDataURI
3016 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3017 || result.contains(info.activityInfo.packageName)) {
3020 result.add(info.activityInfo.packageName);
3026 private boolean packageIsBrowser(String packageName, int userId) {
3027 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3028 PackageManager.MATCH_ALL, userId);
3029 final int N = list.size();
3030 for (int i = 0; i < N; i++) {
3031 ResolveInfo info = list.get(i);
3032 if (packageName.equals(info.activityInfo.packageName)) {
3039 private void checkDefaultBrowser() {
3040 final int myUserId = UserHandle.myUserId();
3041 final String packageName = getDefaultBrowserPackageName(myUserId);
3042 if (packageName != null) {
3043 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3045 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3046 synchronized (mPackages) {
3047 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
3054 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3055 throws RemoteException {
3057 return super.onTransact(code, data, reply, flags);
3058 } catch (RuntimeException e) {
3059 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3060 Slog.wtf(TAG, "Package Manager Crash", e);
3066 static int[] appendInts(int[] cur, int[] add) {
3067 if (add == null) return cur;
3068 if (cur == null) return add;
3069 final int N = add.length;
3070 for (int i=0; i<N; i++) {
3071 cur = appendInt(cur, add[i]);
3076 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3077 if (!sUserManager.exists(userId)) return null;
3081 final PackageParser.Package p = ps.pkg;
3086 final PermissionsState permissionsState = ps.getPermissionsState();
3088 // Compute GIDs only if requested
3089 final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3090 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3091 // Compute granted permissions only if package has requested permissions
3092 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3093 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3094 final PackageUserState state = ps.readUserState(userId);
3096 return PackageParser.generatePackageInfo(p, gids, flags,
3097 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3101 public void checkPackageStartable(String packageName, int userId) {
3102 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3104 synchronized (mPackages) {
3105 final PackageSetting ps = mSettings.mPackages.get(packageName);
3107 throw new SecurityException("Package " + packageName + " was not found!");
3110 if (!ps.getInstalled(userId)) {
3111 throw new SecurityException(
3112 "Package " + packageName + " was not installed for user " + userId + "!");
3115 if (mSafeMode && !ps.isSystem()) {
3116 throw new SecurityException("Package " + packageName + " not a system app!");
3119 if (mFrozenPackages.contains(packageName)) {
3120 throw new SecurityException("Package " + packageName + " is currently frozen!");
3123 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3124 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3125 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3131 public boolean isPackageAvailable(String packageName, int userId) {
3132 if (!sUserManager.exists(userId)) return false;
3133 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3134 false /* requireFullPermission */, false /* checkShell */, "is package available");
3135 synchronized (mPackages) {
3136 PackageParser.Package p = mPackages.get(packageName);
3138 final PackageSetting ps = (PackageSetting) p.mExtras;
3140 final PackageUserState state = ps.readUserState(userId);
3141 if (state != null) {
3142 return PackageParser.isAvailable(state);
3151 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3152 if (!sUserManager.exists(userId)) return null;
3153 flags = updateFlagsForPackage(flags, userId, packageName);
3154 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3155 false /* requireFullPermission */, false /* checkShell */, "get package info");
3158 synchronized (mPackages) {
3159 // Normalize package name to hanlde renamed packages
3160 packageName = normalizePackageNameLPr(packageName);
3162 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3163 PackageParser.Package p = null;
3164 if (matchFactoryOnly) {
3165 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3167 return generatePackageInfo(ps, flags, userId);
3171 p = mPackages.get(packageName);
3172 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3176 if (DEBUG_PACKAGE_INFO)
3177 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3179 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3181 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3182 final PackageSetting ps = mSettings.mPackages.get(packageName);
3183 return generatePackageInfo(ps, flags, userId);
3190 public String[] currentToCanonicalPackageNames(String[] names) {
3191 String[] out = new String[names.length];
3193 synchronized (mPackages) {
3194 for (int i=names.length-1; i>=0; i--) {
3195 PackageSetting ps = mSettings.mPackages.get(names[i]);
3196 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3203 public String[] canonicalToCurrentPackageNames(String[] names) {
3204 String[] out = new String[names.length];
3206 synchronized (mPackages) {
3207 for (int i=names.length-1; i>=0; i--) {
3208 String cur = mSettings.mRenamedPackages.get(names[i]);
3209 out[i] = cur != null ? cur : names[i];
3216 public int getPackageUid(String packageName, int flags, int userId) {
3217 if (!sUserManager.exists(userId)) return -1;
3218 flags = updateFlagsForPackage(flags, userId, packageName);
3219 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3220 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3223 synchronized (mPackages) {
3224 final PackageParser.Package p = mPackages.get(packageName);
3225 if (p != null && p.isMatch(flags)) {
3226 return UserHandle.getUid(userId, p.applicationInfo.uid);
3228 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3229 final PackageSetting ps = mSettings.mPackages.get(packageName);
3230 if (ps != null && ps.isMatch(flags)) {
3231 return UserHandle.getUid(userId, ps.appId);
3240 public int[] getPackageGids(String packageName, int flags, int userId) {
3241 if (!sUserManager.exists(userId)) return null;
3242 flags = updateFlagsForPackage(flags, userId, packageName);
3243 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3244 false /* requireFullPermission */, false /* checkShell */,
3248 synchronized (mPackages) {
3249 final PackageParser.Package p = mPackages.get(packageName);
3250 if (p != null && p.isMatch(flags)) {
3251 PackageSetting ps = (PackageSetting) p.mExtras;
3252 return ps.getPermissionsState().computeGids(userId);
3254 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3255 final PackageSetting ps = mSettings.mPackages.get(packageName);
3256 if (ps != null && ps.isMatch(flags)) {
3257 return ps.getPermissionsState().computeGids(userId);
3265 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3266 if (bp.perm != null) {
3267 return PackageParser.generatePermissionInfo(bp.perm, flags);
3269 PermissionInfo pi = new PermissionInfo();
3271 pi.packageName = bp.sourcePackage;
3272 pi.nonLocalizedLabel = bp.name;
3273 pi.protectionLevel = bp.protectionLevel;
3278 public PermissionInfo getPermissionInfo(String name, int flags) {
3280 synchronized (mPackages) {
3281 final BasePermission p = mSettings.mPermissions.get(name);
3283 return generatePermissionInfo(p, flags);
3290 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3293 synchronized (mPackages) {
3294 if (group != null && !mPermissionGroups.containsKey(group)) {
3295 // This is thrown as NameNotFoundException
3299 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3300 for (BasePermission p : mSettings.mPermissions.values()) {
3301 if (group == null) {
3302 if (p.perm == null || p.perm.info.group == null) {
3303 out.add(generatePermissionInfo(p, flags));
3306 if (p.perm != null && group.equals(p.perm.info.group)) {
3307 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3311 return new ParceledListSlice<>(out);
3316 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3318 synchronized (mPackages) {
3319 return PackageParser.generatePermissionGroupInfo(
3320 mPermissionGroups.get(name), flags);
3325 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3327 synchronized (mPackages) {
3328 final int N = mPermissionGroups.size();
3329 ArrayList<PermissionGroupInfo> out
3330 = new ArrayList<PermissionGroupInfo>(N);
3331 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3332 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3334 return new ParceledListSlice<>(out);
3338 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3340 if (!sUserManager.exists(userId)) return null;
3341 PackageSetting ps = mSettings.mPackages.get(packageName);
3343 if (ps.pkg == null) {
3344 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3345 if (pInfo != null) {
3346 return pInfo.applicationInfo;
3350 return PackageParser.generateApplicationInfo(ps.pkg, flags,
3351 ps.readUserState(userId), userId);
3357 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3358 if (!sUserManager.exists(userId)) return null;
3359 flags = updateFlagsForApplication(flags, userId, packageName);
3360 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3361 false /* requireFullPermission */, false /* checkShell */, "get application info");
3364 synchronized (mPackages) {
3365 // Normalize package name to hanlde renamed packages
3366 packageName = normalizePackageNameLPr(packageName);
3368 PackageParser.Package p = mPackages.get(packageName);
3369 if (DEBUG_PACKAGE_INFO) Log.v(
3370 TAG, "getApplicationInfo " + packageName
3373 PackageSetting ps = mSettings.mPackages.get(packageName);
3374 if (ps == null) return null;
3375 // Note: isEnabledLP() does not apply here - always return info
3376 return PackageParser.generateApplicationInfo(
3377 p, flags, ps.readUserState(userId), userId);
3379 if ("android".equals(packageName)||"system".equals(packageName)) {
3380 return mAndroidApplication;
3382 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3383 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3389 private String normalizePackageNameLPr(String packageName) {
3390 String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3391 return normalizedPackageName != null ? normalizedPackageName : packageName;
3395 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3396 final IPackageDataObserver observer) {
3397 mContext.enforceCallingOrSelfPermission(
3398 android.Manifest.permission.CLEAR_APP_CACHE, null);
3399 // Queue up an async operation since clearing cache may take a little while.
3400 mHandler.post(new Runnable() {
3402 mHandler.removeCallbacks(this);
3403 boolean success = true;
3404 synchronized (mInstallLock) {
3406 mInstaller.freeCache(volumeUuid, freeStorageSize);
3407 } catch (InstallerException e) {
3408 Slog.w(TAG, "Couldn't clear application caches: " + e);
3412 if (observer != null) {
3414 observer.onRemoveCompleted(null, success);
3415 } catch (RemoteException e) {
3416 Slog.w(TAG, "RemoveException when invoking call back");
3424 public void freeStorage(final String volumeUuid, final long freeStorageSize,
3425 final IntentSender pi) {
3426 mContext.enforceCallingOrSelfPermission(
3427 android.Manifest.permission.CLEAR_APP_CACHE, null);
3428 // Queue up an async operation since clearing cache may take a little while.
3429 mHandler.post(new Runnable() {
3431 mHandler.removeCallbacks(this);
3432 boolean success = true;
3433 synchronized (mInstallLock) {
3435 mInstaller.freeCache(volumeUuid, freeStorageSize);
3436 } catch (InstallerException e) {
3437 Slog.w(TAG, "Couldn't clear application caches: " + e);
3443 // Callback via pending intent
3444 int code = success ? 1 : 0;
3445 pi.sendIntent(null, code, null,
3447 } catch (SendIntentException e1) {
3448 Slog.i(TAG, "Failed to send pending intent");
3455 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3456 synchronized (mInstallLock) {
3458 mInstaller.freeCache(volumeUuid, freeStorageSize);
3459 } catch (InstallerException e) {
3460 throw new IOException("Failed to free enough space", e);
3466 * Update given flags based on encryption status of current user.
3468 private int updateFlags(int flags, int userId) {
3469 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3470 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3471 // Caller expressed an explicit opinion about what encryption
3472 // aware/unaware components they want to see, so fall through and
3473 // give them what they want
3475 // Caller expressed no opinion, so match based on user state
3476 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3477 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3479 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3485 private UserManagerInternal getUserManagerInternal() {
3486 if (mUserManagerInternal == null) {
3487 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3489 return mUserManagerInternal;
3493 * Update given flags when being used to request {@link PackageInfo}.
3495 private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3496 boolean triaged = true;
3497 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3498 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3499 // Caller is asking for component details, so they'd better be
3500 // asking for specific encryption matching behavior, or be triaged
3501 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3502 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3503 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3507 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3508 | PackageManager.MATCH_SYSTEM_ONLY
3509 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3512 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3513 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3514 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3516 return updateFlags(flags, userId);
3520 * Update given flags when being used to request {@link ApplicationInfo}.
3522 private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3523 return updateFlagsForPackage(flags, userId, cookie);
3527 * Update given flags when being used to request {@link ComponentInfo}.
3529 private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3530 if (cookie instanceof Intent) {
3531 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3532 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3536 boolean triaged = true;
3537 // Caller is asking for component details, so they'd better be
3538 // asking for specific encryption matching behavior, or be triaged
3539 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3540 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3541 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3544 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3545 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3546 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3549 return updateFlags(flags, userId);
3553 * Update given flags when being used to request {@link ResolveInfo}.
3555 int updateFlagsForResolve(int flags, int userId, Object cookie) {
3556 // Safe mode means we shouldn't match any third-party components
3558 flags |= PackageManager.MATCH_SYSTEM_ONLY;
3561 return updateFlagsForComponent(flags, userId, cookie);
3565 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3566 if (!sUserManager.exists(userId)) return null;
3567 flags = updateFlagsForComponent(flags, userId, component);
3568 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3569 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3570 synchronized (mPackages) {
3571 PackageParser.Activity a = mActivities.mActivities.get(component);
3573 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3574 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3575 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3576 if (ps == null) return null;
3577 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3580 if (mResolveComponentName.equals(component)) {
3581 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3582 new PackageUserState(), userId);
3589 public boolean activitySupportsIntent(ComponentName component, Intent intent,
3590 String resolvedType) {
3591 synchronized (mPackages) {
3592 if (component.equals(mResolveComponentName)) {
3593 // The resolver supports EVERYTHING!
3596 PackageParser.Activity a = mActivities.mActivities.get(component);
3600 for (int i=0; i<a.intents.size(); i++) {
3601 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3602 intent.getData(), intent.getCategories(), TAG) >= 0) {
3611 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3612 if (!sUserManager.exists(userId)) return null;
3613 flags = updateFlagsForComponent(flags, userId, component);
3614 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3615 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3616 synchronized (mPackages) {
3617 PackageParser.Activity a = mReceivers.mActivities.get(component);
3618 if (DEBUG_PACKAGE_INFO) Log.v(
3619 TAG, "getReceiverInfo " + component + ": " + a);
3620 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3621 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3622 if (ps == null) return null;
3623 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3631 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3632 if (!sUserManager.exists(userId)) return null;
3633 flags = updateFlagsForComponent(flags, userId, component);
3634 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3635 false /* requireFullPermission */, false /* checkShell */, "get service info");
3636 synchronized (mPackages) {
3637 PackageParser.Service s = mServices.mServices.get(component);
3638 if (DEBUG_PACKAGE_INFO) Log.v(
3639 TAG, "getServiceInfo " + component + ": " + s);
3640 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3641 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3642 if (ps == null) return null;
3643 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3651 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3652 if (!sUserManager.exists(userId)) return null;
3653 flags = updateFlagsForComponent(flags, userId, component);
3654 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3655 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3656 synchronized (mPackages) {
3657 PackageParser.Provider p = mProviders.mProviders.get(component);
3658 if (DEBUG_PACKAGE_INFO) Log.v(
3659 TAG, "getProviderInfo " + component + ": " + p);
3660 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3661 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3662 if (ps == null) return null;
3663 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3671 public String[] getSystemSharedLibraryNames() {
3673 synchronized (mPackages) {
3674 libSet = mSharedLibraries.keySet();
3675 int size = libSet.size();
3677 String[] libs = new String[size];
3678 libSet.toArray(libs);
3686 public @NonNull String getServicesSystemSharedLibraryPackageName() {
3687 synchronized (mPackages) {
3688 return mServicesSystemSharedLibraryPackageName;
3693 public @NonNull String getSharedSystemSharedLibraryPackageName() {
3694 synchronized (mPackages) {
3695 return mSharedSystemSharedLibraryPackageName;
3700 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3701 synchronized (mPackages) {
3702 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3704 final FeatureInfo fi = new FeatureInfo();
3705 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3706 FeatureInfo.GL_ES_VERSION_UNDEFINED);
3709 return new ParceledListSlice<>(res);
3714 public boolean hasSystemFeature(String name, int version) {
3715 synchronized (mPackages) {
3716 final FeatureInfo feat = mAvailableFeatures.get(name);
3720 return feat.version >= version;
3726 public int checkPermission(String permName, String pkgName, int userId) {
3727 if (!sUserManager.exists(userId)) {
3728 return PackageManager.PERMISSION_DENIED;
3731 synchronized (mPackages) {
3732 final PackageParser.Package p = mPackages.get(pkgName);
3733 if (p != null && p.mExtras != null) {
3734 final PackageSetting ps = (PackageSetting) p.mExtras;
3735 final PermissionsState permissionsState = ps.getPermissionsState();
3736 if (permissionsState.hasPermission(permName, userId)) {
3737 return PackageManager.PERMISSION_GRANTED;
3739 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3740 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3741 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3742 return PackageManager.PERMISSION_GRANTED;
3747 return PackageManager.PERMISSION_DENIED;
3751 public int checkUidPermission(String permName, int uid) {
3752 final int userId = UserHandle.getUserId(uid);
3754 if (!sUserManager.exists(userId)) {
3755 return PackageManager.PERMISSION_DENIED;
3758 synchronized (mPackages) {
3759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3761 final SettingBase ps = (SettingBase) obj;
3762 final PermissionsState permissionsState = ps.getPermissionsState();
3763 if (permissionsState.hasPermission(permName, userId)) {
3764 return PackageManager.PERMISSION_GRANTED;
3766 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3767 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3768 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3769 return PackageManager.PERMISSION_GRANTED;
3772 ArraySet<String> perms = mSystemPermissions.get(uid);
3773 if (perms != null) {
3774 if (perms.contains(permName)) {
3775 return PackageManager.PERMISSION_GRANTED;
3777 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3778 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3779 return PackageManager.PERMISSION_GRANTED;
3785 return PackageManager.PERMISSION_DENIED;
3789 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3790 if (UserHandle.getCallingUserId() != userId) {
3791 mContext.enforceCallingPermission(
3792 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3793 "isPermissionRevokedByPolicy for user " + userId);
3796 if (checkPermission(permission, packageName, userId)
3797 == PackageManager.PERMISSION_GRANTED) {
3801 final long identity = Binder.clearCallingIdentity();
3803 final int flags = getPermissionFlags(permission, packageName, userId);
3804 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3806 Binder.restoreCallingIdentity(identity);
3811 public String getPermissionControllerPackageName() {
3812 synchronized (mPackages) {
3813 return mRequiredInstallerPackage;
3818 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3819 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3820 * @param checkShell whether to prevent shell from access if there's a debugging restriction
3821 * @param message the message to log on security exception
3823 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3824 boolean checkShell, String message) {
3826 throw new IllegalArgumentException("Invalid userId " + userId);
3829 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3831 if (userId == UserHandle.getUserId(callingUid)) return;
3832 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3833 if (requireFullPermission) {
3834 mContext.enforceCallingOrSelfPermission(
3835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3838 mContext.enforceCallingOrSelfPermission(
3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3840 } catch (SecurityException se) {
3841 mContext.enforceCallingOrSelfPermission(
3842 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3848 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3849 if (callingUid == Process.SHELL_UID) {
3851 && sUserManager.hasUserRestriction(restriction, userHandle)) {
3852 throw new SecurityException("Shell does not have permission to access user "
3854 } else if (userHandle < 0) {
3855 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3856 + Debug.getCallers(3));
3861 private BasePermission findPermissionTreeLP(String permName) {
3862 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3863 if (permName.startsWith(bp.name) &&
3864 permName.length() > bp.name.length() &&
3865 permName.charAt(bp.name.length()) == '.') {
3872 private BasePermission checkPermissionTreeLP(String permName) {
3873 if (permName != null) {
3874 BasePermission bp = findPermissionTreeLP(permName);
3876 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3879 throw new SecurityException("Calling uid "
3880 + Binder.getCallingUid()
3881 + " is not allowed to add to permission tree "
3882 + bp.name + " owned by uid " + bp.uid);
3885 throw new SecurityException("No permission tree found for " + permName);
3888 static boolean compareStrings(CharSequence s1, CharSequence s2) {
3895 if (s1.getClass() != s2.getClass()) {
3898 return s1.equals(s2);
3901 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3902 if (pi1.icon != pi2.icon) return false;
3903 if (pi1.logo != pi2.logo) return false;
3904 if (pi1.protectionLevel != pi2.protectionLevel) return false;
3905 if (!compareStrings(pi1.name, pi2.name)) return false;
3906 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3907 // We'll take care of setting this one.
3908 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3909 // These are not currently stored in settings.
3910 //if (!compareStrings(pi1.group, pi2.group)) return false;
3911 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3912 //if (pi1.labelRes != pi2.labelRes) return false;
3913 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3917 int permissionInfoFootprint(PermissionInfo info) {
3918 int size = info.name.length();
3919 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3920 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3924 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3926 for (BasePermission perm : mSettings.mPermissions.values()) {
3927 if (perm.uid == tree.uid) {
3928 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3934 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3935 // We calculate the max size of permissions defined by this uid and throw
3936 // if that plus the size of 'info' would exceed our stated maximum.
3937 if (tree.uid != Process.SYSTEM_UID) {
3938 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3939 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3940 throw new SecurityException("Permission tree size cap exceeded");
3945 boolean addPermissionLocked(PermissionInfo info, boolean async) {
3946 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3947 throw new SecurityException("Label must be specified in permission");
3949 BasePermission tree = checkPermissionTreeLP(info.name);
3950 BasePermission bp = mSettings.mPermissions.get(info.name);
3951 boolean added = bp == null;
3952 boolean changed = true;
3953 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3955 enforcePermissionCapLocked(info, tree);
3956 bp = new BasePermission(info.name, tree.sourcePackage,
3957 BasePermission.TYPE_DYNAMIC);
3958 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3959 throw new SecurityException(
3960 "Not allowed to modify non-dynamic permission "
3963 if (bp.protectionLevel == fixedLevel
3964 && bp.perm.owner.equals(tree.perm.owner)
3965 && bp.uid == tree.uid
3966 && comparePermissionInfos(bp.perm.info, info)) {
3970 bp.protectionLevel = fixedLevel;
3971 info = new PermissionInfo(info);
3972 info.protectionLevel = fixedLevel;
3973 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3974 bp.perm.info.packageName = tree.perm.info.packageName;
3977 mSettings.mPermissions.put(info.name, bp);
3981 mSettings.writeLPr();
3983 scheduleWriteSettingsLocked();
3990 public boolean addPermission(PermissionInfo info) {
3991 synchronized (mPackages) {
3992 return addPermissionLocked(info, false);
3997 public boolean addPermissionAsync(PermissionInfo info) {
3998 synchronized (mPackages) {
3999 return addPermissionLocked(info, true);
4004 public void removePermission(String name) {
4005 synchronized (mPackages) {
4006 checkPermissionTreeLP(name);
4007 BasePermission bp = mSettings.mPermissions.get(name);
4009 if (bp.type != BasePermission.TYPE_DYNAMIC) {
4010 throw new SecurityException(
4011 "Not allowed to modify non-dynamic permission "
4014 mSettings.mPermissions.remove(name);
4015 mSettings.writeLPr();
4020 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4021 BasePermission bp) {
4022 int index = pkg.requestedPermissions.indexOf(bp.name);
4024 throw new SecurityException("Package " + pkg.packageName
4025 + " has not requested permission " + bp.name);
4027 if (!bp.isRuntime() && !bp.isDevelopment()) {
4028 throw new SecurityException("Permission " + bp.name
4029 + " is not a changeable permission type");
4034 public void grantRuntimePermission(String packageName, String name, final int userId) {
4035 if (!sUserManager.exists(userId)) {
4036 Log.e(TAG, "No such user:" + userId);
4040 mContext.enforceCallingOrSelfPermission(
4041 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4042 "grantRuntimePermission");
4044 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4045 true /* requireFullPermission */, true /* checkShell */,
4046 "grantRuntimePermission");
4049 final SettingBase sb;
4051 synchronized (mPackages) {
4052 final PackageParser.Package pkg = mPackages.get(packageName);
4054 throw new IllegalArgumentException("Unknown package: " + packageName);
4057 final BasePermission bp = mSettings.mPermissions.get(name);
4059 throw new IllegalArgumentException("Unknown permission: " + name);
4062 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4064 // If a permission review is required for legacy apps we represent
4065 // their permissions as always granted runtime ones since we need
4066 // to keep the review required permission flag per user while an
4067 // install permission's state is shared across all users.
4068 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4069 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4070 && bp.isRuntime()) {
4074 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4075 sb = (SettingBase) pkg.mExtras;
4077 throw new IllegalArgumentException("Unknown package: " + packageName);
4080 final PermissionsState permissionsState = sb.getPermissionsState();
4082 final int flags = permissionsState.getPermissionFlags(name, userId);
4083 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4084 throw new SecurityException("Cannot grant system fixed permission "
4085 + name + " for package " + packageName);
4088 if (bp.isDevelopment()) {
4089 // Development permissions must be handled specially, since they are not
4090 // normal runtime permissions. For now they apply to all users.
4091 if (permissionsState.grantInstallPermission(bp) !=
4092 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4093 scheduleWriteSettingsLocked();
4098 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4099 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4103 final int result = permissionsState.grantRuntimePermission(bp, userId);
4105 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4109 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4110 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4111 mHandler.post(new Runnable() {
4114 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4121 mOnPermissionChangeListeners.onPermissionsChanged(uid);
4123 // Not critical if that is lost - app has to request again.
4124 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4127 // Only need to do this if user is initialized. Otherwise it's a new user
4128 // and there are no processes running as the user yet and there's no need
4129 // to make an expensive call to remount processes for the changed permissions.
4130 if (READ_EXTERNAL_STORAGE.equals(name)
4131 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4132 final long token = Binder.clearCallingIdentity();
4134 if (sUserManager.isInitialized(userId)) {
4135 MountServiceInternal mountServiceInternal = LocalServices.getService(
4136 MountServiceInternal.class);
4137 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4140 Binder.restoreCallingIdentity(token);
4146 public void revokeRuntimePermission(String packageName, String name, int userId) {
4147 if (!sUserManager.exists(userId)) {
4148 Log.e(TAG, "No such user:" + userId);
4152 mContext.enforceCallingOrSelfPermission(
4153 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4154 "revokeRuntimePermission");
4156 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4157 true /* requireFullPermission */, true /* checkShell */,
4158 "revokeRuntimePermission");
4162 synchronized (mPackages) {
4163 final PackageParser.Package pkg = mPackages.get(packageName);
4165 throw new IllegalArgumentException("Unknown package: " + packageName);
4168 final BasePermission bp = mSettings.mPermissions.get(name);
4170 throw new IllegalArgumentException("Unknown permission: " + name);
4173 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4175 // If a permission review is required for legacy apps we represent
4176 // their permissions as always granted runtime ones since we need
4177 // to keep the review required permission flag per user while an
4178 // install permission's state is shared across all users.
4179 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4180 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4181 && bp.isRuntime()) {
4185 SettingBase sb = (SettingBase) pkg.mExtras;
4187 throw new IllegalArgumentException("Unknown package: " + packageName);
4190 final PermissionsState permissionsState = sb.getPermissionsState();
4192 final int flags = permissionsState.getPermissionFlags(name, userId);
4193 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4194 throw new SecurityException("Cannot revoke system fixed permission "
4195 + name + " for package " + packageName);
4198 if (bp.isDevelopment()) {
4199 // Development permissions must be handled specially, since they are not
4200 // normal runtime permissions. For now they apply to all users.
4201 if (permissionsState.revokeInstallPermission(bp) !=
4202 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4203 scheduleWriteSettingsLocked();
4208 if (permissionsState.revokeRuntimePermission(bp, userId) ==
4209 PermissionsState.PERMISSION_OPERATION_FAILURE) {
4213 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4215 // Critical, after this call app should never have the permission.
4216 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4218 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4221 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4225 public void resetRuntimePermissions() {
4226 mContext.enforceCallingOrSelfPermission(
4227 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4228 "revokeRuntimePermission");
4230 int callingUid = Binder.getCallingUid();
4231 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4232 mContext.enforceCallingOrSelfPermission(
4233 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4234 "resetRuntimePermissions");
4237 synchronized (mPackages) {
4238 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4239 for (int userId : UserManagerService.getInstance().getUserIds()) {
4240 final int packageCount = mPackages.size();
4241 for (int i = 0; i < packageCount; i++) {
4242 PackageParser.Package pkg = mPackages.valueAt(i);
4243 if (!(pkg.mExtras instanceof PackageSetting)) {
4246 PackageSetting ps = (PackageSetting) pkg.mExtras;
4247 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4254 public int getPermissionFlags(String name, String packageName, int userId) {
4255 if (!sUserManager.exists(userId)) {
4259 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4261 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4262 true /* requireFullPermission */, false /* checkShell */,
4263 "getPermissionFlags");
4265 synchronized (mPackages) {
4266 final PackageParser.Package pkg = mPackages.get(packageName);
4271 final BasePermission bp = mSettings.mPermissions.get(name);
4276 SettingBase sb = (SettingBase) pkg.mExtras;
4281 PermissionsState permissionsState = sb.getPermissionsState();
4282 return permissionsState.getPermissionFlags(name, userId);
4287 public void updatePermissionFlags(String name, String packageName, int flagMask,
4288 int flagValues, int userId) {
4289 if (!sUserManager.exists(userId)) {
4293 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4295 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4296 true /* requireFullPermission */, true /* checkShell */,
4297 "updatePermissionFlags");
4299 // Only the system can change these flags and nothing else.
4300 if (getCallingUid() != Process.SYSTEM_UID) {
4301 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4302 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4303 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4304 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4305 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4308 synchronized (mPackages) {
4309 final PackageParser.Package pkg = mPackages.get(packageName);
4311 throw new IllegalArgumentException("Unknown package: " + packageName);
4314 final BasePermission bp = mSettings.mPermissions.get(name);
4316 throw new IllegalArgumentException("Unknown permission: " + name);
4319 SettingBase sb = (SettingBase) pkg.mExtras;
4321 throw new IllegalArgumentException("Unknown package: " + packageName);
4324 PermissionsState permissionsState = sb.getPermissionsState();
4326 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4328 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4329 // Install and runtime permissions are stored in different places,
4330 // so figure out what permission changed and persist the change.
4331 if (permissionsState.getInstallPermissionState(name) != null) {
4332 scheduleWriteSettingsLocked();
4333 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4335 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4342 * Update the permission flags for all packages and runtime permissions of a user in order
4343 * to allow device or profile owner to remove POLICY_FIXED.
4346 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4347 if (!sUserManager.exists(userId)) {
4351 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4353 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4354 true /* requireFullPermission */, true /* checkShell */,
4355 "updatePermissionFlagsForAllApps");
4357 // Only the system can change system fixed flags.
4358 if (getCallingUid() != Process.SYSTEM_UID) {
4359 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4360 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4363 synchronized (mPackages) {
4364 boolean changed = false;
4365 final int packageCount = mPackages.size();
4366 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4367 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4368 SettingBase sb = (SettingBase) pkg.mExtras;
4372 PermissionsState permissionsState = sb.getPermissionsState();
4373 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4374 userId, flagMask, flagValues);
4377 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4382 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4383 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4384 != PackageManager.PERMISSION_GRANTED
4385 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4386 != PackageManager.PERMISSION_GRANTED) {
4387 throw new SecurityException(message + " requires "
4388 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4389 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4394 public boolean shouldShowRequestPermissionRationale(String permissionName,
4395 String packageName, int userId) {
4396 if (UserHandle.getCallingUserId() != userId) {
4397 mContext.enforceCallingPermission(
4398 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4399 "canShowRequestPermissionRationale for user " + userId);
4402 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4403 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4407 if (checkPermission(permissionName, packageName, userId)
4408 == PackageManager.PERMISSION_GRANTED) {
4414 final long identity = Binder.clearCallingIdentity();
4416 flags = getPermissionFlags(permissionName,
4417 packageName, userId);
4419 Binder.restoreCallingIdentity(identity);
4422 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4423 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4424 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4426 if ((flags & fixedFlags) != 0) {
4430 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4434 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4435 mContext.enforceCallingOrSelfPermission(
4436 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4437 "addOnPermissionsChangeListener");
4439 synchronized (mPackages) {
4440 mOnPermissionChangeListeners.addListenerLocked(listener);
4445 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4446 synchronized (mPackages) {
4447 mOnPermissionChangeListeners.removeListenerLocked(listener);
4452 public boolean isProtectedBroadcast(String actionName) {
4453 synchronized (mPackages) {
4454 if (mProtectedBroadcasts.contains(actionName)) {
4456 } else if (actionName != null) {
4457 // TODO: remove these terrible hacks
4458 if (actionName.startsWith("android.net.netmon.lingerExpired")
4459 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4460 || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4461 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4470 public int checkSignatures(String pkg1, String pkg2) {
4471 synchronized (mPackages) {
4472 final PackageParser.Package p1 = mPackages.get(pkg1);
4473 final PackageParser.Package p2 = mPackages.get(pkg2);
4474 if (p1 == null || p1.mExtras == null
4475 || p2 == null || p2.mExtras == null) {
4476 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4478 return compareSignatures(p1.mSignatures, p2.mSignatures);
4483 public int checkUidSignatures(int uid1, int uid2) {
4484 // Map to base uids.
4485 uid1 = UserHandle.getAppId(uid1);
4486 uid2 = UserHandle.getAppId(uid2);
4488 synchronized (mPackages) {
4491 Object obj = mSettings.getUserIdLPr(uid1);
4493 if (obj instanceof SharedUserSetting) {
4494 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4495 } else if (obj instanceof PackageSetting) {
4496 s1 = ((PackageSetting)obj).signatures.mSignatures;
4498 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4501 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4503 obj = mSettings.getUserIdLPr(uid2);
4505 if (obj instanceof SharedUserSetting) {
4506 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4507 } else if (obj instanceof PackageSetting) {
4508 s2 = ((PackageSetting)obj).signatures.mSignatures;
4510 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4513 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4515 return compareSignatures(s1, s2);
4520 * This method should typically only be used when granting or revoking
4521 * permissions, since the app may immediately restart after this call.
4523 * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4524 * guard your work against the app being relaunched.
4526 private void killUid(int appId, int userId, String reason) {
4527 final long identity = Binder.clearCallingIdentity();
4529 IActivityManager am = ActivityManagerNative.getDefault();
4532 am.killUid(appId, userId, reason);
4533 } catch (RemoteException e) {
4534 /* ignore - same process */
4538 Binder.restoreCallingIdentity(identity);
4543 * Compares two sets of signatures. Returns:
4545 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4547 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4549 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4551 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4553 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4555 static int compareSignatures(Signature[] s1, Signature[] s2) {
4558 ? PackageManager.SIGNATURE_NEITHER_SIGNED
4559 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4563 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4566 if (s1.length != s2.length) {
4567 return PackageManager.SIGNATURE_NO_MATCH;
4570 // Since both signature sets are of size 1, we can compare without HashSets.
4571 if (s1.length == 1) {
4572 return s1[0].equals(s2[0]) ?
4573 PackageManager.SIGNATURE_MATCH :
4574 PackageManager.SIGNATURE_NO_MATCH;
4577 ArraySet<Signature> set1 = new ArraySet<Signature>();
4578 for (Signature sig : s1) {
4581 ArraySet<Signature> set2 = new ArraySet<Signature>();
4582 for (Signature sig : s2) {
4585 // Make sure s2 contains all signatures in s1.
4586 if (set1.equals(set2)) {
4587 return PackageManager.SIGNATURE_MATCH;
4589 return PackageManager.SIGNATURE_NO_MATCH;
4593 * If the database version for this type of package (internal storage or
4594 * external storage) is less than the version where package signatures
4595 * were updated, return true.
4597 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4598 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4599 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4603 * Used for backward compatibility to make sure any packages with
4604 * certificate chains get upgraded to the new style. {@code existingSigs}
4605 * will be in the old format (since they were stored on disk from before the
4606 * system upgrade) and {@code scannedSigs} will be in the newer format.
4608 private int compareSignaturesCompat(PackageSignatures existingSigs,
4609 PackageParser.Package scannedPkg) {
4610 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4611 return PackageManager.SIGNATURE_NO_MATCH;
4614 ArraySet<Signature> existingSet = new ArraySet<Signature>();
4615 for (Signature sig : existingSigs.mSignatures) {
4616 existingSet.add(sig);
4618 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4619 for (Signature sig : scannedPkg.mSignatures) {
4621 Signature[] chainSignatures = sig.getChainSignatures();
4622 for (Signature chainSig : chainSignatures) {
4623 scannedCompatSet.add(chainSig);
4625 } catch (CertificateEncodingException e) {
4626 scannedCompatSet.add(sig);
4630 * Make sure the expanded scanned set contains all signatures in the
4633 if (scannedCompatSet.equals(existingSet)) {
4634 // Migrate the old signatures to the new scheme.
4635 existingSigs.assignSignatures(scannedPkg.mSignatures);
4636 // The new KeySets will be re-added later in the scanning process.
4637 synchronized (mPackages) {
4638 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4640 return PackageManager.SIGNATURE_MATCH;
4642 return PackageManager.SIGNATURE_NO_MATCH;
4645 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4646 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4647 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4650 private int compareSignaturesRecover(PackageSignatures existingSigs,
4651 PackageParser.Package scannedPkg) {
4652 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4653 return PackageManager.SIGNATURE_NO_MATCH;
4658 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4659 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4660 + scannedPkg.packageName);
4661 return PackageManager.SIGNATURE_MATCH;
4663 } catch (CertificateException e) {
4664 msg = e.getMessage();
4667 logCriticalInfo(Log.INFO,
4668 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4669 return PackageManager.SIGNATURE_NO_MATCH;
4673 public List<String> getAllPackages() {
4674 synchronized (mPackages) {
4675 return new ArrayList<String>(mPackages.keySet());
4680 public String[] getPackagesForUid(int uid) {
4681 uid = UserHandle.getAppId(uid);
4683 synchronized (mPackages) {
4684 Object obj = mSettings.getUserIdLPr(uid);
4685 if (obj instanceof SharedUserSetting) {
4686 final SharedUserSetting sus = (SharedUserSetting) obj;
4687 final int N = sus.packages.size();
4688 final String[] res = new String[N];
4689 for (int i = 0; i < N; i++) {
4690 res[i] = sus.packages.valueAt(i).name;
4693 } else if (obj instanceof PackageSetting) {
4694 final PackageSetting ps = (PackageSetting) obj;
4695 return new String[] { ps.name };
4702 public String getNameForUid(int uid) {
4704 synchronized (mPackages) {
4705 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4706 if (obj instanceof SharedUserSetting) {
4707 final SharedUserSetting sus = (SharedUserSetting) obj;
4708 return sus.name + ":" + sus.userId;
4709 } else if (obj instanceof PackageSetting) {
4710 final PackageSetting ps = (PackageSetting) obj;
4718 public int getUidForSharedUser(String sharedUserName) {
4719 if(sharedUserName == null) {
4723 synchronized (mPackages) {
4724 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4733 public int getFlagsForUid(int uid) {
4734 synchronized (mPackages) {
4735 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4736 if (obj instanceof SharedUserSetting) {
4737 final SharedUserSetting sus = (SharedUserSetting) obj;
4738 return sus.pkgFlags;
4739 } else if (obj instanceof PackageSetting) {
4740 final PackageSetting ps = (PackageSetting) obj;
4748 public int getPrivateFlagsForUid(int uid) {
4749 synchronized (mPackages) {
4750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4751 if (obj instanceof SharedUserSetting) {
4752 final SharedUserSetting sus = (SharedUserSetting) obj;
4753 return sus.pkgPrivateFlags;
4754 } else if (obj instanceof PackageSetting) {
4755 final PackageSetting ps = (PackageSetting) obj;
4756 return ps.pkgPrivateFlags;
4763 public boolean isUidPrivileged(int uid) {
4764 uid = UserHandle.getAppId(uid);
4766 synchronized (mPackages) {
4767 Object obj = mSettings.getUserIdLPr(uid);
4768 if (obj instanceof SharedUserSetting) {
4769 final SharedUserSetting sus = (SharedUserSetting) obj;
4770 final Iterator<PackageSetting> it = sus.packages.iterator();
4771 while (it.hasNext()) {
4772 if (it.next().isPrivileged()) {
4776 } else if (obj instanceof PackageSetting) {
4777 final PackageSetting ps = (PackageSetting) obj;
4778 return ps.isPrivileged();
4785 public String[] getAppOpPermissionPackages(String permissionName) {
4786 synchronized (mPackages) {
4787 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4791 return pkgs.toArray(new String[pkgs.size()]);
4796 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4797 int flags, int userId) {
4799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4801 if (!sUserManager.exists(userId)) return null;
4802 flags = updateFlagsForResolve(flags, userId, intent);
4803 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4804 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4807 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4809 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4811 final ResolveInfo bestChoice =
4812 chooseBestActivity(intent, resolvedType, flags, query, userId);
4815 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4820 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4821 IntentFilter filter, int match, ComponentName activity) {
4822 final int userId = UserHandle.getCallingUserId();
4823 if (DEBUG_PREFERRED) {
4824 Log.v(TAG, "setLastChosenActivity intent=" + intent
4825 + " resolvedType=" + resolvedType
4827 + " filter=" + filter
4829 + " activity=" + activity);
4830 filter.dump(new PrintStreamPrinter(System.out), " ");
4832 intent.setComponent(null);
4833 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4835 // Find any earlier preferred or last chosen entries and nuke them
4836 findPreferredActivity(intent, resolvedType,
4837 flags, query, 0, false, true, false, userId);
4838 // Add the new activity as the last chosen for this filter
4839 addPreferredActivityInternal(filter, match, null, activity, false, userId,
4840 "Setting last chosen");
4844 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4845 final int userId = UserHandle.getCallingUserId();
4846 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4847 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4849 return findPreferredActivity(intent, resolvedType, flags, query, 0,
4850 false, false, false, userId);
4853 private boolean isEphemeralDisabled() {
4854 // ephemeral apps have been disabled across the board
4855 if (DISABLE_EPHEMERAL_APPS) {
4858 // system isn't up yet; can't read settings, so, assume no ephemeral apps
4859 if (!mSystemReady) {
4862 // we can't get a content resolver until the system is ready; these checks must happen last
4863 final ContentResolver resolver = mContext.getContentResolver();
4864 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4867 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4870 private boolean isEphemeralAllowed(
4871 Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4872 boolean skipPackageCheck) {
4873 // Short circuit and return early if possible.
4874 if (isEphemeralDisabled()) {
4877 final int callingUser = UserHandle.getCallingUserId();
4878 if (callingUser != UserHandle.USER_SYSTEM) {
4881 if (mEphemeralResolverConnection == null) {
4884 if (intent.getComponent() != null) {
4887 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4890 if (!skipPackageCheck && intent.getPackage() != null) {
4893 final boolean isWebUri = hasWebURI(intent);
4894 if (!isWebUri || intent.getData().getHost() == null) {
4897 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4898 synchronized (mPackages) {
4899 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4900 for (int n = 0; n < count; n++) {
4901 ResolveInfo info = resolvedActivities.get(n);
4902 String packageName = info.activityInfo.packageName;
4903 PackageSetting ps = mSettings.mPackages.get(packageName);
4905 // Try to get the status from User settings first
4906 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4907 int status = (int) (packedStatus >> 32);
4908 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4909 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4910 if (DEBUG_EPHEMERAL) {
4911 Slog.v(TAG, "DENY ephemeral apps;"
4912 + " pkg: " + packageName + ", status: " + status);
4919 // We've exhausted all ways to deny ephemeral application; let the system look for them.
4923 private static EphemeralResolveInfo getEphemeralResolveInfo(
4924 Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4925 String resolvedType, int userId, String packageName) {
4926 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4927 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4928 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4929 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4930 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4931 ephemeralPrefixCount);
4932 final int[] shaPrefix = digest.getDigestPrefix();
4933 final byte[][] digestBytes = digest.getDigestBytes();
4934 final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4935 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4936 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4937 // No hash prefix match; there are no ephemeral apps for this domain.
4941 // Go in reverse order so we match the narrowest scope first.
4942 for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4943 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4944 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4947 final List<IntentFilter> filters = ephemeralApplication.getFilters();
4948 // No filters; this should never happen.
4949 if (filters.isEmpty()) {
4952 if (packageName != null
4953 && !packageName.equals(ephemeralApplication.getPackageName())) {
4956 // We have a domain match; resolve the filters to see if anything matches.
4957 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4958 for (int j = filters.size() - 1; j >= 0; --j) {
4959 final EphemeralResolveIntentInfo intentInfo =
4960 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4961 ephemeralResolver.addFilter(intentInfo);
4963 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4964 intent, resolvedType, false /*defaultOnly*/, userId);
4965 if (!matchedResolveInfoList.isEmpty()) {
4966 return matchedResolveInfoList.get(0);
4970 // Hash or filter mis-match; no ephemeral apps for this domain.
4974 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4975 int flags, List<ResolveInfo> query, int userId) {
4976 if (query != null) {
4977 final int N = query.size();
4979 return query.get(0);
4981 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4982 // If there is more than one activity with the same priority,
4983 // then let the user decide between them.
4984 ResolveInfo r0 = query.get(0);
4985 ResolveInfo r1 = query.get(1);
4986 if (DEBUG_INTENT_MATCHING || debug) {
4987 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4988 + r1.activityInfo.name + "=" + r1.priority);
4990 // If the first activity has a higher priority, or a different
4991 // default, then it is always desirable to pick it.
4992 if (r0.priority != r1.priority
4993 || r0.preferredOrder != r1.preferredOrder
4994 || r0.isDefault != r1.isDefault) {
4995 return query.get(0);
4997 // If we have saved a preference for a preferred activity for
4998 // this Intent, use that.
4999 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5000 flags, query, r0.priority, true, false, debug, userId);
5004 ri = new ResolveInfo(mResolveInfo);
5005 ri.activityInfo = new ActivityInfo(ri.activityInfo);
5006 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5007 // If all of the options come from the same package, show the application's
5008 // label and icon instead of the generic resolver's.
5009 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5010 // and then throw away the ResolveInfo itself, meaning that the caller loses
5011 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5012 // a fallback for this case; we only set the target package's resources on
5013 // the ResolveInfo, not the ActivityInfo.
5014 final String intentPackage = intent.getPackage();
5015 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5016 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5017 ri.resolvePackageName = intentPackage;
5018 if (userNeedsBadging(userId)) {
5019 ri.noResourceId = true;
5021 ri.icon = appi.icon;
5023 ri.iconResourceId = appi.icon;
5024 ri.labelRes = appi.labelRes;
5026 ri.activityInfo.applicationInfo = new ApplicationInfo(
5027 ri.activityInfo.applicationInfo);
5029 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5030 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5032 // Make sure that the resolver is displayable in car mode
5033 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5034 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5042 * Return true if the given list is not empty and all of its contents have
5043 * an activityInfo with the given package name.
5045 private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5046 if (ArrayUtils.isEmpty(list)) {
5049 for (int i = 0, N = list.size(); i < N; i++) {
5050 final ResolveInfo ri = list.get(i);
5051 final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5052 if (ai == null || !packageName.equals(ai.packageName)) {
5059 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5060 int flags, List<ResolveInfo> query, boolean debug, int userId) {
5061 final int N = query.size();
5062 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5064 // Get the list of persistent preferred activities that handle the intent
5065 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5066 List<PersistentPreferredActivity> pprefs = ppir != null
5067 ? ppir.queryIntent(intent, resolvedType,
5068 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5070 if (pprefs != null && pprefs.size() > 0) {
5071 final int M = pprefs.size();
5072 for (int i=0; i<M; i++) {
5073 final PersistentPreferredActivity ppa = pprefs.get(i);
5074 if (DEBUG_PREFERRED || debug) {
5075 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5076 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5077 + "\n component=" + ppa.mComponent);
5078 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5080 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5081 flags | MATCH_DISABLED_COMPONENTS, userId);
5082 if (DEBUG_PREFERRED || debug) {
5083 Slog.v(TAG, "Found persistent preferred activity:");
5085 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5087 Slog.v(TAG, " null");
5091 // This previously registered persistent preferred activity
5092 // component is no longer known. Ignore it and do NOT remove it.
5095 for (int j=0; j<N; j++) {
5096 final ResolveInfo ri = query.get(j);
5097 if (!ri.activityInfo.applicationInfo.packageName
5098 .equals(ai.applicationInfo.packageName)) {
5101 if (!ri.activityInfo.name.equals(ai.name)) {
5104 // Found a persistent preference that can handle the intent.
5105 if (DEBUG_PREFERRED || debug) {
5106 Slog.v(TAG, "Returning persistent preferred activity: " +
5107 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5116 // TODO: handle preferred activities missing while user has amnesia
5117 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5118 List<ResolveInfo> query, int priority, boolean always,
5119 boolean removeMatches, boolean debug, int userId) {
5120 if (!sUserManager.exists(userId)) return null;
5121 flags = updateFlagsForResolve(flags, userId, intent);
5123 synchronized (mPackages) {
5124 if (intent.getSelector() != null) {
5125 intent = intent.getSelector();
5127 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5129 // Try to find a matching persistent preferred activity.
5130 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5133 // If a persistent preferred activity matched, use it.
5138 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5139 // Get the list of preferred activities that handle the intent
5140 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5141 List<PreferredActivity> prefs = pir != null
5142 ? pir.queryIntent(intent, resolvedType,
5143 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5145 if (prefs != null && prefs.size() > 0) {
5146 boolean changed = false;
5148 // First figure out how good the original match set is.
5149 // We will only allow preferred activities that came
5150 // from the same match quality.
5153 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5155 final int N = query.size();
5156 for (int j=0; j<N; j++) {
5157 final ResolveInfo ri = query.get(j);
5158 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5159 + ": 0x" + Integer.toHexString(match));
5160 if (ri.match > match) {
5165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5166 + Integer.toHexString(match));
5168 match &= IntentFilter.MATCH_CATEGORY_MASK;
5169 final int M = prefs.size();
5170 for (int i=0; i<M; i++) {
5171 final PreferredActivity pa = prefs.get(i);
5172 if (DEBUG_PREFERRED || debug) {
5173 Slog.v(TAG, "Checking PreferredActivity ds="
5174 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5175 + "\n component=" + pa.mPref.mComponent);
5176 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5178 if (pa.mPref.mMatch != match) {
5179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5180 + Integer.toHexString(pa.mPref.mMatch));
5183 // If it's not an "always" type preferred activity and that's what we're
5184 // looking for, skip it.
5185 if (always && !pa.mPref.mAlways) {
5186 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5189 final ActivityInfo ai = getActivityInfo(
5190 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5191 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5193 if (DEBUG_PREFERRED || debug) {
5194 Slog.v(TAG, "Found preferred activity:");
5196 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
5198 Slog.v(TAG, " null");
5202 // This previously registered preferred activity
5203 // component is no longer known. Most likely an update
5204 // to the app was installed and in the new version this
5205 // component no longer exists. Clean it up by removing
5206 // it from the preferred activities list, and skip it.
5207 Slog.w(TAG, "Removing dangling preferred activity: "
5208 + pa.mPref.mComponent);
5209 pir.removeFilter(pa);
5213 for (int j=0; j<N; j++) {
5214 final ResolveInfo ri = query.get(j);
5215 if (!ri.activityInfo.applicationInfo.packageName
5216 .equals(ai.applicationInfo.packageName)) {
5219 if (!ri.activityInfo.name.equals(ai.name)) {
5223 if (removeMatches) {
5224 pir.removeFilter(pa);
5226 if (DEBUG_PREFERRED) {
5227 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5232 // Okay we found a previously set preferred or last chosen app.
5233 // If the result set is different from when this
5234 // was created, we need to clear it and re-ask the
5235 // user their preference, if we're looking for an "always" type entry.
5236 if (always && !pa.mPref.sameSet(query)) {
5237 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5238 + intent + " type " + resolvedType);
5239 if (DEBUG_PREFERRED) {
5240 Slog.v(TAG, "Removing preferred activity since set changed "
5241 + pa.mPref.mComponent);
5243 pir.removeFilter(pa);
5244 // Re-add the filter as a "last chosen" entry (!always)
5245 PreferredActivity lastChosen = new PreferredActivity(
5246 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5247 pir.addFilter(lastChosen);
5252 // Yay! Either the set matched or we're looking for the last chosen
5253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5254 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5260 if (DEBUG_PREFERRED) {
5261 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5263 scheduleWritePackageRestrictionsLocked(userId);
5268 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5273 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5276 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5278 mContext.enforceCallingOrSelfPermission(
5279 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5280 List<CrossProfileIntentFilter> matches =
5281 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5282 if (matches != null) {
5283 int size = matches.size();
5284 for (int i = 0; i < size; i++) {
5285 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5288 if (hasWebURI(intent)) {
5289 // cross-profile app linking works only towards the parent.
5290 final UserInfo parent = getProfileParent(sourceUserId);
5291 synchronized(mPackages) {
5292 int flags = updateFlagsForResolve(0, parent.id, intent);
5293 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5294 intent, resolvedType, flags, sourceUserId, parent.id);
5295 return xpDomainInfo != null;
5301 private UserInfo getProfileParent(int userId) {
5302 final long identity = Binder.clearCallingIdentity();
5304 return sUserManager.getProfileParent(userId);
5306 Binder.restoreCallingIdentity(identity);
5310 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5311 String resolvedType, int userId) {
5312 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5313 if (resolver != null) {
5314 return resolver.queryIntent(intent, resolvedType, false, userId);
5320 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5321 String resolvedType, int flags, int userId) {
5323 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5325 return new ParceledListSlice<>(
5326 queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5328 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5332 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5333 String resolvedType, int flags, int userId) {
5334 if (!sUserManager.exists(userId)) return Collections.emptyList();
5335 flags = updateFlagsForResolve(flags, userId, intent);
5336 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5337 false /* requireFullPermission */, false /* checkShell */,
5338 "query intent activities");
5339 ComponentName comp = intent.getComponent();
5341 if (intent.getSelector() != null) {
5342 intent = intent.getSelector();
5343 comp = intent.getComponent();
5348 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5349 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5351 final ResolveInfo ri = new ResolveInfo();
5352 ri.activityInfo = ai;
5359 boolean sortResult = false;
5360 boolean addEphemeral = false;
5361 boolean matchEphemeralPackage = false;
5362 List<ResolveInfo> result;
5363 final String pkgName = intent.getPackage();
5364 synchronized (mPackages) {
5365 if (pkgName == null) {
5366 List<CrossProfileIntentFilter> matchingFilters =
5367 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5368 // Check for results that need to skip the current profile.
5369 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
5370 resolvedType, flags, userId);
5371 if (xpResolveInfo != null) {
5372 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5373 xpResult.add(xpResolveInfo);
5374 return filterIfNotSystemUser(xpResult, userId);
5377 // Check for results in the current profile.
5378 result = filterIfNotSystemUser(mActivities.queryIntent(
5379 intent, resolvedType, flags, userId), userId);
5381 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5383 // Check for cross profile results.
5384 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5385 xpResolveInfo = queryCrossProfileIntents(
5386 matchingFilters, intent, resolvedType, flags, userId,
5387 hasNonNegativePriorityResult);
5388 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5389 boolean isVisibleToUser = filterIfNotSystemUser(
5390 Collections.singletonList(xpResolveInfo), userId).size() > 0;
5391 if (isVisibleToUser) {
5392 result.add(xpResolveInfo);
5396 if (hasWebURI(intent)) {
5397 CrossProfileDomainInfo xpDomainInfo = null;
5398 final UserInfo parent = getProfileParent(userId);
5399 if (parent != null) {
5400 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5401 flags, userId, parent.id);
5403 if (xpDomainInfo != null) {
5404 if (xpResolveInfo != null) {
5405 // If we didn't remove it, the cross-profile ResolveInfo would be twice
5407 result.remove(xpResolveInfo);
5409 if (result.size() == 0 && !addEphemeral) {
5410 result.add(xpDomainInfo.resolveInfo);
5414 if (result.size() > 1 || addEphemeral) {
5415 result = filterCandidatesWithDomainPreferredActivitiesLPr(
5416 intent, flags, result, xpDomainInfo, userId);
5421 final PackageParser.Package pkg = mPackages.get(pkgName);
5423 result = filterIfNotSystemUser(
5424 mActivities.queryIntentForPackage(
5425 intent, resolvedType, flags, pkg.activities, userId),
5428 // the caller wants to resolve for a particular package; however, there
5429 // were no installed results, so, try to find an ephemeral result
5430 addEphemeral = isEphemeralAllowed(
5431 intent, null /*result*/, userId, true /*skipPackageCheck*/);
5432 matchEphemeralPackage = true;
5433 result = new ArrayList<ResolveInfo>();
5438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5439 final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5440 mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5441 matchEphemeralPackage ? pkgName : null);
5443 if (DEBUG_EPHEMERAL) {
5444 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5446 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5447 ephemeralInstaller.ephemeralResolveInfo = ai;
5448 // make sure this resolver is the default
5449 ephemeralInstaller.isDefault = true;
5450 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5451 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5452 // add a non-generic filter
5453 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5454 ephemeralInstaller.filter.addDataPath(
5455 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5456 result.add(ephemeralInstaller);
5458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5461 Collections.sort(result, mResolvePrioritySorter);
5466 private static class CrossProfileDomainInfo {
5467 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5468 ResolveInfo resolveInfo;
5469 /* Best domain verification status of the activities found in the other profile */
5470 int bestDomainVerificationStatus;
5473 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5474 String resolvedType, int flags, int sourceUserId, int parentUserId) {
5475 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5479 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5480 resolvedType, flags, parentUserId);
5482 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5485 CrossProfileDomainInfo result = null;
5486 int size = resultTargetUser.size();
5487 for (int i = 0; i < size; i++) {
5488 ResolveInfo riTargetUser = resultTargetUser.get(i);
5489 // Intent filter verification is only for filters that specify a host. So don't return
5490 // those that handle all web uris.
5491 if (riTargetUser.handleAllWebDataURI) {
5494 String packageName = riTargetUser.activityInfo.packageName;
5495 PackageSetting ps = mSettings.mPackages.get(packageName);
5499 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5500 int status = (int)(verificationState >> 32);
5501 if (result == null) {
5502 result = new CrossProfileDomainInfo();
5503 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5504 sourceUserId, parentUserId);
5505 result.bestDomainVerificationStatus = status;
5507 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5508 result.bestDomainVerificationStatus);
5511 // Don't consider matches with status NEVER across profiles.
5512 if (result != null && result.bestDomainVerificationStatus
5513 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5520 * Verification statuses are ordered from the worse to the best, except for
5521 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5523 private int bestDomainVerificationStatus(int status1, int status2) {
5524 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5527 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5530 return (int) MathUtils.max(status1, status2);
5533 private boolean isUserEnabled(int userId) {
5534 long callingId = Binder.clearCallingIdentity();
5536 UserInfo userInfo = sUserManager.getUserInfo(userId);
5537 return userInfo != null && userInfo.isEnabled();
5539 Binder.restoreCallingIdentity(callingId);
5544 * Filter out activities with systemUserOnly flag set, when current user is not System.
5546 * @return filtered list
5548 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5549 if (userId == UserHandle.USER_SYSTEM) {
5550 return resolveInfos;
5552 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5553 ResolveInfo info = resolveInfos.get(i);
5554 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5555 resolveInfos.remove(i);
5558 return resolveInfos;
5562 * @param resolveInfos list of resolve infos in descending priority order
5563 * @return if the list contains a resolve info with non-negative priority
5565 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5566 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5569 private static boolean hasWebURI(Intent intent) {
5570 if (intent.getData() == null) {
5573 final String scheme = intent.getScheme();
5574 if (TextUtils.isEmpty(scheme)) {
5577 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5580 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5581 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5583 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5585 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5586 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5590 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5591 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5592 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5593 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5594 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5595 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5597 synchronized (mPackages) {
5598 final int count = candidates.size();
5599 // First, try to use linked apps. Partition the candidates into four lists:
5600 // one for the final results, one for the "do not use ever", one for "undefined status"
5601 // and finally one for "browser app type".
5602 for (int n=0; n<count; n++) {
5603 ResolveInfo info = candidates.get(n);
5604 String packageName = info.activityInfo.packageName;
5605 PackageSetting ps = mSettings.mPackages.get(packageName);
5607 // Add to the special match all list (Browser use case)
5608 if (info.handleAllWebDataURI) {
5609 matchAllList.add(info);
5612 // Try to get the status from User settings first
5613 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5614 int status = (int)(packedStatus >> 32);
5615 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5616 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5617 if (DEBUG_DOMAIN_VERIFICATION) {
5618 Slog.i(TAG, " + always: " + info.activityInfo.packageName
5619 + " : linkgen=" + linkGeneration);
5621 // Use link-enabled generation as preferredOrder, i.e.
5622 // prefer newly-enabled over earlier-enabled.
5623 info.preferredOrder = linkGeneration;
5624 alwaysList.add(info);
5625 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5626 if (DEBUG_DOMAIN_VERIFICATION) {
5627 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
5629 neverList.add(info);
5630 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5631 if (DEBUG_DOMAIN_VERIFICATION) {
5632 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
5634 alwaysAskList.add(info);
5635 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5636 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5637 if (DEBUG_DOMAIN_VERIFICATION) {
5638 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
5640 undefinedList.add(info);
5645 // We'll want to include browser possibilities in a few cases
5646 boolean includeBrowser = false;
5648 // First try to add the "always" resolution(s) for the current user, if any
5649 if (alwaysList.size() > 0) {
5650 result.addAll(alwaysList);
5652 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5653 result.addAll(undefinedList);
5654 // Maybe add one for the other profile.
5655 if (xpDomainInfo != null && (
5656 xpDomainInfo.bestDomainVerificationStatus
5657 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5658 result.add(xpDomainInfo.resolveInfo);
5660 includeBrowser = true;
5663 // The presence of any 'always ask' alternatives means we'll also offer browsers.
5664 // If there were 'always' entries their preferred order has been set, so we also
5665 // back that off to make the alternatives equivalent
5666 if (alwaysAskList.size() > 0) {
5667 for (ResolveInfo i : result) {
5668 i.preferredOrder = 0;
5670 result.addAll(alwaysAskList);
5671 includeBrowser = true;
5674 if (includeBrowser) {
5675 // Also add browsers (all of them or only the default one)
5676 if (DEBUG_DOMAIN_VERIFICATION) {
5677 Slog.v(TAG, " ...including browsers in candidate set");
5679 if ((matchFlags & MATCH_ALL) != 0) {
5680 result.addAll(matchAllList);
5682 // Browser/generic handling case. If there's a default browser, go straight
5683 // to that (but only if there is no other higher-priority match).
5684 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5685 int maxMatchPrio = 0;
5686 ResolveInfo defaultBrowserMatch = null;
5687 final int numCandidates = matchAllList.size();
5688 for (int n = 0; n < numCandidates; n++) {
5689 ResolveInfo info = matchAllList.get(n);
5690 // track the highest overall match priority...
5691 if (info.priority > maxMatchPrio) {
5692 maxMatchPrio = info.priority;
5694 // ...and the highest-priority default browser match
5695 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5696 if (defaultBrowserMatch == null
5697 || (defaultBrowserMatch.priority < info.priority)) {
5699 Slog.v(TAG, "Considering default browser match " + info);
5701 defaultBrowserMatch = info;
5705 if (defaultBrowserMatch != null
5706 && defaultBrowserMatch.priority >= maxMatchPrio
5707 && !TextUtils.isEmpty(defaultBrowserPackageName))
5710 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5712 result.add(defaultBrowserMatch);
5714 result.addAll(matchAllList);
5718 // If there is nothing selected, add all candidates and remove the ones that the user
5719 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5720 if (result.size() == 0) {
5721 result.addAll(candidates);
5722 result.removeAll(neverList);
5726 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5727 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5729 for (ResolveInfo info : result) {
5730 Slog.v(TAG, " + " + info.activityInfo);
5736 // Returns a packed value as a long:
5738 // high 'int'-sized word: link status: undefined/ask/never/always.
5739 // low 'int'-sized word: relative priority among 'always' results.
5740 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5741 long result = ps.getDomainVerificationStatusForUser(userId);
5742 // if none available, get the master status
5743 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5744 if (ps.getIntentFilterVerificationInfo() != null) {
5745 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5751 private ResolveInfo querySkipCurrentProfileIntents(
5752 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5753 int flags, int sourceUserId) {
5754 if (matchingFilters != null) {
5755 int size = matchingFilters.size();
5756 for (int i = 0; i < size; i ++) {
5757 CrossProfileIntentFilter filter = matchingFilters.get(i);
5758 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5759 // Checking if there are activities in the target user that can handle the
5761 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5762 resolvedType, flags, sourceUserId);
5763 if (resolveInfo != null) {
5772 // Return matching ResolveInfo in target user if any.
5773 private ResolveInfo queryCrossProfileIntents(
5774 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5775 int flags, int sourceUserId, boolean matchInCurrentProfile) {
5776 if (matchingFilters != null) {
5777 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5778 // match the same intent. For performance reasons, it is better not to
5779 // run queryIntent twice for the same userId
5780 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5781 int size = matchingFilters.size();
5782 for (int i = 0; i < size; i++) {
5783 CrossProfileIntentFilter filter = matchingFilters.get(i);
5784 int targetUserId = filter.getTargetUserId();
5785 boolean skipCurrentProfile =
5786 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5787 boolean skipCurrentProfileIfNoMatchFound =
5788 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5789 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5790 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5791 // Checking if there are activities in the target user that can handle the
5793 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5794 resolvedType, flags, sourceUserId);
5795 if (resolveInfo != null) return resolveInfo;
5796 alreadyTriedUserIds.put(targetUserId, true);
5804 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5805 * will forward the intent to the filter's target user.
5806 * Otherwise, returns null.
5808 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5809 String resolvedType, int flags, int sourceUserId) {
5810 int targetUserId = filter.getTargetUserId();
5811 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5812 resolvedType, flags, targetUserId);
5813 if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5814 // If all the matches in the target profile are suspended, return null.
5815 for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5816 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5817 & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5818 return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5826 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5827 int sourceUserId, int targetUserId) {
5828 ResolveInfo forwardingResolveInfo = new ResolveInfo();
5829 long ident = Binder.clearCallingIdentity();
5830 boolean targetIsProfile;
5832 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5834 Binder.restoreCallingIdentity(ident);
5837 if (targetIsProfile) {
5838 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5840 className = FORWARD_INTENT_TO_PARENT;
5842 ComponentName forwardingActivityComponentName = new ComponentName(
5843 mAndroidApplication.packageName, className);
5844 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5846 if (!targetIsProfile) {
5847 forwardingActivityInfo.showUserIcon = targetUserId;
5848 forwardingResolveInfo.noResourceId = true;
5850 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5851 forwardingResolveInfo.priority = 0;
5852 forwardingResolveInfo.preferredOrder = 0;
5853 forwardingResolveInfo.match = 0;
5854 forwardingResolveInfo.isDefault = true;
5855 forwardingResolveInfo.filter = filter;
5856 forwardingResolveInfo.targetUserId = targetUserId;
5857 return forwardingResolveInfo;
5861 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5862 Intent[] specifics, String[] specificTypes, Intent intent,
5863 String resolvedType, int flags, int userId) {
5864 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5865 specificTypes, intent, resolvedType, flags, userId));
5868 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5869 Intent[] specifics, String[] specificTypes, Intent intent,
5870 String resolvedType, int flags, int userId) {
5871 if (!sUserManager.exists(userId)) return Collections.emptyList();
5872 flags = updateFlagsForResolve(flags, userId, intent);
5873 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5874 false /* requireFullPermission */, false /* checkShell */,
5875 "query intent activity options");
5876 final String resultsAction = intent.getAction();
5878 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5879 | PackageManager.GET_RESOLVED_FILTER, userId);
5881 if (DEBUG_INTENT_MATCHING) {
5882 Log.v(TAG, "Query " + intent + ": " + results);
5885 int specificsPos = 0;
5888 // todo: note that the algorithm used here is O(N^2). This
5889 // isn't a problem in our current environment, but if we start running
5890 // into situations where we have more than 5 or 10 matches then this
5891 // should probably be changed to something smarter...
5893 // First we go through and resolve each of the specific items
5894 // that were supplied, taking care of removing any corresponding
5895 // duplicate items in the generic resolve list.
5896 if (specifics != null) {
5897 for (int i=0; i<specifics.length; i++) {
5898 final Intent sintent = specifics[i];
5899 if (sintent == null) {
5903 if (DEBUG_INTENT_MATCHING) {
5904 Log.v(TAG, "Specific #" + i + ": " + sintent);
5907 String action = sintent.getAction();
5908 if (resultsAction != null && resultsAction.equals(action)) {
5909 // If this action was explicitly requested, then don't
5910 // remove things that have it.
5914 ResolveInfo ri = null;
5915 ActivityInfo ai = null;
5917 ComponentName comp = sintent.getComponent();
5921 specificTypes != null ? specificTypes[i] : null,
5926 if (ri == mResolveInfo) {
5927 // ACK! Must do something better with this.
5929 ai = ri.activityInfo;
5930 comp = new ComponentName(ai.applicationInfo.packageName,
5933 ai = getActivityInfo(comp, flags, userId);
5939 // Look for any generic query activities that are duplicates
5940 // of this specific one, and remove them from the results.
5941 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5944 for (j=specificsPos; j<N; j++) {
5945 ResolveInfo sri = results.get(j);
5946 if ((sri.activityInfo.name.equals(comp.getClassName())
5947 && sri.activityInfo.applicationInfo.packageName.equals(
5948 comp.getPackageName()))
5949 || (action != null && sri.filter.matchAction(action))) {
5951 if (DEBUG_INTENT_MATCHING) Log.v(
5952 TAG, "Removing duplicate item from " + j
5953 + " due to specific " + specificsPos);
5962 // Add this specific item to its proper place.
5964 ri = new ResolveInfo();
5965 ri.activityInfo = ai;
5967 results.add(specificsPos, ri);
5968 ri.specificIndex = i;
5973 // Now we go through the remaining generic results and remove any
5974 // duplicate actions that are found here.
5976 for (int i=specificsPos; i<N-1; i++) {
5977 final ResolveInfo rii = results.get(i);
5978 if (rii.filter == null) {
5982 // Iterate over all of the actions of this result's intent
5983 // filter... typically this should be just one.
5984 final Iterator<String> it = rii.filter.actionsIterator();
5988 while (it.hasNext()) {
5989 final String action = it.next();
5990 if (resultsAction != null && resultsAction.equals(action)) {
5991 // If this action was explicitly requested, then don't
5992 // remove things that have it.
5995 for (int j=i+1; j<N; j++) {
5996 final ResolveInfo rij = results.get(j);
5997 if (rij.filter != null && rij.filter.hasAction(action)) {
5999 if (DEBUG_INTENT_MATCHING) Log.v(
6000 TAG, "Removing duplicate item from " + j
6001 + " due to action " + action + " at " + i);
6008 // If the caller didn't request filter information, drop it now
6009 // so we don't have to marshall/unmarshall it.
6010 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6015 // Filter out the caller activity if so requested.
6016 if (caller != null) {
6018 for (int i=0; i<N; i++) {
6019 ActivityInfo ainfo = results.get(i).activityInfo;
6020 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6021 && caller.getClassName().equals(ainfo.name)) {
6028 // If the caller didn't request filter information,
6029 // drop them now so we don't have to
6030 // marshall/unmarshall it.
6031 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6033 for (int i=0; i<N; i++) {
6034 results.get(i).filter = null;
6038 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6043 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6044 String resolvedType, int flags, int userId) {
6045 return new ParceledListSlice<>(
6046 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6049 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6050 String resolvedType, int flags, int userId) {
6051 if (!sUserManager.exists(userId)) return Collections.emptyList();
6052 flags = updateFlagsForResolve(flags, userId, intent);
6053 ComponentName comp = intent.getComponent();
6055 if (intent.getSelector() != null) {
6056 intent = intent.getSelector();
6057 comp = intent.getComponent();
6061 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6062 ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6064 ResolveInfo ri = new ResolveInfo();
6065 ri.activityInfo = ai;
6072 synchronized (mPackages) {
6073 String pkgName = intent.getPackage();
6074 if (pkgName == null) {
6075 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6077 final PackageParser.Package pkg = mPackages.get(pkgName);
6079 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6082 return Collections.emptyList();
6087 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6088 if (!sUserManager.exists(userId)) return null;
6089 flags = updateFlagsForResolve(flags, userId, intent);
6090 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6091 if (query != null) {
6092 if (query.size() >= 1) {
6093 // If there is more than one service with the same priority,
6094 // just arbitrarily pick the first one.
6095 return query.get(0);
6102 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6103 String resolvedType, int flags, int userId) {
6104 return new ParceledListSlice<>(
6105 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6108 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6109 String resolvedType, int flags, int userId) {
6110 if (!sUserManager.exists(userId)) return Collections.emptyList();
6111 flags = updateFlagsForResolve(flags, userId, intent);
6112 ComponentName comp = intent.getComponent();
6114 if (intent.getSelector() != null) {
6115 intent = intent.getSelector();
6116 comp = intent.getComponent();
6120 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6121 final ServiceInfo si = getServiceInfo(comp, flags, userId);
6123 final ResolveInfo ri = new ResolveInfo();
6124 ri.serviceInfo = si;
6131 synchronized (mPackages) {
6132 String pkgName = intent.getPackage();
6133 if (pkgName == null) {
6134 return mServices.queryIntent(intent, resolvedType, flags, userId);
6136 final PackageParser.Package pkg = mPackages.get(pkgName);
6138 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6141 return Collections.emptyList();
6146 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6147 String resolvedType, int flags, int userId) {
6148 return new ParceledListSlice<>(
6149 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6152 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6153 Intent intent, String resolvedType, int flags, int userId) {
6154 if (!sUserManager.exists(userId)) return Collections.emptyList();
6155 flags = updateFlagsForResolve(flags, userId, intent);
6156 ComponentName comp = intent.getComponent();
6158 if (intent.getSelector() != null) {
6159 intent = intent.getSelector();
6160 comp = intent.getComponent();
6164 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6165 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6167 final ResolveInfo ri = new ResolveInfo();
6168 ri.providerInfo = pi;
6175 synchronized (mPackages) {
6176 String pkgName = intent.getPackage();
6177 if (pkgName == null) {
6178 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6180 final PackageParser.Package pkg = mPackages.get(pkgName);
6182 return mProviders.queryIntentForPackage(
6183 intent, resolvedType, flags, pkg.providers, userId);
6185 return Collections.emptyList();
6190 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6191 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6192 flags = updateFlagsForPackage(flags, userId, null);
6193 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6194 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6195 true /* requireFullPermission */, false /* checkShell */,
6196 "get installed packages");
6199 synchronized (mPackages) {
6200 ArrayList<PackageInfo> list;
6201 if (listUninstalled) {
6202 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6203 for (PackageSetting ps : mSettings.mPackages.values()) {
6204 final PackageInfo pi;
6205 if (ps.pkg != null) {
6206 pi = generatePackageInfo(ps, flags, userId);
6208 pi = generatePackageInfo(ps, flags, userId);
6215 list = new ArrayList<PackageInfo>(mPackages.size());
6216 for (PackageParser.Package p : mPackages.values()) {
6217 final PackageInfo pi =
6218 generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6225 return new ParceledListSlice<PackageInfo>(list);
6229 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6230 String[] permissions, boolean[] tmp, int flags, int userId) {
6232 final PermissionsState permissionsState = ps.getPermissionsState();
6233 for (int i=0; i<permissions.length; i++) {
6234 final String permission = permissions[i];
6235 if (permissionsState.hasPermission(permission, userId)) {
6242 if (numMatch == 0) {
6245 final PackageInfo pi;
6246 if (ps.pkg != null) {
6247 pi = generatePackageInfo(ps, flags, userId);
6249 pi = generatePackageInfo(ps, flags, userId);
6251 // The above might return null in cases of uninstalled apps or install-state
6252 // skew across users/profiles.
6254 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6255 if (numMatch == permissions.length) {
6256 pi.requestedPermissions = permissions;
6258 pi.requestedPermissions = new String[numMatch];
6260 for (int i=0; i<permissions.length; i++) {
6262 pi.requestedPermissions[numMatch] = permissions[i];
6273 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6274 String[] permissions, int flags, int userId) {
6275 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6276 flags = updateFlagsForPackage(flags, userId, permissions);
6277 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6280 synchronized (mPackages) {
6281 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6282 boolean[] tmpBools = new boolean[permissions.length];
6283 if (listUninstalled) {
6284 for (PackageSetting ps : mSettings.mPackages.values()) {
6285 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6288 for (PackageParser.Package pkg : mPackages.values()) {
6289 PackageSetting ps = (PackageSetting)pkg.mExtras;
6291 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6297 return new ParceledListSlice<PackageInfo>(list);
6302 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6303 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6304 flags = updateFlagsForApplication(flags, userId, null);
6305 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6308 synchronized (mPackages) {
6309 ArrayList<ApplicationInfo> list;
6310 if (listUninstalled) {
6311 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6312 for (PackageSetting ps : mSettings.mPackages.values()) {
6314 if (ps.pkg != null) {
6315 ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6316 ps.readUserState(userId), userId);
6318 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6325 list = new ArrayList<ApplicationInfo>(mPackages.size());
6326 for (PackageParser.Package p : mPackages.values()) {
6327 if (p.mExtras != null) {
6328 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6329 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6337 return new ParceledListSlice<ApplicationInfo>(list);
6342 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6343 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6347 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6348 "getEphemeralApplications");
6349 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6350 true /* requireFullPermission */, false /* checkShell */,
6351 "getEphemeralApplications");
6352 synchronized (mPackages) {
6353 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6354 .getEphemeralApplicationsLPw(userId);
6355 if (ephemeralApps != null) {
6356 return new ParceledListSlice<>(ephemeralApps);
6363 public boolean isEphemeralApplication(String packageName, int userId) {
6364 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6365 true /* requireFullPermission */, false /* checkShell */,
6367 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6371 if (!isCallerSameApp(packageName)) {
6374 synchronized (mPackages) {
6375 PackageParser.Package pkg = mPackages.get(packageName);
6377 return pkg.applicationInfo.isEphemeralApp();
6384 public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6385 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6389 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6390 true /* requireFullPermission */, false /* checkShell */,
6392 if (!isCallerSameApp(packageName)) {
6395 synchronized (mPackages) {
6396 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6397 packageName, userId);
6402 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6403 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6407 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6408 true /* requireFullPermission */, true /* checkShell */,
6410 if (!isCallerSameApp(packageName)) {
6413 synchronized (mPackages) {
6414 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6415 packageName, cookie, userId);
6420 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6421 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6425 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6426 "getEphemeralApplicationIcon");
6427 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6428 true /* requireFullPermission */, false /* checkShell */,
6429 "getEphemeralApplicationIcon");
6430 synchronized (mPackages) {
6431 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6432 packageName, userId);
6436 private boolean isCallerSameApp(String packageName) {
6437 PackageParser.Package pkg = mPackages.get(packageName);
6439 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6443 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6444 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6447 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6448 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6451 synchronized (mPackages) {
6452 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6453 final int userId = UserHandle.getCallingUserId();
6454 while (i.hasNext()) {
6455 final PackageParser.Package p = i.next();
6456 if (p.applicationInfo == null) continue;
6458 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6459 && !p.applicationInfo.isDirectBootAware();
6460 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6461 && p.applicationInfo.isDirectBootAware();
6463 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6464 && (!mSafeMode || isSystemApp(p))
6465 && (matchesUnaware || matchesAware)) {
6466 PackageSetting ps = mSettings.mPackages.get(p.packageName);
6468 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6469 ps.readUserState(userId), userId);
6482 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6483 if (!sUserManager.exists(userId)) return null;
6484 flags = updateFlagsForComponent(flags, userId, name);
6486 synchronized (mPackages) {
6487 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6488 PackageSetting ps = provider != null
6489 ? mSettings.mPackages.get(provider.owner.packageName)
6492 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6493 ? PackageParser.generateProviderInfo(provider, flags,
6494 ps.readUserState(userId), userId)
6503 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6505 synchronized (mPackages) {
6506 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6507 .entrySet().iterator();
6508 final int userId = UserHandle.getCallingUserId();
6509 while (i.hasNext()) {
6510 Map.Entry<String, PackageParser.Provider> entry = i.next();
6511 PackageParser.Provider p = entry.getValue();
6512 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6514 if (ps != null && p.syncable
6515 && (!mSafeMode || (p.info.applicationInfo.flags
6516 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6517 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6518 ps.readUserState(userId), userId);
6520 outNames.add(entry.getKey());
6529 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6530 int uid, int flags) {
6531 final int userId = processName != null ? UserHandle.getUserId(uid)
6532 : UserHandle.getCallingUserId();
6533 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6534 flags = updateFlagsForComponent(flags, userId, processName);
6536 ArrayList<ProviderInfo> finalList = null;
6538 synchronized (mPackages) {
6539 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6540 while (i.hasNext()) {
6541 final PackageParser.Provider p = i.next();
6542 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6543 if (ps != null && p.info.authority != null
6544 && (processName == null
6545 || (p.info.processName.equals(processName)
6546 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6547 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6548 if (finalList == null) {
6549 finalList = new ArrayList<ProviderInfo>(3);
6551 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6552 ps.readUserState(userId), userId);
6554 finalList.add(info);
6560 if (finalList != null) {
6561 Collections.sort(finalList, mProviderInitOrderSorter);
6562 return new ParceledListSlice<ProviderInfo>(finalList);
6565 return ParceledListSlice.emptyList();
6569 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6571 synchronized (mPackages) {
6572 final PackageParser.Instrumentation i = mInstrumentation.get(name);
6573 return PackageParser.generateInstrumentationInfo(i, flags);
6578 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6579 String targetPackage, int flags) {
6580 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6583 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6585 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6588 synchronized (mPackages) {
6589 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6590 while (i.hasNext()) {
6591 final PackageParser.Instrumentation p = i.next();
6592 if (targetPackage == null
6593 || targetPackage.equals(p.info.targetPackage)) {
6594 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6606 private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6607 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6608 if (overlays == null) {
6609 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6612 for (PackageParser.Package opkg : overlays.values()) {
6613 // Not much to do if idmap fails: we already logged the error
6614 // and we certainly don't want to abort installation of pkg simply
6615 // because an overlay didn't fit properly. For these reasons,
6616 // ignore the return value of createIdmapForPackagePairLI.
6617 createIdmapForPackagePairLI(pkg, opkg);
6621 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6622 PackageParser.Package opkg) {
6623 if (!opkg.mTrustedOverlay) {
6624 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6625 opkg.baseCodePath + ": overlay not trusted");
6628 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6629 if (overlaySet == null) {
6630 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6631 opkg.baseCodePath + " but target package has no known overlays");
6634 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6635 // TODO: generate idmap for split APKs
6637 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6638 } catch (InstallerException e) {
6639 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6640 + opkg.baseCodePath);
6643 PackageParser.Package[] overlayArray =
6644 overlaySet.values().toArray(new PackageParser.Package[0]);
6645 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6646 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6647 return p1.mOverlayPriority - p2.mOverlayPriority;
6650 Arrays.sort(overlayArray, cmp);
6652 pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6654 for (PackageParser.Package p : overlayArray) {
6655 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6660 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6661 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6663 scanDirLI(dir, parseFlags, scanFlags, currentTime);
6665 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6669 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6670 final File[] files = dir.listFiles();
6671 if (ArrayUtils.isEmpty(files)) {
6672 Log.d(TAG, "No files in app dir " + dir);
6676 if (DEBUG_PACKAGE_SCANNING) {
6677 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6678 + " flags=0x" + Integer.toHexString(parseFlags));
6681 for (File file : files) {
6682 final boolean isPackage = (isApkFile(file) || file.isDirectory())
6683 && !PackageInstallerService.isStageName(file.getName());
6685 // Ignore entries which are not packages
6689 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6690 scanFlags, currentTime, null);
6691 } catch (PackageManagerException e) {
6692 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6694 // Delete invalid userdata apps
6695 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6696 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6697 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6698 removeCodePathLI(file);
6704 private static File getSettingsProblemFile() {
6705 File dataDir = Environment.getDataDirectory();
6706 File systemDir = new File(dataDir, "system");
6707 File fname = new File(systemDir, "uiderrors.txt");
6711 static void reportSettingsProblem(int priority, String msg) {
6712 logCriticalInfo(priority, msg);
6715 static void logCriticalInfo(int priority, String msg) {
6716 Slog.println(priority, TAG, msg);
6717 EventLogTags.writePmCriticalInfo(msg);
6719 File fname = getSettingsProblemFile();
6720 FileOutputStream out = new FileOutputStream(fname, true);
6721 PrintWriter pw = new FastPrintWriter(out);
6722 SimpleDateFormat formatter = new SimpleDateFormat();
6723 String dateString = formatter.format(new Date(System.currentTimeMillis()));
6724 pw.println(dateString + ": " + msg);
6726 FileUtils.setPermissions(
6728 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6730 } catch (java.io.IOException e) {
6734 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6735 if (srcFile.isDirectory()) {
6736 final File baseFile = new File(pkg.baseCodePath);
6737 long maxModifiedTime = baseFile.lastModified();
6738 if (pkg.splitCodePaths != null) {
6739 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6740 final File splitFile = new File(pkg.splitCodePaths[i]);
6741 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6744 return maxModifiedTime;
6746 return srcFile.lastModified();
6749 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6750 final int policyFlags) throws PackageManagerException {
6751 // When upgrading from pre-N MR1, verify the package time stamp using the package
6752 // directory and not the APK file.
6753 final long lastModifiedTime = mIsPreNMR1Upgrade
6754 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6756 && ps.codePath.equals(srcFile)
6757 && ps.timeStamp == lastModifiedTime
6758 && !isCompatSignatureUpdateNeeded(pkg)
6759 && !isRecoverSignatureUpdateNeeded(pkg)) {
6760 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6761 KeySetManagerService ksms = mSettings.mKeySetManagerService;
6762 ArraySet<PublicKey> signingKs;
6763 synchronized (mPackages) {
6764 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6766 if (ps.signatures.mSignatures != null
6767 && ps.signatures.mSignatures.length != 0
6768 && signingKs != null) {
6769 // Optimization: reuse the existing cached certificates
6770 // if the package appears to be unchanged.
6771 pkg.mSignatures = ps.signatures.mSignatures;
6772 pkg.mSigningKeys = signingKs;
6776 Slog.w(TAG, "PackageSetting for " + ps.name
6777 + " is missing signatures. Collecting certs again to recover them.");
6779 Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6783 PackageParser.collectCertificates(pkg, policyFlags);
6784 } catch (PackageParserException e) {
6785 throw PackageManagerException.from(e);
6790 * Traces a package scan.
6791 * @see #scanPackageLI(File, int, int, long, UserHandle)
6793 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6794 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6795 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6797 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6799 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6804 * Scans a package and returns the newly parsed package.
6805 * Returns {@code null} in case of errors and the error code is stored in mLastScanError
6807 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6808 long currentTime, UserHandle user) throws PackageManagerException {
6809 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6810 PackageParser pp = new PackageParser();
6811 pp.setSeparateProcesses(mSeparateProcesses);
6812 pp.setOnlyCoreApps(mOnlyCore);
6813 pp.setDisplayMetrics(mMetrics);
6815 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6816 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6819 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6820 final PackageParser.Package pkg;
6822 pkg = pp.parsePackage(scanFile, parseFlags);
6823 } catch (PackageParserException e) {
6824 throw PackageManagerException.from(e);
6826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6829 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6833 * Scans a package and returns the newly parsed package.
6834 * @throws PackageManagerException on a parse error.
6836 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6837 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6838 throws PackageManagerException {
6839 // If the package has children and this is the first dive in the function
6840 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6841 // packages (parent and children) would be successfully scanned before the
6842 // actual scan since scanning mutates internal state and we want to atomically
6843 // install the package and its children.
6844 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6845 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6846 scanFlags |= SCAN_CHECK_ONLY;
6849 scanFlags &= ~SCAN_CHECK_ONLY;
6853 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6854 scanFlags, currentTime, user);
6856 // Scan the children
6857 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6858 for (int i = 0; i < childCount; i++) {
6859 PackageParser.Package childPackage = pkg.childPackages.get(i);
6860 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6865 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6866 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6873 * Scans a package and returns the newly parsed package.
6874 * @throws PackageManagerException on a parse error.
6876 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6877 int policyFlags, int scanFlags, long currentTime, UserHandle user)
6878 throws PackageManagerException {
6879 PackageSetting ps = null;
6880 PackageSetting updatedPkg;
6882 synchronized (mPackages) {
6883 // Look to see if we already know about this package.
6884 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6885 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6886 // This package has been renamed to its original name. Let's
6888 ps = mSettings.peekPackageLPr(oldName);
6890 // If there was no original package, see one for the real package name.
6892 ps = mSettings.peekPackageLPr(pkg.packageName);
6894 // Check to see if this package could be hiding/updating a system
6895 // package. Must look for it either under the original or real
6896 // package name depending on our state.
6897 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6898 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6900 // If this is a package we don't know about on the system partition, we
6901 // may need to remove disabled child packages on the system partition
6902 // or may need to not add child packages if the parent apk is updated
6903 // on the data partition and no longer defines this child package.
6904 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6905 // If this is a parent package for an updated system app and this system
6906 // app got an OTA update which no longer defines some of the child packages
6907 // we have to prune them from the disabled system packages.
6908 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6909 if (disabledPs != null) {
6910 final int scannedChildCount = (pkg.childPackages != null)
6911 ? pkg.childPackages.size() : 0;
6912 final int disabledChildCount = disabledPs.childPackageNames != null
6913 ? disabledPs.childPackageNames.size() : 0;
6914 for (int i = 0; i < disabledChildCount; i++) {
6915 String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6916 boolean disabledPackageAvailable = false;
6917 for (int j = 0; j < scannedChildCount; j++) {
6918 PackageParser.Package childPkg = pkg.childPackages.get(j);
6919 if (childPkg.packageName.equals(disabledChildPackageName)) {
6920 disabledPackageAvailable = true;
6924 if (!disabledPackageAvailable) {
6925 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6932 boolean updatedPkgBetter = false;
6933 // First check if this is a system package that may involve an update
6934 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6935 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6936 // it needs to drop FLAG_PRIVILEGED.
6937 if (locationIsPrivileged(scanFile)) {
6938 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6940 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6943 if (ps != null && !ps.codePath.equals(scanFile)) {
6944 // The path has changed from what was last scanned... check the
6945 // version of the new path against what we have stored to determine
6947 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6948 if (pkg.mVersionCode <= ps.versionCode) {
6949 // The system package has been updated and the code path does not match
6950 // Ignore entry. Skip it.
6951 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6952 + " ignored: updated version " + ps.versionCode
6953 + " better than this " + pkg.mVersionCode);
6954 if (!updatedPkg.codePath.equals(scanFile)) {
6955 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6956 + ps.name + " changing from " + updatedPkg.codePathString
6957 + " to " + scanFile);
6958 updatedPkg.codePath = scanFile;
6959 updatedPkg.codePathString = scanFile.toString();
6960 updatedPkg.resourcePath = scanFile;
6961 updatedPkg.resourcePathString = scanFile.toString();
6963 updatedPkg.pkg = pkg;
6964 updatedPkg.versionCode = pkg.mVersionCode;
6966 // Update the disabled system child packages to point to the package too.
6967 final int childCount = updatedPkg.childPackageNames != null
6968 ? updatedPkg.childPackageNames.size() : 0;
6969 for (int i = 0; i < childCount; i++) {
6970 String childPackageName = updatedPkg.childPackageNames.get(i);
6971 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6973 if (updatedChildPkg != null) {
6974 updatedChildPkg.pkg = pkg;
6975 updatedChildPkg.versionCode = pkg.mVersionCode;
6979 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6980 + scanFile + " ignored: updated version " + ps.versionCode
6981 + " better than this " + pkg.mVersionCode);
6983 // The current app on the system partition is better than
6984 // what we have updated to on the data partition; switch
6985 // back to the system partition version.
6986 // At this point, its safely assumed that package installation for
6987 // apps in system partition will go through. If not there won't be a working
6988 // version of the app
6990 synchronized (mPackages) {
6991 // Just remove the loaded entries from package lists.
6992 mPackages.remove(ps.name);
6995 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6996 + " reverting from " + ps.codePathString
6997 + ": new version " + pkg.mVersionCode
6998 + " better than installed " + ps.versionCode);
7000 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7001 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7002 synchronized (mInstallLock) {
7003 args.cleanUpResourcesLI();
7005 synchronized (mPackages) {
7006 mSettings.enableSystemPackageLPw(ps.name);
7008 updatedPkgBetter = true;
7013 if (updatedPkg != null) {
7014 // An updated system app will not have the PARSE_IS_SYSTEM flag set
7016 policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7018 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7019 // flag set initially
7020 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7021 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7025 // Verify certificates against what was last scanned
7026 collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7029 * A new system app appeared, but we already had a non-system one of the
7030 * same name installed earlier.
7032 boolean shouldHideSystemApp = false;
7033 if (updatedPkg == null && ps != null
7034 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7036 * Check to make sure the signatures match first. If they don't,
7037 * wipe the installed application and its data.
7039 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7040 != PackageManager.SIGNATURE_MATCH) {
7041 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7042 + " signatures don't match existing userdata copy; removing");
7043 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7044 "scanPackageInternalLI")) {
7045 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7050 * If the newly-added system app is an older version than the
7051 * already installed version, hide it. It will be scanned later
7052 * and re-added like an update.
7054 if (pkg.mVersionCode <= ps.versionCode) {
7055 shouldHideSystemApp = true;
7056 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7057 + " but new version " + pkg.mVersionCode + " better than installed "
7058 + ps.versionCode + "; hiding system");
7061 * The newly found system app is a newer version that the
7062 * one previously installed. Simply remove the
7063 * already-installed application and replace it with our own
7064 * while keeping the application data.
7066 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7067 + " reverting from " + ps.codePathString + ": new version "
7068 + pkg.mVersionCode + " better than installed " + ps.versionCode);
7069 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7070 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7071 synchronized (mInstallLock) {
7072 args.cleanUpResourcesLI();
7078 // The apk is forward locked (not public) if its code and resources
7079 // are kept in different files. (except for app in either system or
7081 // TODO grab this value from PackageSettings
7082 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7083 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7084 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7088 // TODO: extend to support forward-locked splits
7089 String resourcePath = null;
7090 String baseResourcePath = null;
7091 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7092 if (ps != null && ps.resourcePathString != null) {
7093 resourcePath = ps.resourcePathString;
7094 baseResourcePath = ps.resourcePathString;
7096 // Should not happen at all. Just log an error.
7097 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7100 resourcePath = pkg.codePath;
7101 baseResourcePath = pkg.baseCodePath;
7104 // Set application objects path explicitly.
7105 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7106 pkg.setApplicationInfoCodePath(pkg.codePath);
7107 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7108 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7109 pkg.setApplicationInfoResourcePath(resourcePath);
7110 pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7111 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7113 // Note that we invoke the following method only if we are about to unpack an application
7114 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7115 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7118 * If the system app should be overridden by a previously installed
7119 * data, hide the system app now and let the /data/app scan pick it up
7122 if (shouldHideSystemApp) {
7123 synchronized (mPackages) {
7124 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7131 private static String fixProcessName(String defProcessName,
7132 String processName, int uid) {
7133 if (processName == null) {
7134 return defProcessName;
7139 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7140 throws PackageManagerException {
7141 if (pkgSetting.signatures.mSignatures != null) {
7142 // Already existing package. Make sure signatures match
7143 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7144 == PackageManager.SIGNATURE_MATCH;
7146 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7147 == PackageManager.SIGNATURE_MATCH;
7150 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7151 == PackageManager.SIGNATURE_MATCH;
7154 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7155 + pkg.packageName + " signatures do not match the "
7156 + "previously installed version; ignoring!");
7160 // Check for shared user signatures
7161 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7162 // Already existing package. Make sure signatures match
7163 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7164 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7166 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7167 == PackageManager.SIGNATURE_MATCH;
7170 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7171 == PackageManager.SIGNATURE_MATCH;
7174 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7175 "Package " + pkg.packageName
7176 + " has no signatures that match those in shared user "
7177 + pkgSetting.sharedUser.name + "; ignoring!");
7183 * Enforces that only the system UID or root's UID can call a method exposed
7186 * @param message used as message if SecurityException is thrown
7187 * @throws SecurityException if the caller is not system or root
7189 private static final void enforceSystemOrRoot(String message) {
7190 final int uid = Binder.getCallingUid();
7191 if (uid != Process.SYSTEM_UID && uid != 0) {
7192 throw new SecurityException(message);
7197 public void performFstrimIfNeeded() {
7198 enforceSystemOrRoot("Only the system can request fstrim");
7200 // Before everything else, see whether we need to fstrim.
7202 IMountService ms = PackageHelper.getMountService();
7204 boolean doTrim = false;
7205 final long interval = android.provider.Settings.Global.getLong(
7206 mContext.getContentResolver(),
7207 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7208 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7210 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7211 if (timeSinceLast > interval) {
7213 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7214 + "; running immediately");
7218 final boolean dexOptDialogShown;
7219 synchronized (mPackages) {
7220 dexOptDialogShown = mDexOptDialogShown;
7222 if (!isFirstBoot() && dexOptDialogShown) {
7224 ActivityManagerNative.getDefault().showBootMessage(
7225 mContext.getResources().getString(
7226 R.string.android_upgrading_fstrim), true);
7227 } catch (RemoteException e) {
7230 ms.runMaintenance();
7233 Slog.e(TAG, "Mount service unavailable!");
7235 } catch (RemoteException e) {
7236 // Can't happen; MountService is local
7241 public void updatePackagesIfNeeded() {
7242 enforceSystemOrRoot("Only the system can request package update");
7244 // We need to re-extract after an OTA.
7245 boolean causeUpgrade = isUpgrade();
7247 // First boot or factory reset.
7248 // Note: we also handle devices that are upgrading to N right now as if it is their
7249 // first boot, as they do not have profile data.
7250 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7252 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7253 boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7255 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7259 List<PackageParser.Package> pkgs;
7260 synchronized (mPackages) {
7261 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7264 final long startTime = System.nanoTime();
7265 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7266 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7268 final int elapsedTimeSeconds =
7269 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7271 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7272 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7273 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7274 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7275 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7279 * Performs dexopt on the set of packages in {@code packages} and returns an int array
7280 * containing statistics about the invocation. The array consists of three elements,
7281 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7282 * and {@code numberOfPackagesFailed}.
7284 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7285 String compilerFilter) {
7287 int numberOfPackagesVisited = 0;
7288 int numberOfPackagesOptimized = 0;
7289 int numberOfPackagesSkipped = 0;
7290 int numberOfPackagesFailed = 0;
7291 final int numberOfPackagesToDexopt = pkgs.size();
7293 for (PackageParser.Package pkg : pkgs) {
7294 numberOfPackagesVisited++;
7296 if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7298 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7300 numberOfPackagesSkipped++;
7305 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7306 numberOfPackagesToDexopt + ": " + pkg.packageName);
7311 ActivityManagerNative.getDefault().showBootMessage(
7312 mContext.getResources().getString(R.string.android_upgrading_apk,
7313 numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7314 } catch (RemoteException e) {
7316 synchronized (mPackages) {
7317 mDexOptDialogShown = true;
7321 // If the OTA updates a system app which was previously preopted to a non-preopted state
7322 // the app might end up being verified at runtime. That's because by default the apps
7323 // are verify-profile but for preopted apps there's no profile.
7324 // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7325 // that before the OTA the app was preopted) the app gets compiled with a non-profile
7326 // filter (by default interpret-only).
7327 // Note that at this stage unused apps are already filtered.
7328 if (isSystemApp(pkg) &&
7329 DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7330 !Environment.getReferenceProfile(pkg.packageName).exists()) {
7331 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7334 // checkProfiles is false to avoid merging profiles during boot which
7335 // might interfere with background compilation (b/28612421).
7336 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7337 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7338 // trade-off worth doing to save boot time work.
7339 int dexOptStatus = performDexOptTraced(pkg.packageName,
7340 false /* checkProfiles */,
7343 switch (dexOptStatus) {
7344 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7345 numberOfPackagesOptimized++;
7347 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7348 numberOfPackagesSkipped++;
7350 case PackageDexOptimizer.DEX_OPT_FAILED:
7351 numberOfPackagesFailed++;
7354 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7359 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7360 numberOfPackagesFailed };
7364 public void notifyPackageUse(String packageName, int reason) {
7365 synchronized (mPackages) {
7366 PackageParser.Package p = mPackages.get(packageName);
7370 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7374 // TODO: this is not used nor needed. Delete it.
7376 public boolean performDexOptIfNeeded(String packageName) {
7377 int dexOptStatus = performDexOptTraced(packageName,
7378 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7379 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7383 public boolean performDexOpt(String packageName,
7384 boolean checkProfiles, int compileReason, boolean force) {
7385 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7386 getCompilerFilterForReason(compileReason), force);
7387 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7391 public boolean performDexOptMode(String packageName,
7392 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7393 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7394 targetCompilerFilter, force);
7395 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7398 private int performDexOptTraced(String packageName,
7399 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7400 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7402 return performDexOptInternal(packageName, checkProfiles,
7403 targetCompilerFilter, force);
7405 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7409 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7410 // if the package can now be considered up to date for the given filter.
7411 private int performDexOptInternal(String packageName,
7412 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7413 PackageParser.Package p;
7414 synchronized (mPackages) {
7415 p = mPackages.get(packageName);
7417 // Package could not be found. Report failure.
7418 return PackageDexOptimizer.DEX_OPT_FAILED;
7420 mPackageUsage.maybeWriteAsync(mPackages);
7421 mCompilerStats.maybeWriteAsync();
7423 long callingId = Binder.clearCallingIdentity();
7425 synchronized (mInstallLock) {
7426 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7427 targetCompilerFilter, force);
7430 Binder.restoreCallingIdentity(callingId);
7434 public ArraySet<String> getOptimizablePackages() {
7435 ArraySet<String> pkgs = new ArraySet<String>();
7436 synchronized (mPackages) {
7437 for (PackageParser.Package p : mPackages.values()) {
7438 if (PackageDexOptimizer.canOptimizePackage(p)) {
7439 pkgs.add(p.packageName);
7446 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7447 boolean checkProfiles, String targetCompilerFilter,
7449 // Select the dex optimizer based on the force parameter.
7450 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7451 // allocate an object here.
7452 PackageDexOptimizer pdo = force
7453 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7454 : mPackageDexOptimizer;
7456 // Optimize all dependencies first. Note: we ignore the return value and march on
7458 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7459 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7460 if (!deps.isEmpty()) {
7461 for (PackageParser.Package depPackage : deps) {
7462 // TODO: Analyze and investigate if we (should) profile libraries.
7463 // Currently this will do a full compilation of the library by default.
7464 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7465 false /* checkProfiles */,
7466 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7467 getOrCreateCompilerPackageStats(depPackage));
7470 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7471 targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7474 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7475 if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7476 ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7477 Set<String> collectedNames = new HashSet<>();
7478 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7484 return Collections.emptyList();
7488 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7489 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7490 if (!collectedNames.contains(p.packageName)) {
7491 collectedNames.add(p.packageName);
7494 if (p.usesLibraries != null) {
7495 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7497 if (p.usesOptionalLibraries != null) {
7498 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7504 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7505 Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7506 for (String libName : libs) {
7507 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7508 if (libPkg != null) {
7509 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7514 private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7515 synchronized (mPackages) {
7516 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7517 if (lib != null && lib.apk != null) {
7518 return mPackages.get(lib.apk);
7524 public void shutdown() {
7525 mPackageUsage.writeNow(mPackages);
7526 mCompilerStats.writeNow();
7530 public void dumpProfiles(String packageName) {
7531 PackageParser.Package pkg;
7532 synchronized (mPackages) {
7533 pkg = mPackages.get(packageName);
7535 throw new IllegalArgumentException("Unknown package: " + packageName);
7538 /* Only the shell, root, or the app user should be able to dump profiles. */
7539 int callingUid = Binder.getCallingUid();
7540 if (callingUid != Process.SHELL_UID &&
7541 callingUid != Process.ROOT_UID &&
7542 callingUid != pkg.applicationInfo.uid) {
7543 throw new SecurityException("dumpProfiles");
7546 synchronized (mInstallLock) {
7547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7548 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7550 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7551 String gid = Integer.toString(sharedGid);
7552 String codePaths = TextUtils.join(";", allCodePaths);
7553 mInstaller.dumpProfiles(gid, packageName, codePaths);
7554 } catch (InstallerException e) {
7555 Slog.w(TAG, "Failed to dump profiles", e);
7557 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7562 public void forceDexOpt(String packageName) {
7563 enforceSystemOrRoot("forceDexOpt");
7565 PackageParser.Package pkg;
7566 synchronized (mPackages) {
7567 pkg = mPackages.get(packageName);
7569 throw new IllegalArgumentException("Unknown package: " + packageName);
7573 synchronized (mInstallLock) {
7574 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7576 // Whoever is calling forceDexOpt wants a fully compiled package.
7577 // Don't use profiles since that may cause compilation to be skipped.
7578 final int res = performDexOptInternalWithDependenciesLI(pkg,
7579 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7582 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7583 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7584 throw new IllegalStateException("Failed to dexopt: " + res);
7589 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7590 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7591 Slog.w(TAG, "Unable to update from " + oldPkg.name
7592 + " to " + newPkg.packageName
7593 + ": old package not in system partition");
7595 } else if (mPackages.get(oldPkg.name) != null) {
7596 Slog.w(TAG, "Unable to update from " + oldPkg.name
7597 + " to " + newPkg.packageName
7598 + ": old package still exists");
7604 void removeCodePathLI(File codePath) {
7605 if (codePath.isDirectory()) {
7607 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7608 } catch (InstallerException e) {
7609 Slog.w(TAG, "Failed to remove code path", e);
7616 private int[] resolveUserIds(int userId) {
7617 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7620 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7622 Slog.wtf(TAG, "Package was null!", new Throwable());
7625 clearAppDataLeafLIF(pkg, userId, flags);
7626 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7627 for (int i = 0; i < childCount; i++) {
7628 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7632 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7633 final PackageSetting ps;
7634 synchronized (mPackages) {
7635 ps = mSettings.mPackages.get(pkg.packageName);
7637 for (int realUserId : resolveUserIds(userId)) {
7638 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7640 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7642 } catch (InstallerException e) {
7643 Slog.w(TAG, String.valueOf(e));
7648 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7650 Slog.wtf(TAG, "Package was null!", new Throwable());
7653 destroyAppDataLeafLIF(pkg, userId, flags);
7654 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7655 for (int i = 0; i < childCount; i++) {
7656 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7660 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7661 final PackageSetting ps;
7662 synchronized (mPackages) {
7663 ps = mSettings.mPackages.get(pkg.packageName);
7665 for (int realUserId : resolveUserIds(userId)) {
7666 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7668 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7670 } catch (InstallerException e) {
7671 Slog.w(TAG, String.valueOf(e));
7676 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7678 Slog.wtf(TAG, "Package was null!", new Throwable());
7681 destroyAppProfilesLeafLIF(pkg);
7682 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7683 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7684 for (int i = 0; i < childCount; i++) {
7685 destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7686 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7687 true /* removeBaseMarker */);
7691 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7692 boolean removeBaseMarker) {
7693 if (pkg.isForwardLocked()) {
7697 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7699 path = PackageManagerServiceUtils.realpath(new File(path));
7700 } catch (IOException e) {
7701 // TODO: Should we return early here ?
7702 Slog.w(TAG, "Failed to get canonical path", e);
7706 final String useMarker = path.replace('/', '@');
7707 for (int realUserId : resolveUserIds(userId)) {
7708 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7709 if (removeBaseMarker) {
7710 File foreignUseMark = new File(profileDir, useMarker);
7711 if (foreignUseMark.exists()) {
7712 if (!foreignUseMark.delete()) {
7713 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7719 File[] markers = profileDir.listFiles();
7720 if (markers != null) {
7721 final String searchString = "@" + pkg.packageName + "@";
7722 // We also delete all markers that contain the package name we're
7723 // uninstalling. These are associated with secondary dex-files belonging
7724 // to the package. Reconstructing the path of these dex files is messy
7726 for (File marker : markers) {
7727 if (marker.getName().indexOf(searchString) > 0) {
7728 if (!marker.delete()) {
7729 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7739 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7741 mInstaller.destroyAppProfiles(pkg.packageName);
7742 } catch (InstallerException e) {
7743 Slog.w(TAG, String.valueOf(e));
7747 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7749 Slog.wtf(TAG, "Package was null!", new Throwable());
7752 clearAppProfilesLeafLIF(pkg);
7753 // We don't remove the base foreign use marker when clearing profiles because
7754 // we will rename it when the app is updated. Unlike the actual profile contents,
7755 // the foreign use marker is good across installs.
7756 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7757 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7758 for (int i = 0; i < childCount; i++) {
7759 clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7763 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7765 mInstaller.clearAppProfiles(pkg.packageName);
7766 } catch (InstallerException e) {
7767 Slog.w(TAG, String.valueOf(e));
7771 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7772 long lastUpdateTime) {
7773 // Set parent install/update time
7774 PackageSetting ps = (PackageSetting) pkg.mExtras;
7776 ps.firstInstallTime = firstInstallTime;
7777 ps.lastUpdateTime = lastUpdateTime;
7779 // Set children install/update time
7780 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7781 for (int i = 0; i < childCount; i++) {
7782 PackageParser.Package childPkg = pkg.childPackages.get(i);
7783 ps = (PackageSetting) childPkg.mExtras;
7785 ps.firstInstallTime = firstInstallTime;
7786 ps.lastUpdateTime = lastUpdateTime;
7791 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7792 PackageParser.Package changingLib) {
7793 if (file.path != null) {
7794 usesLibraryFiles.add(file.path);
7797 PackageParser.Package p = mPackages.get(file.apk);
7798 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7799 // If we are doing this while in the middle of updating a library apk,
7800 // then we need to make sure to use that new apk for determining the
7801 // dependencies here. (We haven't yet finished committing the new apk
7802 // to the package manager state.)
7803 if (p == null || p.packageName.equals(changingLib.packageName)) {
7808 usesLibraryFiles.addAll(p.getAllCodePaths());
7812 private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7813 PackageParser.Package changingLib) throws PackageManagerException {
7814 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7815 final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7816 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7817 for (int i=0; i<N; i++) {
7818 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7820 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7821 "Package " + pkg.packageName + " requires unavailable shared library "
7822 + pkg.usesLibraries.get(i) + "; failing!");
7824 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7826 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7827 for (int i=0; i<N; i++) {
7828 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7830 Slog.w(TAG, "Package " + pkg.packageName
7831 + " desires unavailable shared library "
7832 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7834 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7837 N = usesLibraryFiles.size();
7839 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7841 pkg.usesLibraryFiles = null;
7846 private static boolean hasString(List<String> list, List<String> which) {
7850 for (int i=list.size()-1; i>=0; i--) {
7851 for (int j=which.size()-1; j>=0; j--) {
7852 if (which.get(j).equals(list.get(i))) {
7860 private void updateAllSharedLibrariesLPw() {
7861 for (PackageParser.Package pkg : mPackages.values()) {
7863 updateSharedLibrariesLPw(pkg, null);
7864 } catch (PackageManagerException e) {
7865 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7870 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7871 PackageParser.Package changingPkg) {
7872 ArrayList<PackageParser.Package> res = null;
7873 for (PackageParser.Package pkg : mPackages.values()) {
7874 if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7875 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7877 res = new ArrayList<PackageParser.Package>();
7881 updateSharedLibrariesLPw(pkg, changingPkg);
7882 } catch (PackageManagerException e) {
7883 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7891 * Derive the value of the {@code cpuAbiOverride} based on the provided
7892 * value and an optional stored value from the package settings.
7894 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7895 String cpuAbiOverride = null;
7897 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7898 cpuAbiOverride = null;
7899 } else if (abiOverride != null) {
7900 cpuAbiOverride = abiOverride;
7901 } else if (settings != null) {
7902 cpuAbiOverride = settings.cpuAbiOverrideString;
7905 return cpuAbiOverride;
7908 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7909 final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7910 throws PackageManagerException {
7911 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7912 // If the package has children and this is the first dive in the function
7913 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7914 // whether all packages (parent and children) would be successfully scanned
7915 // before the actual scan since scanning mutates internal state and we want
7916 // to atomically install the package and its children.
7917 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7918 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7919 scanFlags |= SCAN_CHECK_ONLY;
7922 scanFlags &= ~SCAN_CHECK_ONLY;
7925 final PackageParser.Package scannedPkg;
7928 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7929 // Scan the children
7930 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7931 for (int i = 0; i < childCount; i++) {
7932 PackageParser.Package childPkg = pkg.childPackages.get(i);
7933 scanPackageLI(childPkg, policyFlags,
7934 scanFlags, currentTime, user);
7937 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7940 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7941 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7947 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7948 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7949 boolean success = false;
7951 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7956 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7957 // DELETE_DATA_ON_FAILURES is only used by frozen paths
7958 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7959 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7960 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7966 * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7968 private static boolean apkHasCode(String fileName) {
7969 StrictJarFile jarFile = null;
7971 jarFile = new StrictJarFile(fileName,
7972 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7973 return jarFile.findEntry("classes.dex") != null;
7974 } catch (IOException ignore) {
7977 if (jarFile != null) {
7980 } catch (IOException ignore) {}
7986 * Enforces code policy for the package. This ensures that if an APK has
7987 * declared hasCode="true" in its manifest that the APK actually contains
7990 * @throws PackageManagerException If bytecode could not be found when it should exist
7992 private static void enforceCodePolicy(PackageParser.Package pkg)
7993 throws PackageManagerException {
7994 final boolean shouldHaveCode =
7995 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7996 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7997 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7998 "Package " + pkg.baseCodePath + " code is missing");
8001 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8002 for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8003 final boolean splitShouldHaveCode =
8004 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8005 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8006 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8007 "Package " + pkg.splitCodePaths[i] + " code is missing");
8013 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8014 final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8015 throws PackageManagerException {
8016 final File scanFile = new File(pkg.codePath);
8017 if (pkg.applicationInfo.getCodePath() == null ||
8018 pkg.applicationInfo.getResourcePath() == null) {
8019 // Bail out. The resource and code paths haven't been set.
8020 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8021 "Code and resource paths haven't been set correctly");
8025 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8026 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8027 if (pkg.applicationInfo.isDirectBootAware()) {
8028 // we're direct boot aware; set for all components
8029 for (PackageParser.Service s : pkg.services) {
8030 s.info.encryptionAware = s.info.directBootAware = true;
8032 for (PackageParser.Provider p : pkg.providers) {
8033 p.info.encryptionAware = p.info.directBootAware = true;
8035 for (PackageParser.Activity a : pkg.activities) {
8036 a.info.encryptionAware = a.info.directBootAware = true;
8038 for (PackageParser.Activity r : pkg.receivers) {
8039 r.info.encryptionAware = r.info.directBootAware = true;
8043 // Only allow system apps to be flagged as core apps.
8044 pkg.coreApp = false;
8045 // clear flags not applicable to regular apps
8046 pkg.applicationInfo.privateFlags &=
8047 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8048 pkg.applicationInfo.privateFlags &=
8049 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8051 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8053 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8054 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8057 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8058 enforceCodePolicy(pkg);
8061 if (mCustomResolverComponentName != null &&
8062 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8063 setUpCustomResolverActivity(pkg);
8066 if (pkg.packageName.equals("android")) {
8067 synchronized (mPackages) {
8068 if (mAndroidApplication != null) {
8069 Slog.w(TAG, "*************************************************");
8070 Slog.w(TAG, "Core android package being redefined. Skipping.");
8071 Slog.w(TAG, " file=" + scanFile);
8072 Slog.w(TAG, "*************************************************");
8073 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8074 "Core android package being redefined. Skipping.");
8077 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8078 // Set up information for our fall-back user intent resolution activity.
8079 mPlatformPackage = pkg;
8080 pkg.mVersionCode = mSdkVersion;
8081 mAndroidApplication = pkg.applicationInfo;
8083 if (!mResolverReplaced) {
8084 mResolveActivity.applicationInfo = mAndroidApplication;
8085 mResolveActivity.name = ResolverActivity.class.getName();
8086 mResolveActivity.packageName = mAndroidApplication.packageName;
8087 mResolveActivity.processName = "system:ui";
8088 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8089 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8090 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8091 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8092 mResolveActivity.exported = true;
8093 mResolveActivity.enabled = true;
8094 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8095 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8096 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8097 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8098 | ActivityInfo.CONFIG_ORIENTATION
8099 | ActivityInfo.CONFIG_KEYBOARD
8100 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8101 mResolveInfo.activityInfo = mResolveActivity;
8102 mResolveInfo.priority = 0;
8103 mResolveInfo.preferredOrder = 0;
8104 mResolveInfo.match = 0;
8105 mResolveComponentName = new ComponentName(
8106 mAndroidApplication.packageName, mResolveActivity.name);
8112 if (DEBUG_PACKAGE_SCANNING) {
8113 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8114 Log.d(TAG, "Scanning package " + pkg.packageName);
8117 synchronized (mPackages) {
8118 if (mPackages.containsKey(pkg.packageName)
8119 || mSharedLibraries.containsKey(pkg.packageName)) {
8120 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8121 "Application package " + pkg.packageName
8122 + " already installed. Skipping duplicate.");
8125 // If we're only installing presumed-existing packages, require that the
8126 // scanned APK is both already known and at the path previously established
8127 // for it. Previously unknown packages we pick up normally, but if we have an
8128 // a priori expectation about this package's install presence, enforce it.
8129 // With a singular exception for new system packages. When an OTA contains
8130 // a new system package, we allow the codepath to change from a system location
8131 // to the user-installed location. If we don't allow this change, any newer,
8132 // user-installed version of the application will be ignored.
8133 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8134 if (mExpectingBetter.containsKey(pkg.packageName)) {
8135 logCriticalInfo(Log.WARN,
8136 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8138 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8139 if (known != null) {
8140 if (DEBUG_PACKAGE_SCANNING) {
8141 Log.d(TAG, "Examining " + pkg.codePath
8142 + " and requiring known paths " + known.codePathString
8143 + " & " + known.resourcePathString);
8145 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8146 || !pkg.applicationInfo.getResourcePath().equals(
8147 known.resourcePathString)) {
8148 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8149 "Application package " + pkg.packageName
8150 + " found at " + pkg.applicationInfo.getCodePath()
8151 + " but expected at " + known.codePathString
8159 // Initialize package source and resource directories
8160 File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8161 File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8163 SharedUserSetting suid = null;
8164 PackageSetting pkgSetting = null;
8166 if (!isSystemApp(pkg)) {
8167 // Only system apps can use these features.
8168 pkg.mOriginalPackages = null;
8169 pkg.mRealPackage = null;
8170 pkg.mAdoptPermissions = null;
8173 // Getting the package setting may have a side-effect, so if we
8174 // are only checking if scan would succeed, stash a copy of the
8175 // old setting to restore at the end.
8176 PackageSetting nonMutatedPs = null;
8179 synchronized (mPackages) {
8180 if (pkg.mSharedUserId != null) {
8181 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8183 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8184 "Creating application package " + pkg.packageName
8185 + " for shared user failed");
8187 if (DEBUG_PACKAGE_SCANNING) {
8188 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8189 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8190 + "): packages=" + suid.packages);
8194 // Check if we are renaming from an original package name.
8195 PackageSetting origPackage = null;
8196 String realName = null;
8197 if (pkg.mOriginalPackages != null) {
8198 // This package may need to be renamed to a previously
8199 // installed name. Let's check on that...
8200 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8201 if (pkg.mOriginalPackages.contains(renamed)) {
8202 // This package had originally been installed as the
8203 // original name, and we have already taken care of
8204 // transitioning to the new one. Just update the new
8205 // one to continue using the old name.
8206 realName = pkg.mRealPackage;
8207 if (!pkg.packageName.equals(renamed)) {
8208 // Callers into this function may have already taken
8209 // care of renaming the package; only do it here if
8210 // it is not already done.
8211 pkg.setPackageName(renamed);
8215 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8216 if ((origPackage = mSettings.peekPackageLPr(
8217 pkg.mOriginalPackages.get(i))) != null) {
8218 // We do have the package already installed under its
8219 // original name... should we use it?
8220 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8221 // New package is not compatible with original.
8224 } else if (origPackage.sharedUser != null) {
8225 // Make sure uid is compatible between packages.
8226 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8227 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8228 + " to " + pkg.packageName + ": old uid "
8229 + origPackage.sharedUser.name
8230 + " differs from " + pkg.mSharedUserId);
8234 // TODO: Add case when shared user id is added [b/28144775]
8236 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8237 + pkg.packageName + " to old name " + origPackage.name);
8245 if (mTransferedPackages.contains(pkg.packageName)) {
8246 Slog.w(TAG, "Package " + pkg.packageName
8247 + " was transferred to another, but its .apk remains");
8250 // See comments in nonMutatedPs declaration
8251 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8252 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8253 if (foundPs != null) {
8254 nonMutatedPs = new PackageSetting(foundPs);
8258 // Just create the setting, don't add it yet. For already existing packages
8259 // the PkgSetting exists already and doesn't have to be created.
8260 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8261 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8262 pkg.applicationInfo.primaryCpuAbi,
8263 pkg.applicationInfo.secondaryCpuAbi,
8264 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8266 if (pkgSetting == null) {
8267 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8268 "Creating application package " + pkg.packageName + " failed");
8271 if (pkgSetting.origPackage != null) {
8272 // If we are first transitioning from an original package,
8273 // fix up the new package's name now. We need to do this after
8274 // looking up the package under its new name, so getPackageLP
8275 // can take care of fiddling things correctly.
8276 pkg.setPackageName(origPackage.name);
8278 // File a report about this.
8279 String msg = "New package " + pkgSetting.realName
8280 + " renamed to replace old package " + pkgSetting.name;
8281 reportSettingsProblem(Log.WARN, msg);
8283 // Make a note of it.
8284 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8285 mTransferedPackages.add(origPackage.name);
8288 // No longer need to retain this.
8289 pkgSetting.origPackage = null;
8292 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8293 // Make a note of it.
8294 mTransferedPackages.add(pkg.packageName);
8297 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8298 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8301 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8302 // Check all shared libraries and map to their actual file path.
8303 // We only do this here for apps not on a system dir, because those
8304 // are the only ones that can fail an install due to this. We
8305 // will take care of the system apps by updating all of their
8306 // library paths after the scan is done.
8307 updateSharedLibrariesLPw(pkg, null);
8310 if (mFoundPolicyFile) {
8311 SELinuxMMAC.assignSeinfoValue(pkg);
8314 pkg.applicationInfo.uid = pkgSetting.appId;
8315 pkg.mExtras = pkgSetting;
8316 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8317 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8318 // We just determined the app is signed correctly, so bring
8319 // over the latest parsed certs.
8320 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8322 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8323 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8324 "Package " + pkg.packageName + " upgrade keys do not match the "
8325 + "previously installed version");
8327 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8328 String msg = "System package " + pkg.packageName
8329 + " signature changed; retaining data.";
8330 reportSettingsProblem(Log.WARN, msg);
8335 verifySignaturesLP(pkgSetting, pkg);
8336 // We just determined the app is signed correctly, so bring
8337 // over the latest parsed certs.
8338 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8339 } catch (PackageManagerException e) {
8340 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8343 // The signature has changed, but this package is in the system
8344 // image... let's recover!
8345 pkgSetting.signatures.mSignatures = pkg.mSignatures;
8346 // However... if this package is part of a shared user, but it
8347 // doesn't match the signature of the shared user, let's fail.
8348 // What this means is that you can't change the signatures
8349 // associated with an overall shared user, which doesn't seem all
8350 // that unreasonable.
8351 if (pkgSetting.sharedUser != null) {
8352 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8353 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8354 throw new PackageManagerException(
8355 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8356 "Signature mismatch for shared user: "
8357 + pkgSetting.sharedUser);
8360 // File a report about this.
8361 String msg = "System package " + pkg.packageName
8362 + " signature changed; retaining data.";
8363 reportSettingsProblem(Log.WARN, msg);
8366 // Verify that this new package doesn't have any content providers
8367 // that conflict with existing packages. Only do this if the
8368 // package isn't already installed, since we don't want to break
8369 // things that are installed.
8370 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8371 final int N = pkg.providers.size();
8373 for (i=0; i<N; i++) {
8374 PackageParser.Provider p = pkg.providers.get(i);
8375 if (p.info.authority != null) {
8376 String names[] = p.info.authority.split(";");
8377 for (int j = 0; j < names.length; j++) {
8378 if (mProvidersByAuthority.containsKey(names[j])) {
8379 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8380 final String otherPackageName =
8381 ((other != null && other.getComponentName() != null) ?
8382 other.getComponentName().getPackageName() : "?");
8383 throw new PackageManagerException(
8384 INSTALL_FAILED_CONFLICTING_PROVIDER,
8385 "Can't install because provider name " + names[j]
8386 + " (in package " + pkg.applicationInfo.packageName
8387 + ") is already used by " + otherPackageName);
8394 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8395 // This package wants to adopt ownership of permissions from
8397 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8398 final String origName = pkg.mAdoptPermissions.get(i);
8399 final PackageSetting orig = mSettings.peekPackageLPr(origName);
8401 if (verifyPackageUpdateLPr(orig, pkg)) {
8402 Slog.i(TAG, "Adopting permissions from " + origName + " to "
8404 mSettings.transferPermissionsLPw(origName, pkg.packageName);
8411 final String pkgName = pkg.packageName;
8413 final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8414 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8415 pkg.applicationInfo.processName = fixProcessName(
8416 pkg.applicationInfo.packageName,
8417 pkg.applicationInfo.processName,
8418 pkg.applicationInfo.uid);
8420 if (pkg != mPlatformPackage) {
8421 // Get all of our default paths setup
8422 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8425 final String path = scanFile.getPath();
8426 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8428 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8429 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8431 // Some system apps still use directory structure for native libraries
8432 // in which case we might end up not detecting abi solely based on apk
8433 // structure. Try to detect abi based on directory structure.
8434 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8435 pkg.applicationInfo.primaryCpuAbi == null) {
8436 setBundledAppAbisAndRoots(pkg, pkgSetting);
8437 setNativeLibraryPaths(pkg);
8441 if ((scanFlags & SCAN_MOVE) != 0) {
8442 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8443 // but we already have this packages package info in the PackageSetting. We just
8444 // use that and derive the native library path based on the new codepath.
8445 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8446 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8449 // Set native library paths again. For moves, the path will be updated based on the
8450 // ABIs we've determined above. For non-moves, the path will be updated based on the
8451 // ABIs we determined during compilation, but the path will depend on the final
8452 // package path (after the rename away from the stage path).
8453 setNativeLibraryPaths(pkg);
8456 // This is a special case for the "system" package, where the ABI is
8457 // dictated by the zygote configuration (and init.rc). We should keep track
8458 // of this ABI so that we can deal with "normal" applications that run under
8459 // the same UID correctly.
8460 if (mPlatformPackage == pkg) {
8461 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8462 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8465 // If there's a mismatch between the abi-override in the package setting
8466 // and the abiOverride specified for the install. Warn about this because we
8467 // would've already compiled the app without taking the package setting into
8469 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8470 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8471 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8472 " for package " + pkg.packageName);
8476 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8477 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8478 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8480 // Copy the derived override back to the parsed package, so that we can
8481 // update the package settings accordingly.
8482 pkg.cpuAbiOverride = cpuAbiOverride;
8484 if (DEBUG_ABI_SELECTION) {
8485 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8486 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8487 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8490 // Push the derived path down into PackageSettings so we know what to
8491 // clean up at uninstall time.
8492 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8494 if (DEBUG_ABI_SELECTION) {
8495 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8496 " primary=" + pkg.applicationInfo.primaryCpuAbi +
8497 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8500 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8501 // We don't do this here during boot because we can do it all
8502 // at once after scanning all existing packages.
8504 // We also do this *before* we perform dexopt on this package, so that
8505 // we can avoid redundant dexopts, and also to make sure we've got the
8506 // code and package path correct.
8507 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8508 pkg, true /* boot complete */);
8511 if (mFactoryTest && pkg.requestedPermissions.contains(
8512 android.Manifest.permission.FACTORY_TEST)) {
8513 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8516 if (isSystemApp(pkg)) {
8517 pkgSetting.isOrphaned = true;
8520 ArrayList<PackageParser.Package> clientLibPkgs = null;
8522 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8523 if (nonMutatedPs != null) {
8524 synchronized (mPackages) {
8525 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8531 // Only privileged apps and updated privileged apps can add child packages.
8532 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8533 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8534 throw new PackageManagerException("Only privileged apps and updated "
8535 + "privileged apps can add child packages. Ignoring package "
8538 final int childCount = pkg.childPackages.size();
8539 for (int i = 0; i < childCount; i++) {
8540 PackageParser.Package childPkg = pkg.childPackages.get(i);
8541 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8542 childPkg.packageName)) {
8543 throw new PackageManagerException("Cannot override a child package of "
8544 + "another disabled system app. Ignoring package " + pkg.packageName);
8550 synchronized (mPackages) {
8551 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8552 // Only system apps can add new shared libraries.
8553 if (pkg.libraryNames != null) {
8554 for (int i=0; i<pkg.libraryNames.size(); i++) {
8555 String name = pkg.libraryNames.get(i);
8556 boolean allowed = false;
8557 if (pkg.isUpdatedSystemApp()) {
8558 // New library entries can only be added through the
8559 // system image. This is important to get rid of a lot
8560 // of nasty edge cases: for example if we allowed a non-
8561 // system update of the app to add a library, then uninstalling
8562 // the update would make the library go away, and assumptions
8563 // we made such as through app install filtering would now
8564 // have allowed apps on the device which aren't compatible
8565 // with it. Better to just have the restriction here, be
8566 // conservative, and create many fewer cases that can negatively
8567 // impact the user experience.
8568 final PackageSetting sysPs = mSettings
8569 .getDisabledSystemPkgLPr(pkg.packageName);
8570 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8571 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8572 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8582 if (!mSharedLibraries.containsKey(name)) {
8583 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8584 } else if (!name.equals(pkg.packageName)) {
8585 Slog.w(TAG, "Package " + pkg.packageName + " library "
8586 + name + " already exists; skipping");
8589 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8590 + name + " that is not declared on system image; skipping");
8593 if ((scanFlags & SCAN_BOOTING) == 0) {
8594 // If we are not booting, we need to update any applications
8595 // that are clients of our shared library. If we are booting,
8596 // this will all be done once the scan is complete.
8597 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8603 if ((scanFlags & SCAN_BOOTING) != 0) {
8604 // No apps can run during boot scan, so they don't need to be frozen
8605 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8606 // Caller asked to not kill app, so it's probably not frozen
8607 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8608 // Caller asked us to ignore frozen check for some reason; they
8609 // probably didn't know the package name
8611 // We're doing major surgery on this package, so it better be frozen
8612 // right now to keep it from launching
8613 checkPackageFrozen(pkgName);
8616 // Also need to kill any apps that are dependent on the library.
8617 if (clientLibPkgs != null) {
8618 for (int i=0; i<clientLibPkgs.size(); i++) {
8619 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8620 killApplication(clientPkg.applicationInfo.packageName,
8621 clientPkg.applicationInfo.uid, "update lib");
8625 // Make sure we're not adding any bogus keyset info
8626 KeySetManagerService ksms = mSettings.mKeySetManagerService;
8627 ksms.assertScannedPackageValid(pkg);
8630 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8632 boolean createIdmapFailed = false;
8633 synchronized (mPackages) {
8634 // We don't expect installation to fail beyond this point
8636 if (pkgSetting.pkg != null) {
8637 // Note that |user| might be null during the initial boot scan. If a codePath
8638 // for an app has changed during a boot scan, it's due to an app update that's
8639 // part of the system partition and marker changes must be applied to all users.
8640 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8641 (user != null) ? user : UserHandle.ALL);
8644 // Add the new setting to mSettings
8645 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8646 // Add the new setting to mPackages
8647 mPackages.put(pkg.applicationInfo.packageName, pkg);
8648 // Make sure we don't accidentally delete its data.
8649 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8650 while (iter.hasNext()) {
8651 PackageCleanItem item = iter.next();
8652 if (pkgName.equals(item.packageName)) {
8657 // Take care of first install / last update times.
8658 if (currentTime != 0) {
8659 if (pkgSetting.firstInstallTime == 0) {
8660 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8661 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8662 pkgSetting.lastUpdateTime = currentTime;
8664 } else if (pkgSetting.firstInstallTime == 0) {
8665 // We need *something*. Take time time stamp of the file.
8666 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8667 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8668 if (scanFileTime != pkgSetting.timeStamp) {
8669 // A package on the system image has changed; consider this
8671 pkgSetting.lastUpdateTime = scanFileTime;
8675 // Add the package's KeySets to the global KeySetManagerService
8676 ksms.addScannedPackageLPw(pkg);
8678 int N = pkg.providers.size();
8679 StringBuilder r = null;
8681 for (i=0; i<N; i++) {
8682 PackageParser.Provider p = pkg.providers.get(i);
8683 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8684 p.info.processName, pkg.applicationInfo.uid);
8685 mProviders.addProvider(p);
8686 p.syncable = p.info.isSyncable;
8687 if (p.info.authority != null) {
8688 String names[] = p.info.authority.split(";");
8689 p.info.authority = null;
8690 for (int j = 0; j < names.length; j++) {
8691 if (j == 1 && p.syncable) {
8692 // We only want the first authority for a provider to possibly be
8693 // syncable, so if we already added this provider using a different
8694 // authority clear the syncable flag. We copy the provider before
8695 // changing it because the mProviders object contains a reference
8696 // to a provider that we don't want to change.
8697 // Only do this for the second authority since the resulting provider
8698 // object can be the same for all future authorities for this provider.
8699 p = new PackageParser.Provider(p);
8702 if (!mProvidersByAuthority.containsKey(names[j])) {
8703 mProvidersByAuthority.put(names[j], p);
8704 if (p.info.authority == null) {
8705 p.info.authority = names[j];
8707 p.info.authority = p.info.authority + ";" + names[j];
8709 if (DEBUG_PACKAGE_SCANNING) {
8710 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8711 Log.d(TAG, "Registered content provider: " + names[j]
8712 + ", className = " + p.info.name + ", isSyncable = "
8713 + p.info.isSyncable);
8716 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8717 Slog.w(TAG, "Skipping provider name " + names[j] +
8718 " (in package " + pkg.applicationInfo.packageName +
8719 "): name already used by "
8720 + ((other != null && other.getComponentName() != null)
8721 ? other.getComponentName().getPackageName() : "?"));
8725 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8727 r = new StringBuilder(256);
8731 r.append(p.info.name);
8735 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
8738 N = pkg.services.size();
8740 for (i=0; i<N; i++) {
8741 PackageParser.Service s = pkg.services.get(i);
8742 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8743 s.info.processName, pkg.applicationInfo.uid);
8744 mServices.addService(s);
8745 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8747 r = new StringBuilder(256);
8751 r.append(s.info.name);
8755 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
8758 N = pkg.receivers.size();
8760 for (i=0; i<N; i++) {
8761 PackageParser.Activity a = pkg.receivers.get(i);
8762 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8763 a.info.processName, pkg.applicationInfo.uid);
8764 mReceivers.addActivity(a, "receiver");
8765 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8767 r = new StringBuilder(256);
8771 r.append(a.info.name);
8775 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
8778 N = pkg.activities.size();
8780 for (i=0; i<N; i++) {
8781 PackageParser.Activity a = pkg.activities.get(i);
8782 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8783 a.info.processName, pkg.applicationInfo.uid);
8784 mActivities.addActivity(a, "activity");
8785 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8787 r = new StringBuilder(256);
8791 r.append(a.info.name);
8795 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
8798 N = pkg.permissionGroups.size();
8800 for (i=0; i<N; i++) {
8801 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8802 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8803 final String curPackageName = cur == null ? null : cur.info.packageName;
8804 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8805 if (cur == null || isPackageUpdate) {
8806 mPermissionGroups.put(pg.info.name, pg);
8807 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8809 r = new StringBuilder(256);
8813 if (isPackageUpdate) {
8816 r.append(pg.info.name);
8819 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8820 + pg.info.packageName + " ignored: original from "
8821 + cur.info.packageName);
8822 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8824 r = new StringBuilder(256);
8829 r.append(pg.info.name);
8834 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
8837 N = pkg.permissions.size();
8839 for (i=0; i<N; i++) {
8840 PackageParser.Permission p = pkg.permissions.get(i);
8842 // Assume by default that we did not install this permission into the system.
8843 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8845 // Now that permission groups have a special meaning, we ignore permission
8846 // groups for legacy apps to prevent unexpected behavior. In particular,
8847 // permissions for one app being granted to someone just becase they happen
8848 // to be in a group defined by another app (before this had no implications).
8849 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8850 p.group = mPermissionGroups.get(p.info.group);
8851 // Warn for a permission in an unknown group.
8852 if (p.info.group != null && p.group == null) {
8853 Slog.w(TAG, "Permission " + p.info.name + " from package "
8854 + p.info.packageName + " in an unknown group " + p.info.group);
8858 ArrayMap<String, BasePermission> permissionMap =
8859 p.tree ? mSettings.mPermissionTrees
8860 : mSettings.mPermissions;
8861 BasePermission bp = permissionMap.get(p.info.name);
8863 // Allow system apps to redefine non-system permissions
8864 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8865 final boolean currentOwnerIsSystem = (bp.perm != null
8866 && isSystemApp(bp.perm.owner));
8867 if (isSystemApp(p.owner)) {
8868 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8869 // It's a built-in permission and no owner, take ownership now
8870 bp.packageSetting = pkgSetting;
8872 bp.uid = pkg.applicationInfo.uid;
8873 bp.sourcePackage = p.info.packageName;
8874 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8875 } else if (!currentOwnerIsSystem) {
8876 String msg = "New decl " + p.owner + " of permission "
8877 + p.info.name + " is system; overriding " + bp.sourcePackage;
8878 reportSettingsProblem(Log.WARN, msg);
8885 bp = new BasePermission(p.info.name, p.info.packageName,
8886 BasePermission.TYPE_NORMAL);
8887 permissionMap.put(p.info.name, bp);
8890 if (bp.perm == null) {
8891 if (bp.sourcePackage == null
8892 || bp.sourcePackage.equals(p.info.packageName)) {
8893 BasePermission tree = findPermissionTreeLP(p.info.name);
8895 || tree.sourcePackage.equals(p.info.packageName)) {
8896 bp.packageSetting = pkgSetting;
8898 bp.uid = pkg.applicationInfo.uid;
8899 bp.sourcePackage = p.info.packageName;
8900 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8901 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8903 r = new StringBuilder(256);
8907 r.append(p.info.name);
8910 Slog.w(TAG, "Permission " + p.info.name + " from package "
8911 + p.info.packageName + " ignored: base tree "
8912 + tree.name + " is from package "
8913 + tree.sourcePackage);
8916 Slog.w(TAG, "Permission " + p.info.name + " from package "
8917 + p.info.packageName + " ignored: original from "
8918 + bp.sourcePackage);
8920 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8922 r = new StringBuilder(256);
8927 r.append(p.info.name);
8930 bp.protectionLevel = p.info.protectionLevel;
8935 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
8938 N = pkg.instrumentation.size();
8940 for (i=0; i<N; i++) {
8941 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8942 a.info.packageName = pkg.applicationInfo.packageName;
8943 a.info.sourceDir = pkg.applicationInfo.sourceDir;
8944 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8945 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8946 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8947 a.info.dataDir = pkg.applicationInfo.dataDir;
8948 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8949 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8951 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8952 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8953 mInstrumentation.put(a.getComponentName(), a);
8954 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8956 r = new StringBuilder(256);
8960 r.append(a.info.name);
8964 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
8967 if (pkg.protectedBroadcasts != null) {
8968 N = pkg.protectedBroadcasts.size();
8969 for (i=0; i<N; i++) {
8970 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8974 pkgSetting.setTimeStamp(scanFileTime);
8976 // Create idmap files for pairs of (packages, overlay packages).
8977 // Note: "android", ie framework-res.apk, is handled by native layers.
8978 if (pkg.mOverlayTarget != null) {
8979 // This is an overlay package.
8980 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8981 if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8982 mOverlays.put(pkg.mOverlayTarget,
8983 new ArrayMap<String, PackageParser.Package>());
8985 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8986 map.put(pkg.packageName, pkg);
8987 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8988 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8989 createIdmapFailed = true;
8992 } else if (mOverlays.containsKey(pkg.packageName) &&
8993 !pkg.packageName.equals("android")) {
8994 // This is a regular package, with one or more known overlay packages.
8995 createIdmapsForPackageLI(pkg);
8999 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9001 if (createIdmapFailed) {
9002 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9003 "scanPackageLI failed to createIdmap");
9008 private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9009 PackageParser.Package update, UserHandle user) {
9010 if (existing.applicationInfo == null || update.applicationInfo == null) {
9011 // This isn't due to an app installation.
9015 final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9016 final File newCodePath = new File(update.applicationInfo.getCodePath());
9018 // The codePath hasn't changed, so there's nothing for us to do.
9019 if (Objects.equals(oldCodePath, newCodePath)) {
9023 File canonicalNewCodePath;
9025 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9026 } catch (IOException e) {
9027 Slog.w(TAG, "Failed to get canonical path.", e);
9031 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9032 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9033 // that the last component of the path (i.e, the name) doesn't need canonicalization
9034 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9035 // but may change in the future. Hopefully this function won't exist at that point.
9036 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9037 oldCodePath.getName());
9039 // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9041 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9042 if (!oldMarkerPrefix.endsWith("@")) {
9043 oldMarkerPrefix += "@";
9045 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9046 if (!newMarkerPrefix.endsWith("@")) {
9047 newMarkerPrefix += "@";
9050 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9051 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9052 for (String updatedPath : updatedPaths) {
9053 String updatedPathName = new File(updatedPath).getName();
9054 markerSuffixes.add(updatedPathName.replace('/', '@'));
9057 for (int userId : resolveUserIds(user.getIdentifier())) {
9058 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9060 for (String markerSuffix : markerSuffixes) {
9061 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9062 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9063 if (oldForeignUseMark.exists()) {
9065 Os.rename(oldForeignUseMark.getAbsolutePath(),
9066 newForeignUseMark.getAbsolutePath());
9067 } catch (ErrnoException e) {
9068 Slog.w(TAG, "Failed to rename foreign use marker", e);
9069 oldForeignUseMark.delete();
9077 * Derive the ABI of a non-system package located at {@code scanFile}. This information
9078 * is derived purely on the basis of the contents of {@code scanFile} and
9079 * {@code cpuAbiOverride}.
9081 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9083 private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9084 String cpuAbiOverride, boolean extractLibs)
9085 throws PackageManagerException {
9086 // TODO: We can probably be smarter about this stuff. For installed apps,
9087 // we can calculate this information at install time once and for all. For
9088 // system apps, we can probably assume that this information doesn't change
9089 // after the first boot scan. As things stand, we do lots of unnecessary work.
9091 // Give ourselves some initial paths; we'll come back for another
9092 // pass once we've determined ABI below.
9093 setNativeLibraryPaths(pkg);
9095 // We would never need to extract libs for forward-locked and external packages,
9096 // since the container service will do it for us. We shouldn't attempt to
9097 // extract libs from system app when it was not updated.
9098 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9099 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9100 extractLibs = false;
9103 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9104 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9106 NativeLibraryHelper.Handle handle = null;
9108 handle = NativeLibraryHelper.Handle.create(pkg);
9109 // TODO(multiArch): This can be null for apps that didn't go through the
9110 // usual installation process. We can calculate it again, like we
9111 // do during install time.
9113 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9115 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9117 // Null out the abis so that they can be recalculated.
9118 pkg.applicationInfo.primaryCpuAbi = null;
9119 pkg.applicationInfo.secondaryCpuAbi = null;
9120 if (isMultiArch(pkg.applicationInfo)) {
9121 // Warn if we've set an abiOverride for multi-lib packages..
9122 // By definition, we need to copy both 32 and 64 bit libraries for
9124 if (pkg.cpuAbiOverride != null
9125 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9126 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9129 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9130 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9131 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9133 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9134 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9135 useIsaSpecificSubdirs);
9137 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9141 maybeThrowExceptionForMultiArchCopy(
9142 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9144 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9146 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9147 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9148 useIsaSpecificSubdirs);
9150 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9154 maybeThrowExceptionForMultiArchCopy(
9155 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9158 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9162 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9164 if (pkg.use32bitAbi) {
9165 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9166 pkg.applicationInfo.primaryCpuAbi = abi;
9168 pkg.applicationInfo.secondaryCpuAbi = abi;
9171 pkg.applicationInfo.primaryCpuAbi = abi;
9176 String[] abiList = (cpuAbiOverride != null) ?
9177 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9179 // Enable gross and lame hacks for apps that are built with old
9180 // SDK tools. We must scan their APKs for renderscript bitcode and
9181 // not launch them if it's present. Don't bother checking on devices
9182 // that don't have 64 bit support.
9183 boolean needsRenderScriptOverride = false;
9184 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9185 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9186 abiList = Build.SUPPORTED_32_BIT_ABIS;
9187 needsRenderScriptOverride = true;
9192 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9193 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9195 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9198 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9199 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9200 "Error unpackaging native libs for app, errorCode=" + copyRet);
9204 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9205 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9206 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9207 } else if (needsRenderScriptOverride) {
9208 pkg.applicationInfo.primaryCpuAbi = abiList[0];
9211 } catch (IOException ioe) {
9212 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9214 IoUtils.closeQuietly(handle);
9217 // Now that we've calculated the ABIs and determined if it's an internal app,
9218 // we will go ahead and populate the nativeLibraryPath.
9219 setNativeLibraryPaths(pkg);
9223 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9224 * i.e, so that all packages can be run inside a single process if required.
9226 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9227 * this function will either try and make the ABI for all packages in {@code packagesForUser}
9228 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9229 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9230 * updating a package that belongs to a shared user.
9232 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9233 * adds unnecessary complexity.
9235 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9236 PackageParser.Package scannedPackage, boolean bootComplete) {
9237 String requiredInstructionSet = null;
9238 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9239 requiredInstructionSet = VMRuntime.getInstructionSet(
9240 scannedPackage.applicationInfo.primaryCpuAbi);
9243 PackageSetting requirer = null;
9244 for (PackageSetting ps : packagesForUser) {
9245 // If packagesForUser contains scannedPackage, we skip it. This will happen
9246 // when scannedPackage is an update of an existing package. Without this check,
9247 // we will never be able to change the ABI of any package belonging to a shared
9248 // user, even if it's compatible with other packages.
9249 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9250 if (ps.primaryCpuAbiString == null) {
9254 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9255 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9256 // We have a mismatch between instruction sets (say arm vs arm64) warn about
9257 // this but there's not much we can do.
9258 String errorMessage = "Instruction set mismatch, "
9259 + ((requirer == null) ? "[caller]" : requirer)
9260 + " requires " + requiredInstructionSet + " whereas " + ps
9261 + " requires " + instructionSet;
9262 Slog.w(TAG, errorMessage);
9265 if (requiredInstructionSet == null) {
9266 requiredInstructionSet = instructionSet;
9272 if (requiredInstructionSet != null) {
9274 if (requirer != null) {
9275 // requirer != null implies that either scannedPackage was null or that scannedPackage
9276 // did not require an ABI, in which case we have to adjust scannedPackage to match
9277 // the ABI of the set (which is the same as requirer's ABI)
9278 adjustedAbi = requirer.primaryCpuAbiString;
9279 if (scannedPackage != null) {
9280 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9283 // requirer == null implies that we're updating all ABIs in the set to
9284 // match scannedPackage.
9285 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
9288 for (PackageSetting ps : packagesForUser) {
9289 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9290 if (ps.primaryCpuAbiString != null) {
9294 ps.primaryCpuAbiString = adjustedAbi;
9295 if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9296 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9297 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9298 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9300 + (requirer == null ? "null" : requirer.pkg.packageName)
9301 + ", scannedPackage="
9302 + (scannedPackage != null ? scannedPackage.packageName : "null")
9305 mInstaller.rmdex(ps.codePathString,
9306 getDexCodeInstructionSet(getPreferredInstructionSet()));
9307 } catch (InstallerException ignored) {
9315 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9316 synchronized (mPackages) {
9317 mResolverReplaced = true;
9318 // Set up information for custom user intent resolution activity.
9319 mResolveActivity.applicationInfo = pkg.applicationInfo;
9320 mResolveActivity.name = mCustomResolverComponentName.getClassName();
9321 mResolveActivity.packageName = pkg.applicationInfo.packageName;
9322 mResolveActivity.processName = pkg.applicationInfo.packageName;
9323 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9324 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9325 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9326 mResolveActivity.theme = 0;
9327 mResolveActivity.exported = true;
9328 mResolveActivity.enabled = true;
9329 mResolveInfo.activityInfo = mResolveActivity;
9330 mResolveInfo.priority = 0;
9331 mResolveInfo.preferredOrder = 0;
9332 mResolveInfo.match = 0;
9333 mResolveComponentName = mCustomResolverComponentName;
9334 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9335 mResolveComponentName);
9339 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9340 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9342 // Set up information for ephemeral installer activity
9343 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9344 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9345 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9346 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9347 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9348 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9349 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9350 mEphemeralInstallerActivity.theme = 0;
9351 mEphemeralInstallerActivity.exported = true;
9352 mEphemeralInstallerActivity.enabled = true;
9353 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9354 mEphemeralInstallerInfo.priority = 0;
9355 mEphemeralInstallerInfo.preferredOrder = 1;
9356 mEphemeralInstallerInfo.isDefault = true;
9357 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9358 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9360 if (DEBUG_EPHEMERAL) {
9361 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9365 private static String calculateBundledApkRoot(final String codePathString) {
9366 final File codePath = new File(codePathString);
9367 final File codeRoot;
9368 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9369 codeRoot = Environment.getRootDirectory();
9370 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9371 codeRoot = Environment.getOemDirectory();
9372 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9373 codeRoot = Environment.getVendorDirectory();
9375 // Unrecognized code path; take its top real segment as the apk root:
9376 // e.g. /something/app/blah.apk => /something
9378 File f = codePath.getCanonicalFile();
9379 File parent = f.getParentFile(); // non-null because codePath is a file
9381 while ((tmp = parent.getParentFile()) != null) {
9386 Slog.w(TAG, "Unrecognized code path "
9387 + codePath + " - using " + codeRoot);
9388 } catch (IOException e) {
9389 // Can't canonicalize the code path -- shenanigans?
9390 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9391 return Environment.getRootDirectory().getPath();
9394 return codeRoot.getPath();
9398 * Derive and set the location of native libraries for the given package,
9399 * which varies depending on where and how the package was installed.
9401 private void setNativeLibraryPaths(PackageParser.Package pkg) {
9402 final ApplicationInfo info = pkg.applicationInfo;
9403 final String codePath = pkg.codePath;
9404 final File codeFile = new File(codePath);
9405 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9406 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9408 info.nativeLibraryRootDir = null;
9409 info.nativeLibraryRootRequiresIsa = false;
9410 info.nativeLibraryDir = null;
9411 info.secondaryNativeLibraryDir = null;
9413 if (isApkFile(codeFile)) {
9414 // Monolithic install
9416 // If "/system/lib64/apkname" exists, assume that is the per-package
9417 // native library directory to use; otherwise use "/system/lib/apkname".
9418 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9419 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9420 getPrimaryInstructionSet(info));
9422 // This is a bundled system app so choose the path based on the ABI.
9423 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9424 // is just the default path.
9425 final String apkName = deriveCodePathName(codePath);
9426 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9427 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9428 apkName).getAbsolutePath();
9430 if (info.secondaryCpuAbi != null) {
9431 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9432 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9433 secondaryLibDir, apkName).getAbsolutePath();
9435 } else if (asecApp) {
9436 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9439 final String apkName = deriveCodePathName(codePath);
9440 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9444 info.nativeLibraryRootRequiresIsa = false;
9445 info.nativeLibraryDir = info.nativeLibraryRootDir;
9448 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9449 info.nativeLibraryRootRequiresIsa = true;
9451 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9452 getPrimaryInstructionSet(info)).getAbsolutePath();
9454 if (info.secondaryCpuAbi != null) {
9455 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9456 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9462 * Calculate the abis and roots for a bundled app. These can uniquely
9463 * be determined from the contents of the system partition, i.e whether
9464 * it contains 64 or 32 bit shared libraries etc. We do not validate any
9465 * of this information, and instead assume that the system was built
9468 private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9469 PackageSetting pkgSetting) {
9470 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9472 // If "/system/lib64/apkname" exists, assume that is the per-package
9473 // native library directory to use; otherwise use "/system/lib/apkname".
9474 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9475 setBundledAppAbi(pkg, apkRoot, apkName);
9476 // pkgSetting might be null during rescan following uninstall of updates
9477 // to a bundled app, so accommodate that possibility. The settings in
9478 // that case will be established later from the parsed package.
9480 // If the settings aren't null, sync them up with what we've just derived.
9481 // note that apkRoot isn't stored in the package settings.
9482 if (pkgSetting != null) {
9483 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9484 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9489 * Deduces the ABI of a bundled app and sets the relevant fields on the
9490 * parsed pkg object.
9492 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9493 * under which system libraries are installed.
9494 * @param apkName the name of the installed package.
9496 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9497 final File codeFile = new File(pkg.codePath);
9499 final boolean has64BitLibs;
9500 final boolean has32BitLibs;
9501 if (isApkFile(codeFile)) {
9502 // Monolithic install
9503 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9504 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9507 final File rootDir = new File(codeFile, LIB_DIR_NAME);
9508 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9509 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9510 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9511 has64BitLibs = (new File(rootDir, isa)).exists();
9513 has64BitLibs = false;
9515 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9516 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9517 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9518 has32BitLibs = (new File(rootDir, isa)).exists();
9520 has32BitLibs = false;
9524 if (has64BitLibs && !has32BitLibs) {
9525 // The package has 64 bit libs, but not 32 bit libs. Its primary
9526 // ABI should be 64 bit. We can safely assume here that the bundled
9527 // native libraries correspond to the most preferred ABI in the list.
9529 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9530 pkg.applicationInfo.secondaryCpuAbi = null;
9531 } else if (has32BitLibs && !has64BitLibs) {
9532 // The package has 32 bit libs but not 64 bit libs. Its primary
9533 // ABI should be 32 bit.
9535 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9536 pkg.applicationInfo.secondaryCpuAbi = null;
9537 } else if (has32BitLibs && has64BitLibs) {
9538 // The application has both 64 and 32 bit bundled libraries. We check
9539 // here that the app declares multiArch support, and warn if it doesn't.
9541 // We will be lenient here and record both ABIs. The primary will be the
9542 // ABI that's higher on the list, i.e, a device that's configured to prefer
9543 // 64 bit apps will see a 64 bit primary ABI,
9545 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9546 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9549 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9550 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9551 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9553 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9554 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9557 pkg.applicationInfo.primaryCpuAbi = null;
9558 pkg.applicationInfo.secondaryCpuAbi = null;
9562 private void killApplication(String pkgName, int appId, String reason) {
9563 killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9566 private void killApplication(String pkgName, int appId, int userId, String reason) {
9567 // Request the ActivityManager to kill the process(only for existing packages)
9568 // so that we do not end up in a confused state while the user is still using the older
9569 // version of the application while the new one gets installed.
9570 final long token = Binder.clearCallingIdentity();
9572 IActivityManager am = ActivityManagerNative.getDefault();
9575 am.killApplication(pkgName, appId, userId, reason);
9576 } catch (RemoteException e) {
9580 Binder.restoreCallingIdentity(token);
9584 private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9585 // Remove the parent package setting
9586 PackageSetting ps = (PackageSetting) pkg.mExtras;
9588 removePackageLI(ps, chatty);
9590 // Remove the child package setting
9591 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9592 for (int i = 0; i < childCount; i++) {
9593 PackageParser.Package childPkg = pkg.childPackages.get(i);
9594 ps = (PackageSetting) childPkg.mExtras;
9596 removePackageLI(ps, chatty);
9601 void removePackageLI(PackageSetting ps, boolean chatty) {
9602 if (DEBUG_INSTALL) {
9604 Log.d(TAG, "Removing package " + ps.name);
9608 synchronized (mPackages) {
9609 mPackages.remove(ps.name);
9610 final PackageParser.Package pkg = ps.pkg;
9612 cleanPackageDataStructuresLILPw(pkg, chatty);
9617 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9618 if (DEBUG_INSTALL) {
9620 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9624 synchronized (mPackages) {
9625 // Remove the parent package
9626 mPackages.remove(pkg.applicationInfo.packageName);
9627 cleanPackageDataStructuresLILPw(pkg, chatty);
9629 // Remove the child packages
9630 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9631 for (int i = 0; i < childCount; i++) {
9632 PackageParser.Package childPkg = pkg.childPackages.get(i);
9633 mPackages.remove(childPkg.applicationInfo.packageName);
9634 cleanPackageDataStructuresLILPw(childPkg, chatty);
9639 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9640 int N = pkg.providers.size();
9641 StringBuilder r = null;
9643 for (i=0; i<N; i++) {
9644 PackageParser.Provider p = pkg.providers.get(i);
9645 mProviders.removeProvider(p);
9646 if (p.info.authority == null) {
9648 /* There was another ContentProvider with this authority when
9649 * this app was installed so this authority is null,
9650 * Ignore it as we don't have to unregister the provider.
9654 String names[] = p.info.authority.split(";");
9655 for (int j = 0; j < names.length; j++) {
9656 if (mProvidersByAuthority.get(names[j]) == p) {
9657 mProvidersByAuthority.remove(names[j]);
9660 Log.d(TAG, "Unregistered content provider: " + names[j]
9661 + ", className = " + p.info.name + ", isSyncable = "
9662 + p.info.isSyncable);
9666 if (DEBUG_REMOVE && chatty) {
9668 r = new StringBuilder(256);
9672 r.append(p.info.name);
9676 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
9679 N = pkg.services.size();
9681 for (i=0; i<N; i++) {
9682 PackageParser.Service s = pkg.services.get(i);
9683 mServices.removeService(s);
9686 r = new StringBuilder(256);
9690 r.append(s.info.name);
9694 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
9697 N = pkg.receivers.size();
9699 for (i=0; i<N; i++) {
9700 PackageParser.Activity a = pkg.receivers.get(i);
9701 mReceivers.removeActivity(a, "receiver");
9702 if (DEBUG_REMOVE && chatty) {
9704 r = new StringBuilder(256);
9708 r.append(a.info.name);
9712 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
9715 N = pkg.activities.size();
9717 for (i=0; i<N; i++) {
9718 PackageParser.Activity a = pkg.activities.get(i);
9719 mActivities.removeActivity(a, "activity");
9720 if (DEBUG_REMOVE && chatty) {
9722 r = new StringBuilder(256);
9726 r.append(a.info.name);
9730 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
9733 N = pkg.permissions.size();
9735 for (i=0; i<N; i++) {
9736 PackageParser.Permission p = pkg.permissions.get(i);
9737 BasePermission bp = mSettings.mPermissions.get(p.info.name);
9739 bp = mSettings.mPermissionTrees.get(p.info.name);
9741 if (bp != null && bp.perm == p) {
9743 if (DEBUG_REMOVE && chatty) {
9745 r = new StringBuilder(256);
9749 r.append(p.info.name);
9752 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9753 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9754 if (appOpPkgs != null) {
9755 appOpPkgs.remove(pkg.packageName);
9760 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9763 N = pkg.requestedPermissions.size();
9765 for (i=0; i<N; i++) {
9766 String perm = pkg.requestedPermissions.get(i);
9767 BasePermission bp = mSettings.mPermissions.get(perm);
9768 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9769 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9770 if (appOpPkgs != null) {
9771 appOpPkgs.remove(pkg.packageName);
9772 if (appOpPkgs.isEmpty()) {
9773 mAppOpPermissionPackages.remove(perm);
9779 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
9782 N = pkg.instrumentation.size();
9784 for (i=0; i<N; i++) {
9785 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9786 mInstrumentation.remove(a.getComponentName());
9787 if (DEBUG_REMOVE && chatty) {
9789 r = new StringBuilder(256);
9793 r.append(a.info.name);
9797 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
9801 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9802 // Only system apps can hold shared libraries.
9803 if (pkg.libraryNames != null) {
9804 for (i=0; i<pkg.libraryNames.size(); i++) {
9805 String name = pkg.libraryNames.get(i);
9806 SharedLibraryEntry cur = mSharedLibraries.get(name);
9807 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9808 mSharedLibraries.remove(name);
9809 if (DEBUG_REMOVE && chatty) {
9811 r = new StringBuilder(256);
9822 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
9826 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9827 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9828 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9835 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9836 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9837 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9839 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9840 // Update the parent permissions
9841 updatePermissionsLPw(pkg.packageName, pkg, flags);
9842 // Update the child permissions
9843 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9844 for (int i = 0; i < childCount; i++) {
9845 PackageParser.Package childPkg = pkg.childPackages.get(i);
9846 updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9850 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9852 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9853 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9856 private void updatePermissionsLPw(String changingPkg,
9857 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9858 // Make sure there are no dangling permission trees.
9859 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9860 while (it.hasNext()) {
9861 final BasePermission bp = it.next();
9862 if (bp.packageSetting == null) {
9863 // We may not yet have parsed the package, so just see if
9864 // we still know about its settings.
9865 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9867 if (bp.packageSetting == null) {
9868 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9869 + " from package " + bp.sourcePackage);
9871 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9872 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9873 Slog.i(TAG, "Removing old permission tree: " + bp.name
9874 + " from package " + bp.sourcePackage);
9875 flags |= UPDATE_PERMISSIONS_ALL;
9881 // Make sure all dynamic permissions have been assigned to a package,
9882 // and make sure there are no dangling permissions.
9883 it = mSettings.mPermissions.values().iterator();
9884 while (it.hasNext()) {
9885 final BasePermission bp = it.next();
9886 if (bp.type == BasePermission.TYPE_DYNAMIC) {
9887 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9888 + bp.name + " pkg=" + bp.sourcePackage
9889 + " info=" + bp.pendingInfo);
9890 if (bp.packageSetting == null && bp.pendingInfo != null) {
9891 final BasePermission tree = findPermissionTreeLP(bp.name);
9892 if (tree != null && tree.perm != null) {
9893 bp.packageSetting = tree.packageSetting;
9894 bp.perm = new PackageParser.Permission(tree.perm.owner,
9895 new PermissionInfo(bp.pendingInfo));
9896 bp.perm.info.packageName = tree.perm.info.packageName;
9897 bp.perm.info.name = bp.name;
9902 if (bp.packageSetting == null) {
9903 // We may not yet have parsed the package, so just see if
9904 // we still know about its settings.
9905 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9907 if (bp.packageSetting == null) {
9908 Slog.w(TAG, "Removing dangling permission: " + bp.name
9909 + " from package " + bp.sourcePackage);
9911 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9912 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9913 Slog.i(TAG, "Removing old permission: " + bp.name
9914 + " from package " + bp.sourcePackage);
9915 flags |= UPDATE_PERMISSIONS_ALL;
9921 // Now update the permissions for all packages, in particular
9922 // replace the granted permissions of the system packages.
9923 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9924 for (PackageParser.Package pkg : mPackages.values()) {
9925 if (pkg != pkgInfo) {
9926 // Only replace for packages on requested volume
9927 final String volumeUuid = getVolumeUuidForPackage(pkg);
9928 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9929 && Objects.equals(replaceVolumeUuid, volumeUuid);
9930 grantPermissionsLPw(pkg, replace, changingPkg);
9935 if (pkgInfo != null) {
9936 // Only replace for packages on requested volume
9937 final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9938 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9939 && Objects.equals(replaceVolumeUuid, volumeUuid);
9940 grantPermissionsLPw(pkgInfo, replace, changingPkg);
9944 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9945 String packageOfInterest) {
9946 // IMPORTANT: There are two types of permissions: install and runtime.
9947 // Install time permissions are granted when the app is installed to
9948 // all device users and users added in the future. Runtime permissions
9949 // are granted at runtime explicitly to specific users. Normal and signature
9950 // protected permissions are install time permissions. Dangerous permissions
9951 // are install permissions if the app's target SDK is Lollipop MR1 or older,
9952 // otherwise they are runtime permissions. This function does not manage
9953 // runtime permissions except for the case an app targeting Lollipop MR1
9954 // being upgraded to target a newer SDK, in which case dangerous permissions
9955 // are transformed from install time to runtime ones.
9957 final PackageSetting ps = (PackageSetting) pkg.mExtras;
9962 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9964 PermissionsState permissionsState = ps.getPermissionsState();
9965 PermissionsState origPermissions = permissionsState;
9967 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9969 boolean runtimePermissionsRevoked = false;
9970 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9972 boolean changedInstallPermission = false;
9975 ps.installPermissionsFixed = false;
9976 if (!ps.isSharedUser()) {
9977 origPermissions = new PermissionsState(permissionsState);
9978 permissionsState.reset();
9980 // We need to know only about runtime permission changes since the
9981 // calling code always writes the install permissions state but
9982 // the runtime ones are written only if changed. The only cases of
9983 // changed runtime permissions here are promotion of an install to
9984 // runtime and revocation of a runtime from a shared user.
9985 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9986 ps.sharedUser, UserManagerService.getInstance().getUserIds());
9987 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9988 runtimePermissionsRevoked = true;
9993 permissionsState.setGlobalGids(mGlobalGids);
9995 final int N = pkg.requestedPermissions.size();
9996 for (int i=0; i<N; i++) {
9997 final String name = pkg.requestedPermissions.get(i);
9998 final BasePermission bp = mSettings.mPermissions.get(name);
10000 if (DEBUG_INSTALL) {
10001 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10004 if (bp == null || bp.packageSetting == null) {
10005 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10006 Slog.w(TAG, "Unknown permission " + name
10007 + " in package " + pkg.packageName);
10012 final String perm = bp.name;
10013 boolean allowedSig = false;
10014 int grant = GRANT_DENIED;
10016 // Keep track of app op permissions.
10017 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10018 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10019 if (pkgs == null) {
10020 pkgs = new ArraySet<>();
10021 mAppOpPermissionPackages.put(bp.name, pkgs);
10023 pkgs.add(pkg.packageName);
10026 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10027 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10028 >= Build.VERSION_CODES.M;
10030 case PermissionInfo.PROTECTION_NORMAL: {
10031 // For all apps normal permissions are install time ones.
10032 grant = GRANT_INSTALL;
10035 case PermissionInfo.PROTECTION_DANGEROUS: {
10036 // If a permission review is required for legacy apps we represent
10037 // their permissions as always granted runtime ones since we need
10038 // to keep the review required permission flag per user while an
10039 // install permission's state is shared across all users.
10040 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10041 && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10042 // For legacy apps dangerous permissions are install time ones.
10043 grant = GRANT_INSTALL;
10044 } else if (origPermissions.hasInstallPermission(bp.name)) {
10045 // For legacy apps that became modern, install becomes runtime.
10046 grant = GRANT_UPGRADE;
10047 } else if (mPromoteSystemApps
10049 && mExistingSystemPackages.contains(ps.name)) {
10050 // For legacy system apps, install becomes runtime.
10051 // We cannot check hasInstallPermission() for system apps since those
10052 // permissions were granted implicitly and not persisted pre-M.
10053 grant = GRANT_UPGRADE;
10055 // For modern apps keep runtime permissions unchanged.
10056 grant = GRANT_RUNTIME;
10060 case PermissionInfo.PROTECTION_SIGNATURE: {
10061 // For all apps signature permissions are install time ones.
10062 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10064 grant = GRANT_INSTALL;
10069 if (DEBUG_INSTALL) {
10070 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10073 if (grant != GRANT_DENIED) {
10074 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10075 // If this is an existing, non-system package, then
10076 // we can't add any new permissions to it.
10077 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10078 // Except... if this is a permission that was added
10079 // to the platform (note: need to only do this when
10080 // updating the platform).
10081 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10082 grant = GRANT_DENIED;
10088 case GRANT_INSTALL: {
10089 // Revoke this as runtime permission to handle the case of
10090 // a runtime permission being downgraded to an install one.
10091 // Also in permission review mode we keep dangerous permissions
10093 for (int userId : UserManagerService.getInstance().getUserIds()) {
10094 if (origPermissions.getRuntimePermissionState(
10095 bp.name, userId) != null) {
10096 // Revoke the runtime permission and clear the flags.
10097 origPermissions.revokeRuntimePermission(bp, userId);
10098 origPermissions.updatePermissionFlags(bp, userId,
10099 PackageManager.MASK_PERMISSION_FLAGS, 0);
10100 // If we revoked a permission permission, we have to write.
10101 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10102 changedRuntimePermissionUserIds, userId);
10105 // Grant an install permission.
10106 if (permissionsState.grantInstallPermission(bp) !=
10107 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10108 changedInstallPermission = true;
10112 case GRANT_RUNTIME: {
10113 // Grant previously granted runtime permissions.
10114 for (int userId : UserManagerService.getInstance().getUserIds()) {
10115 PermissionState permissionState = origPermissions
10116 .getRuntimePermissionState(bp.name, userId);
10117 int flags = permissionState != null
10118 ? permissionState.getFlags() : 0;
10119 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10120 // Don't propagate the permission in a permission review mode if
10121 // the former was revoked, i.e. marked to not propagate on upgrade.
10122 // Note that in a permission review mode install permissions are
10123 // represented as constantly granted runtime ones since we need to
10124 // keep a per user state associated with the permission. Also the
10125 // revoke on upgrade flag is no longer applicable and is reset.
10126 final boolean revokeOnUpgrade = (flags & PackageManager
10127 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10128 if (revokeOnUpgrade) {
10129 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10130 // Since we changed the flags, we have to write.
10131 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10132 changedRuntimePermissionUserIds, userId);
10134 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10135 if (permissionsState.grantRuntimePermission(bp, userId) ==
10136 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10137 // If we cannot put the permission as it was,
10138 // we have to write.
10139 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10140 changedRuntimePermissionUserIds, userId);
10144 // If the app supports runtime permissions no need for a review.
10145 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10146 && appSupportsRuntimePermissions
10147 && (flags & PackageManager
10148 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10149 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10150 // Since we changed the flags, we have to write.
10151 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10152 changedRuntimePermissionUserIds, userId);
10154 } else if ((mPermissionReviewRequired
10155 || Build.PERMISSIONS_REVIEW_REQUIRED)
10156 && !appSupportsRuntimePermissions) {
10157 // For legacy apps that need a permission review, every new
10158 // runtime permission is granted but it is pending a review.
10159 // We also need to review only platform defined runtime
10160 // permissions as these are the only ones the platform knows
10161 // how to disable the API to simulate revocation as legacy
10162 // apps don't expect to run with revoked permissions.
10163 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10164 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10165 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10166 // We changed the flags, hence have to write.
10167 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10168 changedRuntimePermissionUserIds, userId);
10171 if (permissionsState.grantRuntimePermission(bp, userId)
10172 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10173 // We changed the permission, hence have to write.
10174 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10175 changedRuntimePermissionUserIds, userId);
10178 // Propagate the permission flags.
10179 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10183 case GRANT_UPGRADE: {
10184 // Grant runtime permissions for a previously held install permission.
10185 PermissionState permissionState = origPermissions
10186 .getInstallPermissionState(bp.name);
10187 final int flags = permissionState != null ? permissionState.getFlags() : 0;
10189 if (origPermissions.revokeInstallPermission(bp)
10190 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10191 // We will be transferring the permission flags, so clear them.
10192 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10193 PackageManager.MASK_PERMISSION_FLAGS, 0);
10194 changedInstallPermission = true;
10197 // If the permission is not to be promoted to runtime we ignore it and
10198 // also its other flags as they are not applicable to install permissions.
10199 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10200 for (int userId : currentUserIds) {
10201 if (permissionsState.grantRuntimePermission(bp, userId) !=
10202 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10203 // Transfer the permission flags.
10204 permissionsState.updatePermissionFlags(bp, userId,
10206 // If we granted the permission, we have to write.
10207 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10208 changedRuntimePermissionUserIds, userId);
10215 if (packageOfInterest == null
10216 || packageOfInterest.equals(pkg.packageName)) {
10217 Slog.w(TAG, "Not granting permission " + perm
10218 + " to package " + pkg.packageName
10219 + " because it was previously installed without");
10224 if (permissionsState.revokeInstallPermission(bp) !=
10225 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10226 // Also drop the permission flags.
10227 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10228 PackageManager.MASK_PERMISSION_FLAGS, 0);
10229 changedInstallPermission = true;
10230 Slog.i(TAG, "Un-granting permission " + perm
10231 + " from package " + pkg.packageName
10232 + " (protectionLevel=" + bp.protectionLevel
10233 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10235 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10236 // Don't print warning for app op permissions, since it is fine for them
10237 // not to be granted, there is a UI for the user to decide.
10238 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10239 Slog.w(TAG, "Not granting permission " + perm
10240 + " to package " + pkg.packageName
10241 + " (protectionLevel=" + bp.protectionLevel
10242 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10249 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10250 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10251 // This is the first that we have heard about this package, so the
10252 // permissions we have now selected are fixed until explicitly
10254 ps.installPermissionsFixed = true;
10257 // Persist the runtime permissions state for users with changes. If permissions
10258 // were revoked because no app in the shared user declares them we have to
10259 // write synchronously to avoid losing runtime permissions state.
10260 for (int userId : changedRuntimePermissionUserIds) {
10261 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10264 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10267 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10268 boolean allowed = false;
10269 final int NP = PackageParser.NEW_PERMISSIONS.length;
10270 for (int ip=0; ip<NP; ip++) {
10271 final PackageParser.NewPermissionInfo npi
10272 = PackageParser.NEW_PERMISSIONS[ip];
10273 if (npi.name.equals(perm)
10274 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10276 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10277 + pkg.packageName);
10284 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10285 BasePermission bp, PermissionsState origPermissions) {
10287 allowed = (compareSignatures(
10288 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10289 == PackageManager.SIGNATURE_MATCH)
10290 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10291 == PackageManager.SIGNATURE_MATCH);
10292 if (!allowed && (bp.protectionLevel
10293 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10294 if (isSystemApp(pkg)) {
10295 // For updated system applications, a system permission
10296 // is granted only if it had been defined by the original application.
10297 if (pkg.isUpdatedSystemApp()) {
10298 final PackageSetting sysPs = mSettings
10299 .getDisabledSystemPkgLPr(pkg.packageName);
10300 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10301 // If the original was granted this permission, we take
10302 // that grant decision as read and propagate it to the
10304 if (sysPs.isPrivileged()) {
10308 // The system apk may have been updated with an older
10309 // version of the one on the data partition, but which
10310 // granted a new system permission that it didn't have
10311 // before. In this case we do want to allow the app to
10312 // now get the new permission if the ancestral apk is
10313 // privileged to get it.
10314 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10315 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10316 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10322 // Also if a privileged parent package on the system image or any of
10323 // its children requested a privileged permission, the updated child
10324 // packages can also get the permission.
10325 if (pkg.parentPackage != null) {
10326 final PackageSetting disabledSysParentPs = mSettings
10327 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10328 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10329 && disabledSysParentPs.isPrivileged()) {
10330 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10332 } else if (disabledSysParentPs.pkg.childPackages != null) {
10333 final int count = disabledSysParentPs.pkg.childPackages.size();
10334 for (int i = 0; i < count; i++) {
10335 PackageParser.Package disabledSysChildPkg =
10336 disabledSysParentPs.pkg.childPackages.get(i);
10337 if (isPackageRequestingPermission(disabledSysChildPkg,
10348 allowed = isPrivilegedApp(pkg);
10353 if (!allowed && (bp.protectionLevel
10354 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10355 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10356 // If this was a previously normal/dangerous permission that got moved
10357 // to a system permission as part of the runtime permission redesign, then
10358 // we still want to blindly grant it to old apps.
10361 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10362 && pkg.packageName.equals(mRequiredInstallerPackage)) {
10363 // If this permission is to be granted to the system installer and
10364 // this app is an installer, then it gets the permission.
10367 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10368 && pkg.packageName.equals(mRequiredVerifierPackage)) {
10369 // If this permission is to be granted to the system verifier and
10370 // this app is a verifier, then it gets the permission.
10373 if (!allowed && (bp.protectionLevel
10374 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10375 && isSystemApp(pkg)) {
10376 // Any pre-installed system app is allowed to get this permission.
10379 if (!allowed && (bp.protectionLevel
10380 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10381 // For development permissions, a development permission
10382 // is granted only if it was already granted.
10383 allowed = origPermissions.hasInstallPermission(perm);
10385 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10386 && pkg.packageName.equals(mSetupWizardPackage)) {
10387 // If this permission is to be granted to the system setup wizard and
10388 // this app is a setup wizard, then it gets the permission.
10395 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10396 final int permCount = pkg.requestedPermissions.size();
10397 for (int j = 0; j < permCount; j++) {
10398 String requestedPermission = pkg.requestedPermissions.get(j);
10399 if (permission.equals(requestedPermission)) {
10406 final class ActivityIntentResolver
10407 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10408 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10409 boolean defaultOnly, int userId) {
10410 if (!sUserManager.exists(userId)) return null;
10411 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10412 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10415 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10417 if (!sUserManager.exists(userId)) return null;
10419 return super.queryIntent(intent, resolvedType,
10420 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10423 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10424 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10425 if (!sUserManager.exists(userId)) return null;
10426 if (packageActivities == null) {
10430 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10431 final int N = packageActivities.size();
10432 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10433 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10435 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10436 for (int i = 0; i < N; ++i) {
10437 intentFilters = packageActivities.get(i).intents;
10438 if (intentFilters != null && intentFilters.size() > 0) {
10439 PackageParser.ActivityIntentInfo[] array =
10440 new PackageParser.ActivityIntentInfo[intentFilters.size()];
10441 intentFilters.toArray(array);
10442 listCut.add(array);
10445 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10449 * Finds a privileged activity that matches the specified activity names.
10451 private PackageParser.Activity findMatchingActivity(
10452 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10453 for (PackageParser.Activity sysActivity : activityList) {
10454 if (sysActivity.info.name.equals(activityInfo.name)) {
10455 return sysActivity;
10457 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10458 return sysActivity;
10460 if (sysActivity.info.targetActivity != null) {
10461 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10462 return sysActivity;
10464 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10465 return sysActivity;
10472 public class IterGenerator<E> {
10473 public Iterator<E> generate(ActivityIntentInfo info) {
10478 public class ActionIterGenerator extends IterGenerator<String> {
10480 public Iterator<String> generate(ActivityIntentInfo info) {
10481 return info.actionsIterator();
10485 public class CategoriesIterGenerator extends IterGenerator<String> {
10487 public Iterator<String> generate(ActivityIntentInfo info) {
10488 return info.categoriesIterator();
10492 public class SchemesIterGenerator extends IterGenerator<String> {
10494 public Iterator<String> generate(ActivityIntentInfo info) {
10495 return info.schemesIterator();
10499 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10501 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10502 return info.authoritiesIterator();
10507 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10508 * MODIFIED. Do not pass in a list that should not be changed.
10510 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10511 IterGenerator<T> generator, Iterator<T> searchIterator) {
10512 // loop through the set of actions; every one must be found in the intent filter
10513 while (searchIterator.hasNext()) {
10514 // we must have at least one filter in the list to consider a match
10515 if (intentList.size() == 0) {
10519 final T searchAction = searchIterator.next();
10521 // loop through the set of intent filters
10522 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10523 while (intentIter.hasNext()) {
10524 final ActivityIntentInfo intentInfo = intentIter.next();
10525 boolean selectionFound = false;
10527 // loop through the intent filter's selection criteria; at least one
10528 // of them must match the searched criteria
10529 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10530 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10531 final T intentSelection = intentSelectionIter.next();
10532 if (intentSelection != null && intentSelection.equals(searchAction)) {
10533 selectionFound = true;
10538 // the selection criteria wasn't found in this filter's set; this filter
10539 // is not a potential match
10540 if (!selectionFound) {
10541 intentIter.remove();
10547 private boolean isProtectedAction(ActivityIntentInfo filter) {
10548 final Iterator<String> actionsIter = filter.actionsIterator();
10549 while (actionsIter != null && actionsIter.hasNext()) {
10550 final String filterAction = actionsIter.next();
10551 if (PROTECTED_ACTIONS.contains(filterAction)) {
10559 * Adjusts the priority of the given intent filter according to policy.
10562 * <li>The priority for non privileged applications is capped to '0'</li>
10563 * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10564 * <li>The priority for unbundled updates to privileged applications is capped to the
10565 * priority defined on the system partition</li>
10568 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10569 * allowed to obtain any priority on any action.
10571 private void adjustPriority(
10572 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10573 // nothing to do; priority is fine as-is
10574 if (intent.getPriority() <= 0) {
10578 final ActivityInfo activityInfo = intent.activity.info;
10579 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10581 final boolean privilegedApp =
10582 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10583 if (!privilegedApp) {
10584 // non-privileged applications can never define a priority >0
10585 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10586 + " package: " + applicationInfo.packageName
10587 + " activity: " + intent.activity.className
10588 + " origPrio: " + intent.getPriority());
10589 intent.setPriority(0);
10593 if (systemActivities == null) {
10594 // the system package is not disabled; we're parsing the system partition
10595 if (isProtectedAction(intent)) {
10596 if (mDeferProtectedFilters) {
10597 // We can't deal with these just yet. No component should ever obtain a
10598 // >0 priority for a protected actions, with ONE exception -- the setup
10599 // wizard. The setup wizard, however, cannot be known until we're able to
10600 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10601 // until all intent filters have been processed. Chicken, meet egg.
10602 // Let the filter temporarily have a high priority and rectify the
10603 // priorities after all system packages have been scanned.
10604 mProtectedFilters.add(intent);
10605 if (DEBUG_FILTERS) {
10606 Slog.i(TAG, "Protected action; save for later;"
10607 + " package: " + applicationInfo.packageName
10608 + " activity: " + intent.activity.className
10609 + " origPrio: " + intent.getPriority());
10613 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10614 Slog.i(TAG, "No setup wizard;"
10615 + " All protected intents capped to priority 0");
10617 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10618 if (DEBUG_FILTERS) {
10619 Slog.i(TAG, "Found setup wizard;"
10620 + " allow priority " + intent.getPriority() + ";"
10621 + " package: " + intent.activity.info.packageName
10622 + " activity: " + intent.activity.className
10623 + " priority: " + intent.getPriority());
10625 // setup wizard gets whatever it wants
10628 Slog.w(TAG, "Protected action; cap priority to 0;"
10629 + " package: " + intent.activity.info.packageName
10630 + " activity: " + intent.activity.className
10631 + " origPrio: " + intent.getPriority());
10632 intent.setPriority(0);
10636 // privileged apps on the system image get whatever priority they request
10640 // privileged app unbundled update ... try to find the same activity
10641 final PackageParser.Activity foundActivity =
10642 findMatchingActivity(systemActivities, activityInfo);
10643 if (foundActivity == null) {
10644 // this is a new activity; it cannot obtain >0 priority
10645 if (DEBUG_FILTERS) {
10646 Slog.i(TAG, "New activity; cap priority to 0;"
10647 + " package: " + applicationInfo.packageName
10648 + " activity: " + intent.activity.className
10649 + " origPrio: " + intent.getPriority());
10651 intent.setPriority(0);
10655 // found activity, now check for filter equivalence
10657 // a shallow copy is enough; we modify the list, not its contents
10658 final List<ActivityIntentInfo> intentListCopy =
10659 new ArrayList<>(foundActivity.intents);
10660 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10662 // find matching action subsets
10663 final Iterator<String> actionsIterator = intent.actionsIterator();
10664 if (actionsIterator != null) {
10665 getIntentListSubset(
10666 intentListCopy, new ActionIterGenerator(), actionsIterator);
10667 if (intentListCopy.size() == 0) {
10668 // no more intents to match; we're not equivalent
10669 if (DEBUG_FILTERS) {
10670 Slog.i(TAG, "Mismatched action; cap priority to 0;"
10671 + " package: " + applicationInfo.packageName
10672 + " activity: " + intent.activity.className
10673 + " origPrio: " + intent.getPriority());
10675 intent.setPriority(0);
10680 // find matching category subsets
10681 final Iterator<String> categoriesIterator = intent.categoriesIterator();
10682 if (categoriesIterator != null) {
10683 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10684 categoriesIterator);
10685 if (intentListCopy.size() == 0) {
10686 // no more intents to match; we're not equivalent
10687 if (DEBUG_FILTERS) {
10688 Slog.i(TAG, "Mismatched category; cap priority to 0;"
10689 + " package: " + applicationInfo.packageName
10690 + " activity: " + intent.activity.className
10691 + " origPrio: " + intent.getPriority());
10693 intent.setPriority(0);
10698 // find matching schemes subsets
10699 final Iterator<String> schemesIterator = intent.schemesIterator();
10700 if (schemesIterator != null) {
10701 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10703 if (intentListCopy.size() == 0) {
10704 // no more intents to match; we're not equivalent
10705 if (DEBUG_FILTERS) {
10706 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10707 + " package: " + applicationInfo.packageName
10708 + " activity: " + intent.activity.className
10709 + " origPrio: " + intent.getPriority());
10711 intent.setPriority(0);
10716 // find matching authorities subsets
10717 final Iterator<IntentFilter.AuthorityEntry>
10718 authoritiesIterator = intent.authoritiesIterator();
10719 if (authoritiesIterator != null) {
10720 getIntentListSubset(intentListCopy,
10721 new AuthoritiesIterGenerator(),
10722 authoritiesIterator);
10723 if (intentListCopy.size() == 0) {
10724 // no more intents to match; we're not equivalent
10725 if (DEBUG_FILTERS) {
10726 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10727 + " package: " + applicationInfo.packageName
10728 + " activity: " + intent.activity.className
10729 + " origPrio: " + intent.getPriority());
10731 intent.setPriority(0);
10736 // we found matching filter(s); app gets the max priority of all intents
10737 int cappedPriority = 0;
10738 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10739 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10741 if (intent.getPriority() > cappedPriority) {
10742 if (DEBUG_FILTERS) {
10743 Slog.i(TAG, "Found matching filter(s);"
10744 + " cap priority to " + cappedPriority + ";"
10745 + " package: " + applicationInfo.packageName
10746 + " activity: " + intent.activity.className
10747 + " origPrio: " + intent.getPriority());
10749 intent.setPriority(cappedPriority);
10752 // all this for nothing; the requested priority was <= what was on the system
10755 public final void addActivity(PackageParser.Activity a, String type) {
10756 mActivities.put(a.getComponentName(), a);
10757 if (DEBUG_SHOW_INFO)
10759 TAG, " " + type + " " +
10760 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10761 if (DEBUG_SHOW_INFO)
10762 Log.v(TAG, " Class=" + a.info.name);
10763 final int NI = a.intents.size();
10764 for (int j=0; j<NI; j++) {
10765 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10766 if ("activity".equals(type)) {
10767 final PackageSetting ps =
10768 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10769 final List<PackageParser.Activity> systemActivities =
10770 ps != null && ps.pkg != null ? ps.pkg.activities : null;
10771 adjustPriority(systemActivities, intent);
10773 if (DEBUG_SHOW_INFO) {
10774 Log.v(TAG, " IntentFilter:");
10775 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10777 if (!intent.debugCheck()) {
10778 Log.w(TAG, "==> For Activity " + a.info.name);
10784 public final void removeActivity(PackageParser.Activity a, String type) {
10785 mActivities.remove(a.getComponentName());
10786 if (DEBUG_SHOW_INFO) {
10787 Log.v(TAG, " " + type + " "
10788 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10789 : a.info.name) + ":");
10790 Log.v(TAG, " Class=" + a.info.name);
10792 final int NI = a.intents.size();
10793 for (int j=0; j<NI; j++) {
10794 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10795 if (DEBUG_SHOW_INFO) {
10796 Log.v(TAG, " IntentFilter:");
10797 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10799 removeFilter(intent);
10804 protected boolean allowFilterResult(
10805 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10806 ActivityInfo filterAi = filter.activity.info;
10807 for (int i=dest.size()-1; i>=0; i--) {
10808 ActivityInfo destAi = dest.get(i).activityInfo;
10809 if (destAi.name == filterAi.name
10810 && destAi.packageName == filterAi.packageName) {
10818 protected ActivityIntentInfo[] newArray(int size) {
10819 return new ActivityIntentInfo[size];
10823 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10824 if (!sUserManager.exists(userId)) return true;
10825 PackageParser.Package p = filter.activity.owner;
10827 PackageSetting ps = (PackageSetting)p.mExtras;
10829 // System apps are never considered stopped for purposes of
10830 // filtering, because there may be no way for the user to
10831 // actually re-launch them.
10832 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10833 && ps.getStopped(userId);
10840 protected boolean isPackageForFilter(String packageName,
10841 PackageParser.ActivityIntentInfo info) {
10842 return packageName.equals(info.activity.owner.packageName);
10846 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10847 int match, int userId) {
10848 if (!sUserManager.exists(userId)) return null;
10849 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10852 final PackageParser.Activity activity = info.activity;
10853 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10857 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10858 ps.readUserState(userId), userId);
10862 final ResolveInfo res = new ResolveInfo();
10863 res.activityInfo = ai;
10864 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10867 if (info != null) {
10868 res.handleAllWebDataURI = info.handleAllWebDataURI();
10870 res.priority = info.getPriority();
10871 res.preferredOrder = activity.owner.mPreferredOrder;
10872 //System.out.println("Result: " + res.activityInfo.className +
10873 // " = " + res.priority);
10875 res.isDefault = info.hasDefault;
10876 res.labelRes = info.labelRes;
10877 res.nonLocalizedLabel = info.nonLocalizedLabel;
10878 if (userNeedsBadging(userId)) {
10879 res.noResourceId = true;
10881 res.icon = info.icon;
10883 res.iconResourceId = info.icon;
10884 res.system = res.activityInfo.applicationInfo.isSystemApp();
10889 protected void sortResults(List<ResolveInfo> results) {
10890 Collections.sort(results, mResolvePrioritySorter);
10894 protected void dumpFilter(PrintWriter out, String prefix,
10895 PackageParser.ActivityIntentInfo filter) {
10896 out.print(prefix); out.print(
10897 Integer.toHexString(System.identityHashCode(filter.activity)));
10899 filter.activity.printComponentShortName(out);
10900 out.print(" filter ");
10901 out.println(Integer.toHexString(System.identityHashCode(filter)));
10905 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10906 return filter.activity;
10909 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10910 PackageParser.Activity activity = (PackageParser.Activity)label;
10911 out.print(prefix); out.print(
10912 Integer.toHexString(System.identityHashCode(activity)));
10914 activity.printComponentShortName(out);
10916 out.print(" ("); out.print(count); out.print(" filters)");
10921 // Keys are String (activity class name), values are Activity.
10922 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10923 = new ArrayMap<ComponentName, PackageParser.Activity>();
10924 private int mFlags;
10927 private final class ServiceIntentResolver
10928 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10929 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10930 boolean defaultOnly, int userId) {
10931 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10932 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10935 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10937 if (!sUserManager.exists(userId)) return null;
10939 return super.queryIntent(intent, resolvedType,
10940 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10943 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10944 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10945 if (!sUserManager.exists(userId)) return null;
10946 if (packageServices == null) {
10950 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10951 final int N = packageServices.size();
10952 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10953 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10955 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10956 for (int i = 0; i < N; ++i) {
10957 intentFilters = packageServices.get(i).intents;
10958 if (intentFilters != null && intentFilters.size() > 0) {
10959 PackageParser.ServiceIntentInfo[] array =
10960 new PackageParser.ServiceIntentInfo[intentFilters.size()];
10961 intentFilters.toArray(array);
10962 listCut.add(array);
10965 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10968 public final void addService(PackageParser.Service s) {
10969 mServices.put(s.getComponentName(), s);
10970 if (DEBUG_SHOW_INFO) {
10972 + (s.info.nonLocalizedLabel != null
10973 ? s.info.nonLocalizedLabel : s.info.name) + ":");
10974 Log.v(TAG, " Class=" + s.info.name);
10976 final int NI = s.intents.size();
10978 for (j=0; j<NI; j++) {
10979 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10980 if (DEBUG_SHOW_INFO) {
10981 Log.v(TAG, " IntentFilter:");
10982 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
10984 if (!intent.debugCheck()) {
10985 Log.w(TAG, "==> For Service " + s.info.name);
10991 public final void removeService(PackageParser.Service s) {
10992 mServices.remove(s.getComponentName());
10993 if (DEBUG_SHOW_INFO) {
10994 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
10995 ? s.info.nonLocalizedLabel : s.info.name) + ":");
10996 Log.v(TAG, " Class=" + s.info.name);
10998 final int NI = s.intents.size();
11000 for (j=0; j<NI; j++) {
11001 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11002 if (DEBUG_SHOW_INFO) {
11003 Log.v(TAG, " IntentFilter:");
11004 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11006 removeFilter(intent);
11011 protected boolean allowFilterResult(
11012 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11013 ServiceInfo filterSi = filter.service.info;
11014 for (int i=dest.size()-1; i>=0; i--) {
11015 ServiceInfo destAi = dest.get(i).serviceInfo;
11016 if (destAi.name == filterSi.name
11017 && destAi.packageName == filterSi.packageName) {
11025 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11026 return new PackageParser.ServiceIntentInfo[size];
11030 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11031 if (!sUserManager.exists(userId)) return true;
11032 PackageParser.Package p = filter.service.owner;
11034 PackageSetting ps = (PackageSetting)p.mExtras;
11036 // System apps are never considered stopped for purposes of
11037 // filtering, because there may be no way for the user to
11038 // actually re-launch them.
11039 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11040 && ps.getStopped(userId);
11047 protected boolean isPackageForFilter(String packageName,
11048 PackageParser.ServiceIntentInfo info) {
11049 return packageName.equals(info.service.owner.packageName);
11053 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11054 int match, int userId) {
11055 if (!sUserManager.exists(userId)) return null;
11056 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11057 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11060 final PackageParser.Service service = info.service;
11061 PackageSetting ps = (PackageSetting) service.owner.mExtras;
11065 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11066 ps.readUserState(userId), userId);
11070 final ResolveInfo res = new ResolveInfo();
11071 res.serviceInfo = si;
11072 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11073 res.filter = filter;
11075 res.priority = info.getPriority();
11076 res.preferredOrder = service.owner.mPreferredOrder;
11078 res.isDefault = info.hasDefault;
11079 res.labelRes = info.labelRes;
11080 res.nonLocalizedLabel = info.nonLocalizedLabel;
11081 res.icon = info.icon;
11082 res.system = res.serviceInfo.applicationInfo.isSystemApp();
11087 protected void sortResults(List<ResolveInfo> results) {
11088 Collections.sort(results, mResolvePrioritySorter);
11092 protected void dumpFilter(PrintWriter out, String prefix,
11093 PackageParser.ServiceIntentInfo filter) {
11094 out.print(prefix); out.print(
11095 Integer.toHexString(System.identityHashCode(filter.service)));
11097 filter.service.printComponentShortName(out);
11098 out.print(" filter ");
11099 out.println(Integer.toHexString(System.identityHashCode(filter)));
11103 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11104 return filter.service;
11107 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11108 PackageParser.Service service = (PackageParser.Service)label;
11109 out.print(prefix); out.print(
11110 Integer.toHexString(System.identityHashCode(service)));
11112 service.printComponentShortName(out);
11114 out.print(" ("); out.print(count); out.print(" filters)");
11119 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11120 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11121 // final List<ResolveInfo> retList = Lists.newArrayList();
11122 // while (i.hasNext()) {
11123 // final ResolveInfo resolveInfo = (ResolveInfo) i;
11124 // if (isEnabledLP(resolveInfo.serviceInfo)) {
11125 // retList.add(resolveInfo);
11131 // Keys are String (activity class name), values are Activity.
11132 private final ArrayMap<ComponentName, PackageParser.Service> mServices
11133 = new ArrayMap<ComponentName, PackageParser.Service>();
11134 private int mFlags;
11137 private final class ProviderIntentResolver
11138 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11139 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11140 boolean defaultOnly, int userId) {
11141 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11142 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11145 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11147 if (!sUserManager.exists(userId))
11150 return super.queryIntent(intent, resolvedType,
11151 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11154 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11155 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11156 if (!sUserManager.exists(userId))
11158 if (packageProviders == null) {
11162 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11163 final int N = packageProviders.size();
11164 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11165 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11167 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11168 for (int i = 0; i < N; ++i) {
11169 intentFilters = packageProviders.get(i).intents;
11170 if (intentFilters != null && intentFilters.size() > 0) {
11171 PackageParser.ProviderIntentInfo[] array =
11172 new PackageParser.ProviderIntentInfo[intentFilters.size()];
11173 intentFilters.toArray(array);
11174 listCut.add(array);
11177 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11180 public final void addProvider(PackageParser.Provider p) {
11181 if (mProviders.containsKey(p.getComponentName())) {
11182 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11186 mProviders.put(p.getComponentName(), p);
11187 if (DEBUG_SHOW_INFO) {
11189 + (p.info.nonLocalizedLabel != null
11190 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11191 Log.v(TAG, " Class=" + p.info.name);
11193 final int NI = p.intents.size();
11195 for (j = 0; j < NI; j++) {
11196 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11197 if (DEBUG_SHOW_INFO) {
11198 Log.v(TAG, " IntentFilter:");
11199 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11201 if (!intent.debugCheck()) {
11202 Log.w(TAG, "==> For Provider " + p.info.name);
11208 public final void removeProvider(PackageParser.Provider p) {
11209 mProviders.remove(p.getComponentName());
11210 if (DEBUG_SHOW_INFO) {
11211 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
11212 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11213 Log.v(TAG, " Class=" + p.info.name);
11215 final int NI = p.intents.size();
11217 for (j = 0; j < NI; j++) {
11218 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11219 if (DEBUG_SHOW_INFO) {
11220 Log.v(TAG, " IntentFilter:");
11221 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
11223 removeFilter(intent);
11228 protected boolean allowFilterResult(
11229 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11230 ProviderInfo filterPi = filter.provider.info;
11231 for (int i = dest.size() - 1; i >= 0; i--) {
11232 ProviderInfo destPi = dest.get(i).providerInfo;
11233 if (destPi.name == filterPi.name
11234 && destPi.packageName == filterPi.packageName) {
11242 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11243 return new PackageParser.ProviderIntentInfo[size];
11247 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11248 if (!sUserManager.exists(userId))
11250 PackageParser.Package p = filter.provider.owner;
11252 PackageSetting ps = (PackageSetting) p.mExtras;
11254 // System apps are never considered stopped for purposes of
11255 // filtering, because there may be no way for the user to
11256 // actually re-launch them.
11257 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11258 && ps.getStopped(userId);
11265 protected boolean isPackageForFilter(String packageName,
11266 PackageParser.ProviderIntentInfo info) {
11267 return packageName.equals(info.provider.owner.packageName);
11271 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11272 int match, int userId) {
11273 if (!sUserManager.exists(userId))
11275 final PackageParser.ProviderIntentInfo info = filter;
11276 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11279 final PackageParser.Provider provider = info.provider;
11280 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11284 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11285 ps.readUserState(userId), userId);
11289 final ResolveInfo res = new ResolveInfo();
11290 res.providerInfo = pi;
11291 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11292 res.filter = filter;
11294 res.priority = info.getPriority();
11295 res.preferredOrder = provider.owner.mPreferredOrder;
11297 res.isDefault = info.hasDefault;
11298 res.labelRes = info.labelRes;
11299 res.nonLocalizedLabel = info.nonLocalizedLabel;
11300 res.icon = info.icon;
11301 res.system = res.providerInfo.applicationInfo.isSystemApp();
11306 protected void sortResults(List<ResolveInfo> results) {
11307 Collections.sort(results, mResolvePrioritySorter);
11311 protected void dumpFilter(PrintWriter out, String prefix,
11312 PackageParser.ProviderIntentInfo filter) {
11315 Integer.toHexString(System.identityHashCode(filter.provider)));
11317 filter.provider.printComponentShortName(out);
11318 out.print(" filter ");
11319 out.println(Integer.toHexString(System.identityHashCode(filter)));
11323 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11324 return filter.provider;
11327 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11328 PackageParser.Provider provider = (PackageParser.Provider)label;
11329 out.print(prefix); out.print(
11330 Integer.toHexString(System.identityHashCode(provider)));
11332 provider.printComponentShortName(out);
11334 out.print(" ("); out.print(count); out.print(" filters)");
11339 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11340 = new ArrayMap<ComponentName, PackageParser.Provider>();
11341 private int mFlags;
11344 private static final class EphemeralIntentResolver
11345 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11347 * The result that has the highest defined order. Ordering applies on a
11348 * per-package basis. Mapping is from package name to Pair of order and
11349 * EphemeralResolveInfo.
11351 * NOTE: This is implemented as a field variable for convenience and efficiency.
11352 * By having a field variable, we're able to track filter ordering as soon as
11353 * a non-zero order is defined. Otherwise, multiple loops across the result set
11354 * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11355 * this needs to be contained entirely within {@link #filterResults()}.
11357 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11360 protected EphemeralResolveIntentInfo[] newArray(int size) {
11361 return new EphemeralResolveIntentInfo[size];
11365 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11370 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11372 if (!sUserManager.exists(userId)) {
11375 final String packageName = info.getEphemeralResolveInfo().getPackageName();
11376 final Integer order = info.getOrder();
11377 final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11378 mOrderResult.get(packageName);
11379 // ordering is enabled and this item's order isn't high enough
11380 if (lastOrderResult != null && lastOrderResult.first >= order) {
11383 final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11385 // non-zero order, enable ordering
11386 mOrderResult.put(packageName, new Pair<>(order, res));
11392 protected void filterResults(List<EphemeralResolveInfo> results) {
11393 // only do work if ordering is enabled [most of the time it won't be]
11394 if (mOrderResult.size() == 0) {
11397 int resultSize = results.size();
11398 for (int i = 0; i < resultSize; i++) {
11399 final EphemeralResolveInfo info = results.get(i);
11400 final String packageName = info.getPackageName();
11401 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11402 if (savedInfo == null) {
11403 // package doesn't having ordering
11406 if (savedInfo.second == info) {
11407 // circled back to the highest ordered item; remove from order list
11408 mOrderResult.remove(savedInfo);
11409 if (mOrderResult.size() == 0) {
11410 // no more ordered items
11415 // item has a worse order, remove it from the result list
11423 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11424 new Comparator<ResolveInfo>() {
11425 public int compare(ResolveInfo r1, ResolveInfo r2) {
11426 int v1 = r1.priority;
11427 int v2 = r2.priority;
11428 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11430 return (v1 > v2) ? -1 : 1;
11432 v1 = r1.preferredOrder;
11433 v2 = r2.preferredOrder;
11435 return (v1 > v2) ? -1 : 1;
11437 if (r1.isDefault != r2.isDefault) {
11438 return r1.isDefault ? -1 : 1;
11442 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11444 return (v1 > v2) ? -1 : 1;
11446 if (r1.system != r2.system) {
11447 return r1.system ? -1 : 1;
11449 if (r1.activityInfo != null) {
11450 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11452 if (r1.serviceInfo != null) {
11453 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11455 if (r1.providerInfo != null) {
11456 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11462 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11463 new Comparator<ProviderInfo>() {
11464 public int compare(ProviderInfo p1, ProviderInfo p2) {
11465 final int v1 = p1.initOrder;
11466 final int v2 = p2.initOrder;
11467 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11471 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11472 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11473 final int[] userIds) {
11474 mHandler.post(new Runnable() {
11476 public void run() {
11478 final IActivityManager am = ActivityManagerNative.getDefault();
11479 if (am == null) return;
11480 final int[] resolvedUserIds;
11481 if (userIds == null) {
11482 resolvedUserIds = am.getRunningUserIds();
11484 resolvedUserIds = userIds;
11486 for (int id : resolvedUserIds) {
11487 final Intent intent = new Intent(action,
11488 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11489 if (extras != null) {
11490 intent.putExtras(extras);
11492 if (targetPkg != null) {
11493 intent.setPackage(targetPkg);
11495 // Modify the UID when posting to other users
11496 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11497 if (uid > 0 && UserHandle.getUserId(uid) != id) {
11498 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11499 intent.putExtra(Intent.EXTRA_UID, uid);
11501 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11502 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11503 if (DEBUG_BROADCASTS) {
11504 RuntimeException here = new RuntimeException("here");
11505 here.fillInStackTrace();
11506 Slog.d(TAG, "Sending to user " + id + ": "
11507 + intent.toShortString(false, true, false, false)
11508 + " " + intent.getExtras(), here);
11510 am.broadcastIntent(null, intent, null, finishedReceiver,
11511 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11512 null, finishedReceiver != null, false, id);
11514 } catch (RemoteException ex) {
11521 * Check if the external storage media is available. This is true if there
11522 * is a mounted external storage medium or if the external storage is
11525 private boolean isExternalMediaAvailable() {
11526 return mMediaMounted || Environment.isExternalStorageEmulated();
11530 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11532 synchronized (mPackages) {
11533 if (!isExternalMediaAvailable()) {
11534 // If the external storage is no longer mounted at this point,
11535 // the caller may not have been able to delete all of this
11536 // packages files and can not delete any more. Bail.
11539 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11540 if (lastPackage != null) {
11541 pkgs.remove(lastPackage);
11543 if (pkgs.size() > 0) {
11544 return pkgs.get(0);
11550 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11551 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11552 userId, andCode ? 1 : 0, packageName);
11553 if (mSystemReady) {
11554 msg.sendToTarget();
11556 if (mPostSystemReadyMessages == null) {
11557 mPostSystemReadyMessages = new ArrayList<>();
11559 mPostSystemReadyMessages.add(msg);
11563 void startCleaningPackages() {
11565 if (!isExternalMediaAvailable()) {
11568 synchronized (mPackages) {
11569 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11573 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11574 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11575 IActivityManager am = ActivityManagerNative.getDefault();
11578 am.startService(null, intent, null, mContext.getOpPackageName(),
11579 UserHandle.USER_SYSTEM);
11580 } catch (RemoteException e) {
11586 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11587 int installFlags, String installerPackageName, int userId) {
11588 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11590 final int callingUid = Binder.getCallingUid();
11591 enforceCrossUserPermission(callingUid, userId,
11592 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11594 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11596 if (observer != null) {
11597 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11599 } catch (RemoteException re) {
11604 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11605 installFlags |= PackageManager.INSTALL_FROM_ADB;
11608 // Caller holds INSTALL_PACKAGES permission, so we're less strict
11609 // about installerPackageName.
11611 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11612 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11616 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11617 user = UserHandle.ALL;
11619 user = new UserHandle(userId);
11622 // Only system components can circumvent runtime permissions when installing.
11623 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11624 && mContext.checkCallingOrSelfPermission(Manifest.permission
11625 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11626 throw new SecurityException("You need the "
11627 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11628 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11631 final File originFile = new File(originPath);
11632 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11634 final Message msg = mHandler.obtainMessage(INIT_COPY);
11635 final VerificationInfo verificationInfo = new VerificationInfo(
11636 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11637 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11638 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11639 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11640 null /*certificates*/);
11641 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11644 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11645 System.identityHashCode(msg.obj));
11646 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11647 System.identityHashCode(msg.obj));
11649 mHandler.sendMessage(msg);
11652 void installStage(String packageName, File stagedDir, String stagedCid,
11653 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11654 String installerPackageName, int installerUid, UserHandle user,
11655 Certificate[][] certificates) {
11656 if (DEBUG_EPHEMERAL) {
11657 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11658 Slog.d(TAG, "Ephemeral install of " + packageName);
11661 final VerificationInfo verificationInfo = new VerificationInfo(
11662 sessionParams.originatingUri, sessionParams.referrerUri,
11663 sessionParams.originatingUid, installerUid);
11665 final OriginInfo origin;
11666 if (stagedDir != null) {
11667 origin = OriginInfo.fromStagedFile(stagedDir);
11669 origin = OriginInfo.fromStagedContainer(stagedCid);
11672 final Message msg = mHandler.obtainMessage(INIT_COPY);
11673 final InstallParams params = new InstallParams(origin, null, observer,
11674 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11675 verificationInfo, user, sessionParams.abiOverride,
11676 sessionParams.grantedRuntimePermissions, certificates);
11677 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11680 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11681 System.identityHashCode(msg.obj));
11682 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11683 System.identityHashCode(msg.obj));
11685 mHandler.sendMessage(msg);
11688 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11690 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11691 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11694 private void sendPackageAddedForUser(String packageName, boolean isSystem,
11695 int appId, int userId) {
11696 Bundle extras = new Bundle(1);
11697 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11699 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11700 packageName, extras, 0, null, null, new int[] {userId});
11702 IActivityManager am = ActivityManagerNative.getDefault();
11703 if (isSystem && am.isUserRunning(userId, 0)) {
11704 // The just-installed/enabled app is bundled on the system, so presumed
11705 // to be able to run automatically without needing an explicit launch.
11706 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11707 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11708 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11709 .setPackage(packageName);
11710 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11711 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11713 } catch (RemoteException e) {
11714 // shouldn't happen
11715 Slog.w(TAG, "Unable to bootstrap installed package", e);
11720 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11722 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11723 PackageSetting pkgSetting;
11724 final int uid = Binder.getCallingUid();
11725 enforceCrossUserPermission(uid, userId,
11726 true /* requireFullPermission */, true /* checkShell */,
11727 "setApplicationHiddenSetting for user " + userId);
11729 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11730 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11734 long callingId = Binder.clearCallingIdentity();
11736 boolean sendAdded = false;
11737 boolean sendRemoved = false;
11739 synchronized (mPackages) {
11740 pkgSetting = mSettings.mPackages.get(packageName);
11741 if (pkgSetting == null) {
11744 // Do not allow "android" is being disabled
11745 if ("android".equals(packageName)) {
11746 Slog.w(TAG, "Cannot hide package: android");
11749 // Only allow protected packages to hide themselves.
11750 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11751 && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11752 Slog.w(TAG, "Not hiding protected package: " + packageName);
11756 if (pkgSetting.getHidden(userId) != hidden) {
11757 pkgSetting.setHidden(hidden, userId);
11758 mSettings.writePackageRestrictionsLPr(userId);
11760 sendRemoved = true;
11767 sendPackageAddedForUser(packageName, pkgSetting, userId);
11771 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11773 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11777 Binder.restoreCallingIdentity(callingId);
11782 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11784 final PackageRemovedInfo info = new PackageRemovedInfo();
11785 info.removedPackage = packageName;
11786 info.removedUsers = new int[] {userId};
11787 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11788 info.sendPackageRemovedBroadcasts(true /*killApp*/);
11791 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11792 if (pkgList.length > 0) {
11793 Bundle extras = new Bundle(1);
11794 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11796 sendPackageBroadcast(
11797 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11798 : Intent.ACTION_PACKAGES_UNSUSPENDED,
11799 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11800 new int[] {userId});
11805 * Returns true if application is not found or there was an error. Otherwise it returns
11806 * the hidden state of the package for the given user.
11809 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11810 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11811 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11812 true /* requireFullPermission */, false /* checkShell */,
11813 "getApplicationHidden for user " + userId);
11814 PackageSetting pkgSetting;
11815 long callingId = Binder.clearCallingIdentity();
11818 synchronized (mPackages) {
11819 pkgSetting = mSettings.mPackages.get(packageName);
11820 if (pkgSetting == null) {
11823 return pkgSetting.getHidden(userId);
11826 Binder.restoreCallingIdentity(callingId);
11834 public int installExistingPackageAsUser(String packageName, int userId) {
11835 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11837 PackageSetting pkgSetting;
11838 final int uid = Binder.getCallingUid();
11839 enforceCrossUserPermission(uid, userId,
11840 true /* requireFullPermission */, true /* checkShell */,
11841 "installExistingPackage for user " + userId);
11842 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11843 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11846 long callingId = Binder.clearCallingIdentity();
11848 boolean installed = false;
11851 synchronized (mPackages) {
11852 pkgSetting = mSettings.mPackages.get(packageName);
11853 if (pkgSetting == null) {
11854 return PackageManager.INSTALL_FAILED_INVALID_URI;
11856 if (!pkgSetting.getInstalled(userId)) {
11857 pkgSetting.setInstalled(true, userId);
11858 pkgSetting.setHidden(false, userId);
11859 mSettings.writePackageRestrictionsLPr(userId);
11865 if (pkgSetting.pkg != null) {
11866 synchronized (mInstallLock) {
11867 // We don't need to freeze for a brand new install
11868 prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11871 sendPackageAddedForUser(packageName, pkgSetting, userId);
11874 Binder.restoreCallingIdentity(callingId);
11877 return PackageManager.INSTALL_SUCCEEDED;
11880 boolean isUserRestricted(int userId, String restrictionKey) {
11881 Bundle restrictions = sUserManager.getUserRestrictions(userId);
11882 if (restrictions.getBoolean(restrictionKey, false)) {
11883 Log.w(TAG, "User is restricted: " + restrictionKey);
11890 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11892 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11893 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11894 true /* requireFullPermission */, true /* checkShell */,
11895 "setPackagesSuspended for user " + userId);
11897 if (ArrayUtils.isEmpty(packageNames)) {
11898 return packageNames;
11901 // List of package names for whom the suspended state has changed.
11902 List<String> changedPackages = new ArrayList<>(packageNames.length);
11903 // List of package names for whom the suspended state is not set as requested in this
11905 List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11906 long callingId = Binder.clearCallingIdentity();
11908 for (int i = 0; i < packageNames.length; i++) {
11909 String packageName = packageNames[i];
11910 boolean changed = false;
11912 synchronized (mPackages) {
11913 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11914 if (pkgSetting == null) {
11915 Slog.w(TAG, "Could not find package setting for package \"" + packageName
11916 + "\". Skipping suspending/un-suspending.");
11917 unactionedPackages.add(packageName);
11920 appId = pkgSetting.appId;
11921 if (pkgSetting.getSuspended(userId) != suspended) {
11922 if (!canSuspendPackageForUserLocked(packageName, userId)) {
11923 unactionedPackages.add(packageName);
11926 pkgSetting.setSuspended(suspended, userId);
11927 mSettings.writePackageRestrictionsLPr(userId);
11929 changedPackages.add(packageName);
11933 if (changed && suspended) {
11934 killApplication(packageName, UserHandle.getUid(userId, appId),
11935 "suspending package");
11939 Binder.restoreCallingIdentity(callingId);
11942 if (!changedPackages.isEmpty()) {
11943 sendPackagesSuspendedForUser(changedPackages.toArray(
11944 new String[changedPackages.size()]), userId, suspended);
11947 return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11951 public boolean isPackageSuspendedForUser(String packageName, int userId) {
11952 enforceCrossUserPermission(Binder.getCallingUid(), userId,
11953 true /* requireFullPermission */, false /* checkShell */,
11954 "isPackageSuspendedForUser for user " + userId);
11955 synchronized (mPackages) {
11956 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11957 if (pkgSetting == null) {
11958 throw new IllegalArgumentException("Unknown target package: " + packageName);
11960 return pkgSetting.getSuspended(userId);
11964 private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11965 if (isPackageDeviceAdmin(packageName, userId)) {
11966 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11967 + "\": has an active device admin");
11971 String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11972 if (packageName.equals(activeLauncherPackageName)) {
11973 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11974 + "\": contains the active launcher");
11978 if (packageName.equals(mRequiredInstallerPackage)) {
11979 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11980 + "\": required for package installation");
11984 if (packageName.equals(mRequiredUninstallerPackage)) {
11985 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11986 + "\": required for package uninstallation");
11990 if (packageName.equals(mRequiredVerifierPackage)) {
11991 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11992 + "\": required for package verification");
11996 if (packageName.equals(getDefaultDialerPackageName(userId))) {
11997 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11998 + "\": is the default dialer");
12002 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12003 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12004 + "\": protected package");
12011 private String getActiveLauncherPackageName(int userId) {
12012 Intent intent = new Intent(Intent.ACTION_MAIN);
12013 intent.addCategory(Intent.CATEGORY_HOME);
12014 ResolveInfo resolveInfo = resolveIntent(
12016 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12017 PackageManager.MATCH_DEFAULT_ONLY,
12020 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12023 private String getDefaultDialerPackageName(int userId) {
12024 synchronized (mPackages) {
12025 return mSettings.getDefaultDialerPackageNameLPw(userId);
12030 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12031 mContext.enforceCallingOrSelfPermission(
12032 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12033 "Only package verification agents can verify applications");
12035 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12036 final PackageVerificationResponse response = new PackageVerificationResponse(
12037 verificationCode, Binder.getCallingUid());
12039 msg.obj = response;
12040 mHandler.sendMessage(msg);
12044 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12045 long millisecondsToDelay) {
12046 mContext.enforceCallingOrSelfPermission(
12047 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12048 "Only package verification agents can extend verification timeouts");
12050 final PackageVerificationState state = mPendingVerification.get(id);
12051 final PackageVerificationResponse response = new PackageVerificationResponse(
12052 verificationCodeAtTimeout, Binder.getCallingUid());
12054 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12055 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12057 if (millisecondsToDelay < 0) {
12058 millisecondsToDelay = 0;
12060 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12061 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12062 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12065 if ((state != null) && !state.timeoutExtended()) {
12066 state.extendTimeout();
12068 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12070 msg.obj = response;
12071 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12075 private void broadcastPackageVerified(int verificationId, Uri packageUri,
12076 int verificationCode, UserHandle user) {
12077 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12078 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12079 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12080 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12081 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12083 mContext.sendBroadcastAsUser(intent, user,
12084 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12087 private ComponentName matchComponentForVerifier(String packageName,
12088 List<ResolveInfo> receivers) {
12089 ActivityInfo targetReceiver = null;
12091 final int NR = receivers.size();
12092 for (int i = 0; i < NR; i++) {
12093 final ResolveInfo info = receivers.get(i);
12094 if (info.activityInfo == null) {
12098 if (packageName.equals(info.activityInfo.packageName)) {
12099 targetReceiver = info.activityInfo;
12104 if (targetReceiver == null) {
12108 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12111 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12112 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12113 if (pkgInfo.verifiers.length == 0) {
12117 final int N = pkgInfo.verifiers.length;
12118 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12119 for (int i = 0; i < N; i++) {
12120 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12122 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12124 if (comp == null) {
12128 final int verifierUid = getUidForVerifier(verifierInfo);
12129 if (verifierUid == -1) {
12133 if (DEBUG_VERIFY) {
12134 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12135 + " with the correct signature");
12137 sufficientVerifiers.add(comp);
12138 verificationState.addSufficientVerifier(verifierUid);
12141 return sufficientVerifiers;
12144 private int getUidForVerifier(VerifierInfo verifierInfo) {
12145 synchronized (mPackages) {
12146 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12149 } else if (pkg.mSignatures.length != 1) {
12150 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12151 + " has more than one signature; ignoring");
12156 * If the public key of the package's signature does not match
12157 * our expected public key, then this is a different package and
12161 final byte[] expectedPublicKey;
12163 final Signature verifierSig = pkg.mSignatures[0];
12164 final PublicKey publicKey = verifierSig.getPublicKey();
12165 expectedPublicKey = publicKey.getEncoded();
12166 } catch (CertificateException e) {
12170 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12172 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12173 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12174 + " does not have the expected public key; ignoring");
12178 return pkg.applicationInfo.uid;
12183 public void finishPackageInstall(int token, boolean didLaunch) {
12184 enforceSystemOrRoot("Only the system is allowed to finish installs");
12186 if (DEBUG_INSTALL) {
12187 Slog.v(TAG, "BM finishing package install for " + token);
12189 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12191 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12192 mHandler.sendMessage(msg);
12196 * Get the verification agent timeout.
12198 * @return verification timeout in milliseconds
12200 private long getVerificationTimeout() {
12201 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12202 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12203 DEFAULT_VERIFICATION_TIMEOUT);
12207 * Get the default verification agent response code.
12209 * @return default verification response code
12211 private int getDefaultVerificationResponse() {
12212 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12213 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12214 DEFAULT_VERIFICATION_RESPONSE);
12218 * Check whether or not package verification has been enabled.
12220 * @return true if verification should be performed
12222 private boolean isVerificationEnabled(int userId, int installFlags) {
12223 if (!DEFAULT_VERIFY_ENABLE) {
12226 // Ephemeral apps don't get the full verification treatment
12227 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12228 if (DEBUG_EPHEMERAL) {
12229 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12234 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12236 // Check if installing from ADB
12237 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12238 // Do not run verification in a test harness environment
12239 if (ActivityManager.isRunningInTestHarness()) {
12242 if (ensureVerifyAppsEnabled) {
12245 // Check if the developer does not want package verification for ADB installs
12246 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12247 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12252 if (ensureVerifyAppsEnabled) {
12256 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12257 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12261 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12262 throws RemoteException {
12263 mContext.enforceCallingOrSelfPermission(
12264 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12265 "Only intentfilter verification agents can verify applications");
12267 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12268 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12269 Binder.getCallingUid(), verificationCode, failedDomains);
12271 msg.obj = response;
12272 mHandler.sendMessage(msg);
12276 public int getIntentVerificationStatus(String packageName, int userId) {
12277 synchronized (mPackages) {
12278 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12283 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12284 mContext.enforceCallingOrSelfPermission(
12285 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12287 boolean result = false;
12288 synchronized (mPackages) {
12289 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12292 scheduleWritePackageRestrictionsLocked(userId);
12298 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12299 String packageName) {
12300 synchronized (mPackages) {
12301 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12306 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12307 if (TextUtils.isEmpty(packageName)) {
12308 return ParceledListSlice.emptyList();
12310 synchronized (mPackages) {
12311 PackageParser.Package pkg = mPackages.get(packageName);
12312 if (pkg == null || pkg.activities == null) {
12313 return ParceledListSlice.emptyList();
12315 final int count = pkg.activities.size();
12316 ArrayList<IntentFilter> result = new ArrayList<>();
12317 for (int n=0; n<count; n++) {
12318 PackageParser.Activity activity = pkg.activities.get(n);
12319 if (activity.intents != null && activity.intents.size() > 0) {
12320 result.addAll(activity.intents);
12323 return new ParceledListSlice<>(result);
12328 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12329 mContext.enforceCallingOrSelfPermission(
12330 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12332 synchronized (mPackages) {
12333 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12334 if (packageName != null) {
12335 result |= updateIntentVerificationStatus(packageName,
12336 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12338 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12339 packageName, userId);
12346 public String getDefaultBrowserPackageName(int userId) {
12347 synchronized (mPackages) {
12348 return mSettings.getDefaultBrowserPackageNameLPw(userId);
12353 * Get the "allow unknown sources" setting.
12355 * @return the current "allow unknown sources" setting
12357 private int getUnknownSourcesSettings() {
12358 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12359 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12364 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12365 final int uid = Binder.getCallingUid();
12367 synchronized (mPackages) {
12368 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12369 if (targetPackageSetting == null) {
12370 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12373 PackageSetting installerPackageSetting;
12374 if (installerPackageName != null) {
12375 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12376 if (installerPackageSetting == null) {
12377 throw new IllegalArgumentException("Unknown installer package: "
12378 + installerPackageName);
12381 installerPackageSetting = null;
12384 Signature[] callerSignature;
12385 Object obj = mSettings.getUserIdLPr(uid);
12387 if (obj instanceof SharedUserSetting) {
12388 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12389 } else if (obj instanceof PackageSetting) {
12390 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12392 throw new SecurityException("Bad object " + obj + " for uid " + uid);
12395 throw new SecurityException("Unknown calling UID: " + uid);
12398 // Verify: can't set installerPackageName to a package that is
12399 // not signed with the same cert as the caller.
12400 if (installerPackageSetting != null) {
12401 if (compareSignatures(callerSignature,
12402 installerPackageSetting.signatures.mSignatures)
12403 != PackageManager.SIGNATURE_MATCH) {
12404 throw new SecurityException(
12405 "Caller does not have same cert as new installer package "
12406 + installerPackageName);
12410 // Verify: if target already has an installer package, it must
12411 // be signed with the same cert as the caller.
12412 if (targetPackageSetting.installerPackageName != null) {
12413 PackageSetting setting = mSettings.mPackages.get(
12414 targetPackageSetting.installerPackageName);
12415 // If the currently set package isn't valid, then it's always
12416 // okay to change it.
12417 if (setting != null) {
12418 if (compareSignatures(callerSignature,
12419 setting.signatures.mSignatures)
12420 != PackageManager.SIGNATURE_MATCH) {
12421 throw new SecurityException(
12422 "Caller does not have same cert as old installer package "
12423 + targetPackageSetting.installerPackageName);
12429 targetPackageSetting.installerPackageName = installerPackageName;
12430 if (installerPackageName != null) {
12431 mSettings.mInstallerPackages.add(installerPackageName);
12433 scheduleWriteSettingsLocked();
12437 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12438 // Queue up an async operation since the package installation may take a little while.
12439 mHandler.post(new Runnable() {
12440 public void run() {
12441 mHandler.removeCallbacks(this);
12442 // Result object to be returned
12443 PackageInstalledInfo res = new PackageInstalledInfo();
12444 res.setReturnCode(currentStatus);
12447 res.removedInfo = null;
12448 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12449 args.doPreInstall(res.returnCode);
12450 synchronized (mInstallLock) {
12451 installPackageTracedLI(args, res);
12453 args.doPostInstall(res.returnCode, res.uid);
12456 // A restore should be performed at this point if (a) the install
12457 // succeeded, (b) the operation is not an update, and (c) the new
12458 // package has not opted out of backup participation.
12459 final boolean update = res.removedInfo != null
12460 && res.removedInfo.removedPackage != null;
12461 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12462 boolean doRestore = !update
12463 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12465 // Set up the post-install work request bookkeeping. This will be used
12466 // and cleaned up by the post-install event handling regardless of whether
12467 // there's a restore pass performed. Token values are >= 1.
12469 if (mNextInstallToken < 0) mNextInstallToken = 1;
12470 token = mNextInstallToken++;
12472 PostInstallData data = new PostInstallData(args, res);
12473 mRunningInstalls.put(token, data);
12474 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12476 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12477 // Pass responsibility to the Backup Manager. It will perform a
12478 // restore if appropriate, then pass responsibility back to the
12479 // Package Manager to run the post-install observer callbacks
12481 IBackupManager bm = IBackupManager.Stub.asInterface(
12482 ServiceManager.getService(Context.BACKUP_SERVICE));
12484 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12485 + " to BM for possible restore");
12486 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12488 // TODO: http://b/22388012
12489 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12490 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12494 } catch (RemoteException e) {
12495 // can't happen; the backup manager is local
12496 } catch (Exception e) {
12497 Slog.e(TAG, "Exception trying to enqueue restore", e);
12501 Slog.e(TAG, "Backup Manager not found!");
12507 // No restore possible, or the Backup Manager was mysteriously not
12508 // available -- just fire the post-install work request directly.
12509 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12511 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12513 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12514 mHandler.sendMessage(msg);
12521 * Callback from PackageSettings whenever an app is first transitioned out of the
12522 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if
12523 * the app was "launched" for a restoreAtInstall operation. Therefore we check
12524 * here whether the app is the target of an ongoing install, and only send the
12525 * broadcast immediately if it is not in that state. If it *is* undergoing a restore,
12526 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12529 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12530 // Serialize this with the rest of the install-process message chain. In the
12531 // restore-at-install case, this Runnable will necessarily run before the
12532 // POST_INSTALL message is processed, so the contents of mRunningInstalls
12533 // are coherent. In the non-restore case, the app has already completed install
12534 // and been launched through some other means, so it is not in a problematic
12535 // state for observers to see the FIRST_LAUNCH signal.
12536 mHandler.post(new Runnable() {
12538 public void run() {
12539 for (int i = 0; i < mRunningInstalls.size(); i++) {
12540 final PostInstallData data = mRunningInstalls.valueAt(i);
12541 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12544 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12545 // right package; but is it for the right user?
12546 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12547 if (userId == data.res.newUsers[uIndex]) {
12548 if (DEBUG_BACKUP) {
12549 Slog.i(TAG, "Package " + pkgName
12550 + " being restored so deferring FIRST_LAUNCH");
12557 // didn't find it, so not being restored
12558 if (DEBUG_BACKUP) {
12559 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12561 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12566 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12567 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12568 installerPkg, null, userIds);
12571 private abstract class HandlerParams {
12572 private static final int MAX_RETRIES = 4;
12575 * Number of times startCopy() has been attempted and had a non-fatal
12578 private int mRetries = 0;
12580 /** User handle for the user requesting the information or installation. */
12581 private final UserHandle mUser;
12582 String traceMethod;
12585 HandlerParams(UserHandle user) {
12589 UserHandle getUser() {
12593 HandlerParams setTraceMethod(String traceMethod) {
12594 this.traceMethod = traceMethod;
12598 HandlerParams setTraceCookie(int traceCookie) {
12599 this.traceCookie = traceCookie;
12603 final boolean startCopy() {
12606 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12608 if (++mRetries > MAX_RETRIES) {
12609 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12610 mHandler.sendEmptyMessage(MCS_GIVE_UP);
12611 handleServiceError();
12617 } catch (RemoteException e) {
12618 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12619 mHandler.sendEmptyMessage(MCS_RECONNECT);
12622 handleReturnCode();
12626 final void serviceError() {
12627 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12628 handleServiceError();
12629 handleReturnCode();
12632 abstract void handleStartCopy() throws RemoteException;
12633 abstract void handleServiceError();
12634 abstract void handleReturnCode();
12637 class MeasureParams extends HandlerParams {
12638 private final PackageStats mStats;
12639 private boolean mSuccess;
12641 private final IPackageStatsObserver mObserver;
12643 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12644 super(new UserHandle(stats.userHandle));
12645 mObserver = observer;
12650 public String toString() {
12651 return "MeasureParams{"
12652 + Integer.toHexString(System.identityHashCode(this))
12653 + " " + mStats.packageName + "}";
12657 void handleStartCopy() throws RemoteException {
12658 synchronized (mInstallLock) {
12659 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12663 boolean mounted = false;
12665 final String status = Environment.getExternalStorageState();
12666 mounted = (Environment.MEDIA_MOUNTED.equals(status)
12667 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12668 } catch (Exception e) {
12672 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12674 mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12675 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12677 mStats.externalDataSize = calculateDirectorySize(mContainerService,
12678 userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12680 // Always subtract cache size, since it's a subdirectory
12681 mStats.externalDataSize -= mStats.externalCacheSize;
12683 mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12684 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12686 mStats.externalObbSize = calculateDirectorySize(mContainerService,
12687 userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12693 void handleReturnCode() {
12694 if (mObserver != null) {
12696 mObserver.onGetStatsCompleted(mStats, mSuccess);
12697 } catch (RemoteException e) {
12698 Slog.i(TAG, "Observer no longer exists.");
12704 void handleServiceError() {
12705 Slog.e(TAG, "Could not measure application " + mStats.packageName
12706 + " external storage");
12710 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12711 throws RemoteException {
12713 for (File path : paths) {
12714 result += mcs.calculateDirectorySize(path.getAbsolutePath());
12719 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12720 for (File path : paths) {
12722 mcs.clearDirectory(path.getAbsolutePath());
12723 } catch (RemoteException e) {
12728 static class OriginInfo {
12730 * Location where install is coming from, before it has been
12731 * copied/renamed into place. This could be a single monolithic APK
12732 * file, or a cluster directory. This location may be untrusted.
12738 * Flag indicating that {@link #file} or {@link #cid} has already been
12739 * staged, meaning downstream users don't need to defensively copy the
12742 final boolean staged;
12745 * Flag indicating that {@link #file} or {@link #cid} is an already
12746 * installed app that is being moved.
12748 final boolean existing;
12750 final String resolvedPath;
12751 final File resolvedFile;
12753 static OriginInfo fromNothing() {
12754 return new OriginInfo(null, null, false, false);
12757 static OriginInfo fromUntrustedFile(File file) {
12758 return new OriginInfo(file, null, false, false);
12761 static OriginInfo fromExistingFile(File file) {
12762 return new OriginInfo(file, null, false, true);
12765 static OriginInfo fromStagedFile(File file) {
12766 return new OriginInfo(file, null, true, false);
12769 static OriginInfo fromStagedContainer(String cid) {
12770 return new OriginInfo(null, cid, true, false);
12773 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12776 this.staged = staged;
12777 this.existing = existing;
12780 resolvedPath = PackageHelper.getSdDir(cid);
12781 resolvedFile = new File(resolvedPath);
12782 } else if (file != null) {
12783 resolvedPath = file.getAbsolutePath();
12784 resolvedFile = file;
12786 resolvedPath = null;
12787 resolvedFile = null;
12792 static class MoveInfo {
12794 final String fromUuid;
12795 final String toUuid;
12796 final String packageName;
12797 final String dataAppName;
12799 final String seinfo;
12800 final int targetSdkVersion;
12802 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12803 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12804 this.moveId = moveId;
12805 this.fromUuid = fromUuid;
12806 this.toUuid = toUuid;
12807 this.packageName = packageName;
12808 this.dataAppName = dataAppName;
12809 this.appId = appId;
12810 this.seinfo = seinfo;
12811 this.targetSdkVersion = targetSdkVersion;
12815 static class VerificationInfo {
12816 /** A constant used to indicate that a uid value is not present. */
12817 public static final int NO_UID = -1;
12819 /** URI referencing where the package was downloaded from. */
12820 final Uri originatingUri;
12822 /** HTTP referrer URI associated with the originatingURI. */
12823 final Uri referrer;
12825 /** UID of the application that the install request originated from. */
12826 final int originatingUid;
12828 /** UID of application requesting the install */
12829 final int installerUid;
12831 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12832 this.originatingUri = originatingUri;
12833 this.referrer = referrer;
12834 this.originatingUid = originatingUid;
12835 this.installerUid = installerUid;
12839 class InstallParams extends HandlerParams {
12840 final OriginInfo origin;
12841 final MoveInfo move;
12842 final IPackageInstallObserver2 observer;
12844 final String installerPackageName;
12845 final String volumeUuid;
12846 private InstallArgs mArgs;
12848 final String packageAbiOverride;
12849 final String[] grantedRuntimePermissions;
12850 final VerificationInfo verificationInfo;
12851 final Certificate[][] certificates;
12853 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12854 int installFlags, String installerPackageName, String volumeUuid,
12855 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12856 String[] grantedPermissions, Certificate[][] certificates) {
12858 this.origin = origin;
12860 this.observer = observer;
12861 this.installFlags = installFlags;
12862 this.installerPackageName = installerPackageName;
12863 this.volumeUuid = volumeUuid;
12864 this.verificationInfo = verificationInfo;
12865 this.packageAbiOverride = packageAbiOverride;
12866 this.grantedRuntimePermissions = grantedPermissions;
12867 this.certificates = certificates;
12871 public String toString() {
12872 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12873 + " file=" + origin.file + " cid=" + origin.cid + "}";
12876 private int installLocationPolicy(PackageInfoLite pkgLite) {
12877 String packageName = pkgLite.packageName;
12878 int installLocation = pkgLite.installLocation;
12879 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12881 synchronized (mPackages) {
12882 // Currently installed package which the new package is attempting to replace or
12883 // null if no such package is installed.
12884 PackageParser.Package installedPkg = mPackages.get(packageName);
12885 // Package which currently owns the data which the new package will own if installed.
12886 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12887 // will be null whereas dataOwnerPkg will contain information about the package
12888 // which was uninstalled while keeping its data.
12889 PackageParser.Package dataOwnerPkg = installedPkg;
12890 if (dataOwnerPkg == null) {
12891 PackageSetting ps = mSettings.mPackages.get(packageName);
12893 dataOwnerPkg = ps.pkg;
12897 if (dataOwnerPkg != null) {
12898 // If installed, the package will get access to data left on the device by its
12899 // predecessor. As a security measure, this is permited only if this is not a
12900 // version downgrade or if the predecessor package is marked as debuggable and
12901 // a downgrade is explicitly requested.
12903 // On debuggable platform builds, downgrades are permitted even for
12904 // non-debuggable packages to make testing easier. Debuggable platform builds do
12905 // not offer security guarantees and thus it's OK to disable some security
12906 // mechanisms to make debugging/testing easier on those builds. However, even on
12907 // debuggable builds downgrades of packages are permitted only if requested via
12908 // installFlags. This is because we aim to keep the behavior of debuggable
12909 // platform builds as close as possible to the behavior of non-debuggable
12910 // platform builds.
12911 final boolean downgradeRequested =
12912 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12913 final boolean packageDebuggable =
12914 (dataOwnerPkg.applicationInfo.flags
12915 & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12916 final boolean downgradePermitted =
12917 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12918 if (!downgradePermitted) {
12920 checkDowngrade(dataOwnerPkg, pkgLite);
12921 } catch (PackageManagerException e) {
12922 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12923 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12928 if (installedPkg != null) {
12929 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12930 // Check for updated system application.
12931 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12933 Slog.w(TAG, "Cannot install update to system app on sdcard");
12934 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12936 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12939 // Install flag overrides everything.
12940 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12942 // If current upgrade specifies particular preference
12943 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12944 // Application explicitly specified internal.
12945 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12946 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12947 // App explictly prefers external. Let policy decide
12949 // Prefer previous location
12950 if (isExternal(installedPkg)) {
12951 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12953 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12957 // Invalid install. Return error code
12958 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12962 // All the special cases have been taken care of.
12963 // Return result based on recommended install location.
12965 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12967 return pkgLite.recommendedInstallLocation;
12971 * Invoke remote method to get package information and install
12972 * location values. Override install location based on default
12973 * policy if needed and then create install arguments based
12974 * on the install location.
12976 public void handleStartCopy() throws RemoteException {
12977 int ret = PackageManager.INSTALL_SUCCEEDED;
12979 // If we're already staged, we've firmly committed to an install location
12980 if (origin.staged) {
12981 if (origin.file != null) {
12982 installFlags |= PackageManager.INSTALL_INTERNAL;
12983 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12984 } else if (origin.cid != null) {
12985 installFlags |= PackageManager.INSTALL_EXTERNAL;
12986 installFlags &= ~PackageManager.INSTALL_INTERNAL;
12988 throw new IllegalStateException("Invalid stage location");
12992 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12993 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12994 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12995 PackageInfoLite pkgLite = null;
12997 if (onInt && onSd) {
12998 // Check if both bits are set.
12999 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13000 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13001 } else if (onSd && ephemeral) {
13002 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external");
13003 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13005 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13006 packageAbiOverride);
13008 if (DEBUG_EPHEMERAL && ephemeral) {
13009 Slog.v(TAG, "pkgLite for install: " + pkgLite);
13013 * If we have too little free space, try to free cache
13014 * before giving up.
13016 if (!origin.staged && pkgLite.recommendedInstallLocation
13017 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13018 // TODO: focus freeing disk space on the target device
13019 final StorageManager storage = StorageManager.from(mContext);
13020 final long lowThreshold = storage.getStorageLowBytes(
13021 Environment.getDataDirectory());
13023 final long sizeBytes = mContainerService.calculateInstalledSize(
13024 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13027 mInstaller.freeCache(null, sizeBytes + lowThreshold);
13028 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13029 installFlags, packageAbiOverride);
13030 } catch (InstallerException e) {
13031 Slog.w(TAG, "Failed to free cache", e);
13035 * The cache free must have deleted the file we
13036 * downloaded to install.
13038 * TODO: fix the "freeCache" call to not delete
13039 * the file we care about.
13041 if (pkgLite.recommendedInstallLocation
13042 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13043 pkgLite.recommendedInstallLocation
13044 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13049 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13050 int loc = pkgLite.recommendedInstallLocation;
13051 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13052 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13053 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13054 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13055 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13056 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13057 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13058 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13059 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13060 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13061 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13062 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13064 // Override with defaults if needed.
13065 loc = installLocationPolicy(pkgLite);
13066 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13067 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13068 } else if (!onSd && !onInt) {
13069 // Override install location with flags
13070 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13071 // Set the flag to install on external media.
13072 installFlags |= PackageManager.INSTALL_EXTERNAL;
13073 installFlags &= ~PackageManager.INSTALL_INTERNAL;
13074 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13075 if (DEBUG_EPHEMERAL) {
13076 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13078 installFlags |= PackageManager.INSTALL_EPHEMERAL;
13079 installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13080 |PackageManager.INSTALL_INTERNAL);
13082 // Make sure the flag for installing on external
13084 installFlags |= PackageManager.INSTALL_INTERNAL;
13085 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13091 final InstallArgs args = createInstallArgs(this);
13094 if (ret == PackageManager.INSTALL_SUCCEEDED) {
13095 // TODO: http://b/22976637
13096 // Apps installed for "all" users use the device owner to verify the app
13097 UserHandle verifierUser = getUser();
13098 if (verifierUser == UserHandle.ALL) {
13099 verifierUser = UserHandle.SYSTEM;
13103 * Determine if we have any installed package verifiers. If we
13104 * do, then we'll defer to them to verify the packages.
13106 final int requiredUid = mRequiredVerifierPackage == null ? -1
13107 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13108 verifierUser.getIdentifier());
13109 if (!origin.existing && requiredUid != -1
13110 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13111 final Intent verification = new Intent(
13112 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13113 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13114 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13115 PACKAGE_MIME_TYPE);
13116 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13118 // Query all live verifiers based on current user state
13119 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13120 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13122 if (DEBUG_VERIFY) {
13123 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13124 + verification.toString() + " with " + pkgLite.verifiers.length
13125 + " optional verifiers");
13128 final int verificationId = mPendingVerificationToken++;
13130 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13132 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13133 installerPackageName);
13135 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13138 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13139 pkgLite.packageName);
13141 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13142 pkgLite.versionCode);
13144 if (verificationInfo != null) {
13145 if (verificationInfo.originatingUri != null) {
13146 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13147 verificationInfo.originatingUri);
13149 if (verificationInfo.referrer != null) {
13150 verification.putExtra(Intent.EXTRA_REFERRER,
13151 verificationInfo.referrer);
13153 if (verificationInfo.originatingUid >= 0) {
13154 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13155 verificationInfo.originatingUid);
13157 if (verificationInfo.installerUid >= 0) {
13158 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13159 verificationInfo.installerUid);
13163 final PackageVerificationState verificationState = new PackageVerificationState(
13164 requiredUid, args);
13166 mPendingVerification.append(verificationId, verificationState);
13168 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13169 receivers, verificationState);
13172 * If any sufficient verifiers were listed in the package
13173 * manifest, attempt to ask them.
13175 if (sufficientVerifiers != null) {
13176 final int N = sufficientVerifiers.size();
13178 Slog.i(TAG, "Additional verifiers required, but none installed.");
13179 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13181 for (int i = 0; i < N; i++) {
13182 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13184 final Intent sufficientIntent = new Intent(verification);
13185 sufficientIntent.setComponent(verifierComponent);
13186 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13191 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13192 mRequiredVerifierPackage, receivers);
13193 if (ret == PackageManager.INSTALL_SUCCEEDED
13194 && mRequiredVerifierPackage != null) {
13195 Trace.asyncTraceBegin(
13196 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13198 * Send the intent to the required verification agent,
13199 * but only start the verification timeout after the
13200 * target BroadcastReceivers have run.
13202 verification.setComponent(requiredVerifierComponent);
13203 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13204 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13205 new BroadcastReceiver() {
13207 public void onReceive(Context context, Intent intent) {
13208 final Message msg = mHandler
13209 .obtainMessage(CHECK_PENDING_VERIFICATION);
13210 msg.arg1 = verificationId;
13211 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13213 }, null, 0, null, null);
13216 * We don't want the copy to proceed until verification
13217 * succeeds, so null out this field.
13223 * No package verification is enabled, so immediately start
13224 * the remote call to initiate copy using temporary file.
13226 ret = args.copyApk(mContainerService, true);
13234 void handleReturnCode() {
13235 // If mArgs is null, then MCS couldn't be reached. When it
13236 // reconnects, it will try again to install. At that point, this
13238 if (mArgs != null) {
13239 processPendingInstall(mArgs, mRet);
13244 void handleServiceError() {
13245 mArgs = createInstallArgs(this);
13246 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13249 public boolean isForwardLocked() {
13250 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13255 * Used during creation of InstallArgs
13257 * @param installFlags package installation flags
13258 * @return true if should be installed on external storage
13260 private static boolean installOnExternalAsec(int installFlags) {
13261 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13264 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13271 * Used during creation of InstallArgs
13273 * @param installFlags package installation flags
13274 * @return true if should be installed as forward locked
13276 private static boolean installForwardLocked(int installFlags) {
13277 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13280 private InstallArgs createInstallArgs(InstallParams params) {
13281 if (params.move != null) {
13282 return new MoveInstallArgs(params);
13283 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13284 return new AsecInstallArgs(params);
13286 return new FileInstallArgs(params);
13291 * Create args that describe an existing installed package. Typically used
13292 * when cleaning up old installs, or used as a move source.
13294 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13295 String resourcePath, String[] instructionSets) {
13296 final boolean isInAsec;
13297 if (installOnExternalAsec(installFlags)) {
13298 /* Apps on SD card are always in ASEC containers. */
13300 } else if (installForwardLocked(installFlags)
13301 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13303 * Forward-locked apps are only in ASEC containers if they're the
13312 return new AsecInstallArgs(codePath, instructionSets,
13313 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13315 return new FileInstallArgs(codePath, resourcePath, instructionSets);
13319 static abstract class InstallArgs {
13320 /** @see InstallParams#origin */
13321 final OriginInfo origin;
13322 /** @see InstallParams#move */
13323 final MoveInfo move;
13325 final IPackageInstallObserver2 observer;
13326 // Always refers to PackageManager flags only
13327 final int installFlags;
13328 final String installerPackageName;
13329 final String volumeUuid;
13330 final UserHandle user;
13331 final String abiOverride;
13332 final String[] installGrantPermissions;
13333 /** If non-null, drop an async trace when the install completes */
13334 final String traceMethod;
13335 final int traceCookie;
13336 final Certificate[][] certificates;
13338 // The list of instruction sets supported by this app. This is currently
13339 // only used during the rmdex() phase to clean up resources. We can get rid of this
13340 // if we move dex files under the common app path.
13341 /* nullable */ String[] instructionSets;
13343 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13344 int installFlags, String installerPackageName, String volumeUuid,
13345 UserHandle user, String[] instructionSets,
13346 String abiOverride, String[] installGrantPermissions,
13347 String traceMethod, int traceCookie, Certificate[][] certificates) {
13348 this.origin = origin;
13350 this.installFlags = installFlags;
13351 this.observer = observer;
13352 this.installerPackageName = installerPackageName;
13353 this.volumeUuid = volumeUuid;
13355 this.instructionSets = instructionSets;
13356 this.abiOverride = abiOverride;
13357 this.installGrantPermissions = installGrantPermissions;
13358 this.traceMethod = traceMethod;
13359 this.traceCookie = traceCookie;
13360 this.certificates = certificates;
13363 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13364 abstract int doPreInstall(int status);
13367 * Rename package into final resting place. All paths on the given
13368 * scanned package should be updated to reflect the rename.
13370 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13371 abstract int doPostInstall(int status, int uid);
13373 /** @see PackageSettingBase#codePathString */
13374 abstract String getCodePath();
13375 /** @see PackageSettingBase#resourcePathString */
13376 abstract String getResourcePath();
13378 // Need installer lock especially for dex file removal.
13379 abstract void cleanUpResourcesLI();
13380 abstract boolean doPostDeleteLI(boolean delete);
13383 * Called before the source arguments are copied. This is used mostly
13384 * for MoveParams when it needs to read the source file to put it in the
13388 return PackageManager.INSTALL_SUCCEEDED;
13392 * Called after the source arguments are copied. This is used mostly for
13393 * MoveParams when it needs to read the source file to put it in the
13396 int doPostCopy(int uid) {
13397 return PackageManager.INSTALL_SUCCEEDED;
13400 protected boolean isFwdLocked() {
13401 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13404 protected boolean isExternalAsec() {
13405 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13408 protected boolean isEphemeral() {
13409 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13412 UserHandle getUser() {
13417 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13418 if (!allCodePaths.isEmpty()) {
13419 if (instructionSets == null) {
13420 throw new IllegalStateException("instructionSet == null");
13422 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13423 for (String codePath : allCodePaths) {
13424 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13426 mInstaller.rmdex(codePath, dexCodeInstructionSet);
13427 } catch (InstallerException ignored) {
13435 * Logic to handle installation of non-ASEC applications, including copying
13436 * and renaming logic.
13438 class FileInstallArgs extends InstallArgs {
13439 private File codeFile;
13440 private File resourceFile;
13442 // Example topology:
13443 // /data/app/com.example/base.apk
13444 // /data/app/com.example/split_foo.apk
13445 // /data/app/com.example/lib/arm/libfoo.so
13446 // /data/app/com.example/lib/arm64/libfoo.so
13447 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13450 FileInstallArgs(InstallParams params) {
13451 super(params.origin, params.move, params.observer, params.installFlags,
13452 params.installerPackageName, params.volumeUuid,
13453 params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13454 params.grantedRuntimePermissions,
13455 params.traceMethod, params.traceCookie, params.certificates);
13456 if (isFwdLocked()) {
13457 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13461 /** Existing install */
13462 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13463 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13464 null, null, null, 0, null /*certificates*/);
13465 this.codeFile = (codePath != null) ? new File(codePath) : null;
13466 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13469 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13470 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13472 return doCopyApk(imcs, temp);
13474 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13478 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13479 if (origin.staged) {
13480 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13481 codeFile = origin.file;
13482 resourceFile = origin.file;
13483 return PackageManager.INSTALL_SUCCEEDED;
13487 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13488 final File tempDir =
13489 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13490 codeFile = tempDir;
13491 resourceFile = tempDir;
13492 } catch (IOException e) {
13493 Slog.w(TAG, "Failed to create copy file: " + e);
13494 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13497 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13499 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13500 if (!FileUtils.isValidExtFilename(name)) {
13501 throw new IllegalArgumentException("Invalid filename: " + name);
13504 final File file = new File(codeFile, name);
13505 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13506 O_RDWR | O_CREAT, 0644);
13507 Os.chmod(file.getAbsolutePath(), 0644);
13508 return new ParcelFileDescriptor(fd);
13509 } catch (ErrnoException e) {
13510 throw new RemoteException("Failed to open: " + e.getMessage());
13515 int ret = PackageManager.INSTALL_SUCCEEDED;
13516 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13517 if (ret != PackageManager.INSTALL_SUCCEEDED) {
13518 Slog.e(TAG, "Failed to copy package");
13522 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13523 NativeLibraryHelper.Handle handle = null;
13525 handle = NativeLibraryHelper.Handle.create(codeFile);
13526 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13528 } catch (IOException e) {
13529 Slog.e(TAG, "Copying native libraries failed", e);
13530 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13532 IoUtils.closeQuietly(handle);
13538 int doPreInstall(int status) {
13539 if (status != PackageManager.INSTALL_SUCCEEDED) {
13545 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13546 if (status != PackageManager.INSTALL_SUCCEEDED) {
13551 final File targetDir = codeFile.getParentFile();
13552 final File beforeCodeFile = codeFile;
13553 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13555 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13557 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13558 } catch (ErrnoException e) {
13559 Slog.w(TAG, "Failed to rename", e);
13563 if (!SELinux.restoreconRecursive(afterCodeFile)) {
13564 Slog.w(TAG, "Failed to restorecon");
13568 // Reflect the rename internally
13569 codeFile = afterCodeFile;
13570 resourceFile = afterCodeFile;
13572 // Reflect the rename in scanned details
13573 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13574 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13575 afterCodeFile, pkg.baseCodePath));
13576 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13577 afterCodeFile, pkg.splitCodePaths));
13579 // Reflect the rename in app info
13580 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13581 pkg.setApplicationInfoCodePath(pkg.codePath);
13582 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13583 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13584 pkg.setApplicationInfoResourcePath(pkg.codePath);
13585 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13586 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13591 int doPostInstall(int status, int uid) {
13592 if (status != PackageManager.INSTALL_SUCCEEDED) {
13599 String getCodePath() {
13600 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13604 String getResourcePath() {
13605 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13608 private boolean cleanUp() {
13609 if (codeFile == null || !codeFile.exists()) {
13613 removeCodePathLI(codeFile);
13615 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13616 resourceFile.delete();
13622 void cleanUpResourcesLI() {
13623 // Try enumerating all code paths before deleting
13624 List<String> allCodePaths = Collections.EMPTY_LIST;
13625 if (codeFile != null && codeFile.exists()) {
13627 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13628 allCodePaths = pkg.getAllCodePaths();
13629 } catch (PackageParserException e) {
13630 // Ignored; we tried our best
13635 removeDexFiles(allCodePaths, instructionSets);
13638 boolean doPostDeleteLI(boolean delete) {
13639 // XXX err, shouldn't we respect the delete flag?
13640 cleanUpResourcesLI();
13645 private boolean isAsecExternal(String cid) {
13646 final String asecPath = PackageHelper.getSdFilesystem(cid);
13647 return !asecPath.startsWith(mAsecInternalPath);
13650 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13651 PackageManagerException {
13653 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13654 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13655 throw new PackageManagerException(copyRet, message);
13661 * Extract the MountService "container ID" from the full code path of an
13664 static String cidFromCodePath(String fullCodePath) {
13665 int eidx = fullCodePath.lastIndexOf("/");
13666 String subStr1 = fullCodePath.substring(0, eidx);
13667 int sidx = subStr1.lastIndexOf("/");
13668 return subStr1.substring(sidx+1, eidx);
13672 * Logic to handle installation of ASEC applications, including copying and
13675 class AsecInstallArgs extends InstallArgs {
13676 static final String RES_FILE_NAME = "pkg.apk";
13677 static final String PUBLIC_RES_FILE_NAME = "res.zip";
13680 String packagePath;
13681 String resourcePath;
13684 AsecInstallArgs(InstallParams params) {
13685 super(params.origin, params.move, params.observer, params.installFlags,
13686 params.installerPackageName, params.volumeUuid,
13687 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13688 params.grantedRuntimePermissions,
13689 params.traceMethod, params.traceCookie, params.certificates);
13692 /** Existing install */
13693 AsecInstallArgs(String fullCodePath, String[] instructionSets,
13694 boolean isExternal, boolean isForwardLocked) {
13695 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13696 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13697 instructionSets, null, null, null, 0, null /*certificates*/);
13698 // Hackily pretend we're still looking at a full code path
13699 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13700 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13703 // Extract cid from fullCodePath
13704 int eidx = fullCodePath.lastIndexOf("/");
13705 String subStr1 = fullCodePath.substring(0, eidx);
13706 int sidx = subStr1.lastIndexOf("/");
13707 cid = subStr1.substring(sidx+1, eidx);
13708 setMountPath(subStr1);
13711 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13712 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13713 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13714 instructionSets, null, null, null, 0, null /*certificates*/);
13716 setMountPath(PackageHelper.getSdDir(cid));
13719 void createCopyFile() {
13720 cid = mInstallerService.allocateExternalStageCidLegacy();
13723 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13724 if (origin.staged && origin.cid != null) {
13725 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13727 setMountPath(PackageHelper.getSdDir(cid));
13728 return PackageManager.INSTALL_SUCCEEDED;
13735 * Pre-emptively destroy the container since it's destroyed if
13736 * copying fails due to it existing anyway.
13738 PackageHelper.destroySdDir(cid);
13741 final String newMountPath = imcs.copyPackageToContainer(
13742 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13743 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13745 if (newMountPath != null) {
13746 setMountPath(newMountPath);
13747 return PackageManager.INSTALL_SUCCEEDED;
13749 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13754 String getCodePath() {
13755 return packagePath;
13759 String getResourcePath() {
13760 return resourcePath;
13763 int doPreInstall(int status) {
13764 if (status != PackageManager.INSTALL_SUCCEEDED) {
13765 // Destroy container
13766 PackageHelper.destroySdDir(cid);
13768 boolean mounted = PackageHelper.isContainerMounted(cid);
13770 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13771 Process.SYSTEM_UID);
13772 if (newMountPath != null) {
13773 setMountPath(newMountPath);
13775 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13782 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13783 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13784 String newMountPath = null;
13785 if (PackageHelper.isContainerMounted(cid)) {
13786 // Unmount the container
13787 if (!PackageHelper.unMountSdDir(cid)) {
13788 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13792 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13793 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13794 " which might be stale. Will try to clean up.");
13795 // Clean up the stale container and proceed to recreate.
13796 if (!PackageHelper.destroySdDir(newCacheId)) {
13797 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13800 // Successfully cleaned up stale container. Try to rename again.
13801 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13802 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13803 + " inspite of cleaning it up.");
13807 if (!PackageHelper.isContainerMounted(newCacheId)) {
13808 Slog.w(TAG, "Mounting container " + newCacheId);
13809 newMountPath = PackageHelper.mountSdDir(newCacheId,
13810 getEncryptKey(), Process.SYSTEM_UID);
13812 newMountPath = PackageHelper.getSdDir(newCacheId);
13814 if (newMountPath == null) {
13815 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
13818 Log.i(TAG, "Succesfully renamed " + cid +
13819 " to " + newCacheId +
13820 " at new path: " + newMountPath);
13823 final File beforeCodeFile = new File(packagePath);
13824 setMountPath(newMountPath);
13825 final File afterCodeFile = new File(packagePath);
13827 // Reflect the rename in scanned details
13828 pkg.setCodePath(afterCodeFile.getAbsolutePath());
13829 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13830 afterCodeFile, pkg.baseCodePath));
13831 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13832 afterCodeFile, pkg.splitCodePaths));
13834 // Reflect the rename in app info
13835 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13836 pkg.setApplicationInfoCodePath(pkg.codePath);
13837 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13838 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13839 pkg.setApplicationInfoResourcePath(pkg.codePath);
13840 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13841 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13846 private void setMountPath(String mountPath) {
13847 final File mountFile = new File(mountPath);
13849 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13850 if (monolithicFile.exists()) {
13851 packagePath = monolithicFile.getAbsolutePath();
13852 if (isFwdLocked()) {
13853 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13855 resourcePath = packagePath;
13858 packagePath = mountFile.getAbsolutePath();
13859 resourcePath = packagePath;
13863 int doPostInstall(int status, int uid) {
13864 if (status != PackageManager.INSTALL_SUCCEEDED) {
13867 final int groupOwner;
13868 final String protectedFile;
13869 if (isFwdLocked()) {
13870 groupOwner = UserHandle.getSharedAppGid(uid);
13871 protectedFile = RES_FILE_NAME;
13874 protectedFile = null;
13877 if (uid < Process.FIRST_APPLICATION_UID
13878 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13879 Slog.e(TAG, "Failed to finalize " + cid);
13880 PackageHelper.destroySdDir(cid);
13881 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13884 boolean mounted = PackageHelper.isContainerMounted(cid);
13886 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13892 private void cleanUp() {
13893 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13895 // Destroy secure container
13896 PackageHelper.destroySdDir(cid);
13899 private List<String> getAllCodePaths() {
13900 final File codeFile = new File(getCodePath());
13901 if (codeFile != null && codeFile.exists()) {
13903 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13904 return pkg.getAllCodePaths();
13905 } catch (PackageParserException e) {
13906 // Ignored; we tried our best
13909 return Collections.EMPTY_LIST;
13912 void cleanUpResourcesLI() {
13913 // Enumerate all code paths before deleting
13914 cleanUpResourcesLI(getAllCodePaths());
13917 private void cleanUpResourcesLI(List<String> allCodePaths) {
13919 removeDexFiles(allCodePaths, instructionSets);
13922 String getPackageName() {
13923 return getAsecPackageName(cid);
13926 boolean doPostDeleteLI(boolean delete) {
13927 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13928 final List<String> allCodePaths = getAllCodePaths();
13929 boolean mounted = PackageHelper.isContainerMounted(cid);
13932 if (PackageHelper.unMountSdDir(cid)) {
13936 if (!mounted && delete) {
13937 cleanUpResourcesLI(allCodePaths);
13944 if (isFwdLocked()) {
13945 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13946 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13947 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13951 return PackageManager.INSTALL_SUCCEEDED;
13955 int doPostCopy(int uid) {
13956 if (isFwdLocked()) {
13957 if (uid < Process.FIRST_APPLICATION_UID
13958 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13960 Slog.e(TAG, "Failed to finalize " + cid);
13961 PackageHelper.destroySdDir(cid);
13962 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13966 return PackageManager.INSTALL_SUCCEEDED;
13971 * Logic to handle movement of existing installed applications.
13973 class MoveInstallArgs extends InstallArgs {
13974 private File codeFile;
13975 private File resourceFile;
13978 MoveInstallArgs(InstallParams params) {
13979 super(params.origin, params.move, params.observer, params.installFlags,
13980 params.installerPackageName, params.volumeUuid,
13981 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13982 params.grantedRuntimePermissions,
13983 params.traceMethod, params.traceCookie, params.certificates);
13986 int copyApk(IMediaContainerService imcs, boolean temp) {
13987 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13988 + move.fromUuid + " to " + move.toUuid);
13989 synchronized (mInstaller) {
13991 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13992 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13993 } catch (InstallerException e) {
13994 Slog.w(TAG, "Failed to move app", e);
13995 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13999 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14000 resourceFile = codeFile;
14001 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14003 return PackageManager.INSTALL_SUCCEEDED;
14006 int doPreInstall(int status) {
14007 if (status != PackageManager.INSTALL_SUCCEEDED) {
14008 cleanUp(move.toUuid);
14013 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14014 if (status != PackageManager.INSTALL_SUCCEEDED) {
14015 cleanUp(move.toUuid);
14019 // Reflect the move in app info
14020 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14021 pkg.setApplicationInfoCodePath(pkg.codePath);
14022 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14023 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14024 pkg.setApplicationInfoResourcePath(pkg.codePath);
14025 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14026 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14031 int doPostInstall(int status, int uid) {
14032 if (status == PackageManager.INSTALL_SUCCEEDED) {
14033 cleanUp(move.fromUuid);
14035 cleanUp(move.toUuid);
14041 String getCodePath() {
14042 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14046 String getResourcePath() {
14047 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14050 private boolean cleanUp(String volumeUuid) {
14051 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14053 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14054 final int[] userIds = sUserManager.getUserIds();
14055 synchronized (mInstallLock) {
14056 // Clean up both app data and code
14057 // All package moves are frozen until finished
14058 for (int userId : userIds) {
14060 mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14061 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14062 } catch (InstallerException e) {
14063 Slog.w(TAG, String.valueOf(e));
14066 removeCodePathLI(codeFile);
14071 void cleanUpResourcesLI() {
14072 throw new UnsupportedOperationException();
14075 boolean doPostDeleteLI(boolean delete) {
14076 throw new UnsupportedOperationException();
14080 static String getAsecPackageName(String packageCid) {
14081 int idx = packageCid.lastIndexOf("-");
14085 return packageCid.substring(0, idx);
14088 // Utility method used to create code paths based on package name and available index.
14089 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14090 String idxStr = "";
14092 // Fall back to default value of idx=1 if prefix is not
14093 // part of oldCodePath
14094 if (oldCodePath != null) {
14095 String subStr = oldCodePath;
14096 // Drop the suffix right away
14097 if (suffix != null && subStr.endsWith(suffix)) {
14098 subStr = subStr.substring(0, subStr.length() - suffix.length());
14100 // If oldCodePath already contains prefix find out the
14101 // ending index to either increment or decrement.
14102 int sidx = subStr.lastIndexOf(prefix);
14104 subStr = subStr.substring(sidx + prefix.length());
14105 if (subStr != null) {
14106 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14107 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14110 idx = Integer.parseInt(subStr);
14116 } catch(NumberFormatException e) {
14121 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14122 return prefix + idxStr;
14125 private File getNextCodePath(File targetDir, String packageName) {
14129 result = new File(targetDir, packageName + "-" + suffix);
14131 } while (result.exists());
14135 // Utility method that returns the relative package path with respect
14136 // to the installation directory. Like say for /data/data/com.test-1.apk
14137 // string com.test-1 is returned.
14138 static String deriveCodePathName(String codePath) {
14139 if (codePath == null) {
14142 final File codeFile = new File(codePath);
14143 final String name = codeFile.getName();
14144 if (codeFile.isDirectory()) {
14146 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14147 final int lastDot = name.lastIndexOf('.');
14148 return name.substring(0, lastDot);
14150 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14155 static class PackageInstalledInfo {
14158 // The set of users that originally had this package installed.
14160 // The set of users that now have this package installed.
14162 PackageParser.Package pkg;
14165 PackageRemovedInfo removedInfo;
14166 ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14168 public void setError(int code, String msg) {
14169 setReturnCode(code);
14170 setReturnMessage(msg);
14174 public void setError(String msg, PackageParserException e) {
14175 setReturnCode(e.error);
14176 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14177 Slog.w(TAG, msg, e);
14180 public void setError(String msg, PackageManagerException e) {
14181 returnCode = e.error;
14182 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14183 Slog.w(TAG, msg, e);
14186 public void setReturnCode(int returnCode) {
14187 this.returnCode = returnCode;
14188 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14189 for (int i = 0; i < childCount; i++) {
14190 addedChildPackages.valueAt(i).returnCode = returnCode;
14194 private void setReturnMessage(String returnMsg) {
14195 this.returnMsg = returnMsg;
14196 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14197 for (int i = 0; i < childCount; i++) {
14198 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14202 // In some error cases we want to convey more info back to the observer
14203 String origPackage;
14204 String origPermission;
14208 * Install a non-existing package.
14210 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14211 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14212 PackageInstalledInfo res) {
14213 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14215 // Remember this for later, in case we need to rollback this install
14216 String pkgName = pkg.packageName;
14218 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14220 synchronized(mPackages) {
14221 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14222 // A package with the same name is already installed, though
14223 // it has been renamed to an older name. The package we
14224 // are trying to install should be installed as an update to
14225 // the existing one, but that has not been requested, so bail.
14226 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14227 + " without first uninstalling package running as "
14228 + mSettings.mRenamedPackages.get(pkgName));
14231 if (mPackages.containsKey(pkgName)) {
14232 // Don't allow installation over an existing package with the same name.
14233 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14234 + " without first uninstalling.");
14240 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14241 System.currentTimeMillis(), user);
14243 updateSettingsLI(newPackage, installerPackageName, null, res, user);
14245 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14246 prepareAppDataAfterInstallLIF(newPackage);
14249 // Remove package from internal structures, but keep around any
14250 // data that might have already existed
14251 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14252 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14254 } catch (PackageManagerException e) {
14255 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14261 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14262 // Can't rotate keys during boot or if sharedUser.
14263 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14264 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14267 // app is using upgradeKeySets; make sure all are valid
14268 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14269 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14270 for (int i = 0; i < upgradeKeySets.length; i++) {
14271 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14272 Slog.wtf(TAG, "Package "
14273 + (oldPs.name != null ? oldPs.name : "<null>")
14274 + " contains upgrade-key-set reference to unknown key-set: "
14275 + upgradeKeySets[i]
14276 + " reverting to signatures check.");
14283 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14284 // Upgrade keysets are being used. Determine if new package has a superset of the
14286 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14287 KeySetManagerService ksms = mSettings.mKeySetManagerService;
14288 for (int i = 0; i < upgradeKeySets.length; i++) {
14289 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14290 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14297 private static void updateDigest(MessageDigest digest, File file) throws IOException {
14298 try (DigestInputStream digestStream =
14299 new DigestInputStream(new FileInputStream(file), digest)) {
14300 while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14304 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14305 UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14306 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14308 final PackageParser.Package oldPackage;
14309 final String pkgName = pkg.packageName;
14310 final int[] allUsers;
14311 final int[] installedUsers;
14313 synchronized(mPackages) {
14314 oldPackage = mPackages.get(pkgName);
14315 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14317 // don't allow upgrade to target a release SDK from a pre-release SDK
14318 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14319 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14320 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14321 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14322 if (oldTargetsPreRelease
14323 && !newTargetsPreRelease
14324 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14325 Slog.w(TAG, "Can't install package targeting released sdk");
14326 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14330 // don't allow an upgrade from full to ephemeral
14331 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14332 if (isEphemeral && !oldIsEphemeral) {
14333 // can't downgrade from full to ephemeral
14334 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14335 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14339 // verify signatures are valid
14340 final PackageSetting ps = mSettings.mPackages.get(pkgName);
14341 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14342 if (!checkUpgradeKeySetLP(ps, pkg)) {
14343 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14344 "New package not signed by keys specified by upgrade-keysets: "
14349 // default to original signature matching
14350 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14351 != PackageManager.SIGNATURE_MATCH) {
14352 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14353 "New package has a different signature: " + pkgName);
14358 // don't allow a system upgrade unless the upgrade hash matches
14359 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14360 byte[] digestBytes = null;
14362 final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14363 updateDigest(digest, new File(pkg.baseCodePath));
14364 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14365 for (String path : pkg.splitCodePaths) {
14366 updateDigest(digest, new File(path));
14369 digestBytes = digest.digest();
14370 } catch (NoSuchAlgorithmException | IOException e) {
14371 res.setError(INSTALL_FAILED_INVALID_APK,
14372 "Could not compute hash: " + pkgName);
14375 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14376 res.setError(INSTALL_FAILED_INVALID_APK,
14377 "New package fails restrict-update check: " + pkgName);
14380 // retain upgrade restriction
14381 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14384 // Check for shared user id changes
14385 String invalidPackageName =
14386 getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14387 if (invalidPackageName != null) {
14388 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14389 "Package " + invalidPackageName + " tried to change user "
14390 + oldPackage.mSharedUserId);
14394 // In case of rollback, remember per-user/profile install state
14395 allUsers = sUserManager.getUserIds();
14396 installedUsers = ps.queryInstalledUsers(allUsers, true);
14399 // Update what is removed
14400 res.removedInfo = new PackageRemovedInfo();
14401 res.removedInfo.uid = oldPackage.applicationInfo.uid;
14402 res.removedInfo.removedPackage = oldPackage.packageName;
14403 res.removedInfo.isUpdate = true;
14404 res.removedInfo.origUsers = installedUsers;
14405 final int childCount = (oldPackage.childPackages != null)
14406 ? oldPackage.childPackages.size() : 0;
14407 for (int i = 0; i < childCount; i++) {
14408 boolean childPackageUpdated = false;
14409 PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14410 if (res.addedChildPackages != null) {
14411 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14412 if (childRes != null) {
14413 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14414 childRes.removedInfo.removedPackage = childPkg.packageName;
14415 childRes.removedInfo.isUpdate = true;
14416 childPackageUpdated = true;
14419 if (!childPackageUpdated) {
14420 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14421 childRemovedRes.removedPackage = childPkg.packageName;
14422 childRemovedRes.isUpdate = false;
14423 childRemovedRes.dataRemoved = true;
14424 synchronized (mPackages) {
14425 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14426 if (childPs != null) {
14427 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14430 if (res.removedInfo.removedChildPackages == null) {
14431 res.removedInfo.removedChildPackages = new ArrayMap<>();
14433 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14437 boolean sysPkg = (isSystemApp(oldPackage));
14439 // Set the system/privileged flags as needed
14440 final boolean privileged =
14441 (oldPackage.applicationInfo.privateFlags
14442 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14443 final int systemPolicyFlags = policyFlags
14444 | PackageParser.PARSE_IS_SYSTEM
14445 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14447 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14448 user, allUsers, installerPackageName, res);
14450 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14451 user, allUsers, installerPackageName, res);
14455 public List<String> getPreviousCodePaths(String packageName) {
14456 final PackageSetting ps = mSettings.mPackages.get(packageName);
14457 final List<String> result = new ArrayList<String>();
14458 if (ps != null && ps.oldCodePaths != null) {
14459 result.addAll(ps.oldCodePaths);
14464 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14465 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14466 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14467 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14470 String pkgName = deletedPackage.packageName;
14471 boolean deletedPkg = true;
14472 boolean addedPkg = false;
14473 boolean updatedSettings = false;
14474 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14475 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14476 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14478 final long origUpdateTime = (pkg.mExtras != null)
14479 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14481 // First delete the existing package while retaining the data directory
14482 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14483 res.removedInfo, true, pkg)) {
14484 // If the existing package wasn't successfully deleted
14485 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14486 deletedPkg = false;
14488 // Successfully deleted the old package; proceed with replace.
14490 // If deleted package lived in a container, give users a chance to
14491 // relinquish resources before killing.
14492 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14493 if (DEBUG_INSTALL) {
14494 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14496 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14497 final ArrayList<String> pkgList = new ArrayList<String>(1);
14498 pkgList.add(deletedPackage.applicationInfo.packageName);
14499 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14502 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14503 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14504 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14507 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14508 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14509 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14511 // Update the in-memory copy of the previous code paths.
14512 PackageSetting ps = mSettings.mPackages.get(pkgName);
14514 if (ps.oldCodePaths == null) {
14515 ps.oldCodePaths = new ArraySet<>();
14517 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14518 if (deletedPackage.splitCodePaths != null) {
14519 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14522 ps.oldCodePaths = null;
14524 if (ps.childPackageNames != null) {
14525 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14526 final String childPkgName = ps.childPackageNames.get(i);
14527 final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14528 childPs.oldCodePaths = ps.oldCodePaths;
14531 prepareAppDataAfterInstallLIF(newPackage);
14533 } catch (PackageManagerException e) {
14534 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14538 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14539 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14541 // Revert all internal state mutations and added folders for the failed install
14543 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14544 res.removedInfo, true, null);
14547 // Restore the old package
14549 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14550 File restoreFile = new File(deletedPackage.codePath);
14551 // Parse old package
14552 boolean oldExternal = isExternal(deletedPackage);
14553 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
14554 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14555 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14556 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14558 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14560 } catch (PackageManagerException e) {
14561 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14566 synchronized (mPackages) {
14567 // Ensure the installer package name up to date
14568 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14570 // Update permissions for restored package
14571 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14573 mSettings.writeLPr();
14576 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14579 synchronized (mPackages) {
14580 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14582 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14583 if (res.removedInfo.removedChildPackages != null) {
14584 final int childCount = res.removedInfo.removedChildPackages.size();
14585 // Iterate in reverse as we may modify the collection
14586 for (int i = childCount - 1; i >= 0; i--) {
14587 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14588 if (res.addedChildPackages.containsKey(childPackageName)) {
14589 res.removedInfo.removedChildPackages.removeAt(i);
14591 PackageRemovedInfo childInfo = res.removedInfo
14592 .removedChildPackages.valueAt(i);
14593 childInfo.removedForAllUsers = mPackages.get(
14594 childInfo.removedPackage) == null;
14603 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14604 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14605 int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14606 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14607 + ", old=" + deletedPackage);
14609 final boolean disabledSystem;
14611 // Remove existing system package
14612 removePackageLI(deletedPackage, true);
14614 synchronized (mPackages) {
14615 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14617 if (!disabledSystem) {
14618 // We didn't need to disable the .apk as a current system package,
14619 // which means we are replacing another update that is already
14620 // installed. We need to make sure to delete the older one's .apk.
14621 res.removedInfo.args = createInstallArgsForExisting(0,
14622 deletedPackage.applicationInfo.getCodePath(),
14623 deletedPackage.applicationInfo.getResourcePath(),
14624 getAppDexInstructionSets(deletedPackage.applicationInfo));
14626 res.removedInfo.args = null;
14629 // Successfully disabled the old package. Now proceed with re-installation
14630 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14631 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14632 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14634 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14635 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14636 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14638 PackageParser.Package newPackage = null;
14640 // Add the package to the internal data structures
14641 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14643 // Set the update and install times
14644 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14645 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14646 System.currentTimeMillis());
14648 // Update the package dynamic state if succeeded
14649 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14650 // Now that the install succeeded make sure we remove data
14651 // directories for any child package the update removed.
14652 final int deletedChildCount = (deletedPackage.childPackages != null)
14653 ? deletedPackage.childPackages.size() : 0;
14654 final int newChildCount = (newPackage.childPackages != null)
14655 ? newPackage.childPackages.size() : 0;
14656 for (int i = 0; i < deletedChildCount; i++) {
14657 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14658 boolean childPackageDeleted = true;
14659 for (int j = 0; j < newChildCount; j++) {
14660 PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14661 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14662 childPackageDeleted = false;
14666 if (childPackageDeleted) {
14667 PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14668 deletedChildPkg.packageName);
14669 if (ps != null && res.removedInfo.removedChildPackages != null) {
14670 PackageRemovedInfo removedChildRes = res.removedInfo
14671 .removedChildPackages.get(deletedChildPkg.packageName);
14672 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14673 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14678 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14679 prepareAppDataAfterInstallLIF(newPackage);
14681 } catch (PackageManagerException e) {
14682 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14683 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14686 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14687 // Re installation failed. Restore old information
14688 // Remove new pkg information
14689 if (newPackage != null) {
14690 removeInstalledPackageLI(newPackage, true);
14692 // Add back the old system package
14694 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14695 } catch (PackageManagerException e) {
14696 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14699 synchronized (mPackages) {
14700 if (disabledSystem) {
14701 enableSystemPackageLPw(deletedPackage);
14704 // Ensure the installer package name up to date
14705 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14707 // Update permissions for restored package
14708 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14710 mSettings.writeLPr();
14713 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14714 + " after failed upgrade");
14719 * Checks whether the parent or any of the child packages have a change shared
14720 * user. For a package to be a valid update the shred users of the parent and
14721 * the children should match. We may later support changing child shared users.
14722 * @param oldPkg The updated package.
14723 * @param newPkg The update package.
14724 * @return The shared user that change between the versions.
14726 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14727 PackageParser.Package newPkg) {
14728 // Check parent shared user
14729 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14730 return newPkg.packageName;
14732 // Check child shared users
14733 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14734 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14735 for (int i = 0; i < newChildCount; i++) {
14736 PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14737 // If this child was present, did it have the same shared user?
14738 for (int j = 0; j < oldChildCount; j++) {
14739 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14740 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14741 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14742 return newChildPkg.packageName;
14749 private void removeNativeBinariesLI(PackageSetting ps) {
14750 // Remove the lib path for the parent package
14752 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14753 // Remove the lib path for the child packages
14754 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14755 for (int i = 0; i < childCount; i++) {
14756 PackageSetting childPs = null;
14757 synchronized (mPackages) {
14758 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14760 if (childPs != null) {
14761 NativeLibraryHelper.removeNativeBinariesLI(childPs
14762 .legacyNativeLibraryPathString);
14768 private void enableSystemPackageLPw(PackageParser.Package pkg) {
14769 // Enable the parent package
14770 mSettings.enableSystemPackageLPw(pkg.packageName);
14771 // Enable the child packages
14772 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14773 for (int i = 0; i < childCount; i++) {
14774 PackageParser.Package childPkg = pkg.childPackages.get(i);
14775 mSettings.enableSystemPackageLPw(childPkg.packageName);
14779 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14780 PackageParser.Package newPkg) {
14781 // Disable the parent package (parent always replaced)
14782 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14783 // Disable the child packages
14784 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14785 for (int i = 0; i < childCount; i++) {
14786 PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14787 final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14788 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14793 private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14794 String installerPackageName) {
14795 // Enable the parent package
14796 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14797 // Enable the child packages
14798 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14799 for (int i = 0; i < childCount; i++) {
14800 PackageParser.Package childPkg = pkg.childPackages.get(i);
14801 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14805 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14806 // Collect all used permissions in the UID
14807 ArraySet<String> usedPermissions = new ArraySet<>();
14808 final int packageCount = su.packages.size();
14809 for (int i = 0; i < packageCount; i++) {
14810 PackageSetting ps = su.packages.valueAt(i);
14811 if (ps.pkg == null) {
14814 final int requestedPermCount = ps.pkg.requestedPermissions.size();
14815 for (int j = 0; j < requestedPermCount; j++) {
14816 String permission = ps.pkg.requestedPermissions.get(j);
14817 BasePermission bp = mSettings.mPermissions.get(permission);
14819 usedPermissions.add(permission);
14824 PermissionsState permissionsState = su.getPermissionsState();
14825 // Prune install permissions
14826 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14827 final int installPermCount = installPermStates.size();
14828 for (int i = installPermCount - 1; i >= 0; i--) {
14829 PermissionState permissionState = installPermStates.get(i);
14830 if (!usedPermissions.contains(permissionState.getName())) {
14831 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14833 permissionsState.revokeInstallPermission(bp);
14834 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14835 PackageManager.MASK_PERMISSION_FLAGS, 0);
14840 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14842 // Prune runtime permissions
14843 for (int userId : allUserIds) {
14844 List<PermissionState> runtimePermStates = permissionsState
14845 .getRuntimePermissionStates(userId);
14846 final int runtimePermCount = runtimePermStates.size();
14847 for (int i = runtimePermCount - 1; i >= 0; i--) {
14848 PermissionState permissionState = runtimePermStates.get(i);
14849 if (!usedPermissions.contains(permissionState.getName())) {
14850 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14852 permissionsState.revokeRuntimePermission(bp, userId);
14853 permissionsState.updatePermissionFlags(bp, userId,
14854 PackageManager.MASK_PERMISSION_FLAGS, 0);
14855 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14856 runtimePermissionChangedUserIds, userId);
14862 return runtimePermissionChangedUserIds;
14865 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14866 int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14867 // Update the parent package setting
14868 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14870 // Update the child packages setting
14871 final int childCount = (newPackage.childPackages != null)
14872 ? newPackage.childPackages.size() : 0;
14873 for (int i = 0; i < childCount; i++) {
14874 PackageParser.Package childPackage = newPackage.childPackages.get(i);
14875 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14876 updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14877 childRes.origUsers, childRes, user);
14881 private void updateSettingsInternalLI(PackageParser.Package newPackage,
14882 String installerPackageName, int[] allUsers, int[] installedForUsers,
14883 PackageInstalledInfo res, UserHandle user) {
14884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14886 String pkgName = newPackage.packageName;
14887 synchronized (mPackages) {
14888 //write settings. the installStatus will be incomplete at this stage.
14889 //note that the new package setting would have already been
14890 //added to mPackages. It hasn't been persisted yet.
14891 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14892 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14893 mSettings.writeLPr();
14894 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14897 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14898 synchronized (mPackages) {
14899 updatePermissionsLPw(newPackage.packageName, newPackage,
14900 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14901 ? UPDATE_PERMISSIONS_ALL : 0));
14902 // For system-bundled packages, we assume that installing an upgraded version
14903 // of the package implies that the user actually wants to run that new code,
14904 // so we enable the package.
14905 PackageSetting ps = mSettings.mPackages.get(pkgName);
14906 final int userId = user.getIdentifier();
14908 if (isSystemApp(newPackage)) {
14909 if (DEBUG_INSTALL) {
14910 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14912 // Enable system package for requested users
14913 if (res.origUsers != null) {
14914 for (int origUserId : res.origUsers) {
14915 if (userId == UserHandle.USER_ALL || userId == origUserId) {
14916 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14917 origUserId, installerPackageName);
14921 // Also convey the prior install/uninstall state
14922 if (allUsers != null && installedForUsers != null) {
14923 for (int currentUserId : allUsers) {
14924 final boolean installed = ArrayUtils.contains(
14925 installedForUsers, currentUserId);
14926 if (DEBUG_INSTALL) {
14927 Slog.d(TAG, " user " + currentUserId + " => " + installed);
14929 ps.setInstalled(installed, currentUserId);
14931 // these install state changes will be persisted in the
14932 // upcoming call to mSettings.writeLPr().
14935 // It's implied that when a user requests installation, they want the app to be
14936 // installed and enabled.
14937 if (userId != UserHandle.USER_ALL) {
14938 ps.setInstalled(true, userId);
14939 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14942 res.name = pkgName;
14943 res.uid = newPackage.applicationInfo.uid;
14944 res.pkg = newPackage;
14945 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14946 mSettings.setInstallerPackageName(pkgName, installerPackageName);
14947 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14948 //to update install status
14949 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14950 mSettings.writeLPr();
14951 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14954 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14957 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14959 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14960 installPackageLI(args, res);
14962 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14966 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14967 final int installFlags = args.installFlags;
14968 final String installerPackageName = args.installerPackageName;
14969 final String volumeUuid = args.volumeUuid;
14970 final File tmpPackageFile = new File(args.getCodePath());
14971 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14972 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14973 || (args.volumeUuid != null));
14974 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14975 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14976 boolean replace = false;
14977 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14978 if (args.move != null) {
14979 // moving a complete application; perform an initial scan on the new install location
14980 scanFlags |= SCAN_INITIAL;
14982 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14983 scanFlags |= SCAN_DONT_KILL_APP;
14986 // Result object to be returned
14987 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14989 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14992 if (ephemeral && (forwardLocked || onExternal)) {
14993 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14994 + " external=" + onExternal);
14995 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14999 // Retrieve PackageSettings and parse package
15000 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15001 | PackageParser.PARSE_ENFORCE_CODE
15002 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15003 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15004 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15005 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15006 PackageParser pp = new PackageParser();
15007 pp.setSeparateProcesses(mSeparateProcesses);
15008 pp.setDisplayMetrics(mMetrics);
15010 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15011 final PackageParser.Package pkg;
15013 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15014 } catch (PackageParserException e) {
15015 res.setError("Failed parse during installPackageLI", e);
15018 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15021 // If we are installing a clustered package add results for the children
15022 if (pkg.childPackages != null) {
15023 synchronized (mPackages) {
15024 final int childCount = pkg.childPackages.size();
15025 for (int i = 0; i < childCount; i++) {
15026 PackageParser.Package childPkg = pkg.childPackages.get(i);
15027 PackageInstalledInfo childRes = new PackageInstalledInfo();
15028 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15029 childRes.pkg = childPkg;
15030 childRes.name = childPkg.packageName;
15031 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15032 if (childPs != null) {
15033 childRes.origUsers = childPs.queryInstalledUsers(
15034 sUserManager.getUserIds(), true);
15036 if ((mPackages.containsKey(childPkg.packageName))) {
15037 childRes.removedInfo = new PackageRemovedInfo();
15038 childRes.removedInfo.removedPackage = childPkg.packageName;
15040 if (res.addedChildPackages == null) {
15041 res.addedChildPackages = new ArrayMap<>();
15043 res.addedChildPackages.put(childPkg.packageName, childRes);
15048 // If package doesn't declare API override, mark that we have an install
15049 // time CPU ABI override.
15050 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15051 pkg.cpuAbiOverride = args.abiOverride;
15054 String pkgName = res.name = pkg.packageName;
15055 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15056 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15057 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15063 // either use what we've been given or parse directly from the APK
15064 if (args.certificates != null) {
15066 PackageParser.populateCertificates(pkg, args.certificates);
15067 } catch (PackageParserException e) {
15068 // there was something wrong with the certificates we were given;
15069 // try to pull them from the APK
15070 PackageParser.collectCertificates(pkg, parseFlags);
15073 PackageParser.collectCertificates(pkg, parseFlags);
15075 } catch (PackageParserException e) {
15076 res.setError("Failed collect during installPackageLI", e);
15080 // Get rid of all references to package scan path via parser.
15082 String oldCodePath = null;
15083 boolean systemApp = false;
15084 synchronized (mPackages) {
15085 // Check if installing already existing package
15086 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15087 String oldName = mSettings.mRenamedPackages.get(pkgName);
15088 if (pkg.mOriginalPackages != null
15089 && pkg.mOriginalPackages.contains(oldName)
15090 && mPackages.containsKey(oldName)) {
15091 // This package is derived from an original package,
15092 // and this device has been updating from that original
15093 // name. We must continue using the original name, so
15094 // rename the new package here.
15095 pkg.setPackageName(oldName);
15096 pkgName = pkg.packageName;
15098 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15099 + oldName + " pkgName=" + pkgName);
15100 } else if (mPackages.containsKey(pkgName)) {
15101 // This package, under its official name, already exists
15102 // on the device; we should replace it.
15104 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15107 // Child packages are installed through the parent package
15108 if (pkg.parentPackage != null) {
15109 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15110 "Package " + pkg.packageName + " is child of package "
15111 + pkg.parentPackage.parentPackage + ". Child packages "
15112 + "can be updated only through the parent package.");
15117 // Prevent apps opting out from runtime permissions
15118 PackageParser.Package oldPackage = mPackages.get(pkgName);
15119 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15120 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15121 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15122 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15123 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15124 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15125 + " doesn't support runtime permissions but the old"
15126 + " target SDK " + oldTargetSdk + " does.");
15130 // Prevent installing of child packages
15131 if (oldPackage.parentPackage != null) {
15132 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15133 "Package " + pkg.packageName + " is child of package "
15134 + oldPackage.parentPackage + ". Child packages "
15135 + "can be updated only through the parent package.");
15141 PackageSetting ps = mSettings.mPackages.get(pkgName);
15143 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15145 // Quick sanity check that we're signed correctly if updating;
15146 // we'll check this again later when scanning, but we want to
15147 // bail early here before tripping over redefined permissions.
15148 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15149 if (!checkUpgradeKeySetLP(ps, pkg)) {
15150 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15151 + pkg.packageName + " upgrade keys do not match the "
15152 + "previously installed version");
15157 verifySignaturesLP(ps, pkg);
15158 } catch (PackageManagerException e) {
15159 res.setError(e.error, e.getMessage());
15164 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15165 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15166 systemApp = (ps.pkg.applicationInfo.flags &
15167 ApplicationInfo.FLAG_SYSTEM) != 0;
15169 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15172 // Check whether the newly-scanned package wants to define an already-defined perm
15173 int N = pkg.permissions.size();
15174 for (int i = N-1; i >= 0; i--) {
15175 PackageParser.Permission perm = pkg.permissions.get(i);
15176 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15178 // If the defining package is signed with our cert, it's okay. This
15179 // also includes the "updating the same package" case, of course.
15180 // "updating same package" could also involve key-rotation.
15181 final boolean sigsOk;
15182 if (bp.sourcePackage.equals(pkg.packageName)
15183 && (bp.packageSetting instanceof PackageSetting)
15184 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15186 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15188 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15189 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15192 // If the owning package is the system itself, we log but allow
15193 // install to proceed; we fail the install on all other permission
15195 if (!bp.sourcePackage.equals("android")) {
15196 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15197 + pkg.packageName + " attempting to redeclare permission "
15198 + perm.info.name + " already owned by " + bp.sourcePackage);
15199 res.origPermission = perm.info.name;
15200 res.origPackage = bp.sourcePackage;
15203 Slog.w(TAG, "Package " + pkg.packageName
15204 + " attempting to redeclare system permission "
15205 + perm.info.name + "; ignoring new declaration");
15206 pkg.permissions.remove(i);
15215 // Abort update; system app can't be replaced with app on sdcard
15216 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15217 "Cannot install updates to system apps on sdcard");
15219 } else if (ephemeral) {
15220 // Abort update; system app can't be replaced with an ephemeral app
15221 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15222 "Cannot update a system app with an ephemeral app");
15227 if (args.move != null) {
15228 // We did an in-place move, so dex is ready to roll
15229 scanFlags |= SCAN_NO_DEX;
15230 scanFlags |= SCAN_MOVE;
15232 synchronized (mPackages) {
15233 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15235 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15236 "Missing settings for moved package " + pkgName);
15239 // We moved the entire application as-is, so bring over the
15240 // previously derived ABI information.
15241 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15242 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15245 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15246 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15247 scanFlags |= SCAN_NO_DEX;
15250 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15251 args.abiOverride : pkg.cpuAbiOverride);
15252 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15253 true /* extract libs */);
15254 } catch (PackageManagerException pme) {
15255 Slog.e(TAG, "Error deriving application ABI", pme);
15256 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15260 // Shared libraries for the package need to be updated.
15261 synchronized (mPackages) {
15263 updateSharedLibrariesLPw(pkg, null);
15264 } catch (PackageManagerException e) {
15265 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15269 // Do not run PackageDexOptimizer through the local performDexOpt
15270 // method because `pkg` may not be in `mPackages` yet.
15272 // Also, don't fail application installs if the dexopt step fails.
15273 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15274 null /* instructionSets */, false /* checkProfiles */,
15275 getCompilerFilterForReason(REASON_INSTALL),
15276 getOrCreateCompilerPackageStats(pkg));
15277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15279 // Notify BackgroundDexOptService that the package has been changed.
15280 // If this is an update of a package which used to fail to compile,
15281 // BDOS will remove it from its blacklist.
15282 BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15285 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15286 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15290 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15292 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15293 "installPackageLI")) {
15295 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15296 installerPackageName, res);
15298 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15299 args.user, installerPackageName, volumeUuid, res);
15302 synchronized (mPackages) {
15303 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15305 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15308 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15309 for (int i = 0; i < childCount; i++) {
15310 PackageParser.Package childPkg = pkg.childPackages.get(i);
15311 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15312 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15313 if (childPs != null) {
15314 childRes.newUsers = childPs.queryInstalledUsers(
15315 sUserManager.getUserIds(), true);
15321 private void startIntentFilterVerifications(int userId, boolean replacing,
15322 PackageParser.Package pkg) {
15323 if (mIntentFilterVerifierComponent == null) {
15324 Slog.w(TAG, "No IntentFilter verification will not be done as "
15325 + "there is no IntentFilterVerifier available!");
15329 final int verifierUid = getPackageUid(
15330 mIntentFilterVerifierComponent.getPackageName(),
15331 MATCH_DEBUG_TRIAGED_MISSING,
15332 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15334 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15335 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15336 mHandler.sendMessage(msg);
15338 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15339 for (int i = 0; i < childCount; i++) {
15340 PackageParser.Package childPkg = pkg.childPackages.get(i);
15341 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15342 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15343 mHandler.sendMessage(msg);
15347 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15348 PackageParser.Package pkg) {
15349 int size = pkg.activities.size();
15351 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15352 "No activity, so no need to verify any IntentFilter!");
15356 final boolean hasDomainURLs = hasDomainURLs(pkg);
15357 if (!hasDomainURLs) {
15358 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15359 "No domain URLs, so no need to verify any IntentFilter!");
15363 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15364 + " if any IntentFilter from the " + size
15365 + " Activities needs verification ...");
15368 final String packageName = pkg.packageName;
15370 synchronized (mPackages) {
15371 // If this is a new install and we see that we've already run verification for this
15372 // package, we have nothing to do: it means the state was restored from backup.
15374 IntentFilterVerificationInfo ivi =
15375 mSettings.getIntentFilterVerificationLPr(packageName);
15377 if (DEBUG_DOMAIN_VERIFICATION) {
15378 Slog.i(TAG, "Package " + packageName+ " already verified: status="
15379 + ivi.getStatusString());
15385 // If any filters need to be verified, then all need to be.
15386 boolean needToVerify = false;
15387 for (PackageParser.Activity a : pkg.activities) {
15388 for (ActivityIntentInfo filter : a.intents) {
15389 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15390 if (DEBUG_DOMAIN_VERIFICATION) {
15391 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15393 needToVerify = true;
15399 if (needToVerify) {
15400 final int verificationId = mIntentFilterVerificationToken++;
15401 for (PackageParser.Activity a : pkg.activities) {
15402 for (ActivityIntentInfo filter : a.intents) {
15403 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15404 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15405 "Verification needed for IntentFilter:" + filter.toString());
15406 mIntentFilterVerifier.addOneIntentFilterVerification(
15407 verifierUid, userId, verificationId, filter, packageName);
15416 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15417 + " IntentFilter verification" + (count > 1 ? "s" : "")
15418 + " for userId:" + userId);
15419 mIntentFilterVerifier.startVerifications(userId);
15421 if (DEBUG_DOMAIN_VERIFICATION) {
15422 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15427 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15428 final ComponentName cn = filter.activity.getComponentName();
15429 final String packageName = cn.getPackageName();
15431 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15436 int status = ivi.getStatus();
15438 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15439 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15448 private static boolean isMultiArch(ApplicationInfo info) {
15449 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15452 private static boolean isExternal(PackageParser.Package pkg) {
15453 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15456 private static boolean isExternal(PackageSetting ps) {
15457 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15460 private static boolean isEphemeral(PackageParser.Package pkg) {
15461 return pkg.applicationInfo.isEphemeralApp();
15464 private static boolean isEphemeral(PackageSetting ps) {
15465 return ps.pkg != null && isEphemeral(ps.pkg);
15468 private static boolean isSystemApp(PackageParser.Package pkg) {
15469 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15472 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15473 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15476 private static boolean hasDomainURLs(PackageParser.Package pkg) {
15477 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15480 private static boolean isSystemApp(PackageSetting ps) {
15481 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15484 private static boolean isUpdatedSystemApp(PackageSetting ps) {
15485 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15488 private int packageFlagsToInstallFlags(PackageSetting ps) {
15489 int installFlags = 0;
15490 if (isEphemeral(ps)) {
15491 installFlags |= PackageManager.INSTALL_EPHEMERAL;
15493 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15494 // This existing package was an external ASEC install when we have
15495 // the external flag without a UUID
15496 installFlags |= PackageManager.INSTALL_EXTERNAL;
15498 if (ps.isForwardLocked()) {
15499 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15501 return installFlags;
15504 private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15505 if (isExternal(pkg)) {
15506 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15507 return StorageManager.UUID_PRIMARY_PHYSICAL;
15509 return pkg.volumeUuid;
15512 return StorageManager.UUID_PRIVATE_INTERNAL;
15516 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15517 if (isExternal(pkg)) {
15518 if (TextUtils.isEmpty(pkg.volumeUuid)) {
15519 return mSettings.getExternalVersion();
15521 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15524 return mSettings.getInternalVersion();
15528 private void deleteTempPackageFiles() {
15529 final FilenameFilter filter = new FilenameFilter() {
15530 public boolean accept(File dir, String name) {
15531 return name.startsWith("vmdl") && name.endsWith(".tmp");
15534 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15540 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15542 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15547 public void deletePackage(final String packageName,
15548 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15549 mContext.enforceCallingOrSelfPermission(
15550 android.Manifest.permission.DELETE_PACKAGES, null);
15551 Preconditions.checkNotNull(packageName);
15552 Preconditions.checkNotNull(observer);
15553 final int uid = Binder.getCallingUid();
15554 if (!isOrphaned(packageName)
15555 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15557 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15558 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15559 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15560 observer.onUserActionRequired(intent);
15561 } catch (RemoteException re) {
15565 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15566 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15567 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15568 mContext.enforceCallingOrSelfPermission(
15569 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15570 "deletePackage for user " + userId);
15573 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15575 observer.onPackageDeleted(packageName,
15576 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15577 } catch (RemoteException re) {
15582 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15584 observer.onPackageDeleted(packageName,
15585 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15586 } catch (RemoteException re) {
15591 if (DEBUG_REMOVE) {
15592 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15593 + " deleteAllUsers: " + deleteAllUsers );
15595 // Queue up an async operation since the package deletion may take a little while.
15596 mHandler.post(new Runnable() {
15597 public void run() {
15598 mHandler.removeCallbacks(this);
15600 if (!deleteAllUsers) {
15601 returnCode = deletePackageX(packageName, userId, deleteFlags);
15603 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15604 // If nobody is blocking uninstall, proceed with delete for all users
15605 if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15606 returnCode = deletePackageX(packageName, userId, deleteFlags);
15608 // Otherwise uninstall individually for users with blockUninstalls=false
15609 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15610 for (int userId : users) {
15611 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15612 returnCode = deletePackageX(packageName, userId, userFlags);
15613 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15614 Slog.w(TAG, "Package delete failed for user " + userId
15615 + ", returnCode " + returnCode);
15619 // The app has only been marked uninstalled for certain users.
15620 // We still need to report that delete was blocked
15621 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15625 observer.onPackageDeleted(packageName, returnCode, null);
15626 } catch (RemoteException e) {
15627 Log.i(TAG, "Observer no longer exists.");
15633 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15634 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15635 || callingUid == Process.SYSTEM_UID) {
15638 final int callingUserId = UserHandle.getUserId(callingUid);
15639 // If the caller installed the pkgName, then allow it to silently uninstall.
15640 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15644 // Allow package verifier to silently uninstall.
15645 if (mRequiredVerifierPackage != null &&
15646 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15650 // Allow package uninstaller to silently uninstall.
15651 if (mRequiredUninstallerPackage != null &&
15652 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15656 // Allow storage manager to silently uninstall.
15657 if (mStorageManagerPackage != null &&
15658 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15664 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15665 int[] result = EMPTY_INT_ARRAY;
15666 for (int userId : userIds) {
15667 if (getBlockUninstallForUser(packageName, userId)) {
15668 result = ArrayUtils.appendInt(result, userId);
15675 public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15676 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15679 private boolean isPackageDeviceAdmin(String packageName, int userId) {
15680 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15681 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15684 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15685 /* callingUserOnly =*/ false);
15686 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15687 : deviceOwnerComponentName.getPackageName();
15688 // Does the package contains the device owner?
15689 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise,
15690 // this check is probably not needed, since DO should be registered as a device
15691 // admin on some user too. (Original bug for this: b/17657954)
15692 if (packageName.equals(deviceOwnerPackageName)) {
15695 // Does it contain a device admin for any user?
15697 if (userId == UserHandle.USER_ALL) {
15698 users = sUserManager.getUserIds();
15700 users = new int[]{userId};
15702 for (int i = 0; i < users.length; ++i) {
15703 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15708 } catch (RemoteException e) {
15713 private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15714 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15718 * This method is an internal method that could be get invoked either
15719 * to delete an installed package or to clean up a failed installation.
15720 * After deleting an installed package, a broadcast is sent to notify any
15721 * listeners that the package has been removed. For cleaning up a failed
15722 * installation, the broadcast is not necessary since the package's
15723 * installation wouldn't have sent the initial broadcast either
15724 * The key steps in deleting a package are
15725 * deleting the package information in internal structures like mPackages,
15726 * deleting the packages base directories through installd
15727 * updating mSettings to reflect current status
15728 * persisting settings for later use
15729 * sending a broadcast if necessary
15731 private int deletePackageX(String packageName, int userId, int deleteFlags) {
15732 final PackageRemovedInfo info = new PackageRemovedInfo();
15735 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15736 ? UserHandle.USER_ALL : userId;
15738 if (isPackageDeviceAdmin(packageName, removeUser)) {
15739 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15740 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15743 PackageSetting uninstalledPs = null;
15745 // for the uninstall-updates case and restricted profiles, remember the per-
15746 // user handle installed state
15748 synchronized (mPackages) {
15749 uninstalledPs = mSettings.mPackages.get(packageName);
15750 if (uninstalledPs == null) {
15751 Slog.w(TAG, "Not removing non-existent package " + packageName);
15752 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15754 allUsers = sUserManager.getUserIds();
15755 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15758 final int freezeUser;
15759 if (isUpdatedSystemApp(uninstalledPs)
15760 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15761 // We're downgrading a system app, which will apply to all users, so
15762 // freeze them all during the downgrade
15763 freezeUser = UserHandle.USER_ALL;
15765 freezeUser = removeUser;
15768 synchronized (mInstallLock) {
15769 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15770 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15771 deleteFlags, "deletePackageX")) {
15772 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15773 deleteFlags | REMOVE_CHATTY, info, true, null);
15775 synchronized (mPackages) {
15777 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15783 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15784 info.sendPackageRemovedBroadcasts(killApp);
15785 info.sendSystemPackageUpdatedBroadcasts();
15786 info.sendSystemPackageAppearedBroadcasts();
15788 // Force a gc here.
15789 Runtime.getRuntime().gc();
15790 // Delete the resources here after sending the broadcast to let
15791 // other processes clean up before deleting resources.
15792 if (info.args != null) {
15793 synchronized (mInstallLock) {
15794 info.args.doPostDeleteLI(true);
15798 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15801 class PackageRemovedInfo {
15802 String removedPackage;
15804 int removedAppId = -1;
15806 int[] removedUsers = null;
15807 boolean isRemovedPackageSystemUpdate = false;
15809 boolean dataRemoved;
15810 boolean removedForAllUsers;
15811 // Clean up resources deleted packages.
15812 InstallArgs args = null;
15813 ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15814 ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15816 void sendPackageRemovedBroadcasts(boolean killApp) {
15817 sendPackageRemovedBroadcastInternal(killApp);
15818 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15819 for (int i = 0; i < childCount; i++) {
15820 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15821 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15825 void sendSystemPackageUpdatedBroadcasts() {
15826 if (isRemovedPackageSystemUpdate) {
15827 sendSystemPackageUpdatedBroadcastsInternal();
15828 final int childCount = (removedChildPackages != null)
15829 ? removedChildPackages.size() : 0;
15830 for (int i = 0; i < childCount; i++) {
15831 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15832 if (childInfo.isRemovedPackageSystemUpdate) {
15833 childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15839 void sendSystemPackageAppearedBroadcasts() {
15840 final int packageCount = (appearedChildPackages != null)
15841 ? appearedChildPackages.size() : 0;
15842 for (int i = 0; i < packageCount; i++) {
15843 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15844 for (int userId : installedInfo.newUsers) {
15845 sendPackageAddedForUser(installedInfo.name, true,
15846 UserHandle.getAppId(installedInfo.uid), userId);
15851 private void sendSystemPackageUpdatedBroadcastsInternal() {
15852 Bundle extras = new Bundle(2);
15853 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15854 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15855 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15856 extras, 0, null, null, null);
15857 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15858 extras, 0, null, null, null);
15859 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15860 null, 0, removedPackage, null, null);
15863 private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15864 Bundle extras = new Bundle(2);
15865 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15866 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15867 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15868 if (isUpdate || isRemovedPackageSystemUpdate) {
15869 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15871 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15872 if (removedPackage != null) {
15873 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15874 extras, 0, null, null, removedUsers);
15875 if (dataRemoved && !isRemovedPackageSystemUpdate) {
15876 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15877 removedPackage, extras, 0, null, null, removedUsers);
15880 if (removedAppId >= 0) {
15881 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15888 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15889 * flag is not set, the data directory is removed as well.
15890 * make sure this flag is set for partially installed apps. If not its meaningless to
15891 * delete a partially installed application.
15893 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15894 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15895 String packageName = ps.name;
15896 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15897 // Retrieve object to delete permissions for shared user later on
15898 final PackageParser.Package deletedPkg;
15899 final PackageSetting deletedPs;
15901 synchronized (mPackages) {
15902 deletedPkg = mPackages.get(packageName);
15903 deletedPs = mSettings.mPackages.get(packageName);
15904 if (outInfo != null) {
15905 outInfo.removedPackage = packageName;
15906 outInfo.removedUsers = deletedPs != null
15907 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15912 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15914 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15915 final PackageParser.Package resolvedPkg;
15916 if (deletedPkg != null) {
15917 resolvedPkg = deletedPkg;
15919 // We don't have a parsed package when it lives on an ejected
15920 // adopted storage device, so fake something together
15921 resolvedPkg = new PackageParser.Package(ps.name);
15922 resolvedPkg.setVolumeUuid(ps.volumeUuid);
15924 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15925 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15926 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15927 if (outInfo != null) {
15928 outInfo.dataRemoved = true;
15930 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15934 synchronized (mPackages) {
15935 if (deletedPs != null) {
15936 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15937 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15938 clearDefaultBrowserIfNeeded(packageName);
15939 if (outInfo != null) {
15940 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15941 outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15943 updatePermissionsLPw(deletedPs.name, null, 0);
15944 if (deletedPs.sharedUser != null) {
15945 // Remove permissions associated with package. Since runtime
15946 // permissions are per user we have to kill the removed package
15947 // or packages running under the shared user of the removed
15948 // package if revoking the permissions requested only by the removed
15949 // package is successful and this causes a change in gids.
15950 for (int userId : UserManagerService.getInstance().getUserIds()) {
15951 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15953 if (userIdToKill == UserHandle.USER_ALL
15954 || userIdToKill >= UserHandle.USER_SYSTEM) {
15955 // If gids changed for this user, kill all affected packages.
15956 mHandler.post(new Runnable() {
15958 public void run() {
15959 // This has to happen with no lock held.
15960 killApplication(deletedPs.name, deletedPs.appId,
15961 KILL_APP_REASON_GIDS_CHANGED);
15968 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15970 // make sure to preserve per-user disabled state if this removal was just
15971 // a downgrade of a system app to the factory package
15972 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15973 if (DEBUG_REMOVE) {
15974 Slog.d(TAG, "Propagating install state across downgrade");
15976 for (int userId : allUserHandles) {
15977 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15978 if (DEBUG_REMOVE) {
15979 Slog.d(TAG, " user " + userId + " => " + installed);
15981 ps.setInstalled(installed, userId);
15985 // can downgrade to reader
15986 if (writeSettings) {
15987 // Save settings now
15988 mSettings.writeLPr();
15991 if (outInfo != null) {
15992 // A user ID was deleted here. Go through all users and remove it
15994 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15998 static boolean locationIsPrivileged(File path) {
16000 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16001 .getCanonicalPath();
16002 return path.getCanonicalPath().startsWith(privilegedAppDir);
16003 } catch (IOException e) {
16004 Slog.e(TAG, "Unable to access code path " + path);
16010 * Tries to delete system package.
16012 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16013 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16014 boolean writeSettings) {
16015 if (deletedPs.parentPackageName != null) {
16016 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16020 final boolean applyUserRestrictions
16021 = (allUserHandles != null) && (outInfo.origUsers != null);
16022 final PackageSetting disabledPs;
16023 // Confirm if the system package has been updated
16024 // An updated system app can be deleted. This will also have to restore
16025 // the system pkg from system partition
16027 synchronized (mPackages) {
16028 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16031 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16032 + " disabledPs=" + disabledPs);
16034 if (disabledPs == null) {
16035 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16037 } else if (DEBUG_REMOVE) {
16038 Slog.d(TAG, "Deleting system pkg from data partition");
16041 if (DEBUG_REMOVE) {
16042 if (applyUserRestrictions) {
16043 Slog.d(TAG, "Remembering install states:");
16044 for (int userId : allUserHandles) {
16045 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16046 Slog.d(TAG, " u=" + userId + " inst=" + finstalled);
16051 // Delete the updated package
16052 outInfo.isRemovedPackageSystemUpdate = true;
16053 if (outInfo.removedChildPackages != null) {
16054 final int childCount = (deletedPs.childPackageNames != null)
16055 ? deletedPs.childPackageNames.size() : 0;
16056 for (int i = 0; i < childCount; i++) {
16057 String childPackageName = deletedPs.childPackageNames.get(i);
16058 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16059 .contains(childPackageName)) {
16060 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16062 if (childInfo != null) {
16063 childInfo.isRemovedPackageSystemUpdate = true;
16069 if (disabledPs.versionCode < deletedPs.versionCode) {
16070 // Delete data for downgrades
16071 flags &= ~PackageManager.DELETE_KEEP_DATA;
16073 // Preserve data by setting flag
16074 flags |= PackageManager.DELETE_KEEP_DATA;
16077 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16078 outInfo, writeSettings, disabledPs.pkg);
16084 synchronized (mPackages) {
16085 // Reinstate the old system package
16086 enableSystemPackageLPw(disabledPs.pkg);
16087 // Remove any native libraries from the upgraded package.
16088 removeNativeBinariesLI(deletedPs);
16091 // Install the system package
16092 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16093 int parseFlags = mDefParseFlags
16094 | PackageParser.PARSE_MUST_BE_APK
16095 | PackageParser.PARSE_IS_SYSTEM
16096 | PackageParser.PARSE_IS_SYSTEM_DIR;
16097 if (locationIsPrivileged(disabledPs.codePath)) {
16098 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16101 final PackageParser.Package newPkg;
16103 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16104 } catch (PackageManagerException e) {
16105 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16110 // update shared libraries for the newly re-installed system package
16111 updateSharedLibrariesLPw(newPkg, null);
16112 } catch (PackageManagerException e) {
16113 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16116 prepareAppDataAfterInstallLIF(newPkg);
16119 synchronized (mPackages) {
16120 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16122 // Propagate the permissions state as we do not want to drop on the floor
16123 // runtime permissions. The update permissions method below will take
16124 // care of removing obsolete permissions and grant install permissions.
16125 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16126 updatePermissionsLPw(newPkg.packageName, newPkg,
16127 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16129 if (applyUserRestrictions) {
16130 if (DEBUG_REMOVE) {
16131 Slog.d(TAG, "Propagating install state across reinstall");
16133 for (int userId : allUserHandles) {
16134 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16135 if (DEBUG_REMOVE) {
16136 Slog.d(TAG, " user " + userId + " => " + installed);
16138 ps.setInstalled(installed, userId);
16140 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16142 // Regardless of writeSettings we need to ensure that this restriction
16143 // state propagation is persisted
16144 mSettings.writeAllUsersPackageRestrictionsLPr();
16146 // can downgrade to reader here
16147 if (writeSettings) {
16148 mSettings.writeLPr();
16154 private boolean deleteInstalledPackageLIF(PackageSetting ps,
16155 boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16156 PackageRemovedInfo outInfo, boolean writeSettings,
16157 PackageParser.Package replacingPackage) {
16158 synchronized (mPackages) {
16159 if (outInfo != null) {
16160 outInfo.uid = ps.appId;
16163 if (outInfo != null && outInfo.removedChildPackages != null) {
16164 final int childCount = (ps.childPackageNames != null)
16165 ? ps.childPackageNames.size() : 0;
16166 for (int i = 0; i < childCount; i++) {
16167 String childPackageName = ps.childPackageNames.get(i);
16168 PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16169 if (childPs == null) {
16172 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16174 if (childInfo != null) {
16175 childInfo.uid = childPs.appId;
16181 // Delete package data from internal structures and also remove data if flag is set
16182 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16184 // Delete the child packages data
16185 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16186 for (int i = 0; i < childCount; i++) {
16187 PackageSetting childPs;
16188 synchronized (mPackages) {
16189 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16191 if (childPs != null) {
16192 PackageRemovedInfo childOutInfo = (outInfo != null
16193 && outInfo.removedChildPackages != null)
16194 ? outInfo.removedChildPackages.get(childPs.name) : null;
16195 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16196 && (replacingPackage != null
16197 && !replacingPackage.hasChildPackage(childPs.name))
16198 ? flags & ~DELETE_KEEP_DATA : flags;
16199 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16200 deleteFlags, writeSettings);
16204 // Delete application code and resources only for parent packages
16205 if (ps.parentPackageName == null) {
16206 if (deleteCodeAndResources && (outInfo != null)) {
16207 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16208 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16209 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16217 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16219 mContext.enforceCallingOrSelfPermission(
16220 android.Manifest.permission.DELETE_PACKAGES, null);
16221 synchronized (mPackages) {
16222 PackageSetting ps = mSettings.mPackages.get(packageName);
16224 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16227 if (!ps.getInstalled(userId)) {
16228 // Can't block uninstall for an app that is not installed or enabled.
16229 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16232 ps.setBlockUninstall(blockUninstall, userId);
16233 mSettings.writePackageRestrictionsLPr(userId);
16239 public boolean getBlockUninstallForUser(String packageName, int userId) {
16240 synchronized (mPackages) {
16241 PackageSetting ps = mSettings.mPackages.get(packageName);
16243 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16246 return ps.getBlockUninstall(userId);
16251 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16252 int callingUid = Binder.getCallingUid();
16253 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16254 throw new SecurityException(
16255 "setRequiredForSystemUser can only be run by the system or root");
16257 synchronized (mPackages) {
16258 PackageSetting ps = mSettings.mPackages.get(packageName);
16260 Log.w(TAG, "Package doesn't exist: " + packageName);
16263 if (systemUserApp) {
16264 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16266 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16268 mSettings.writeLPr();
16274 * This method handles package deletion in general
16276 private boolean deletePackageLIF(String packageName, UserHandle user,
16277 boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16278 PackageRemovedInfo outInfo, boolean writeSettings,
16279 PackageParser.Package replacingPackage) {
16280 if (packageName == null) {
16281 Slog.w(TAG, "Attempt to delete null packageName.");
16285 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16289 synchronized (mPackages) {
16290 ps = mSettings.mPackages.get(packageName);
16292 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16296 if (ps.parentPackageName != null && (!isSystemApp(ps)
16297 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16298 if (DEBUG_REMOVE) {
16299 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16300 + ((user == null) ? UserHandle.USER_ALL : user));
16302 final int removedUserId = (user != null) ? user.getIdentifier()
16303 : UserHandle.USER_ALL;
16304 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16307 markPackageUninstalledForUserLPw(ps, user);
16308 scheduleWritePackageRestrictionsLocked(user);
16313 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16314 && user.getIdentifier() != UserHandle.USER_ALL)) {
16315 // The caller is asking that the package only be deleted for a single
16316 // user. To do this, we just mark its uninstalled state and delete
16317 // its data. If this is a system app, we only allow this to happen if
16318 // they have set the special DELETE_SYSTEM_APP which requests different
16319 // semantics than normal for uninstalling system apps.
16320 markPackageUninstalledForUserLPw(ps, user);
16322 if (!isSystemApp(ps)) {
16323 // Do not uninstall the APK if an app should be cached
16324 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16325 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16326 // Other user still have this package installed, so all
16327 // we need to do is clear this user's data and save that
16328 // it is uninstalled.
16329 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16330 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16333 scheduleWritePackageRestrictionsLocked(user);
16336 // We need to set it back to 'installed' so the uninstall
16337 // broadcasts will be sent correctly.
16338 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16339 ps.setInstalled(true, user.getIdentifier());
16342 // This is a system app, so we assume that the
16343 // other users still have this package installed, so all
16344 // we need to do is clear this user's data and save that
16345 // it is uninstalled.
16346 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16347 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16350 scheduleWritePackageRestrictionsLocked(user);
16355 // If we are deleting a composite package for all users, keep track
16356 // of result for each child.
16357 if (ps.childPackageNames != null && outInfo != null) {
16358 synchronized (mPackages) {
16359 final int childCount = ps.childPackageNames.size();
16360 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16361 for (int i = 0; i < childCount; i++) {
16362 String childPackageName = ps.childPackageNames.get(i);
16363 PackageRemovedInfo childInfo = new PackageRemovedInfo();
16364 childInfo.removedPackage = childPackageName;
16365 outInfo.removedChildPackages.put(childPackageName, childInfo);
16366 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16367 if (childPs != null) {
16368 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16374 boolean ret = false;
16375 if (isSystemApp(ps)) {
16376 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16377 // When an updated system application is deleted we delete the existing resources
16378 // as well and fall back to existing code in system partition
16379 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16381 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16382 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16383 outInfo, writeSettings, replacingPackage);
16386 // Take a note whether we deleted the package for all users
16387 if (outInfo != null) {
16388 outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16389 if (outInfo.removedChildPackages != null) {
16390 synchronized (mPackages) {
16391 final int childCount = outInfo.removedChildPackages.size();
16392 for (int i = 0; i < childCount; i++) {
16393 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16394 if (childInfo != null) {
16395 childInfo.removedForAllUsers = mPackages.get(
16396 childInfo.removedPackage) == null;
16401 // If we uninstalled an update to a system app there may be some
16402 // child packages that appeared as they are declared in the system
16403 // app but were not declared in the update.
16404 if (isSystemApp(ps)) {
16405 synchronized (mPackages) {
16406 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16407 final int childCount = (updatedPs.childPackageNames != null)
16408 ? updatedPs.childPackageNames.size() : 0;
16409 for (int i = 0; i < childCount; i++) {
16410 String childPackageName = updatedPs.childPackageNames.get(i);
16411 if (outInfo.removedChildPackages == null
16412 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16413 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16414 if (childPs == null) {
16417 PackageInstalledInfo installRes = new PackageInstalledInfo();
16418 installRes.name = childPackageName;
16419 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16420 installRes.pkg = mPackages.get(childPackageName);
16421 installRes.uid = childPs.pkg.applicationInfo.uid;
16422 if (outInfo.appearedChildPackages == null) {
16423 outInfo.appearedChildPackages = new ArrayMap<>();
16425 outInfo.appearedChildPackages.put(childPackageName, installRes);
16435 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16436 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16437 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16438 for (int nextUserId : userIds) {
16439 if (DEBUG_REMOVE) {
16440 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16442 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16443 false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16444 false /*hidden*/, false /*suspended*/, null, null, null,
16445 false /*blockUninstall*/,
16446 ps.readUserState(nextUserId).domainVerificationStatus, 0);
16450 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16451 PackageRemovedInfo outInfo) {
16452 final PackageParser.Package pkg;
16453 synchronized (mPackages) {
16454 pkg = mPackages.get(ps.name);
16457 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16458 : new int[] {userId};
16459 for (int nextUserId : userIds) {
16460 if (DEBUG_REMOVE) {
16461 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16465 destroyAppDataLIF(pkg, userId,
16466 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16467 destroyAppProfilesLIF(pkg, userId);
16468 removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16469 schedulePackageCleaning(ps.name, nextUserId, false);
16470 synchronized (mPackages) {
16471 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16472 scheduleWritePackageRestrictionsLocked(nextUserId);
16474 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16478 if (outInfo != null) {
16479 outInfo.removedPackage = ps.name;
16480 outInfo.removedAppId = ps.appId;
16481 outInfo.removedUsers = userIds;
16487 private final class ClearStorageConnection implements ServiceConnection {
16488 IMediaContainerService mContainerService;
16491 public void onServiceConnected(ComponentName name, IBinder service) {
16492 synchronized (this) {
16493 mContainerService = IMediaContainerService.Stub.asInterface(service);
16499 public void onServiceDisconnected(ComponentName name) {
16503 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16504 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16506 final boolean mounted;
16507 if (Environment.isExternalStorageEmulated()) {
16510 final String status = Environment.getExternalStorageState();
16512 mounted = status.equals(Environment.MEDIA_MOUNTED)
16513 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16520 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16522 if (userId == UserHandle.USER_ALL) {
16523 users = sUserManager.getUserIds();
16525 users = new int[] { userId };
16527 final ClearStorageConnection conn = new ClearStorageConnection();
16528 if (mContext.bindServiceAsUser(
16529 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16531 for (int curUser : users) {
16532 long timeout = SystemClock.uptimeMillis() + 5000;
16533 synchronized (conn) {
16535 while (conn.mContainerService == null &&
16536 (now = SystemClock.uptimeMillis()) < timeout) {
16538 conn.wait(timeout - now);
16539 } catch (InterruptedException e) {
16543 if (conn.mContainerService == null) {
16547 final UserEnvironment userEnv = new UserEnvironment(curUser);
16548 clearDirectory(conn.mContainerService,
16549 userEnv.buildExternalStorageAppCacheDirs(packageName));
16551 clearDirectory(conn.mContainerService,
16552 userEnv.buildExternalStorageAppDataDirs(packageName));
16553 clearDirectory(conn.mContainerService,
16554 userEnv.buildExternalStorageAppMediaDirs(packageName));
16558 mContext.unbindService(conn);
16564 public void clearApplicationProfileData(String packageName) {
16565 enforceSystemOrRoot("Only the system can clear all profile data");
16567 final PackageParser.Package pkg;
16568 synchronized (mPackages) {
16569 pkg = mPackages.get(packageName);
16572 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16573 synchronized (mInstallLock) {
16574 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16575 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16576 true /* removeBaseMarker */);
16582 public void clearApplicationUserData(final String packageName,
16583 final IPackageDataObserver observer, final int userId) {
16584 mContext.enforceCallingOrSelfPermission(
16585 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16587 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16588 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16590 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16591 throw new SecurityException("Cannot clear data for a protected package: "
16594 // Queue up an async operation since the package deletion may take a little while.
16595 mHandler.post(new Runnable() {
16596 public void run() {
16597 mHandler.removeCallbacks(this);
16598 final boolean succeeded;
16599 try (PackageFreezer freezer = freezePackage(packageName,
16600 "clearApplicationUserData")) {
16601 synchronized (mInstallLock) {
16602 succeeded = clearApplicationUserDataLIF(packageName, userId);
16604 clearExternalStorageDataSync(packageName, userId, true);
16607 // invoke DeviceStorageMonitor's update method to clear any notifications
16608 DeviceStorageMonitorInternal dsm = LocalServices
16609 .getService(DeviceStorageMonitorInternal.class);
16614 if(observer != null) {
16616 observer.onRemoveCompleted(packageName, succeeded);
16617 } catch (RemoteException e) {
16618 Log.i(TAG, "Observer no longer exists.");
16620 } //end if observer
16625 private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16626 if (packageName == null) {
16627 Slog.w(TAG, "Attempt to delete null packageName.");
16631 // Try finding details about the requested package
16632 PackageParser.Package pkg;
16633 synchronized (mPackages) {
16634 pkg = mPackages.get(packageName);
16636 final PackageSetting ps = mSettings.mPackages.get(packageName);
16643 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16647 PackageSetting ps = (PackageSetting) pkg.mExtras;
16648 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16651 clearAppDataLIF(pkg, userId,
16652 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16654 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16655 removeKeystoreDataIfNeeded(userId, appId);
16657 UserManagerInternal umInternal = getUserManagerInternal();
16659 if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16660 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16661 } else if (umInternal.isUserRunning(userId)) {
16662 flags = StorageManager.FLAG_STORAGE_DE;
16666 prepareAppDataContentsLIF(pkg, userId, flags);
16672 * Reverts user permission state changes (permissions and flags) in
16673 * all packages for a given user.
16675 * @param userId The device user for which to do a reset.
16677 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16678 final int packageCount = mPackages.size();
16679 for (int i = 0; i < packageCount; i++) {
16680 PackageParser.Package pkg = mPackages.valueAt(i);
16681 PackageSetting ps = (PackageSetting) pkg.mExtras;
16682 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16686 private void resetNetworkPolicies(int userId) {
16687 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16691 * Reverts user permission state changes (permissions and flags).
16693 * @param ps The package for which to reset.
16694 * @param userId The device user for which to do a reset.
16696 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16697 final PackageSetting ps, final int userId) {
16698 if (ps.pkg == null) {
16702 // These are flags that can change base on user actions.
16703 final int userSettableMask = FLAG_PERMISSION_USER_SET
16704 | FLAG_PERMISSION_USER_FIXED
16705 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16706 | FLAG_PERMISSION_REVIEW_REQUIRED;
16708 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16709 | FLAG_PERMISSION_POLICY_FIXED;
16711 boolean writeInstallPermissions = false;
16712 boolean writeRuntimePermissions = false;
16714 final int permissionCount = ps.pkg.requestedPermissions.size();
16715 for (int i = 0; i < permissionCount; i++) {
16716 String permission = ps.pkg.requestedPermissions.get(i);
16718 BasePermission bp = mSettings.mPermissions.get(permission);
16723 // If shared user we just reset the state to which only this app contributed.
16724 if (ps.sharedUser != null) {
16725 boolean used = false;
16726 final int packageCount = ps.sharedUser.packages.size();
16727 for (int j = 0; j < packageCount; j++) {
16728 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16729 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16730 && pkg.pkg.requestedPermissions.contains(permission)) {
16740 PermissionsState permissionsState = ps.getPermissionsState();
16742 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16744 // Always clear the user settable flags.
16745 final boolean hasInstallState = permissionsState.getInstallPermissionState(
16747 // If permission review is enabled and this is a legacy app, mark the
16748 // permission as requiring a review as this is the initial state.
16750 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16751 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16752 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16754 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16755 if (hasInstallState) {
16756 writeInstallPermissions = true;
16758 writeRuntimePermissions = true;
16762 // Below is only runtime permission handling.
16763 if (!bp.isRuntime()) {
16767 // Never clobber system or policy.
16768 if ((oldFlags & policyOrSystemFlags) != 0) {
16772 // If this permission was granted by default, make sure it is.
16773 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16774 if (permissionsState.grantRuntimePermission(bp, userId)
16775 != PERMISSION_OPERATION_FAILURE) {
16776 writeRuntimePermissions = true;
16778 // If permission review is enabled the permissions for a legacy apps
16779 // are represented as constantly granted runtime ones, so don't revoke.
16780 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16781 // Otherwise, reset the permission.
16782 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16783 switch (revokeResult) {
16784 case PERMISSION_OPERATION_SUCCESS:
16785 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16786 writeRuntimePermissions = true;
16787 final int appId = ps.appId;
16788 mHandler.post(new Runnable() {
16790 public void run() {
16791 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16799 // Synchronously write as we are taking permissions away.
16800 if (writeRuntimePermissions) {
16801 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16804 // Synchronously write as we are taking permissions away.
16805 if (writeInstallPermissions) {
16806 mSettings.writeLPr();
16811 * Remove entries from the keystore daemon. Will only remove it if the
16812 * {@code appId} is valid.
16814 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16819 final KeyStore keyStore = KeyStore.getInstance();
16820 if (keyStore != null) {
16821 if (userId == UserHandle.USER_ALL) {
16822 for (final int individual : sUserManager.getUserIds()) {
16823 keyStore.clearUid(UserHandle.getUid(individual, appId));
16826 keyStore.clearUid(UserHandle.getUid(userId, appId));
16829 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16834 public void deleteApplicationCacheFiles(final String packageName,
16835 final IPackageDataObserver observer) {
16836 final int userId = UserHandle.getCallingUserId();
16837 deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16841 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16842 final IPackageDataObserver observer) {
16843 mContext.enforceCallingOrSelfPermission(
16844 android.Manifest.permission.DELETE_CACHE_FILES, null);
16845 enforceCrossUserPermission(Binder.getCallingUid(), userId,
16846 /* requireFullPermission= */ true, /* checkShell= */ false,
16847 "delete application cache files");
16849 final PackageParser.Package pkg;
16850 synchronized (mPackages) {
16851 pkg = mPackages.get(packageName);
16854 // Queue up an async operation since the package deletion may take a little while.
16855 mHandler.post(new Runnable() {
16856 public void run() {
16857 synchronized (mInstallLock) {
16858 final int flags = StorageManager.FLAG_STORAGE_DE
16859 | StorageManager.FLAG_STORAGE_CE;
16860 // We're only clearing cache files, so we don't care if the
16861 // app is unfrozen and still able to run
16862 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16863 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16865 clearExternalStorageDataSync(packageName, userId, false);
16866 if (observer != null) {
16868 observer.onRemoveCompleted(packageName, true);
16869 } catch (RemoteException e) {
16870 Log.i(TAG, "Observer no longer exists.");
16878 public void getPackageSizeInfo(final String packageName, int userHandle,
16879 final IPackageStatsObserver observer) {
16880 mContext.enforceCallingOrSelfPermission(
16881 android.Manifest.permission.GET_PACKAGE_SIZE, null);
16882 if (packageName == null) {
16883 throw new IllegalArgumentException("Attempt to get size of null packageName");
16886 PackageStats stats = new PackageStats(packageName, userHandle);
16889 * Queue up an async operation since the package measurement may take a
16892 Message msg = mHandler.obtainMessage(INIT_COPY);
16893 msg.obj = new MeasureParams(stats, observer);
16894 mHandler.sendMessage(msg);
16897 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16898 final PackageSetting ps;
16899 synchronized (mPackages) {
16900 ps = mSettings.mPackages.get(packageName);
16902 Slog.w(TAG, "Failed to find settings for " + packageName);
16907 mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16908 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16909 ps.getCeDataInode(userId), ps.codePathString, stats);
16910 } catch (InstallerException e) {
16911 Slog.w(TAG, String.valueOf(e));
16915 // For now, ignore code size of packages on system partition
16916 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16917 stats.codeSize = 0;
16923 private int getUidTargetSdkVersionLockedLPr(int uid) {
16924 Object obj = mSettings.getUserIdLPr(uid);
16925 if (obj instanceof SharedUserSetting) {
16926 final SharedUserSetting sus = (SharedUserSetting) obj;
16927 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16928 final Iterator<PackageSetting> it = sus.packages.iterator();
16929 while (it.hasNext()) {
16930 final PackageSetting ps = it.next();
16931 if (ps.pkg != null) {
16932 int v = ps.pkg.applicationInfo.targetSdkVersion;
16933 if (v < vers) vers = v;
16937 } else if (obj instanceof PackageSetting) {
16938 final PackageSetting ps = (PackageSetting) obj;
16939 if (ps.pkg != null) {
16940 return ps.pkg.applicationInfo.targetSdkVersion;
16943 return Build.VERSION_CODES.CUR_DEVELOPMENT;
16947 public void addPreferredActivity(IntentFilter filter, int match,
16948 ComponentName[] set, ComponentName activity, int userId) {
16949 addPreferredActivityInternal(filter, match, set, activity, true, userId,
16950 "Adding preferred");
16953 private void addPreferredActivityInternal(IntentFilter filter, int match,
16954 ComponentName[] set, ComponentName activity, boolean always, int userId,
16957 int callingUid = Binder.getCallingUid();
16958 enforceCrossUserPermission(callingUid, userId,
16959 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16960 if (filter.countActions() == 0) {
16961 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16964 synchronized (mPackages) {
16965 if (mContext.checkCallingOrSelfPermission(
16966 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16967 != PackageManager.PERMISSION_GRANTED) {
16968 if (getUidTargetSdkVersionLockedLPr(callingUid)
16969 < Build.VERSION_CODES.FROYO) {
16970 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16974 mContext.enforceCallingOrSelfPermission(
16975 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16978 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16979 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16981 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
16982 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16983 scheduleWritePackageRestrictionsLocked(userId);
16984 postPreferredActivityChangedBroadcast(userId);
16988 private void postPreferredActivityChangedBroadcast(int userId) {
16989 mHandler.post(() -> {
16990 final IActivityManager am = ActivityManagerNative.getDefault();
16995 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16996 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16998 am.broadcastIntent(null, intent, null, null,
16999 0, null, null, null, android.app.AppOpsManager.OP_NONE,
17000 null, false, false, userId);
17001 } catch (RemoteException e) {
17007 public void replacePreferredActivity(IntentFilter filter, int match,
17008 ComponentName[] set, ComponentName activity, int userId) {
17009 if (filter.countActions() != 1) {
17010 throw new IllegalArgumentException(
17011 "replacePreferredActivity expects filter to have only 1 action.");
17013 if (filter.countDataAuthorities() != 0
17014 || filter.countDataPaths() != 0
17015 || filter.countDataSchemes() > 1
17016 || filter.countDataTypes() != 0) {
17017 throw new IllegalArgumentException(
17018 "replacePreferredActivity expects filter to have no data authorities, " +
17019 "paths, or types; and at most one scheme.");
17022 final int callingUid = Binder.getCallingUid();
17023 enforceCrossUserPermission(callingUid, userId,
17024 true /* requireFullPermission */, false /* checkShell */,
17025 "replace preferred activity");
17026 synchronized (mPackages) {
17027 if (mContext.checkCallingOrSelfPermission(
17028 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17029 != PackageManager.PERMISSION_GRANTED) {
17030 if (getUidTargetSdkVersionLockedLPr(callingUid)
17031 < Build.VERSION_CODES.FROYO) {
17032 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17033 + Binder.getCallingUid());
17036 mContext.enforceCallingOrSelfPermission(
17037 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17040 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17042 // Get all of the existing entries that exactly match this filter.
17043 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17044 if (existing != null && existing.size() == 1) {
17045 PreferredActivity cur = existing.get(0);
17046 if (DEBUG_PREFERRED) {
17047 Slog.i(TAG, "Checking replace of preferred:");
17048 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17049 if (!cur.mPref.mAlways) {
17050 Slog.i(TAG, " -- CUR; not mAlways!");
17052 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
17053 Slog.i(TAG, " -- CUR: mSet="
17054 + Arrays.toString(cur.mPref.mSetComponents));
17055 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
17056 Slog.i(TAG, " -- NEW: mMatch="
17057 + (match&IntentFilter.MATCH_CATEGORY_MASK));
17058 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
17059 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
17062 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17063 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17064 && cur.mPref.sameSet(set)) {
17065 // Setting the preferred activity to what it happens to be already
17066 if (DEBUG_PREFERRED) {
17067 Slog.i(TAG, "Replacing with same preferred activity "
17068 + cur.mPref.mShortComponent + " for user "
17070 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17076 if (existing != null) {
17077 if (DEBUG_PREFERRED) {
17078 Slog.i(TAG, existing.size() + " existing preferred matches for:");
17079 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17081 for (int i = 0; i < existing.size(); i++) {
17082 PreferredActivity pa = existing.get(i);
17083 if (DEBUG_PREFERRED) {
17084 Slog.i(TAG, "Removing existing preferred activity "
17085 + pa.mPref.mComponent + ":");
17086 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
17088 pir.removeFilter(pa);
17092 addPreferredActivityInternal(filter, match, set, activity, true, userId,
17093 "Replacing preferred");
17098 public void clearPackagePreferredActivities(String packageName) {
17099 final int uid = Binder.getCallingUid();
17101 synchronized (mPackages) {
17102 PackageParser.Package pkg = mPackages.get(packageName);
17103 if (pkg == null || pkg.applicationInfo.uid != uid) {
17104 if (mContext.checkCallingOrSelfPermission(
17105 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17106 != PackageManager.PERMISSION_GRANTED) {
17107 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17108 < Build.VERSION_CODES.FROYO) {
17109 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17110 + Binder.getCallingUid());
17113 mContext.enforceCallingOrSelfPermission(
17114 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17118 int user = UserHandle.getCallingUserId();
17119 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17120 scheduleWritePackageRestrictionsLocked(user);
17125 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17126 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17127 ArrayList<PreferredActivity> removed = null;
17128 boolean changed = false;
17129 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17130 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17131 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17132 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17135 Iterator<PreferredActivity> it = pir.filterIterator();
17136 while (it.hasNext()) {
17137 PreferredActivity pa = it.next();
17138 // Mark entry for removal only if it matches the package name
17139 // and the entry is of type "always".
17140 if (packageName == null ||
17141 (pa.mPref.mComponent.getPackageName().equals(packageName)
17142 && pa.mPref.mAlways)) {
17143 if (removed == null) {
17144 removed = new ArrayList<PreferredActivity>();
17149 if (removed != null) {
17150 for (int j=0; j<removed.size(); j++) {
17151 PreferredActivity pa = removed.get(j);
17152 pir.removeFilter(pa);
17158 postPreferredActivityChangedBroadcast(userId);
17163 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17164 private void clearIntentFilterVerificationsLPw(int userId) {
17165 final int packageCount = mPackages.size();
17166 for (int i = 0; i < packageCount; i++) {
17167 PackageParser.Package pkg = mPackages.valueAt(i);
17168 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17172 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17173 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17174 if (userId == UserHandle.USER_ALL) {
17175 if (mSettings.removeIntentFilterVerificationLPw(packageName,
17176 sUserManager.getUserIds())) {
17177 for (int oneUserId : sUserManager.getUserIds()) {
17178 scheduleWritePackageRestrictionsLocked(oneUserId);
17182 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17183 scheduleWritePackageRestrictionsLocked(userId);
17188 void clearDefaultBrowserIfNeeded(String packageName) {
17189 for (int oneUserId : sUserManager.getUserIds()) {
17190 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17191 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17192 if (packageName.equals(defaultBrowserPackageName)) {
17193 setDefaultBrowserPackageName(null, oneUserId);
17199 public void resetApplicationPreferences(int userId) {
17200 mContext.enforceCallingOrSelfPermission(
17201 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17202 final long identity = Binder.clearCallingIdentity();
17205 synchronized (mPackages) {
17206 clearPackagePreferredActivitiesLPw(null, userId);
17207 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17208 // TODO: We have to reset the default SMS and Phone. This requires
17209 // significant refactoring to keep all default apps in the package
17210 // manager (cleaner but more work) or have the services provide
17211 // callbacks to the package manager to request a default app reset.
17212 applyFactoryDefaultBrowserLPw(userId);
17213 clearIntentFilterVerificationsLPw(userId);
17214 primeDomainVerificationsLPw(userId);
17215 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17216 scheduleWritePackageRestrictionsLocked(userId);
17218 resetNetworkPolicies(userId);
17220 Binder.restoreCallingIdentity(identity);
17225 public int getPreferredActivities(List<IntentFilter> outFilters,
17226 List<ComponentName> outActivities, String packageName) {
17229 final int userId = UserHandle.getCallingUserId();
17231 synchronized (mPackages) {
17232 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17234 final Iterator<PreferredActivity> it = pir.filterIterator();
17235 while (it.hasNext()) {
17236 final PreferredActivity pa = it.next();
17237 if (packageName == null
17238 || (pa.mPref.mComponent.getPackageName().equals(packageName)
17239 && pa.mPref.mAlways)) {
17240 if (outFilters != null) {
17241 outFilters.add(new IntentFilter(pa));
17243 if (outActivities != null) {
17244 outActivities.add(pa.mPref.mComponent);
17255 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17257 int callingUid = Binder.getCallingUid();
17258 if (callingUid != Process.SYSTEM_UID) {
17259 throw new SecurityException(
17260 "addPersistentPreferredActivity can only be run by the system");
17262 if (filter.countActions() == 0) {
17263 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17266 synchronized (mPackages) {
17267 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17269 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
17270 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17271 new PersistentPreferredActivity(filter, activity));
17272 scheduleWritePackageRestrictionsLocked(userId);
17273 postPreferredActivityChangedBroadcast(userId);
17278 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17279 int callingUid = Binder.getCallingUid();
17280 if (callingUid != Process.SYSTEM_UID) {
17281 throw new SecurityException(
17282 "clearPackagePersistentPreferredActivities can only be run by the system");
17284 ArrayList<PersistentPreferredActivity> removed = null;
17285 boolean changed = false;
17286 synchronized (mPackages) {
17287 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17288 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17289 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17291 if (userId != thisUserId) {
17294 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17295 while (it.hasNext()) {
17296 PersistentPreferredActivity ppa = it.next();
17297 // Mark entry for removal only if it matches the package name.
17298 if (ppa.mComponent.getPackageName().equals(packageName)) {
17299 if (removed == null) {
17300 removed = new ArrayList<PersistentPreferredActivity>();
17305 if (removed != null) {
17306 for (int j=0; j<removed.size(); j++) {
17307 PersistentPreferredActivity ppa = removed.get(j);
17308 ppir.removeFilter(ppa);
17315 scheduleWritePackageRestrictionsLocked(userId);
17316 postPreferredActivityChangedBroadcast(userId);
17322 * Common machinery for picking apart a restored XML blob and passing
17323 * it to a caller-supplied functor to be applied to the running system.
17325 private void restoreFromXml(XmlPullParser parser, int userId,
17326 String expectedStartTag, BlobXmlRestorer functor)
17327 throws IOException, XmlPullParserException {
17329 while ((type = parser.next()) != XmlPullParser.START_TAG
17330 && type != XmlPullParser.END_DOCUMENT) {
17332 if (type != XmlPullParser.START_TAG) {
17333 // oops didn't find a start tag?!
17334 if (DEBUG_BACKUP) {
17335 Slog.e(TAG, "Didn't find start tag during restore");
17339 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17340 // this is supposed to be TAG_PREFERRED_BACKUP
17341 if (!expectedStartTag.equals(parser.getName())) {
17342 if (DEBUG_BACKUP) {
17343 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17348 // skip interfering stuff, then we're aligned with the backing implementation
17349 while ((type = parser.next()) == XmlPullParser.TEXT) { }
17350 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17351 functor.apply(parser, userId);
17354 private interface BlobXmlRestorer {
17355 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17359 * Non-Binder method, support for the backup/restore mechanism: write the
17360 * full set of preferred activities in its canonical XML format. Returns the
17361 * XML output as a byte array, or null if there is none.
17364 public byte[] getPreferredActivityBackup(int userId) {
17365 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17366 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17369 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17371 final XmlSerializer serializer = new FastXmlSerializer();
17372 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17373 serializer.startDocument(null, true);
17374 serializer.startTag(null, TAG_PREFERRED_BACKUP);
17376 synchronized (mPackages) {
17377 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17380 serializer.endTag(null, TAG_PREFERRED_BACKUP);
17381 serializer.endDocument();
17382 serializer.flush();
17383 } catch (Exception e) {
17384 if (DEBUG_BACKUP) {
17385 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17390 return dataStream.toByteArray();
17394 public void restorePreferredActivities(byte[] backup, int userId) {
17395 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17396 throw new SecurityException("Only the system may call restorePreferredActivities()");
17400 final XmlPullParser parser = Xml.newPullParser();
17401 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17402 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17403 new BlobXmlRestorer() {
17405 public void apply(XmlPullParser parser, int userId)
17406 throws XmlPullParserException, IOException {
17407 synchronized (mPackages) {
17408 mSettings.readPreferredActivitiesLPw(parser, userId);
17412 } catch (Exception e) {
17413 if (DEBUG_BACKUP) {
17414 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17420 * Non-Binder method, support for the backup/restore mechanism: write the
17421 * default browser (etc) settings in its canonical XML format. Returns the default
17422 * browser XML representation as a byte array, or null if there is none.
17425 public byte[] getDefaultAppsBackup(int userId) {
17426 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17427 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17430 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17432 final XmlSerializer serializer = new FastXmlSerializer();
17433 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17434 serializer.startDocument(null, true);
17435 serializer.startTag(null, TAG_DEFAULT_APPS);
17437 synchronized (mPackages) {
17438 mSettings.writeDefaultAppsLPr(serializer, userId);
17441 serializer.endTag(null, TAG_DEFAULT_APPS);
17442 serializer.endDocument();
17443 serializer.flush();
17444 } catch (Exception e) {
17445 if (DEBUG_BACKUP) {
17446 Slog.e(TAG, "Unable to write default apps for backup", e);
17451 return dataStream.toByteArray();
17455 public void restoreDefaultApps(byte[] backup, int userId) {
17456 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17457 throw new SecurityException("Only the system may call restoreDefaultApps()");
17461 final XmlPullParser parser = Xml.newPullParser();
17462 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17463 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17464 new BlobXmlRestorer() {
17466 public void apply(XmlPullParser parser, int userId)
17467 throws XmlPullParserException, IOException {
17468 synchronized (mPackages) {
17469 mSettings.readDefaultAppsLPw(parser, userId);
17473 } catch (Exception e) {
17474 if (DEBUG_BACKUP) {
17475 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17481 public byte[] getIntentFilterVerificationBackup(int userId) {
17482 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17483 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17486 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17488 final XmlSerializer serializer = new FastXmlSerializer();
17489 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17490 serializer.startDocument(null, true);
17491 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17493 synchronized (mPackages) {
17494 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17497 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17498 serializer.endDocument();
17499 serializer.flush();
17500 } catch (Exception e) {
17501 if (DEBUG_BACKUP) {
17502 Slog.e(TAG, "Unable to write default apps for backup", e);
17507 return dataStream.toByteArray();
17511 public void restoreIntentFilterVerification(byte[] backup, int userId) {
17512 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17513 throw new SecurityException("Only the system may call restorePreferredActivities()");
17517 final XmlPullParser parser = Xml.newPullParser();
17518 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17519 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17520 new BlobXmlRestorer() {
17522 public void apply(XmlPullParser parser, int userId)
17523 throws XmlPullParserException, IOException {
17524 synchronized (mPackages) {
17525 mSettings.readAllDomainVerificationsLPr(parser, userId);
17526 mSettings.writeLPr();
17530 } catch (Exception e) {
17531 if (DEBUG_BACKUP) {
17532 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17538 public byte[] getPermissionGrantBackup(int userId) {
17539 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17540 throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17543 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17545 final XmlSerializer serializer = new FastXmlSerializer();
17546 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17547 serializer.startDocument(null, true);
17548 serializer.startTag(null, TAG_PERMISSION_BACKUP);
17550 synchronized (mPackages) {
17551 serializeRuntimePermissionGrantsLPr(serializer, userId);
17554 serializer.endTag(null, TAG_PERMISSION_BACKUP);
17555 serializer.endDocument();
17556 serializer.flush();
17557 } catch (Exception e) {
17558 if (DEBUG_BACKUP) {
17559 Slog.e(TAG, "Unable to write default apps for backup", e);
17564 return dataStream.toByteArray();
17568 public void restorePermissionGrants(byte[] backup, int userId) {
17569 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17570 throw new SecurityException("Only the system may call restorePermissionGrants()");
17574 final XmlPullParser parser = Xml.newPullParser();
17575 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17576 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17577 new BlobXmlRestorer() {
17579 public void apply(XmlPullParser parser, int userId)
17580 throws XmlPullParserException, IOException {
17581 synchronized (mPackages) {
17582 processRestoredPermissionGrantsLPr(parser, userId);
17586 } catch (Exception e) {
17587 if (DEBUG_BACKUP) {
17588 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17593 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17594 throws IOException {
17595 serializer.startTag(null, TAG_ALL_GRANTS);
17597 final int N = mSettings.mPackages.size();
17598 for (int i = 0; i < N; i++) {
17599 final PackageSetting ps = mSettings.mPackages.valueAt(i);
17600 boolean pkgGrantsKnown = false;
17602 PermissionsState packagePerms = ps.getPermissionsState();
17604 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17605 final int grantFlags = state.getFlags();
17606 // only look at grants that are not system/policy fixed
17607 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17608 final boolean isGranted = state.isGranted();
17609 // And only back up the user-twiddled state bits
17610 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17611 final String packageName = mSettings.mPackages.keyAt(i);
17612 if (!pkgGrantsKnown) {
17613 serializer.startTag(null, TAG_GRANT);
17614 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17615 pkgGrantsKnown = true;
17618 final boolean userSet =
17619 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17620 final boolean userFixed =
17621 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17622 final boolean revoke =
17623 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17625 serializer.startTag(null, TAG_PERMISSION);
17626 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17628 serializer.attribute(null, ATTR_IS_GRANTED, "true");
17631 serializer.attribute(null, ATTR_USER_SET, "true");
17634 serializer.attribute(null, ATTR_USER_FIXED, "true");
17637 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17639 serializer.endTag(null, TAG_PERMISSION);
17644 if (pkgGrantsKnown) {
17645 serializer.endTag(null, TAG_GRANT);
17649 serializer.endTag(null, TAG_ALL_GRANTS);
17652 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17653 throws XmlPullParserException, IOException {
17654 String pkgName = null;
17655 int outerDepth = parser.getDepth();
17657 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17658 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17659 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17663 final String tagName = parser.getName();
17664 if (tagName.equals(TAG_GRANT)) {
17665 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17666 if (DEBUG_BACKUP) {
17667 Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17669 } else if (tagName.equals(TAG_PERMISSION)) {
17671 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17672 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17674 int newFlagSet = 0;
17675 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17676 newFlagSet |= FLAG_PERMISSION_USER_SET;
17678 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17679 newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17681 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17682 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17684 if (DEBUG_BACKUP) {
17685 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName
17686 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17688 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17690 // Already installed so we apply the grant immediately
17691 if (DEBUG_BACKUP) {
17692 Slog.v(TAG, " + already installed; applying");
17694 PermissionsState perms = ps.getPermissionsState();
17695 BasePermission bp = mSettings.mPermissions.get(permName);
17698 perms.grantRuntimePermission(bp, userId);
17700 if (newFlagSet != 0) {
17701 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17705 // Need to wait for post-restore install to apply the grant
17706 if (DEBUG_BACKUP) {
17707 Slog.v(TAG, " - not yet installed; saving for later");
17709 mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17710 isGranted, newFlagSet, userId);
17713 PackageManagerService.reportSettingsProblem(Log.WARN,
17714 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17715 XmlUtils.skipCurrentTag(parser);
17719 scheduleWriteSettingsLocked();
17720 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17724 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17725 int sourceUserId, int targetUserId, int flags) {
17726 mContext.enforceCallingOrSelfPermission(
17727 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17728 int callingUid = Binder.getCallingUid();
17729 enforceOwnerRights(ownerPackage, callingUid);
17730 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17731 if (intentFilter.countActions() == 0) {
17732 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17735 synchronized (mPackages) {
17736 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17737 ownerPackage, targetUserId, flags);
17738 CrossProfileIntentResolver resolver =
17739 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17740 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17741 // We have all those whose filter is equal. Now checking if the rest is equal as well.
17742 if (existing != null) {
17743 int size = existing.size();
17744 for (int i = 0; i < size; i++) {
17745 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17750 resolver.addFilter(newFilter);
17751 scheduleWritePackageRestrictionsLocked(sourceUserId);
17756 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17757 mContext.enforceCallingOrSelfPermission(
17758 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17759 int callingUid = Binder.getCallingUid();
17760 enforceOwnerRights(ownerPackage, callingUid);
17761 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17762 synchronized (mPackages) {
17763 CrossProfileIntentResolver resolver =
17764 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17765 ArraySet<CrossProfileIntentFilter> set =
17766 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17767 for (CrossProfileIntentFilter filter : set) {
17768 if (filter.getOwnerPackage().equals(ownerPackage)) {
17769 resolver.removeFilter(filter);
17772 scheduleWritePackageRestrictionsLocked(sourceUserId);
17776 // Enforcing that callingUid is owning pkg on userId
17777 private void enforceOwnerRights(String pkg, int callingUid) {
17778 // The system owns everything.
17779 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17782 int callingUserId = UserHandle.getUserId(callingUid);
17783 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17785 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17788 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17789 throw new SecurityException("Calling uid " + callingUid
17790 + " does not own package " + pkg);
17795 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17796 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17799 private Intent getHomeIntent() {
17800 Intent intent = new Intent(Intent.ACTION_MAIN);
17801 intent.addCategory(Intent.CATEGORY_HOME);
17802 intent.addCategory(Intent.CATEGORY_DEFAULT);
17806 private IntentFilter getHomeFilter() {
17807 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17808 filter.addCategory(Intent.CATEGORY_HOME);
17809 filter.addCategory(Intent.CATEGORY_DEFAULT);
17813 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17815 Intent intent = getHomeIntent();
17816 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17817 PackageManager.GET_META_DATA, userId);
17818 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17819 true, false, false, userId);
17821 allHomeCandidates.clear();
17822 if (list != null) {
17823 for (ResolveInfo ri : list) {
17824 allHomeCandidates.add(ri);
17827 return (preferred == null || preferred.activityInfo == null)
17829 : new ComponentName(preferred.activityInfo.packageName,
17830 preferred.activityInfo.name);
17834 public void setHomeActivity(ComponentName comp, int userId) {
17835 ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17836 getHomeActivitiesAsUser(homeActivities, userId);
17838 boolean found = false;
17840 final int size = homeActivities.size();
17841 final ComponentName[] set = new ComponentName[size];
17842 for (int i = 0; i < size; i++) {
17843 final ResolveInfo candidate = homeActivities.get(i);
17844 final ActivityInfo info = candidate.activityInfo;
17845 final ComponentName activityName = new ComponentName(info.packageName, info.name);
17846 set[i] = activityName;
17847 if (!found && activityName.equals(comp)) {
17852 throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17855 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17856 set, comp, userId);
17859 private @Nullable String getSetupWizardPackageName() {
17860 final Intent intent = new Intent(Intent.ACTION_MAIN);
17861 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17863 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17864 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17865 | MATCH_DISABLED_COMPONENTS,
17866 UserHandle.myUserId());
17867 if (matches.size() == 1) {
17868 return matches.get(0).getComponentInfo().packageName;
17870 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17871 + ": matches=" + matches);
17876 private @Nullable String getStorageManagerPackageName() {
17877 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17879 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17880 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17881 | MATCH_DISABLED_COMPONENTS,
17882 UserHandle.myUserId());
17883 if (matches.size() == 1) {
17884 return matches.get(0).getComponentInfo().packageName;
17886 Slog.e(TAG, "There should probably be exactly one storage manager; found "
17887 + matches.size() + ": matches=" + matches);
17893 public void setApplicationEnabledSetting(String appPackageName,
17894 int newState, int flags, int userId, String callingPackage) {
17895 if (!sUserManager.exists(userId)) return;
17896 if (callingPackage == null) {
17897 callingPackage = Integer.toString(Binder.getCallingUid());
17899 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17903 public void setComponentEnabledSetting(ComponentName componentName,
17904 int newState, int flags, int userId) {
17905 if (!sUserManager.exists(userId)) return;
17906 setEnabledSetting(componentName.getPackageName(),
17907 componentName.getClassName(), newState, flags, userId, null);
17910 private void setEnabledSetting(final String packageName, String className, int newState,
17911 final int flags, int userId, String callingPackage) {
17912 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17913 || newState == COMPONENT_ENABLED_STATE_ENABLED
17914 || newState == COMPONENT_ENABLED_STATE_DISABLED
17915 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17916 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17917 throw new IllegalArgumentException("Invalid new component state: "
17920 PackageSetting pkgSetting;
17921 final int uid = Binder.getCallingUid();
17922 final int permission;
17923 if (uid == Process.SYSTEM_UID) {
17924 permission = PackageManager.PERMISSION_GRANTED;
17926 permission = mContext.checkCallingOrSelfPermission(
17927 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17929 enforceCrossUserPermission(uid, userId,
17930 false /* requireFullPermission */, true /* checkShell */, "set enabled");
17931 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17932 boolean sendNow = false;
17933 boolean isApp = (className == null);
17934 String componentName = isApp ? packageName : className;
17935 int packageUid = -1;
17936 ArrayList<String> components;
17939 synchronized (mPackages) {
17940 pkgSetting = mSettings.mPackages.get(packageName);
17941 if (pkgSetting == null) {
17942 if (className == null) {
17943 throw new IllegalArgumentException("Unknown package: " + packageName);
17945 throw new IllegalArgumentException(
17946 "Unknown component: " + packageName + "/" + className);
17950 // Limit who can change which apps
17951 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17952 // Don't allow apps that don't have permission to modify other apps
17953 if (!allowedByPermission) {
17954 throw new SecurityException(
17955 "Permission Denial: attempt to change component state from pid="
17956 + Binder.getCallingPid()
17957 + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17959 // Don't allow changing protected packages.
17960 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17961 throw new SecurityException("Cannot disable a protected package: " + packageName);
17965 synchronized (mPackages) {
17966 if (uid == Process.SHELL_UID) {
17967 // Shell can only change whole packages between ENABLED and DISABLED_USER states
17968 int oldState = pkgSetting.getEnabled(userId);
17969 if (className == null
17971 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17972 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17973 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17975 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17976 || newState == COMPONENT_ENABLED_STATE_DEFAULT
17977 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17980 throw new SecurityException(
17981 "Shell cannot change component state for " + packageName + "/"
17982 + className + " to " + newState);
17985 if (className == null) {
17986 // We're dealing with an application/package level state change
17987 if (pkgSetting.getEnabled(userId) == newState) {
17991 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17992 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17993 // Don't care about who enables an app.
17994 callingPackage = null;
17996 pkgSetting.setEnabled(newState, userId, callingPackage);
17997 // pkgSetting.pkg.mSetEnabled = newState;
17999 // We're dealing with a component level state change
18000 // First, verify that this is a valid class name.
18001 PackageParser.Package pkg = pkgSetting.pkg;
18002 if (pkg == null || !pkg.hasComponentClassName(className)) {
18004 pkg.applicationInfo.targetSdkVersion >=
18005 Build.VERSION_CODES.JELLY_BEAN) {
18006 throw new IllegalArgumentException("Component class " + className
18007 + " does not exist in " + packageName);
18009 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18010 + className + " does not exist in " + packageName);
18013 switch (newState) {
18014 case COMPONENT_ENABLED_STATE_ENABLED:
18015 if (!pkgSetting.enableComponentLPw(className, userId)) {
18019 case COMPONENT_ENABLED_STATE_DISABLED:
18020 if (!pkgSetting.disableComponentLPw(className, userId)) {
18024 case COMPONENT_ENABLED_STATE_DEFAULT:
18025 if (!pkgSetting.restoreComponentLPw(className, userId)) {
18030 Slog.e(TAG, "Invalid new component state: " + newState);
18034 scheduleWritePackageRestrictionsLocked(userId);
18035 components = mPendingBroadcasts.get(userId, packageName);
18036 final boolean newPackage = components == null;
18038 components = new ArrayList<String>();
18040 if (!components.contains(componentName)) {
18041 components.add(componentName);
18043 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18045 // Purge entry from pending broadcast list if another one exists already
18046 // since we are sending one right away.
18047 mPendingBroadcasts.remove(userId, packageName);
18050 mPendingBroadcasts.put(userId, packageName, components);
18052 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18053 // Schedule a message
18054 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18059 long callingId = Binder.clearCallingIdentity();
18062 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18063 sendPackageChangedBroadcast(packageName,
18064 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18067 Binder.restoreCallingIdentity(callingId);
18072 public void flushPackageRestrictionsAsUser(int userId) {
18073 if (!sUserManager.exists(userId)) {
18076 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18077 false /* checkShell */, "flushPackageRestrictions");
18078 synchronized (mPackages) {
18079 mSettings.writePackageRestrictionsLPr(userId);
18080 mDirtyUsers.remove(userId);
18081 if (mDirtyUsers.isEmpty()) {
18082 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18087 private void sendPackageChangedBroadcast(String packageName,
18088 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18090 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18092 Bundle extras = new Bundle(4);
18093 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18094 String nameList[] = new String[componentNames.size()];
18095 componentNames.toArray(nameList);
18096 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18097 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18098 extras.putInt(Intent.EXTRA_UID, packageUid);
18099 // If this is not reporting a change of the overall package, then only send it
18100 // to registered receivers. We don't want to launch a swath of apps for every
18101 // little component state change.
18102 final int flags = !componentNames.contains(packageName)
18103 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18104 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null,
18105 new int[] {UserHandle.getUserId(packageUid)});
18109 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18110 if (!sUserManager.exists(userId)) return;
18111 final int uid = Binder.getCallingUid();
18112 final int permission = mContext.checkCallingOrSelfPermission(
18113 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18114 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18115 enforceCrossUserPermission(uid, userId,
18116 true /* requireFullPermission */, true /* checkShell */, "stop package");
18118 synchronized (mPackages) {
18119 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18120 allowedByPermission, uid, userId)) {
18121 scheduleWritePackageRestrictionsLocked(userId);
18127 public String getInstallerPackageName(String packageName) {
18129 synchronized (mPackages) {
18130 return mSettings.getInstallerPackageNameLPr(packageName);
18134 public boolean isOrphaned(String packageName) {
18136 synchronized (mPackages) {
18137 return mSettings.isOrphaned(packageName);
18142 public int getApplicationEnabledSetting(String packageName, int userId) {
18143 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18144 int uid = Binder.getCallingUid();
18145 enforceCrossUserPermission(uid, userId,
18146 false /* requireFullPermission */, false /* checkShell */, "get enabled");
18148 synchronized (mPackages) {
18149 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18154 public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18155 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18156 int uid = Binder.getCallingUid();
18157 enforceCrossUserPermission(uid, userId,
18158 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18160 synchronized (mPackages) {
18161 return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18166 public void enterSafeMode() {
18167 enforceSystemOrRoot("Only the system can request entering safe mode");
18169 if (!mSystemReady) {
18175 public void systemReady() {
18176 mSystemReady = true;
18178 // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18179 // disabled after already being started.
18180 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18181 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18183 // Read the compatibilty setting when the system is ready.
18184 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18185 mContext.getContentResolver(),
18186 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18187 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18188 if (DEBUG_SETTINGS) {
18189 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18192 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18194 synchronized (mPackages) {
18195 // Verify that all of the preferred activity components actually
18196 // exist. It is possible for applications to be updated and at
18197 // that point remove a previously declared activity component that
18198 // had been set as a preferred activity. We try to clean this up
18199 // the next time we encounter that preferred activity, but it is
18200 // possible for the user flow to never be able to return to that
18201 // situation so here we do a sanity check to make sure we haven't
18202 // left any junk around.
18203 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18204 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18205 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18207 for (PreferredActivity pa : pir.filterSet()) {
18208 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18212 if (removed.size() > 0) {
18213 for (int r=0; r<removed.size(); r++) {
18214 PreferredActivity pa = removed.get(r);
18215 Slog.w(TAG, "Removing dangling preferred activity: "
18216 + pa.mPref.mComponent);
18217 pir.removeFilter(pa);
18219 mSettings.writePackageRestrictionsLPr(
18220 mSettings.mPreferredActivities.keyAt(i));
18224 for (int userId : UserManagerService.getInstance().getUserIds()) {
18225 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18226 grantPermissionsUserIds = ArrayUtils.appendInt(
18227 grantPermissionsUserIds, userId);
18231 sUserManager.systemReady();
18233 // If we upgraded grant all default permissions before kicking off.
18234 for (int userId : grantPermissionsUserIds) {
18235 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18238 // If we did not grant default permissions, we preload from this the
18239 // default permission exceptions lazily to ensure we don't hit the
18240 // disk on a new user creation.
18241 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18242 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18245 // Kick off any messages waiting for system ready
18246 if (mPostSystemReadyMessages != null) {
18247 for (Message msg : mPostSystemReadyMessages) {
18248 msg.sendToTarget();
18250 mPostSystemReadyMessages = null;
18253 // Watch for external volumes that come and go over time
18254 final StorageManager storage = mContext.getSystemService(StorageManager.class);
18255 storage.registerListener(mStorageListener);
18257 mInstallerService.systemReady();
18258 mPackageDexOptimizer.systemReady();
18260 MountServiceInternal mountServiceInternal = LocalServices.getService(
18261 MountServiceInternal.class);
18262 mountServiceInternal.addExternalStoragePolicy(
18263 new MountServiceInternal.ExternalStorageMountPolicy() {
18265 public int getMountMode(int uid, String packageName) {
18266 if (Process.isIsolated(uid)) {
18267 return Zygote.MOUNT_EXTERNAL_NONE;
18269 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18270 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18272 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18273 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18275 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18276 return Zygote.MOUNT_EXTERNAL_READ;
18278 return Zygote.MOUNT_EXTERNAL_WRITE;
18282 public boolean hasExternalStorage(int uid, String packageName) {
18287 // Now that we're mostly running, clean up stale users and apps
18288 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18289 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18293 public boolean isSafeMode() {
18298 public boolean hasSystemUidErrors() {
18299 return mHasSystemUidErrors;
18302 static String arrayToString(int[] array) {
18303 StringBuffer buf = new StringBuffer(128);
18305 if (array != null) {
18306 for (int i=0; i<array.length; i++) {
18307 if (i > 0) buf.append(", ");
18308 buf.append(array[i]);
18312 return buf.toString();
18315 static class DumpState {
18316 public static final int DUMP_LIBS = 1 << 0;
18317 public static final int DUMP_FEATURES = 1 << 1;
18318 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18319 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18320 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18321 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18322 public static final int DUMP_PERMISSIONS = 1 << 6;
18323 public static final int DUMP_PACKAGES = 1 << 7;
18324 public static final int DUMP_SHARED_USERS = 1 << 8;
18325 public static final int DUMP_MESSAGES = 1 << 9;
18326 public static final int DUMP_PROVIDERS = 1 << 10;
18327 public static final int DUMP_VERIFIERS = 1 << 11;
18328 public static final int DUMP_PREFERRED = 1 << 12;
18329 public static final int DUMP_PREFERRED_XML = 1 << 13;
18330 public static final int DUMP_KEYSETS = 1 << 14;
18331 public static final int DUMP_VERSION = 1 << 15;
18332 public static final int DUMP_INSTALLS = 1 << 16;
18333 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18334 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18335 public static final int DUMP_FROZEN = 1 << 19;
18336 public static final int DUMP_DEXOPT = 1 << 20;
18337 public static final int DUMP_COMPILER_STATS = 1 << 21;
18339 public static final int OPTION_SHOW_FILTERS = 1 << 0;
18341 private int mTypes;
18343 private int mOptions;
18345 private boolean mTitlePrinted;
18347 private SharedUserSetting mSharedUser;
18349 public boolean isDumping(int type) {
18350 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18354 return (mTypes & type) != 0;
18357 public void setDump(int type) {
18361 public boolean isOptionEnabled(int option) {
18362 return (mOptions & option) != 0;
18365 public void setOptionEnabled(int option) {
18366 mOptions |= option;
18369 public boolean onTitlePrinted() {
18370 final boolean printed = mTitlePrinted;
18371 mTitlePrinted = true;
18375 public boolean getTitlePrinted() {
18376 return mTitlePrinted;
18379 public void setTitlePrinted(boolean enabled) {
18380 mTitlePrinted = enabled;
18383 public SharedUserSetting getSharedUser() {
18384 return mSharedUser;
18387 public void setSharedUser(SharedUserSetting user) {
18388 mSharedUser = user;
18393 public void onShellCommand(FileDescriptor in, FileDescriptor out,
18394 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18395 (new PackageManagerShellCommand(this)).exec(
18396 this, in, out, err, args, resultReceiver);
18400 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18401 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18402 != PackageManager.PERMISSION_GRANTED) {
18403 pw.println("Permission Denial: can't dump ActivityManager from from pid="
18404 + Binder.getCallingPid()
18405 + ", uid=" + Binder.getCallingUid()
18406 + " without permission "
18407 + android.Manifest.permission.DUMP);
18411 DumpState dumpState = new DumpState();
18412 boolean fullPreferred = false;
18413 boolean checkin = false;
18415 String packageName = null;
18416 ArraySet<String> permissionNames = null;
18419 while (opti < args.length) {
18420 String opt = args[opti];
18421 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18426 if ("-a".equals(opt)) {
18427 // Right now we only know how to print all.
18428 } else if ("-h".equals(opt)) {
18429 pw.println("Package manager dump options:");
18430 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
18431 pw.println(" --checkin: dump for a checkin");
18432 pw.println(" -f: print details of intent filters");
18433 pw.println(" -h: print this help");
18434 pw.println(" cmd may be one of:");
18435 pw.println(" l[ibraries]: list known shared libraries");
18436 pw.println(" f[eatures]: list device features");
18437 pw.println(" k[eysets]: print known keysets");
18438 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18439 pw.println(" perm[issions]: dump permissions");
18440 pw.println(" permission [name ...]: dump declaration and use of given permission");
18441 pw.println(" pref[erred]: print preferred package settings");
18442 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
18443 pw.println(" prov[iders]: dump content providers");
18444 pw.println(" p[ackages]: dump installed packages");
18445 pw.println(" s[hared-users]: dump shared user IDs");
18446 pw.println(" m[essages]: print collected runtime messages");
18447 pw.println(" v[erifiers]: print package verifier info");
18448 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
18449 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18450 pw.println(" version: print database version info");
18451 pw.println(" write: write current settings now");
18452 pw.println(" installs: details about install sessions");
18453 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
18454 pw.println(" dexopt: dump dexopt state");
18455 pw.println(" compiler-stats: dump compiler statistics");
18456 pw.println(" <package.name>: info about given package");
18458 } else if ("--checkin".equals(opt)) {
18460 } else if ("-f".equals(opt)) {
18461 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18463 pw.println("Unknown argument: " + opt + "; use -h for help");
18467 // Is the caller requesting to dump a particular piece of data?
18468 if (opti < args.length) {
18469 String cmd = args[opti];
18471 // Is this a package name?
18472 if ("android".equals(cmd) || cmd.contains(".")) {
18474 // When dumping a single package, we always dump all of its
18475 // filter information since the amount of data will be reasonable.
18476 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18477 } else if ("check-permission".equals(cmd)) {
18478 if (opti >= args.length) {
18479 pw.println("Error: check-permission missing permission argument");
18482 String perm = args[opti];
18484 if (opti >= args.length) {
18485 pw.println("Error: check-permission missing package argument");
18488 String pkg = args[opti];
18490 int user = UserHandle.getUserId(Binder.getCallingUid());
18491 if (opti < args.length) {
18493 user = Integer.parseInt(args[opti]);
18494 } catch (NumberFormatException e) {
18495 pw.println("Error: check-permission user argument is not a number: "
18500 pw.println(checkPermission(perm, pkg, user));
18502 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18503 dumpState.setDump(DumpState.DUMP_LIBS);
18504 } else if ("f".equals(cmd) || "features".equals(cmd)) {
18505 dumpState.setDump(DumpState.DUMP_FEATURES);
18506 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18507 if (opti >= args.length) {
18508 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18509 | DumpState.DUMP_SERVICE_RESOLVERS
18510 | DumpState.DUMP_RECEIVER_RESOLVERS
18511 | DumpState.DUMP_CONTENT_RESOLVERS);
18513 while (opti < args.length) {
18514 String name = args[opti];
18515 if ("a".equals(name) || "activity".equals(name)) {
18516 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18517 } else if ("s".equals(name) || "service".equals(name)) {
18518 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18519 } else if ("r".equals(name) || "receiver".equals(name)) {
18520 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18521 } else if ("c".equals(name) || "content".equals(name)) {
18522 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18524 pw.println("Error: unknown resolver table type: " + name);
18530 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18531 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18532 } else if ("permission".equals(cmd)) {
18533 if (opti >= args.length) {
18534 pw.println("Error: permission requires permission name");
18537 permissionNames = new ArraySet<>();
18538 while (opti < args.length) {
18539 permissionNames.add(args[opti]);
18542 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18543 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18544 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18545 dumpState.setDump(DumpState.DUMP_PREFERRED);
18546 } else if ("preferred-xml".equals(cmd)) {
18547 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18548 if (opti < args.length && "--full".equals(args[opti])) {
18549 fullPreferred = true;
18552 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18553 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18554 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18555 dumpState.setDump(DumpState.DUMP_PACKAGES);
18556 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18557 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18558 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18559 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18560 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18561 dumpState.setDump(DumpState.DUMP_MESSAGES);
18562 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18563 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18564 } else if ("i".equals(cmd) || "ifv".equals(cmd)
18565 || "intent-filter-verifiers".equals(cmd)) {
18566 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18567 } else if ("version".equals(cmd)) {
18568 dumpState.setDump(DumpState.DUMP_VERSION);
18569 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18570 dumpState.setDump(DumpState.DUMP_KEYSETS);
18571 } else if ("installs".equals(cmd)) {
18572 dumpState.setDump(DumpState.DUMP_INSTALLS);
18573 } else if ("frozen".equals(cmd)) {
18574 dumpState.setDump(DumpState.DUMP_FROZEN);
18575 } else if ("dexopt".equals(cmd)) {
18576 dumpState.setDump(DumpState.DUMP_DEXOPT);
18577 } else if ("compiler-stats".equals(cmd)) {
18578 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18579 } else if ("write".equals(cmd)) {
18580 synchronized (mPackages) {
18581 mSettings.writeLPr();
18582 pw.println("Settings written.");
18589 pw.println("vers,1");
18593 synchronized (mPackages) {
18594 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18596 if (dumpState.onTitlePrinted())
18598 pw.println("Database versions:");
18599 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
18603 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18605 if (dumpState.onTitlePrinted())
18607 pw.println("Verifiers:");
18608 pw.print(" Required: ");
18609 pw.print(mRequiredVerifierPackage);
18610 pw.print(" (uid=");
18611 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18612 UserHandle.USER_SYSTEM));
18614 } else if (mRequiredVerifierPackage != null) {
18615 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18617 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18618 UserHandle.USER_SYSTEM));
18622 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18623 packageName == null) {
18624 if (mIntentFilterVerifierComponent != null) {
18625 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18627 if (dumpState.onTitlePrinted())
18629 pw.println("Intent Filter Verifier:");
18630 pw.print(" Using: ");
18631 pw.print(verifierPackageName);
18632 pw.print(" (uid=");
18633 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18634 UserHandle.USER_SYSTEM));
18636 } else if (verifierPackageName != null) {
18637 pw.print("ifv,"); pw.print(verifierPackageName);
18639 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18640 UserHandle.USER_SYSTEM));
18644 pw.println("No Intent Filter Verifier available!");
18648 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18649 boolean printedHeader = false;
18650 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18651 while (it.hasNext()) {
18652 String name = it.next();
18653 SharedLibraryEntry ent = mSharedLibraries.get(name);
18655 if (!printedHeader) {
18656 if (dumpState.onTitlePrinted())
18658 pw.println("Libraries:");
18659 printedHeader = true;
18669 if (ent.path != null) {
18671 pw.print("(jar) ");
18672 pw.print(ent.path);
18675 pw.print(ent.path);
18679 pw.print("(apk) ");
18690 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18691 if (dumpState.onTitlePrinted())
18694 pw.println("Features:");
18697 for (FeatureInfo feat : mAvailableFeatures.values()) {
18700 pw.print(feat.name);
18702 pw.println(feat.version);
18705 pw.print(feat.name);
18706 if (feat.version > 0) {
18707 pw.print(" version=");
18708 pw.print(feat.version);
18715 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18716 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18717 : "Activity Resolver Table:", " ", packageName,
18718 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18719 dumpState.setTitlePrinted(true);
18722 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18723 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18724 : "Receiver Resolver Table:", " ", packageName,
18725 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18726 dumpState.setTitlePrinted(true);
18729 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18730 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18731 : "Service Resolver Table:", " ", packageName,
18732 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18733 dumpState.setTitlePrinted(true);
18736 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18737 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18738 : "Provider Resolver Table:", " ", packageName,
18739 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18740 dumpState.setTitlePrinted(true);
18744 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18745 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18746 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18747 int user = mSettings.mPreferredActivities.keyAt(i);
18749 dumpState.getTitlePrinted()
18750 ? "\nPreferred Activities User " + user + ":"
18751 : "Preferred Activities User " + user + ":", " ",
18752 packageName, true, false)) {
18753 dumpState.setTitlePrinted(true);
18758 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18760 FileOutputStream fout = new FileOutputStream(fd);
18761 BufferedOutputStream str = new BufferedOutputStream(fout);
18762 XmlSerializer serializer = new FastXmlSerializer();
18764 serializer.setOutput(str, StandardCharsets.UTF_8.name());
18765 serializer.startDocument(null, true);
18766 serializer.setFeature(
18767 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18768 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18769 serializer.endDocument();
18770 serializer.flush();
18771 } catch (IllegalArgumentException e) {
18772 pw.println("Failed writing: " + e);
18773 } catch (IllegalStateException e) {
18774 pw.println("Failed writing: " + e);
18775 } catch (IOException e) {
18776 pw.println("Failed writing: " + e);
18781 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18782 && packageName == null) {
18784 int count = mSettings.mPackages.size();
18786 pw.println("No applications!");
18789 final String prefix = " ";
18790 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18791 if (allPackageSettings.size() == 0) {
18792 pw.println("No domain preferred apps!");
18795 pw.println("App verification status:");
18798 for (PackageSetting ps : allPackageSettings) {
18799 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18800 if (ivi == null || ivi.getPackageName() == null) continue;
18801 pw.println(prefix + "Package: " + ivi.getPackageName());
18802 pw.println(prefix + "Domains: " + ivi.getDomainsString());
18803 pw.println(prefix + "Status: " + ivi.getStatusString());
18808 pw.println(prefix + "No app verification established.");
18811 for (int userId : sUserManager.getUserIds()) {
18812 pw.println("App linkages for user " + userId + ":");
18815 for (PackageSetting ps : allPackageSettings) {
18816 final long status = ps.getDomainVerificationStatusForUser(userId);
18817 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18820 pw.println(prefix + "Package: " + ps.name);
18821 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18822 String statusStr = IntentFilterVerificationInfo.
18823 getStatusStringFromValue(status);
18824 pw.println(prefix + "Status: " + statusStr);
18829 pw.println(prefix + "No configured app linkages.");
18837 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18838 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18839 if (packageName == null && permissionNames == null) {
18840 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18842 if (dumpState.onTitlePrinted())
18844 pw.println("AppOp Permissions:");
18846 pw.print(" AppOp Permission ");
18847 pw.print(mAppOpPermissionPackages.keyAt(iperm));
18849 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18850 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18851 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
18857 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18858 boolean printedSomething = false;
18859 for (PackageParser.Provider p : mProviders.mProviders.values()) {
18860 if (packageName != null && !packageName.equals(p.info.packageName)) {
18863 if (!printedSomething) {
18864 if (dumpState.onTitlePrinted())
18866 pw.println("Registered ContentProviders:");
18867 printedSomething = true;
18869 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
18870 pw.print(" "); pw.println(p.toString());
18872 printedSomething = false;
18873 for (Map.Entry<String, PackageParser.Provider> entry :
18874 mProvidersByAuthority.entrySet()) {
18875 PackageParser.Provider p = entry.getValue();
18876 if (packageName != null && !packageName.equals(p.info.packageName)) {
18879 if (!printedSomething) {
18880 if (dumpState.onTitlePrinted())
18882 pw.println("ContentProvider Authorities:");
18883 printedSomething = true;
18885 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
18886 pw.print(" "); pw.println(p.toString());
18887 if (p.info != null && p.info.applicationInfo != null) {
18888 final String appInfo = p.info.applicationInfo.toString();
18889 pw.print(" applicationInfo="); pw.println(appInfo);
18894 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18895 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18898 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18899 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18902 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18903 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18906 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18907 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18910 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18911 // XXX should handle packageName != null by dumping only install data that
18912 // the given package is involved with.
18913 if (dumpState.onTitlePrinted()) pw.println();
18914 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
18917 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18918 // XXX should handle packageName != null by dumping only install data that
18919 // the given package is involved with.
18920 if (dumpState.onTitlePrinted()) pw.println();
18922 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
18924 ipw.println("Frozen packages:");
18925 ipw.increaseIndent();
18926 if (mFrozenPackages.size() == 0) {
18927 ipw.println("(none)");
18929 for (int i = 0; i < mFrozenPackages.size(); i++) {
18930 ipw.println(mFrozenPackages.valueAt(i));
18933 ipw.decreaseIndent();
18936 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18937 if (dumpState.onTitlePrinted()) pw.println();
18938 dumpDexoptStateLPr(pw, packageName);
18941 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18942 if (dumpState.onTitlePrinted()) pw.println();
18943 dumpCompilerStatsLPr(pw, packageName);
18946 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18947 if (dumpState.onTitlePrinted()) pw.println();
18948 mSettings.dumpReadMessagesLPr(pw, dumpState);
18951 pw.println("Package warning messages:");
18952 BufferedReader in = null;
18953 String line = null;
18955 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18956 while ((line = in.readLine()) != null) {
18957 if (line.contains("ignored: updated version")) continue;
18960 } catch (IOException ignored) {
18962 IoUtils.closeQuietly(in);
18966 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18967 BufferedReader in = null;
18968 String line = null;
18970 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18971 while ((line = in.readLine()) != null) {
18972 if (line.contains("ignored: updated version")) continue;
18976 } catch (IOException ignored) {
18978 IoUtils.closeQuietly(in);
18984 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18985 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
18987 ipw.println("Dexopt state:");
18988 ipw.increaseIndent();
18989 Collection<PackageParser.Package> packages = null;
18990 if (packageName != null) {
18991 PackageParser.Package targetPackage = mPackages.get(packageName);
18992 if (targetPackage != null) {
18993 packages = Collections.singletonList(targetPackage);
18995 ipw.println("Unable to find package: " + packageName);
18999 packages = mPackages.values();
19002 for (PackageParser.Package pkg : packages) {
19003 ipw.println("[" + pkg.packageName + "]");
19004 ipw.increaseIndent();
19005 mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19006 ipw.decreaseIndent();
19010 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19011 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
19013 ipw.println("Compiler stats:");
19014 ipw.increaseIndent();
19015 Collection<PackageParser.Package> packages = null;
19016 if (packageName != null) {
19017 PackageParser.Package targetPackage = mPackages.get(packageName);
19018 if (targetPackage != null) {
19019 packages = Collections.singletonList(targetPackage);
19021 ipw.println("Unable to find package: " + packageName);
19025 packages = mPackages.values();
19028 for (PackageParser.Package pkg : packages) {
19029 ipw.println("[" + pkg.packageName + "]");
19030 ipw.increaseIndent();
19032 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19033 if (stats == null) {
19034 ipw.println("(No recorded stats)");
19038 ipw.decreaseIndent();
19042 private String dumpDomainString(String packageName) {
19043 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19045 List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19047 ArraySet<String> result = new ArraySet<>();
19048 if (iviList.size() > 0) {
19049 for (IntentFilterVerificationInfo ivi : iviList) {
19050 for (String host : ivi.getDomains()) {
19055 if (filters != null && filters.size() > 0) {
19056 for (IntentFilter filter : filters) {
19057 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19058 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19059 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19060 result.addAll(filter.getHostsList());
19065 StringBuilder sb = new StringBuilder(result.size() * 16);
19066 for (String domain : result) {
19067 if (sb.length() > 0) sb.append(" ");
19070 return sb.toString();
19073 // ------- apps on sdcard specific code -------
19074 static final boolean DEBUG_SD_INSTALL = false;
19076 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19078 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19080 private boolean mMediaMounted = false;
19082 static String getEncryptKey() {
19084 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19085 SD_ENCRYPTION_KEYSTORE_NAME);
19086 if (sdEncKey == null) {
19087 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19088 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19089 if (sdEncKey == null) {
19090 Slog.e(TAG, "Failed to create encryption keys");
19095 } catch (NoSuchAlgorithmException nsae) {
19096 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19098 } catch (IOException ioe) {
19099 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19105 * Update media status on PackageManager.
19108 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19109 int callingUid = Binder.getCallingUid();
19110 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19111 throw new SecurityException("Media status can only be updated by the system");
19113 // reader; this apparently protects mMediaMounted, but should probably
19114 // be a different lock in that case.
19115 synchronized (mPackages) {
19116 Log.i(TAG, "Updating external media status from "
19117 + (mMediaMounted ? "mounted" : "unmounted") + " to "
19118 + (mediaStatus ? "mounted" : "unmounted"));
19119 if (DEBUG_SD_INSTALL)
19120 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19121 + ", mMediaMounted=" + mMediaMounted);
19122 if (mediaStatus == mMediaMounted) {
19123 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19125 mHandler.sendMessage(msg);
19128 mMediaMounted = mediaStatus;
19130 // Queue up an async operation since the package installation may take a
19132 mHandler.post(new Runnable() {
19133 public void run() {
19134 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19140 * Called by MountService when the initial ASECs to scan are available.
19141 * Should block until all the ASEC containers are finished being scanned.
19143 public void scanAvailableAsecs() {
19144 updateExternalMediaStatusInner(true, false, false);
19148 * Collect information of applications on external media, map them against
19149 * existing containers and update information based on current mount status.
19150 * Please note that we always have to report status if reportStatus has been
19151 * set to true especially when unloading packages.
19153 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19154 boolean externalStorage) {
19155 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19156 int[] uidArr = EmptyArray.INT;
19158 final String[] list = PackageHelper.getSecureContainerList();
19159 if (ArrayUtils.isEmpty(list)) {
19160 Log.i(TAG, "No secure containers found");
19162 // Process list of secure containers and categorize them
19163 // as active or stale based on their package internal state.
19166 synchronized (mPackages) {
19167 for (String cid : list) {
19168 // Leave stages untouched for now; installer service owns them
19169 if (PackageInstallerService.isStageName(cid)) continue;
19171 if (DEBUG_SD_INSTALL)
19172 Log.i(TAG, "Processing container " + cid);
19173 String pkgName = getAsecPackageName(cid);
19174 if (pkgName == null) {
19175 Slog.i(TAG, "Found stale container " + cid + " with no package name");
19178 if (DEBUG_SD_INSTALL)
19179 Log.i(TAG, "Looking for pkg : " + pkgName);
19181 final PackageSetting ps = mSettings.mPackages.get(pkgName);
19183 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19188 * Skip packages that are not external if we're unmounting
19189 * external storage.
19191 if (externalStorage && !isMounted && !isExternal(ps)) {
19195 final AsecInstallArgs args = new AsecInstallArgs(cid,
19196 getAppDexInstructionSets(ps), ps.isForwardLocked());
19197 // The package status is changed only if the code path
19198 // matches between settings and the container id.
19199 if (ps.codePathString != null
19200 && ps.codePathString.startsWith(args.getCodePath())) {
19201 if (DEBUG_SD_INSTALL) {
19202 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19203 + " at code path: " + ps.codePathString);
19206 // We do have a valid package installed on sdcard
19207 processCids.put(args, ps.codePathString);
19208 final int uid = ps.appId;
19210 uidArr = ArrayUtils.appendInt(uidArr, uid);
19213 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19214 + ps.codePathString);
19219 Arrays.sort(uidArr);
19222 // Process packages with valid entries.
19224 if (DEBUG_SD_INSTALL)
19225 Log.i(TAG, "Loading packages");
19226 loadMediaPackages(processCids, uidArr, externalStorage);
19227 startCleaningPackages();
19228 mInstallerService.onSecureContainersAvailable();
19230 if (DEBUG_SD_INSTALL)
19231 Log.i(TAG, "Unloading packages");
19232 unloadMediaPackages(processCids, uidArr, reportStatus);
19236 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19237 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19238 final int size = infos.size();
19239 final String[] packageNames = new String[size];
19240 final int[] packageUids = new int[size];
19241 for (int i = 0; i < size; i++) {
19242 final ApplicationInfo info = infos.get(i);
19243 packageNames[i] = info.packageName;
19244 packageUids[i] = info.uid;
19246 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19250 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19251 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19252 sendResourcesChangedBroadcast(mediaStatus, replacing,
19253 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19256 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19257 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19258 int size = pkgList.length;
19260 // Send broadcasts here
19261 Bundle extras = new Bundle();
19262 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19263 if (uidArr != null) {
19264 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19267 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19269 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19270 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19271 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19276 * Look at potentially valid container ids from processCids If package
19277 * information doesn't match the one on record or package scanning fails,
19278 * the cid is added to list of removeCids. We currently don't delete stale
19281 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19282 boolean externalStorage) {
19283 ArrayList<String> pkgList = new ArrayList<String>();
19284 Set<AsecInstallArgs> keys = processCids.keySet();
19286 for (AsecInstallArgs args : keys) {
19287 String codePath = processCids.get(args);
19288 if (DEBUG_SD_INSTALL)
19289 Log.i(TAG, "Loading container : " + args.cid);
19290 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19292 // Make sure there are no container errors first.
19293 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19294 Slog.e(TAG, "Failed to mount cid : " + args.cid
19295 + " when installing from sdcard");
19298 // Check code path here.
19299 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19300 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19301 + " does not match one in settings " + codePath);
19305 int parseFlags = mDefParseFlags;
19306 if (args.isExternalAsec()) {
19307 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19309 if (args.isFwdLocked()) {
19310 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19313 synchronized (mInstallLock) {
19314 PackageParser.Package pkg = null;
19316 // Sadly we don't know the package name yet to freeze it
19317 pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19318 SCAN_IGNORE_FROZEN, 0, null);
19319 } catch (PackageManagerException e) {
19320 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19322 // Scan the package
19325 * TODO why is the lock being held? doPostInstall is
19326 * called in other places without the lock. This needs
19327 * to be straightened out.
19330 synchronized (mPackages) {
19331 retCode = PackageManager.INSTALL_SUCCEEDED;
19332 pkgList.add(pkg.packageName);
19333 // Post process args
19334 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19335 pkg.applicationInfo.uid);
19338 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
19343 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19344 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19349 synchronized (mPackages) {
19350 // If the platform SDK has changed since the last time we booted,
19351 // we need to re-grant app permission to catch any new ones that
19352 // appear. This is really a hack, and means that apps can in some
19353 // cases get permissions that the user didn't initially explicitly
19354 // allow... it would be nice to have some better way to handle
19356 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19357 : mSettings.getInternalVersion();
19358 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19359 : StorageManager.UUID_PRIVATE_INTERNAL;
19361 int updateFlags = UPDATE_PERMISSIONS_ALL;
19362 if (ver.sdkVersion != mSdkVersion) {
19363 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19364 + mSdkVersion + "; regranting permissions for external");
19365 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19367 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19369 // Yay, everything is now upgraded
19370 ver.forceCurrent();
19372 // can downgrade to reader
19373 // Persist settings
19374 mSettings.writeLPr();
19376 // Send a broadcast to let everyone know we are done processing
19377 if (pkgList.size() > 0) {
19378 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19383 * Utility method to unload a list of specified containers
19385 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19386 // Just unmount all valid containers.
19387 for (AsecInstallArgs arg : cidArgs) {
19388 synchronized (mInstallLock) {
19389 arg.doPostDeleteLI(false);
19395 * Unload packages mounted on external media. This involves deleting package
19396 * data from internal structures, sending broadcasts about disabled packages,
19397 * gc'ing to free up references, unmounting all secure containers
19398 * corresponding to packages on external media, and posting a
19399 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19400 * that we always have to post this message if status has been requested no
19403 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19404 final boolean reportStatus) {
19405 if (DEBUG_SD_INSTALL)
19406 Log.i(TAG, "unloading media packages");
19407 ArrayList<String> pkgList = new ArrayList<String>();
19408 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19409 final Set<AsecInstallArgs> keys = processCids.keySet();
19410 for (AsecInstallArgs args : keys) {
19411 String pkgName = args.getPackageName();
19412 if (DEBUG_SD_INSTALL)
19413 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19414 // Delete package internally
19415 PackageRemovedInfo outInfo = new PackageRemovedInfo();
19416 synchronized (mInstallLock) {
19417 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19419 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19420 "unloadMediaPackages")) {
19421 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19425 pkgList.add(pkgName);
19427 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19428 failedList.add(args);
19434 synchronized (mPackages) {
19435 // We didn't update the settings after removing each package;
19436 // write them now for all packages.
19437 mSettings.writeLPr();
19440 // We have to absolutely send UPDATED_MEDIA_STATUS only
19441 // after confirming that all the receivers processed the ordered
19442 // broadcast when packages get disabled, force a gc to clean things up.
19443 // and unload all the containers.
19444 if (pkgList.size() > 0) {
19445 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19446 new IIntentReceiver.Stub() {
19447 public void performReceive(Intent intent, int resultCode, String data,
19448 Bundle extras, boolean ordered, boolean sticky,
19449 int sendingUser) throws RemoteException {
19450 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19451 reportStatus ? 1 : 0, 1, keys);
19452 mHandler.sendMessage(msg);
19456 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19458 mHandler.sendMessage(msg);
19462 private void loadPrivatePackages(final VolumeInfo vol) {
19463 mHandler.post(new Runnable() {
19465 public void run() {
19466 loadPrivatePackagesInner(vol);
19471 private void loadPrivatePackagesInner(VolumeInfo vol) {
19472 final String volumeUuid = vol.fsUuid;
19473 if (TextUtils.isEmpty(volumeUuid)) {
19474 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19478 final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19479 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19480 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19482 final VersionInfo ver;
19483 final List<PackageSetting> packages;
19484 synchronized (mPackages) {
19485 ver = mSettings.findOrCreateVersion(volumeUuid);
19486 packages = mSettings.getVolumePackagesLPr(volumeUuid);
19489 for (PackageSetting ps : packages) {
19490 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19491 synchronized (mInstallLock) {
19492 final PackageParser.Package pkg;
19494 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19495 loaded.add(pkg.applicationInfo);
19497 } catch (PackageManagerException e) {
19498 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19501 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19502 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19503 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19504 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19509 // Reconcile app data for all started/unlocked users
19510 final StorageManager sm = mContext.getSystemService(StorageManager.class);
19511 final UserManager um = mContext.getSystemService(UserManager.class);
19512 UserManagerInternal umInternal = getUserManagerInternal();
19513 for (UserInfo user : um.getUsers()) {
19515 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19516 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19517 } else if (umInternal.isUserRunning(user.id)) {
19518 flags = StorageManager.FLAG_STORAGE_DE;
19524 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19525 synchronized (mInstallLock) {
19526 reconcileAppsDataLI(volumeUuid, user.id, flags);
19528 } catch (IllegalStateException e) {
19529 // Device was probably ejected, and we'll process that event momentarily
19530 Slog.w(TAG, "Failed to prepare storage: " + e);
19534 synchronized (mPackages) {
19535 int updateFlags = UPDATE_PERMISSIONS_ALL;
19536 if (ver.sdkVersion != mSdkVersion) {
19537 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19538 + mSdkVersion + "; regranting permissions for " + volumeUuid);
19539 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19541 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19543 // Yay, everything is now upgraded
19544 ver.forceCurrent();
19546 mSettings.writeLPr();
19549 for (PackageFreezer freezer : freezers) {
19553 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19554 sendResourcesChangedBroadcast(true, false, loaded, null);
19557 private void unloadPrivatePackages(final VolumeInfo vol) {
19558 mHandler.post(new Runnable() {
19560 public void run() {
19561 unloadPrivatePackagesInner(vol);
19566 private void unloadPrivatePackagesInner(VolumeInfo vol) {
19567 final String volumeUuid = vol.fsUuid;
19568 if (TextUtils.isEmpty(volumeUuid)) {
19569 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19573 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19574 synchronized (mInstallLock) {
19575 synchronized (mPackages) {
19576 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19577 for (PackageSetting ps : packages) {
19578 if (ps.pkg == null) continue;
19580 final ApplicationInfo info = ps.pkg.applicationInfo;
19581 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19582 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19584 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19585 "unloadPrivatePackagesInner")) {
19586 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19588 unloaded.add(info);
19590 Slog.w(TAG, "Failed to unload " + ps.codePath);
19594 // Try very hard to release any references to this package
19595 // so we don't risk the system server being killed due to
19597 AttributeCache.instance().removePackage(ps.name);
19600 mSettings.writeLPr();
19604 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19605 sendResourcesChangedBroadcast(false, false, unloaded, null);
19607 // Try very hard to release any references to this path so we don't risk
19608 // the system server being killed due to open FDs
19609 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19611 for (int i = 0; i < 3; i++) {
19613 System.runFinalization();
19618 * Prepare storage areas for given user on all mounted devices.
19620 void prepareUserData(int userId, int userSerial, int flags) {
19621 synchronized (mInstallLock) {
19622 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19623 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19624 final String volumeUuid = vol.getFsUuid();
19625 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19630 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19631 boolean allowRecover) {
19632 // Prepare storage and verify that serial numbers are consistent; if
19633 // there's a mismatch we need to destroy to avoid leaking data
19634 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19636 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19638 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19639 UserManagerService.enforceSerialNumber(
19640 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19641 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19642 UserManagerService.enforceSerialNumber(
19643 Environment.getDataSystemDeDirectory(userId), userSerial);
19646 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19647 UserManagerService.enforceSerialNumber(
19648 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19649 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19650 UserManagerService.enforceSerialNumber(
19651 Environment.getDataSystemCeDirectory(userId), userSerial);
19655 synchronized (mInstallLock) {
19656 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19658 } catch (Exception e) {
19659 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19660 + " because we failed to prepare: " + e);
19661 destroyUserDataLI(volumeUuid, userId,
19662 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19664 if (allowRecover) {
19665 // Try one last time; if we fail again we're really in trouble
19666 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19672 * Destroy storage areas for given user on all mounted devices.
19674 void destroyUserData(int userId, int flags) {
19675 synchronized (mInstallLock) {
19676 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19677 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19678 final String volumeUuid = vol.getFsUuid();
19679 destroyUserDataLI(volumeUuid, userId, flags);
19684 private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19685 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19687 // Clean up app data, profile data, and media data
19688 mInstaller.destroyUserData(volumeUuid, userId, flags);
19690 // Clean up system data
19691 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19692 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19693 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19694 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19696 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19697 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19701 // Data with special labels is now gone, so finish the job
19702 storage.destroyUserStorage(volumeUuid, userId, flags);
19704 } catch (Exception e) {
19705 logCriticalInfo(Log.WARN,
19706 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19711 * Examine all users present on given mounted volume, and destroy data
19712 * belonging to users that are no longer valid, or whose user ID has been
19715 private void reconcileUsers(String volumeUuid) {
19716 final List<File> files = new ArrayList<>();
19717 Collections.addAll(files, FileUtils
19718 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19719 Collections.addAll(files, FileUtils
19720 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19721 Collections.addAll(files, FileUtils
19722 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19723 Collections.addAll(files, FileUtils
19724 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19725 for (File file : files) {
19726 if (!file.isDirectory()) continue;
19729 final UserInfo info;
19731 userId = Integer.parseInt(file.getName());
19732 info = sUserManager.getUserInfo(userId);
19733 } catch (NumberFormatException e) {
19734 Slog.w(TAG, "Invalid user directory " + file);
19738 boolean destroyUser = false;
19739 if (info == null) {
19740 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19741 + " because no matching user was found");
19742 destroyUser = true;
19743 } else if (!mOnlyCore) {
19745 UserManagerService.enforceSerialNumber(file, info.serialNumber);
19746 } catch (IOException e) {
19747 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19748 + " because we failed to enforce serial number: " + e);
19749 destroyUser = true;
19754 synchronized (mInstallLock) {
19755 destroyUserDataLI(volumeUuid, userId,
19756 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19762 private void assertPackageKnown(String volumeUuid, String packageName)
19763 throws PackageManagerException {
19764 synchronized (mPackages) {
19765 // Normalize package name to handle renamed packages
19766 packageName = normalizePackageNameLPr(packageName);
19768 final PackageSetting ps = mSettings.mPackages.get(packageName);
19770 throw new PackageManagerException("Package " + packageName + " is unknown");
19771 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19772 throw new PackageManagerException(
19773 "Package " + packageName + " found on unknown volume " + volumeUuid
19774 + "; expected volume " + ps.volumeUuid);
19779 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19780 throws PackageManagerException {
19781 synchronized (mPackages) {
19782 // Normalize package name to handle renamed packages
19783 packageName = normalizePackageNameLPr(packageName);
19785 final PackageSetting ps = mSettings.mPackages.get(packageName);
19787 throw new PackageManagerException("Package " + packageName + " is unknown");
19788 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19789 throw new PackageManagerException(
19790 "Package " + packageName + " found on unknown volume " + volumeUuid
19791 + "; expected volume " + ps.volumeUuid);
19792 } else if (!ps.getInstalled(userId)) {
19793 throw new PackageManagerException(
19794 "Package " + packageName + " not installed for user " + userId);
19800 * Examine all apps present on given mounted volume, and destroy apps that
19801 * aren't expected, either due to uninstallation or reinstallation on
19804 private void reconcileApps(String volumeUuid) {
19805 final File[] files = FileUtils
19806 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19807 for (File file : files) {
19808 final boolean isPackage = (isApkFile(file) || file.isDirectory())
19809 && !PackageInstallerService.isStageName(file.getName());
19811 // Ignore entries which are not packages
19816 final PackageLite pkg = PackageParser.parsePackageLite(file,
19817 PackageParser.PARSE_MUST_BE_APK);
19818 assertPackageKnown(volumeUuid, pkg.packageName);
19820 } catch (PackageParserException | PackageManagerException e) {
19821 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19822 synchronized (mInstallLock) {
19823 removeCodePathLI(file);
19830 * Reconcile all app data for the given user.
19832 * Verifies that directories exist and that ownership and labeling is
19833 * correct for all installed apps on all mounted volumes.
19835 void reconcileAppsData(int userId, int flags) {
19836 final StorageManager storage = mContext.getSystemService(StorageManager.class);
19837 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19838 final String volumeUuid = vol.getFsUuid();
19839 synchronized (mInstallLock) {
19840 reconcileAppsDataLI(volumeUuid, userId, flags);
19846 * Reconcile all app data on given mounted volume.
19848 * Destroys app data that isn't expected, either due to uninstallation or
19849 * reinstallation on another volume.
19851 * Verifies that directories exist and that ownership and labeling is
19852 * correct for all installed apps.
19854 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19855 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19856 + Integer.toHexString(flags));
19858 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19859 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19861 // First look for stale data that doesn't belong, and check if things
19862 // have changed since we did our last restorecon
19863 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19864 if (StorageManager.isFileEncryptedNativeOrEmulated()
19865 && !StorageManager.isUserKeyUnlocked(userId)) {
19866 throw new RuntimeException(
19867 "Yikes, someone asked us to reconcile CE storage while " + userId
19868 + " was still locked; this would have caused massive data loss!");
19871 final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19872 for (File file : files) {
19873 final String packageName = file.getName();
19875 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19876 } catch (PackageManagerException e) {
19877 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19879 mInstaller.destroyAppData(volumeUuid, packageName, userId,
19880 StorageManager.FLAG_STORAGE_CE, 0);
19881 } catch (InstallerException e2) {
19882 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19887 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19888 final File[] files = FileUtils.listFilesOrEmpty(deDir);
19889 for (File file : files) {
19890 final String packageName = file.getName();
19892 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19893 } catch (PackageManagerException e) {
19894 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19896 mInstaller.destroyAppData(volumeUuid, packageName, userId,
19897 StorageManager.FLAG_STORAGE_DE, 0);
19898 } catch (InstallerException e2) {
19899 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19905 // Ensure that data directories are ready to roll for all packages
19906 // installed for this volume and user
19907 final List<PackageSetting> packages;
19908 synchronized (mPackages) {
19909 packages = mSettings.getVolumePackagesLPr(volumeUuid);
19911 int preparedCount = 0;
19912 for (PackageSetting ps : packages) {
19913 final String packageName = ps.name;
19914 if (ps.pkg == null) {
19915 Slog.w(TAG, "Odd, missing scanned package " + packageName);
19916 // TODO: might be due to legacy ASEC apps; we should circle back
19917 // and reconcile again once they're scanned
19921 if (ps.getInstalled(userId)) {
19922 prepareAppDataLIF(ps.pkg, userId, flags);
19924 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19925 // We may have just shuffled around app data directories, so
19926 // prepare them one more time
19927 prepareAppDataLIF(ps.pkg, userId, flags);
19934 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19938 * Prepare app data for the given app just after it was installed or
19939 * upgraded. This method carefully only touches users that it's installed
19940 * for, and it forces a restorecon to handle any seinfo changes.
19942 * Verifies that directories exist and that ownership and labeling is
19943 * correct for all installed apps. If there is an ownership mismatch, it
19944 * will try recovering system apps by wiping data; third-party app data is
19947 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19949 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19950 final PackageSetting ps;
19951 synchronized (mPackages) {
19952 ps = mSettings.mPackages.get(pkg.packageName);
19953 mSettings.writeKernelMappingLPr(ps);
19956 final UserManager um = mContext.getSystemService(UserManager.class);
19957 UserManagerInternal umInternal = getUserManagerInternal();
19958 for (UserInfo user : um.getUsers()) {
19960 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19961 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19962 } else if (umInternal.isUserRunning(user.id)) {
19963 flags = StorageManager.FLAG_STORAGE_DE;
19968 if (ps.getInstalled(user.id)) {
19969 // TODO: when user data is locked, mark that we're still dirty
19970 prepareAppDataLIF(pkg, user.id, flags);
19976 * Prepare app data for the given app.
19978 * Verifies that directories exist and that ownership and labeling is
19979 * correct for all installed apps. If there is an ownership mismatch, this
19980 * will try recovering system apps by wiping data; third-party app data is
19983 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19985 Slog.wtf(TAG, "Package was null!", new Throwable());
19988 prepareAppDataLeafLIF(pkg, userId, flags);
19989 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19990 for (int i = 0; i < childCount; i++) {
19991 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19995 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19996 if (DEBUG_APP_DATA) {
19997 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19998 + Integer.toHexString(flags));
20001 final String volumeUuid = pkg.volumeUuid;
20002 final String packageName = pkg.packageName;
20003 final ApplicationInfo app = pkg.applicationInfo;
20004 final int appId = UserHandle.getAppId(app.uid);
20006 Preconditions.checkNotNull(app.seinfo);
20009 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20010 appId, app.seinfo, app.targetSdkVersion);
20011 } catch (InstallerException e) {
20012 if (app.isSystemApp()) {
20013 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20014 + ", but trying to recover: " + e);
20015 destroyAppDataLeafLIF(pkg, userId, flags);
20017 mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20018 appId, app.seinfo, app.targetSdkVersion);
20019 logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20020 } catch (InstallerException e2) {
20021 logCriticalInfo(Log.DEBUG, "Recovery failed!");
20024 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20028 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20030 // CE storage is unlocked right now, so read out the inode and
20031 // remember for use later when it's locked
20032 // TODO: mark this structure as dirty so we persist it!
20033 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20034 StorageManager.FLAG_STORAGE_CE);
20035 synchronized (mPackages) {
20036 final PackageSetting ps = mSettings.mPackages.get(packageName);
20038 ps.setCeDataInode(ceDataInode, userId);
20041 } catch (InstallerException e) {
20042 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20046 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20049 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20051 Slog.wtf(TAG, "Package was null!", new Throwable());
20054 prepareAppDataContentsLeafLIF(pkg, userId, flags);
20055 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20056 for (int i = 0; i < childCount; i++) {
20057 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20061 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20062 final String volumeUuid = pkg.volumeUuid;
20063 final String packageName = pkg.packageName;
20064 final ApplicationInfo app = pkg.applicationInfo;
20066 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20067 // Create a native library symlink only if we have native libraries
20068 // and if the native libraries are 32 bit libraries. We do not provide
20069 // this symlink for 64 bit libraries.
20070 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20071 final String nativeLibPath = app.nativeLibraryDir;
20073 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20074 nativeLibPath, userId);
20075 } catch (InstallerException e) {
20076 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20083 * For system apps on non-FBE devices, this method migrates any existing
20084 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20085 * requested by the app.
20087 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20088 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20089 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20090 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20091 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20093 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20095 } catch (InstallerException e) {
20096 logCriticalInfo(Log.WARN,
20097 "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20105 public PackageFreezer freezePackage(String packageName, String killReason) {
20106 return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20109 public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20110 return new PackageFreezer(packageName, userId, killReason);
20113 public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20114 String killReason) {
20115 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20118 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20119 String killReason) {
20120 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20121 return new PackageFreezer();
20123 return freezePackage(packageName, userId, killReason);
20127 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20128 String killReason) {
20129 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20132 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20133 String killReason) {
20134 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20135 return new PackageFreezer();
20137 return freezePackage(packageName, userId, killReason);
20142 * Class that freezes and kills the given package upon creation, and
20143 * unfreezes it upon closing. This is typically used when doing surgery on
20144 * app code/data to prevent the app from running while you're working.
20146 private class PackageFreezer implements AutoCloseable {
20147 private final String mPackageName;
20148 private final PackageFreezer[] mChildren;
20150 private final boolean mWeFroze;
20152 private final AtomicBoolean mClosed = new AtomicBoolean();
20153 private final CloseGuard mCloseGuard = CloseGuard.get();
20156 * Create and return a stub freezer that doesn't actually do anything,
20157 * typically used when someone requested
20158 * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20159 * {@link PackageManager#DELETE_DONT_KILL_APP}.
20161 public PackageFreezer() {
20162 mPackageName = null;
20165 mCloseGuard.open("close");
20168 public PackageFreezer(String packageName, int userId, String killReason) {
20169 synchronized (mPackages) {
20170 mPackageName = packageName;
20171 mWeFroze = mFrozenPackages.add(mPackageName);
20173 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20175 killApplication(ps.name, ps.appId, userId, killReason);
20178 final PackageParser.Package p = mPackages.get(packageName);
20179 if (p != null && p.childPackages != null) {
20180 final int N = p.childPackages.size();
20181 mChildren = new PackageFreezer[N];
20182 for (int i = 0; i < N; i++) {
20183 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20184 userId, killReason);
20190 mCloseGuard.open("close");
20194 protected void finalize() throws Throwable {
20196 mCloseGuard.warnIfOpen();
20204 public void close() {
20205 mCloseGuard.close();
20206 if (mClosed.compareAndSet(false, true)) {
20207 synchronized (mPackages) {
20209 mFrozenPackages.remove(mPackageName);
20212 if (mChildren != null) {
20213 for (PackageFreezer freezer : mChildren) {
20223 * Verify that given package is currently frozen.
20225 private void checkPackageFrozen(String packageName) {
20226 synchronized (mPackages) {
20227 if (!mFrozenPackages.contains(packageName)) {
20228 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20234 public int movePackage(final String packageName, final String volumeUuid) {
20235 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20237 final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20238 final int moveId = mNextMoveId.getAndIncrement();
20239 mHandler.post(new Runnable() {
20241 public void run() {
20243 movePackageInternal(packageName, volumeUuid, moveId, user);
20244 } catch (PackageManagerException e) {
20245 Slog.w(TAG, "Failed to move " + packageName, e);
20246 mMoveCallbacks.notifyStatusChanged(moveId,
20247 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20254 private void movePackageInternal(final String packageName, final String volumeUuid,
20255 final int moveId, UserHandle user) throws PackageManagerException {
20256 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20257 final PackageManager pm = mContext.getPackageManager();
20259 final boolean currentAsec;
20260 final String currentVolumeUuid;
20261 final File codeFile;
20262 final String installerPackageName;
20263 final String packageAbiOverride;
20265 final String seinfo;
20266 final String label;
20267 final int targetSdkVersion;
20268 final PackageFreezer freezer;
20269 final int[] installedUserIds;
20272 synchronized (mPackages) {
20273 final PackageParser.Package pkg = mPackages.get(packageName);
20274 final PackageSetting ps = mSettings.mPackages.get(packageName);
20275 if (pkg == null || ps == null) {
20276 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20279 if (pkg.applicationInfo.isSystemApp()) {
20280 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20281 "Cannot move system application");
20284 if (pkg.applicationInfo.isExternalAsec()) {
20285 currentAsec = true;
20286 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20287 } else if (pkg.applicationInfo.isForwardLocked()) {
20288 currentAsec = true;
20289 currentVolumeUuid = "forward_locked";
20291 currentAsec = false;
20292 currentVolumeUuid = ps.volumeUuid;
20294 final File probe = new File(pkg.codePath);
20295 final File probeOat = new File(probe, "oat");
20296 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20297 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20298 "Move only supported for modern cluster style installs");
20302 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20303 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20304 "Package already moved to " + volumeUuid);
20306 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20307 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20308 "Device admin cannot be moved");
20311 if (mFrozenPackages.contains(packageName)) {
20312 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20313 "Failed to move already frozen package");
20316 codeFile = new File(pkg.codePath);
20317 installerPackageName = ps.installerPackageName;
20318 packageAbiOverride = ps.cpuAbiOverrideString;
20319 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20320 seinfo = pkg.applicationInfo.seinfo;
20321 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20322 targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20323 freezer = freezePackage(packageName, "movePackageInternal");
20324 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20327 final Bundle extras = new Bundle();
20328 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20329 extras.putString(Intent.EXTRA_TITLE, label);
20330 mMoveCallbacks.notifyCreated(moveId, extras);
20333 final boolean moveCompleteApp;
20334 final File measurePath;
20336 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20337 installFlags = INSTALL_INTERNAL;
20338 moveCompleteApp = !currentAsec;
20339 measurePath = Environment.getDataAppDirectory(volumeUuid);
20340 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20341 installFlags = INSTALL_EXTERNAL;
20342 moveCompleteApp = false;
20343 measurePath = storage.getPrimaryPhysicalVolume().getPath();
20345 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20346 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20347 || !volume.isMountedWritable()) {
20349 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20350 "Move location not mounted private volume");
20353 Preconditions.checkState(!currentAsec);
20355 installFlags = INSTALL_INTERNAL;
20356 moveCompleteApp = true;
20357 measurePath = Environment.getDataAppDirectory(volumeUuid);
20360 final PackageStats stats = new PackageStats(null, -1);
20361 synchronized (mInstaller) {
20362 for (int userId : installedUserIds) {
20363 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20365 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20366 "Failed to measure package size");
20371 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20374 final long startFreeBytes = measurePath.getFreeSpace();
20375 final long sizeBytes;
20376 if (moveCompleteApp) {
20377 sizeBytes = stats.codeSize + stats.dataSize;
20379 sizeBytes = stats.codeSize;
20382 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20384 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20385 "Not enough free space to move");
20388 mMoveCallbacks.notifyStatusChanged(moveId, 10);
20390 final CountDownLatch installedLatch = new CountDownLatch(1);
20391 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20393 public void onUserActionRequired(Intent intent) throws RemoteException {
20394 throw new IllegalStateException();
20398 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20399 Bundle extras) throws RemoteException {
20400 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20401 + PackageManager.installStatusToString(returnCode, msg));
20403 installedLatch.countDown();
20406 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20408 case PackageInstaller.STATUS_SUCCESS:
20409 mMoveCallbacks.notifyStatusChanged(moveId,
20410 PackageManager.MOVE_SUCCEEDED);
20412 case PackageInstaller.STATUS_FAILURE_STORAGE:
20413 mMoveCallbacks.notifyStatusChanged(moveId,
20414 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20417 mMoveCallbacks.notifyStatusChanged(moveId,
20418 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20424 final MoveInfo move;
20425 if (moveCompleteApp) {
20426 // Kick off a thread to report progress estimates
20429 public void run() {
20432 if (installedLatch.await(1, TimeUnit.SECONDS)) {
20435 } catch (InterruptedException ignored) {
20438 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20439 final int progress = 10 + (int) MathUtils.constrain(
20440 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20441 mMoveCallbacks.notifyStatusChanged(moveId, progress);
20446 final String dataAppName = codeFile.getName();
20447 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20448 dataAppName, appId, seinfo, targetSdkVersion);
20453 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20455 final Message msg = mHandler.obtainMessage(INIT_COPY);
20456 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20457 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20458 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20459 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20460 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20463 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20464 System.identityHashCode(msg.obj));
20465 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20466 System.identityHashCode(msg.obj));
20468 mHandler.sendMessage(msg);
20472 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20473 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20475 final int realMoveId = mNextMoveId.getAndIncrement();
20476 final Bundle extras = new Bundle();
20477 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20478 mMoveCallbacks.notifyCreated(realMoveId, extras);
20480 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20482 public void onCreated(int moveId, Bundle extras) {
20487 public void onStatusChanged(int moveId, int status, long estMillis) {
20488 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20492 final StorageManager storage = mContext.getSystemService(StorageManager.class);
20493 storage.setPrimaryStorageUuid(volumeUuid, callback);
20498 public int getMoveStatus(int moveId) {
20499 mContext.enforceCallingOrSelfPermission(
20500 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20501 return mMoveCallbacks.mLastStatus.get(moveId);
20505 public void registerMoveCallback(IPackageMoveObserver callback) {
20506 mContext.enforceCallingOrSelfPermission(
20507 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20508 mMoveCallbacks.register(callback);
20512 public void unregisterMoveCallback(IPackageMoveObserver callback) {
20513 mContext.enforceCallingOrSelfPermission(
20514 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20515 mMoveCallbacks.unregister(callback);
20519 public boolean setInstallLocation(int loc) {
20520 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20522 if (getInstallLocation() == loc) {
20525 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20526 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20527 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20528 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20535 public int getInstallLocation() {
20536 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20537 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20538 PackageHelper.APP_INSTALL_AUTO);
20541 /** Called by UserManagerService */
20542 void cleanUpUser(UserManagerService userManager, int userHandle) {
20543 synchronized (mPackages) {
20544 mDirtyUsers.remove(userHandle);
20545 mUserNeedsBadging.delete(userHandle);
20546 mSettings.removeUserLPw(userHandle);
20547 mPendingBroadcasts.remove(userHandle);
20548 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20549 removeUnusedPackagesLPw(userManager, userHandle);
20554 * We're removing userHandle and would like to remove any downloaded packages
20555 * that are no longer in use by any other user.
20556 * @param userHandle the user being removed
20558 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20559 final boolean DEBUG_CLEAN_APKS = false;
20560 int [] users = userManager.getUserIds();
20561 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20562 while (psit.hasNext()) {
20563 PackageSetting ps = psit.next();
20564 if (ps.pkg == null) {
20567 final String packageName = ps.pkg.packageName;
20568 // Skip over if system app
20569 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20572 if (DEBUG_CLEAN_APKS) {
20573 Slog.i(TAG, "Checking package " + packageName);
20575 boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20577 if (DEBUG_CLEAN_APKS) {
20578 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO");
20581 for (int i = 0; i < users.length; i++) {
20582 if (users[i] != userHandle && ps.getInstalled(users[i])) {
20584 if (DEBUG_CLEAN_APKS) {
20585 Slog.i(TAG, " Keeping package " + packageName + " for user "
20593 if (DEBUG_CLEAN_APKS) {
20594 Slog.i(TAG, " Removing package " + packageName);
20596 mHandler.post(new Runnable() {
20597 public void run() {
20598 deletePackageX(packageName, userHandle, 0);
20605 /** Called by UserManagerService */
20606 void createNewUser(int userId) {
20607 synchronized (mInstallLock) {
20608 mSettings.createNewUserLI(this, mInstaller, userId);
20610 synchronized (mPackages) {
20611 scheduleWritePackageRestrictionsLocked(userId);
20612 scheduleWritePackageListLocked(userId);
20613 applyFactoryDefaultBrowserLPw(userId);
20614 primeDomainVerificationsLPw(userId);
20618 void onNewUserCreated(final int userId) {
20619 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20620 // If permission review for legacy apps is required, we represent
20621 // dagerous permissions for such apps as always granted runtime
20622 // permissions to keep per user flag state whether review is needed.
20623 // Hence, if a new user is added we have to propagate dangerous
20624 // permission grants for these legacy apps.
20625 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20626 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20627 | UPDATE_PERMISSIONS_REPLACE_ALL);
20632 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20633 mContext.enforceCallingOrSelfPermission(
20634 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20635 "Only package verification agents can read the verifier device identity");
20637 synchronized (mPackages) {
20638 return mSettings.getVerifierDeviceIdentityLPw();
20643 public void setPermissionEnforced(String permission, boolean enforced) {
20644 // TODO: Now that we no longer change GID for storage, this should to away.
20645 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20646 "setPermissionEnforced");
20647 if (READ_EXTERNAL_STORAGE.equals(permission)) {
20648 synchronized (mPackages) {
20649 if (mSettings.mReadExternalStorageEnforced == null
20650 || mSettings.mReadExternalStorageEnforced != enforced) {
20651 mSettings.mReadExternalStorageEnforced = enforced;
20652 mSettings.writeLPr();
20655 // kill any non-foreground processes so we restart them and
20656 // grant/revoke the GID.
20657 final IActivityManager am = ActivityManagerNative.getDefault();
20659 final long token = Binder.clearCallingIdentity();
20661 am.killProcessesBelowForeground("setPermissionEnforcement");
20662 } catch (RemoteException e) {
20664 Binder.restoreCallingIdentity(token);
20668 throw new IllegalArgumentException("No selective enforcement for " + permission);
20674 public boolean isPermissionEnforced(String permission) {
20679 public boolean isStorageLow() {
20680 final long token = Binder.clearCallingIdentity();
20682 final DeviceStorageMonitorInternal
20683 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20685 return dsm.isMemoryLow();
20690 Binder.restoreCallingIdentity(token);
20695 public IPackageInstaller getPackageInstaller() {
20696 return mInstallerService;
20699 private boolean userNeedsBadging(int userId) {
20700 int index = mUserNeedsBadging.indexOfKey(userId);
20702 final UserInfo userInfo;
20703 final long token = Binder.clearCallingIdentity();
20705 userInfo = sUserManager.getUserInfo(userId);
20707 Binder.restoreCallingIdentity(token);
20710 if (userInfo != null && userInfo.isManagedProfile()) {
20715 mUserNeedsBadging.put(userId, b);
20718 return mUserNeedsBadging.valueAt(index);
20722 public KeySet getKeySetByAlias(String packageName, String alias) {
20723 if (packageName == null || alias == null) {
20726 synchronized(mPackages) {
20727 final PackageParser.Package pkg = mPackages.get(packageName);
20729 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20730 throw new IllegalArgumentException("Unknown package: " + packageName);
20732 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20733 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20738 public KeySet getSigningKeySet(String packageName) {
20739 if (packageName == null) {
20742 synchronized(mPackages) {
20743 final PackageParser.Package pkg = mPackages.get(packageName);
20745 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20746 throw new IllegalArgumentException("Unknown package: " + packageName);
20748 if (pkg.applicationInfo.uid != Binder.getCallingUid()
20749 && Process.SYSTEM_UID != Binder.getCallingUid()) {
20750 throw new SecurityException("May not access signing KeySet of other apps.");
20752 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20753 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20758 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20759 if (packageName == null || ks == null) {
20762 synchronized(mPackages) {
20763 final PackageParser.Package pkg = mPackages.get(packageName);
20765 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20766 throw new IllegalArgumentException("Unknown package: " + packageName);
20768 IBinder ksh = ks.getToken();
20769 if (ksh instanceof KeySetHandle) {
20770 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20771 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20778 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20779 if (packageName == null || ks == null) {
20782 synchronized(mPackages) {
20783 final PackageParser.Package pkg = mPackages.get(packageName);
20785 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20786 throw new IllegalArgumentException("Unknown package: " + packageName);
20788 IBinder ksh = ks.getToken();
20789 if (ksh instanceof KeySetHandle) {
20790 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20791 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20797 private void deletePackageIfUnusedLPr(final String packageName) {
20798 PackageSetting ps = mSettings.mPackages.get(packageName);
20802 if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20803 // TODO Implement atomic delete if package is unused
20804 // It is currently possible that the package will be deleted even if it is installed
20805 // after this method returns.
20806 mHandler.post(new Runnable() {
20807 public void run() {
20808 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20815 * Check and throw if the given before/after packages would be considered a
20818 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20819 throws PackageManagerException {
20820 if (after.versionCode < before.mVersionCode) {
20821 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20822 "Update version code " + after.versionCode + " is older than current "
20823 + before.mVersionCode);
20824 } else if (after.versionCode == before.mVersionCode) {
20825 if (after.baseRevisionCode < before.baseRevisionCode) {
20826 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20827 "Update base revision code " + after.baseRevisionCode
20828 + " is older than current " + before.baseRevisionCode);
20831 if (!ArrayUtils.isEmpty(after.splitNames)) {
20832 for (int i = 0; i < after.splitNames.length; i++) {
20833 final String splitName = after.splitNames[i];
20834 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20836 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20837 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20838 "Update split " + splitName + " revision code "
20839 + after.splitRevisionCodes[i] + " is older than current "
20840 + before.splitRevisionCodes[j]);
20848 private static class MoveCallbacks extends Handler {
20849 private static final int MSG_CREATED = 1;
20850 private static final int MSG_STATUS_CHANGED = 2;
20852 private final RemoteCallbackList<IPackageMoveObserver>
20853 mCallbacks = new RemoteCallbackList<>();
20855 private final SparseIntArray mLastStatus = new SparseIntArray();
20857 public MoveCallbacks(Looper looper) {
20861 public void register(IPackageMoveObserver callback) {
20862 mCallbacks.register(callback);
20865 public void unregister(IPackageMoveObserver callback) {
20866 mCallbacks.unregister(callback);
20870 public void handleMessage(Message msg) {
20871 final SomeArgs args = (SomeArgs) msg.obj;
20872 final int n = mCallbacks.beginBroadcast();
20873 for (int i = 0; i < n; i++) {
20874 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20876 invokeCallback(callback, msg.what, args);
20877 } catch (RemoteException ignored) {
20880 mCallbacks.finishBroadcast();
20884 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20885 throws RemoteException {
20887 case MSG_CREATED: {
20888 callback.onCreated(args.argi1, (Bundle) args.arg2);
20891 case MSG_STATUS_CHANGED: {
20892 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20898 private void notifyCreated(int moveId, Bundle extras) {
20899 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20901 final SomeArgs args = SomeArgs.obtain();
20902 args.argi1 = moveId;
20903 args.arg2 = extras;
20904 obtainMessage(MSG_CREATED, args).sendToTarget();
20907 private void notifyStatusChanged(int moveId, int status) {
20908 notifyStatusChanged(moveId, status, -1);
20911 private void notifyStatusChanged(int moveId, int status, long estMillis) {
20912 Slog.v(TAG, "Move " + moveId + " status " + status);
20914 final SomeArgs args = SomeArgs.obtain();
20915 args.argi1 = moveId;
20916 args.argi2 = status;
20917 args.arg3 = estMillis;
20918 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20920 synchronized (mLastStatus) {
20921 mLastStatus.put(moveId, status);
20926 private final static class OnPermissionChangeListeners extends Handler {
20927 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20929 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20930 new RemoteCallbackList<>();
20932 public OnPermissionChangeListeners(Looper looper) {
20937 public void handleMessage(Message msg) {
20938 switch (msg.what) {
20939 case MSG_ON_PERMISSIONS_CHANGED: {
20940 final int uid = msg.arg1;
20941 handleOnPermissionsChanged(uid);
20946 public void addListenerLocked(IOnPermissionsChangeListener listener) {
20947 mPermissionListeners.register(listener);
20951 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20952 mPermissionListeners.unregister(listener);
20955 public void onPermissionsChanged(int uid) {
20956 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20957 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20961 private void handleOnPermissionsChanged(int uid) {
20962 final int count = mPermissionListeners.beginBroadcast();
20964 for (int i = 0; i < count; i++) {
20965 IOnPermissionsChangeListener callback = mPermissionListeners
20966 .getBroadcastItem(i);
20968 callback.onPermissionsChanged(uid);
20969 } catch (RemoteException e) {
20970 Log.e(TAG, "Permission listener is dead", e);
20974 mPermissionListeners.finishBroadcast();
20979 private class PackageManagerInternalImpl extends PackageManagerInternal {
20981 public void setLocationPackagesProvider(PackagesProvider provider) {
20982 synchronized (mPackages) {
20983 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20988 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20989 synchronized (mPackages) {
20990 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20995 public void setSmsAppPackagesProvider(PackagesProvider provider) {
20996 synchronized (mPackages) {
20997 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21002 public void setDialerAppPackagesProvider(PackagesProvider provider) {
21003 synchronized (mPackages) {
21004 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21009 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21010 synchronized (mPackages) {
21011 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21016 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21017 synchronized (mPackages) {
21018 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21023 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21024 synchronized (mPackages) {
21025 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21026 packageName, userId);
21031 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21032 synchronized (mPackages) {
21033 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21034 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21035 packageName, userId);
21040 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21041 synchronized (mPackages) {
21042 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21043 packageName, userId);
21048 public void setKeepUninstalledPackages(final List<String> packageList) {
21049 Preconditions.checkNotNull(packageList);
21050 List<String> removedFromList = null;
21051 synchronized (mPackages) {
21052 if (mKeepUninstalledPackages != null) {
21053 final int packagesCount = mKeepUninstalledPackages.size();
21054 for (int i = 0; i < packagesCount; i++) {
21055 String oldPackage = mKeepUninstalledPackages.get(i);
21056 if (packageList != null && packageList.contains(oldPackage)) {
21059 if (removedFromList == null) {
21060 removedFromList = new ArrayList<>();
21062 removedFromList.add(oldPackage);
21065 mKeepUninstalledPackages = new ArrayList<>(packageList);
21066 if (removedFromList != null) {
21067 final int removedCount = removedFromList.size();
21068 for (int i = 0; i < removedCount; i++) {
21069 deletePackageIfUnusedLPr(removedFromList.get(i));
21076 public boolean isPermissionsReviewRequired(String packageName, int userId) {
21077 synchronized (mPackages) {
21078 // If we do not support permission review, done.
21079 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21083 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21084 if (packageSetting == null) {
21088 // Permission review applies only to apps not supporting the new permission model.
21089 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21093 // Legacy apps have the permission and get user consent on launch.
21094 PermissionsState permissionsState = packageSetting.getPermissionsState();
21095 return permissionsState.isPermissionReviewRequired(userId);
21100 public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21101 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21105 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21107 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21111 public void setDeviceAndProfileOwnerPackages(
21112 int deviceOwnerUserId, String deviceOwnerPackage,
21113 SparseArray<String> profileOwnerPackages) {
21114 mProtectedPackages.setDeviceAndProfileOwnerPackages(
21115 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21119 public boolean isPackageDataProtected(int userId, String packageName) {
21120 return mProtectedPackages.isPackageDataProtected(userId, packageName);
21124 public boolean wasPackageEverLaunched(String packageName, int userId) {
21125 synchronized (mPackages) {
21126 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21132 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21133 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21134 synchronized (mPackages) {
21135 final long identity = Binder.clearCallingIdentity();
21137 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21138 packageNames, userId);
21140 Binder.restoreCallingIdentity(identity);
21145 private static void enforceSystemOrPhoneCaller(String tag) {
21146 int callingUid = Binder.getCallingUid();
21147 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21148 throw new SecurityException(
21149 "Cannot call " + tag + " from UID " + callingUid);
21153 boolean isHistoricalPackageUsageAvailable() {
21154 return mPackageUsage.isHistoricalPackageUsageAvailable();
21158 * Return a <b>copy</b> of the collection of packages known to the package manager.
21159 * @return A copy of the values of mPackages.
21161 Collection<PackageParser.Package> getPackages() {
21162 synchronized (mPackages) {
21163 return new ArrayList<>(mPackages.values());
21168 * Logs process start information (including base APK hash) to the security log.
21171 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21172 String apkFile, int pid) {
21173 if (!SecurityLog.isLoggingEnabled()) {
21176 Bundle data = new Bundle();
21177 data.putLong("startTimestamp", System.currentTimeMillis());
21178 data.putString("processName", processName);
21179 data.putInt("uid", uid);
21180 data.putString("seinfo", seinfo);
21181 data.putString("apkFile", apkFile);
21182 data.putInt("pid", pid);
21183 Message msg = mProcessLoggingHandler.obtainMessage(
21184 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21186 mProcessLoggingHandler.sendMessage(msg);
21189 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21190 return mCompilerStats.getPackageStats(pkgName);
21193 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21194 return getOrCreateCompilerPackageStats(pkg.packageName);
21197 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21198 return mCompilerStats.getOrCreatePackageStats(pkgName);
21201 public void deleteCompilerPackageStats(String pkgName) {
21202 mCompilerStats.deletePackageStats(pkgName);