1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 package com.android.server.pm; 17 18 import android.Manifest.permission; 19 import android.annotation.IntDef; 20 import android.annotation.NonNull; 21 import android.annotation.Nullable; 22 import android.annotation.UserIdInt; 23 import android.app.ActivityManager; 24 import android.app.ActivityManagerInternal; 25 import android.app.AppGlobals; 26 import android.app.IUidObserver; 27 import android.app.usage.UsageStatsManagerInternal; 28 import android.appwidget.AppWidgetProviderInfo; 29 import android.content.BroadcastReceiver; 30 import android.content.ComponentName; 31 import android.content.Context; 32 import android.content.Intent; 33 import android.content.IntentFilter; 34 import android.content.IntentSender; 35 import android.content.IntentSender.SendIntentException; 36 import android.content.pm.ActivityInfo; 37 import android.content.pm.ApplicationInfo; 38 import android.content.pm.IPackageManager; 39 import android.content.pm.IShortcutService; 40 import android.content.pm.LauncherApps; 41 import android.content.pm.LauncherApps.ShortcutQuery; 42 import android.content.pm.PackageInfo; 43 import android.content.pm.PackageManager; 44 import android.content.pm.PackageManager.NameNotFoundException; 45 import android.content.pm.PackageManagerInternal; 46 import android.content.pm.ParceledListSlice; 47 import android.content.pm.ResolveInfo; 48 import android.content.pm.ShortcutInfo; 49 import android.content.pm.ShortcutManager; 50 import android.content.pm.ShortcutServiceInternal; 51 import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener; 52 import android.content.res.Resources; 53 import android.content.res.XmlResourceParser; 54 import android.graphics.Bitmap; 55 import android.graphics.Bitmap.CompressFormat; 56 import android.graphics.Canvas; 57 import android.graphics.RectF; 58 import android.graphics.drawable.AdaptiveIconDrawable; 59 import android.graphics.drawable.Icon; 60 import android.net.Uri; 61 import android.os.Binder; 62 import android.os.Build; 63 import android.os.Bundle; 64 import android.os.Environment; 65 import android.os.FileUtils; 66 import android.os.Handler; 67 import android.os.LocaleList; 68 import android.os.Looper; 69 import android.os.ParcelFileDescriptor; 70 import android.os.PersistableBundle; 71 import android.os.Process; 72 import android.os.RemoteException; 73 import android.os.ResultReceiver; 74 import android.os.SELinux; 75 import android.os.ServiceManager; 76 import android.os.ShellCallback; 77 import android.os.ShellCommand; 78 import android.os.SystemClock; 79 import android.os.UserHandle; 80 import android.os.UserManagerInternal; 81 import android.text.TextUtils; 82 import android.text.format.TimeMigrationUtils; 83 import android.util.ArraySet; 84 import android.util.AtomicFile; 85 import android.util.KeyValueListParser; 86 import android.util.Log; 87 import android.util.Slog; 88 import android.util.SparseArray; 89 import android.util.SparseBooleanArray; 90 import android.util.SparseIntArray; 91 import android.util.SparseLongArray; 92 import android.util.TypedValue; 93 import android.util.Xml; 94 import android.view.IWindowManager; 95 96 import com.android.internal.annotations.GuardedBy; 97 import com.android.internal.annotations.VisibleForTesting; 98 import com.android.internal.logging.MetricsLogger; 99 import com.android.internal.os.BackgroundThread; 100 import com.android.internal.util.DumpUtils; 101 import com.android.internal.util.FastXmlSerializer; 102 import com.android.internal.util.Preconditions; 103 import com.android.internal.util.StatLogger; 104 import com.android.server.LocalServices; 105 import com.android.server.SystemService; 106 import com.android.server.pm.ShortcutUser.PackageWithUser; 107 108 import libcore.io.IoUtils; 109 110 import org.json.JSONArray; 111 import org.json.JSONException; 112 import org.json.JSONObject; 113 import org.xmlpull.v1.XmlPullParser; 114 import org.xmlpull.v1.XmlPullParserException; 115 import org.xmlpull.v1.XmlSerializer; 116 117 import java.io.BufferedInputStream; 118 import java.io.BufferedOutputStream; 119 import java.io.ByteArrayInputStream; 120 import java.io.ByteArrayOutputStream; 121 import java.io.File; 122 import java.io.FileDescriptor; 123 import java.io.FileInputStream; 124 import java.io.FileNotFoundException; 125 import java.io.FileOutputStream; 126 import java.io.IOException; 127 import java.io.InputStream; 128 import java.io.OutputStream; 129 import java.io.PrintWriter; 130 import java.lang.annotation.Retention; 131 import java.lang.annotation.RetentionPolicy; 132 import java.net.URISyntaxException; 133 import java.nio.charset.StandardCharsets; 134 import java.util.ArrayList; 135 import java.util.Collections; 136 import java.util.List; 137 import java.util.Objects; 138 import java.util.concurrent.atomic.AtomicBoolean; 139 import java.util.function.Consumer; 140 import java.util.function.Predicate; 141 import java.util.regex.Pattern; 142 143 /** 144 * TODO: 145 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi. 146 * -> But TypedValue.applyDimension() doesn't differentiate x and y..? 147 * 148 * - Detect when already registered instances are passed to APIs again, which might break 149 * internal bitmap handling. 150 */ 151 public class ShortcutService extends IShortcutService.Stub { 152 static final String TAG = "ShortcutService"; 153 154 static final boolean DEBUG = false; // STOPSHIP if true 155 static final boolean DEBUG_LOAD = false; // STOPSHIP if true 156 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true 157 158 @VisibleForTesting 159 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day 160 161 @VisibleForTesting 162 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10; 163 164 @VisibleForTesting 165 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 10; 166 167 @VisibleForTesting 168 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96; 169 170 @VisibleForTesting 171 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48; 172 173 @VisibleForTesting 174 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name(); 175 176 @VisibleForTesting 177 static final int DEFAULT_ICON_PERSIST_QUALITY = 100; 178 179 @VisibleForTesting 180 static final int DEFAULT_SAVE_DELAY_MS = 3000; 181 182 @VisibleForTesting 183 static final String FILENAME_BASE_STATE = "shortcut_service.xml"; 184 185 @VisibleForTesting 186 static final String DIRECTORY_PER_USER = "shortcut_service"; 187 188 @VisibleForTesting 189 static final String DIRECTORY_DUMP = "shortcut_dump"; 190 191 @VisibleForTesting 192 static final String FILENAME_USER_PACKAGES = "shortcuts.xml"; 193 194 static final String DIRECTORY_BITMAPS = "bitmaps"; 195 196 private static final String TAG_ROOT = "root"; 197 private static final String TAG_LAST_RESET_TIME = "last_reset_time"; 198 199 private static final String ATTR_VALUE = "value"; 200 201 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER; 202 203 private static final String KEY_SHORTCUT = "shortcut"; 204 private static final String KEY_LOW_RAM = "lowRam"; 205 private static final String KEY_ICON_SIZE = "iconSize"; 206 207 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__"; 208 209 @VisibleForTesting 210 interface ConfigConstants { 211 /** 212 * Key name for the save delay, in milliseconds. (int) 213 */ 214 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms"; 215 216 /** 217 * Key name for the throttling reset interval, in seconds. (long) 218 */ 219 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec"; 220 221 /** 222 * Key name for the max number of modifying API calls per app for every interval. (int) 223 */ 224 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval"; 225 226 /** 227 * Key name for the max icon dimensions in DP, for non-low-memory devices. 228 */ 229 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp"; 230 231 /** 232 * Key name for the max icon dimensions in DP, for low-memory devices. 233 */ 234 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram"; 235 236 /** 237 * Key name for the max dynamic shortcuts per activity. (int) 238 */ 239 String KEY_MAX_SHORTCUTS = "max_shortcuts"; 240 241 /** 242 * Key name for icon compression quality, 0-100. 243 */ 244 String KEY_ICON_QUALITY = "icon_quality"; 245 246 /** 247 * Key name for icon compression format: "PNG", "JPEG" or "WEBP" 248 */ 249 String KEY_ICON_FORMAT = "icon_format"; 250 } 251 252 final Context mContext; 253 254 private final Object mLock = new Object(); 255 256 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0); 257 258 // Temporarily reverted to anonymous inner class form due to: b/32554459 259 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() { 260 public boolean test(ResolveInfo ri) { 261 return !ri.activityInfo.exported; 262 } 263 }; 264 265 // Temporarily reverted to anonymous inner class form due to: b/32554459 266 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() { 267 public boolean test(PackageInfo pi) { 268 return !isInstalled(pi); 269 } 270 }; 271 272 private final Handler mHandler; 273 274 @GuardedBy("mLock") 275 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1); 276 277 @GuardedBy("mLock") 278 private long mRawLastResetTime; 279 280 /** 281 * User ID -> UserShortcuts 282 */ 283 @GuardedBy("mLock") 284 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>(); 285 286 /** 287 * User ID -> ShortcutNonPersistentUser 288 */ 289 @GuardedBy("mLock") 290 private final SparseArray<ShortcutNonPersistentUser> mShortcutNonPersistentUsers = 291 new SparseArray<>(); 292 293 /** 294 * Max number of dynamic + manifest shortcuts that each application can have at a time. 295 */ 296 private int mMaxShortcuts; 297 298 /** 299 * Max number of updating API calls that each application can make during the interval. 300 */ 301 int mMaxUpdatesPerInterval; 302 303 /** 304 * Actual throttling-reset interval. By default it's a day. 305 */ 306 private long mResetInterval; 307 308 /** 309 * Icon max width/height in pixels. 310 */ 311 private int mMaxIconDimension; 312 313 private CompressFormat mIconPersistFormat; 314 private int mIconPersistQuality; 315 316 private int mSaveDelayMillis; 317 318 private final IPackageManager mIPackageManager; 319 private final PackageManagerInternal mPackageManagerInternal; 320 private final UserManagerInternal mUserManagerInternal; 321 private final UsageStatsManagerInternal mUsageStatsManagerInternal; 322 private final ActivityManagerInternal mActivityManagerInternal; 323 324 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor; 325 private final ShortcutBitmapSaver mShortcutBitmapSaver; 326 private final ShortcutDumpFiles mShortcutDumpFiles; 327 328 @GuardedBy("mLock") 329 final SparseIntArray mUidState = new SparseIntArray(); 330 331 @GuardedBy("mLock") 332 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray(); 333 334 @GuardedBy("mLock") 335 private List<Integer> mDirtyUserIds = new ArrayList<>(); 336 337 private final AtomicBoolean mBootCompleted = new AtomicBoolean(); 338 339 private static final int PACKAGE_MATCH_FLAGS = 340 PackageManager.MATCH_DIRECT_BOOT_AWARE 341 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE 342 | PackageManager.MATCH_UNINSTALLED_PACKAGES; 343 344 /** 345 * Note we use a fine-grained lock for {@link #mUnlockedUsers} due to b/64303666. 346 */ 347 @GuardedBy("mUnlockedUsers") 348 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray(); 349 350 // Stats 351 @VisibleForTesting 352 interface Stats { 353 int GET_DEFAULT_HOME = 0; 354 int GET_PACKAGE_INFO = 1; 355 int GET_PACKAGE_INFO_WITH_SIG = 2; 356 int GET_APPLICATION_INFO = 3; 357 int LAUNCHER_PERMISSION_CHECK = 4; 358 int CLEANUP_DANGLING_BITMAPS = 5; 359 int GET_ACTIVITY_WITH_METADATA = 6; 360 int GET_INSTALLED_PACKAGES = 7; 361 int CHECK_PACKAGE_CHANGES = 8; 362 int GET_APPLICATION_RESOURCES = 9; 363 int RESOURCE_NAME_LOOKUP = 10; 364 int GET_LAUNCHER_ACTIVITY = 11; 365 int CHECK_LAUNCHER_ACTIVITY = 12; 366 int IS_ACTIVITY_ENABLED = 13; 367 int PACKAGE_UPDATE_CHECK = 14; 368 int ASYNC_PRELOAD_USER_DELAY = 15; 369 int GET_DEFAULT_LAUNCHER = 16; 370 371 int COUNT = GET_DEFAULT_LAUNCHER + 1; 372 } 373 374 private final StatLogger mStatLogger = new StatLogger(new String[] { 375 "getHomeActivities()", 376 "Launcher permission check", 377 "getPackageInfo()", 378 "getPackageInfo(SIG)", 379 "getApplicationInfo", 380 "cleanupDanglingBitmaps", 381 "getActivity+metadata", 382 "getInstalledPackages", 383 "checkPackageChanges", 384 "getApplicationResources", 385 "resourceNameLookup", 386 "getLauncherActivity", 387 "checkLauncherActivity", 388 "isActivityEnabled", 389 "packageUpdateCheck", 390 "asyncPreloadUserDelay", 391 "getDefaultLauncher()" 392 }); 393 394 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD = 395 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE; 396 397 static final int OPERATION_SET = 0; 398 static final int OPERATION_ADD = 1; 399 static final int OPERATION_UPDATE = 2; 400 401 /** @hide */ 402 @IntDef(value = { 403 OPERATION_SET, 404 OPERATION_ADD, 405 OPERATION_UPDATE 406 }) 407 @Retention(RetentionPolicy.SOURCE) 408 @interface ShortcutOperation { 409 } 410 411 @GuardedBy("mLock") 412 private int mWtfCount = 0; 413 414 @GuardedBy("mLock") 415 private Exception mLastWtfStacktrace; 416 417 @GuardedBy("mLock") 418 private final MetricsLogger mMetricsLogger = new MetricsLogger(); 419 420 static class InvalidFileFormatException extends Exception { InvalidFileFormatException(String message, Throwable cause)421 public InvalidFileFormatException(String message, Throwable cause) { 422 super(message, cause); 423 } 424 } 425 ShortcutService(Context context)426 public ShortcutService(Context context) { 427 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false); 428 } 429 430 @VisibleForTesting ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis)431 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) { 432 mContext = Preconditions.checkNotNull(context); 433 LocalServices.addService(ShortcutServiceInternal.class, new LocalService()); 434 mHandler = new Handler(looper); 435 mIPackageManager = AppGlobals.getPackageManager(); 436 mPackageManagerInternal = Preconditions.checkNotNull( 437 LocalServices.getService(PackageManagerInternal.class)); 438 mUserManagerInternal = Preconditions.checkNotNull( 439 LocalServices.getService(UserManagerInternal.class)); 440 mUsageStatsManagerInternal = Preconditions.checkNotNull( 441 LocalServices.getService(UsageStatsManagerInternal.class)); 442 mActivityManagerInternal = Preconditions.checkNotNull( 443 LocalServices.getService(ActivityManagerInternal.class)); 444 445 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock); 446 mShortcutBitmapSaver = new ShortcutBitmapSaver(this); 447 mShortcutDumpFiles = new ShortcutDumpFiles(this); 448 449 if (onlyForPackageManagerApis) { 450 return; // Don't do anything further. For unit tests only. 451 } 452 453 // Register receivers. 454 455 // We need to set a priority, so let's just not use PackageMonitor for now. 456 // TODO Refactor PackageMonitor to support priorities. 457 final IntentFilter packageFilter = new IntentFilter(); 458 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 459 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 460 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED); 461 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED); 462 packageFilter.addDataScheme("package"); 463 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 464 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL, 465 packageFilter, null, mHandler); 466 467 final IntentFilter preferedActivityFilter = new IntentFilter(); 468 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 469 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 470 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL, 471 preferedActivityFilter, null, mHandler); 472 473 final IntentFilter localeFilter = new IntentFilter(); 474 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED); 475 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 476 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, 477 localeFilter, null, mHandler); 478 479 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE 480 | ActivityManager.UID_OBSERVER_GONE); 481 } 482 getStatStartTime()483 long getStatStartTime() { 484 return mStatLogger.getTime(); 485 } 486 logDurationStat(int statId, long start)487 void logDurationStat(int statId, long start) { 488 mStatLogger.logDurationStat(statId, start); 489 } 490 injectGetLocaleTagsForUser(@serIdInt int userId)491 public String injectGetLocaleTagsForUser(@UserIdInt int userId) { 492 // TODO This should get the per-user locale. b/30123329 b/30119489 493 return LocaleList.getDefault().toLanguageTags(); 494 } 495 496 final private IUidObserver mUidObserver = new IUidObserver.Stub() { 497 @Override 498 public void onUidStateChanged(int uid, int procState, long procStateSeq) { 499 injectPostToHandler(() -> handleOnUidStateChanged(uid, procState)); 500 } 501 502 @Override 503 public void onUidGone(int uid, boolean disabled) { 504 injectPostToHandler(() -> 505 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT)); 506 } 507 508 @Override 509 public void onUidActive(int uid) { 510 } 511 512 @Override 513 public void onUidIdle(int uid, boolean disabled) { 514 } 515 516 @Override public void onUidCachedChanged(int uid, boolean cached) { 517 } 518 }; 519 handleOnUidStateChanged(int uid, int procState)520 void handleOnUidStateChanged(int uid, int procState) { 521 if (DEBUG_PROCSTATE) { 522 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState); 523 } 524 synchronized (mLock) { 525 mUidState.put(uid, procState); 526 527 // We need to keep track of last time an app comes to foreground. 528 // See ShortcutPackage.getApiCallCount() for how it's used. 529 // It doesn't have to be persisted, but it needs to be the elapsed time. 530 if (isProcessStateForeground(procState)) { 531 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime()); 532 } 533 } 534 } 535 isProcessStateForeground(int processState)536 private boolean isProcessStateForeground(int processState) { 537 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD; 538 } 539 540 @GuardedBy("mLock") isUidForegroundLocked(int uid)541 boolean isUidForegroundLocked(int uid) { 542 if (uid == Process.SYSTEM_UID) { 543 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services, 544 // so it's foreground anyway. 545 return true; 546 } 547 // First, check with the local cache. 548 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) { 549 return true; 550 } 551 // If the cache says background, reach out to AM. Since it'll internally need to hold 552 // the AM lock, we use it as a last resort. 553 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid)); 554 } 555 556 @GuardedBy("mLock") getUidLastForegroundElapsedTimeLocked(int uid)557 long getUidLastForegroundElapsedTimeLocked(int uid) { 558 return mUidLastForegroundElapsedTime.get(uid); 559 } 560 561 /** 562 * System service lifecycle. 563 */ 564 public static final class Lifecycle extends SystemService { 565 final ShortcutService mService; 566 Lifecycle(Context context)567 public Lifecycle(Context context) { 568 super(context); 569 if (DEBUG) { 570 Binder.LOG_RUNTIME_EXCEPTION = true; 571 } 572 mService = new ShortcutService(context); 573 } 574 575 @Override onStart()576 public void onStart() { 577 publishBinderService(Context.SHORTCUT_SERVICE, mService); 578 } 579 580 @Override onBootPhase(int phase)581 public void onBootPhase(int phase) { 582 mService.onBootPhase(phase); 583 } 584 585 @Override onStopUser(int userHandle)586 public void onStopUser(int userHandle) { 587 mService.handleStopUser(userHandle); 588 } 589 590 @Override onUnlockUser(int userId)591 public void onUnlockUser(int userId) { 592 mService.handleUnlockUser(userId); 593 } 594 } 595 596 /** lifecycle event */ onBootPhase(int phase)597 void onBootPhase(int phase) { 598 if (DEBUG) { 599 Slog.d(TAG, "onBootPhase: " + phase); 600 } 601 switch (phase) { 602 case SystemService.PHASE_LOCK_SETTINGS_READY: 603 initialize(); 604 break; 605 case SystemService.PHASE_BOOT_COMPLETED: 606 mBootCompleted.set(true); 607 break; 608 } 609 } 610 611 /** lifecycle event */ handleUnlockUser(int userId)612 void handleUnlockUser(int userId) { 613 if (DEBUG) { 614 Slog.d(TAG, "handleUnlockUser: user=" + userId); 615 } 616 synchronized (mUnlockedUsers) { 617 mUnlockedUsers.put(userId, true); 618 } 619 620 // Preload the user data. 621 // Note, we don't use mHandler here but instead just start a new thread. 622 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very 623 // busy at this point and this could take hundreds of milliseconds, which would be too 624 // late since the launcher would already have started. 625 // So we just create a new thread. This code runs rarely, so we don't use a thread pool 626 // or anything. 627 final long start = getStatStartTime(); 628 injectRunOnNewThread(() -> { 629 synchronized (mLock) { 630 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start); 631 getUserShortcutsLocked(userId); 632 } 633 }); 634 } 635 636 /** lifecycle event */ handleStopUser(int userId)637 void handleStopUser(int userId) { 638 if (DEBUG) { 639 Slog.d(TAG, "handleStopUser: user=" + userId); 640 } 641 synchronized (mLock) { 642 unloadUserLocked(userId); 643 644 synchronized (mUnlockedUsers) { 645 mUnlockedUsers.put(userId, false); 646 } 647 } 648 } 649 650 @GuardedBy("mLock") unloadUserLocked(int userId)651 private void unloadUserLocked(int userId) { 652 if (DEBUG) { 653 Slog.d(TAG, "unloadUserLocked: user=" + userId); 654 } 655 // Save all dirty information. 656 saveDirtyInfo(); 657 658 // Unload 659 mUsers.delete(userId); 660 } 661 662 /** Return the base state file name */ getBaseStateFile()663 private AtomicFile getBaseStateFile() { 664 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE); 665 path.mkdirs(); 666 return new AtomicFile(path); 667 } 668 669 /** 670 * Init the instance. (load the state file, etc) 671 */ initialize()672 private void initialize() { 673 synchronized (mLock) { 674 loadConfigurationLocked(); 675 loadBaseStateLocked(); 676 } 677 } 678 679 /** 680 * Load the configuration from Settings. 681 */ loadConfigurationLocked()682 private void loadConfigurationLocked() { 683 updateConfigurationLocked(injectShortcutManagerConstants()); 684 } 685 686 /** 687 * Load the configuration from Settings. 688 */ 689 @VisibleForTesting updateConfigurationLocked(String config)690 boolean updateConfigurationLocked(String config) { 691 boolean result = true; 692 693 final KeyValueListParser parser = new KeyValueListParser(','); 694 try { 695 parser.setString(config); 696 } catch (IllegalArgumentException e) { 697 // Failed to parse the settings string, log this and move on 698 // with defaults. 699 Slog.e(TAG, "Bad shortcut manager settings", e); 700 result = false; 701 } 702 703 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS, 704 DEFAULT_SAVE_DELAY_MS)); 705 706 mResetInterval = Math.max(1, parser.getLong( 707 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC) 708 * 1000L); 709 710 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong( 711 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL)); 712 713 mMaxShortcuts = Math.max(0, (int) parser.getLong( 714 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP)); 715 716 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice() 717 ? (int) parser.getLong( 718 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM, 719 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP) 720 : (int) parser.getLong( 721 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP, 722 DEFAULT_MAX_ICON_DIMENSION_DP)); 723 724 mMaxIconDimension = injectDipToPixel(iconDimensionDp); 725 726 mIconPersistFormat = CompressFormat.valueOf( 727 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT)); 728 729 mIconPersistQuality = (int) parser.getLong( 730 ConfigConstants.KEY_ICON_QUALITY, 731 DEFAULT_ICON_PERSIST_QUALITY); 732 733 return result; 734 } 735 736 @VisibleForTesting injectShortcutManagerConstants()737 String injectShortcutManagerConstants() { 738 return android.provider.Settings.Global.getString( 739 mContext.getContentResolver(), 740 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS); 741 } 742 743 @VisibleForTesting injectDipToPixel(int dip)744 int injectDipToPixel(int dip) { 745 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, 746 mContext.getResources().getDisplayMetrics()); 747 } 748 749 // === Persisting === 750 751 @Nullable parseStringAttribute(XmlPullParser parser, String attribute)752 static String parseStringAttribute(XmlPullParser parser, String attribute) { 753 return parser.getAttributeValue(null, attribute); 754 } 755 parseBooleanAttribute(XmlPullParser parser, String attribute)756 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) { 757 return parseLongAttribute(parser, attribute) == 1; 758 } 759 parseBooleanAttribute(XmlPullParser parser, String attribute, boolean def)760 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute, boolean def) { 761 return parseLongAttribute(parser, attribute, (def ? 1 : 0)) == 1; 762 } 763 parseIntAttribute(XmlPullParser parser, String attribute)764 static int parseIntAttribute(XmlPullParser parser, String attribute) { 765 return (int) parseLongAttribute(parser, attribute); 766 } 767 parseIntAttribute(XmlPullParser parser, String attribute, int def)768 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) { 769 return (int) parseLongAttribute(parser, attribute, def); 770 } 771 parseLongAttribute(XmlPullParser parser, String attribute)772 static long parseLongAttribute(XmlPullParser parser, String attribute) { 773 return parseLongAttribute(parser, attribute, 0); 774 } 775 parseLongAttribute(XmlPullParser parser, String attribute, long def)776 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) { 777 final String value = parseStringAttribute(parser, attribute); 778 if (TextUtils.isEmpty(value)) { 779 return def; 780 } 781 try { 782 return Long.parseLong(value); 783 } catch (NumberFormatException e) { 784 Slog.e(TAG, "Error parsing long " + value); 785 return def; 786 } 787 } 788 789 @Nullable parseComponentNameAttribute(XmlPullParser parser, String attribute)790 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) { 791 final String value = parseStringAttribute(parser, attribute); 792 if (TextUtils.isEmpty(value)) { 793 return null; 794 } 795 return ComponentName.unflattenFromString(value); 796 } 797 798 @Nullable parseIntentAttributeNoDefault(XmlPullParser parser, String attribute)799 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) { 800 final String value = parseStringAttribute(parser, attribute); 801 Intent parsed = null; 802 if (!TextUtils.isEmpty(value)) { 803 try { 804 parsed = Intent.parseUri(value, /* flags =*/ 0); 805 } catch (URISyntaxException e) { 806 Slog.e(TAG, "Error parsing intent", e); 807 } 808 } 809 return parsed; 810 } 811 812 @Nullable parseIntentAttribute(XmlPullParser parser, String attribute)813 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) { 814 Intent parsed = parseIntentAttributeNoDefault(parser, attribute); 815 if (parsed == null) { 816 // Default intent. 817 parsed = new Intent(Intent.ACTION_VIEW); 818 } 819 return parsed; 820 } 821 writeTagValue(XmlSerializer out, String tag, String value)822 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException { 823 if (TextUtils.isEmpty(value)) return; 824 825 out.startTag(null, tag); 826 out.attribute(null, ATTR_VALUE, value); 827 out.endTag(null, tag); 828 } 829 writeTagValue(XmlSerializer out, String tag, long value)830 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException { 831 writeTagValue(out, tag, Long.toString(value)); 832 } 833 writeTagValue(XmlSerializer out, String tag, ComponentName name)834 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException { 835 if (name == null) return; 836 writeTagValue(out, tag, name.flattenToString()); 837 } 838 writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)839 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle) 840 throws IOException, XmlPullParserException { 841 if (bundle == null) return; 842 843 out.startTag(null, tag); 844 bundle.saveToXml(out); 845 out.endTag(null, tag); 846 } 847 writeAttr(XmlSerializer out, String name, CharSequence value)848 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException { 849 if (TextUtils.isEmpty(value)) return; 850 851 out.attribute(null, name, value.toString()); 852 } 853 writeAttr(XmlSerializer out, String name, long value)854 static void writeAttr(XmlSerializer out, String name, long value) throws IOException { 855 writeAttr(out, name, String.valueOf(value)); 856 } 857 writeAttr(XmlSerializer out, String name, boolean value)858 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException { 859 if (value) { 860 writeAttr(out, name, "1"); 861 } else { 862 writeAttr(out, name, "0"); 863 } 864 } 865 writeAttr(XmlSerializer out, String name, ComponentName comp)866 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException { 867 if (comp == null) return; 868 writeAttr(out, name, comp.flattenToString()); 869 } 870 writeAttr(XmlSerializer out, String name, Intent intent)871 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException { 872 if (intent == null) return; 873 874 writeAttr(out, name, intent.toUri(/* flags =*/ 0)); 875 } 876 877 @GuardedBy("mLock") 878 @VisibleForTesting saveBaseStateLocked()879 void saveBaseStateLocked() { 880 final AtomicFile file = getBaseStateFile(); 881 if (DEBUG) { 882 Slog.d(TAG, "Saving to " + file.getBaseFile()); 883 } 884 885 FileOutputStream outs = null; 886 try { 887 outs = file.startWrite(); 888 889 // Write to XML 890 XmlSerializer out = new FastXmlSerializer(); 891 out.setOutput(outs, StandardCharsets.UTF_8.name()); 892 out.startDocument(null, true); 893 out.startTag(null, TAG_ROOT); 894 895 // Body. 896 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime); 897 898 // Epilogue. 899 out.endTag(null, TAG_ROOT); 900 out.endDocument(); 901 902 // Close. 903 file.finishWrite(outs); 904 } catch (IOException e) { 905 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e); 906 file.failWrite(outs); 907 } 908 } 909 910 @GuardedBy("mLock") loadBaseStateLocked()911 private void loadBaseStateLocked() { 912 mRawLastResetTime = 0; 913 914 final AtomicFile file = getBaseStateFile(); 915 if (DEBUG) { 916 Slog.d(TAG, "Loading from " + file.getBaseFile()); 917 } 918 try (FileInputStream in = file.openRead()) { 919 XmlPullParser parser = Xml.newPullParser(); 920 parser.setInput(in, StandardCharsets.UTF_8.name()); 921 922 int type; 923 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 924 if (type != XmlPullParser.START_TAG) { 925 continue; 926 } 927 final int depth = parser.getDepth(); 928 // Check the root tag 929 final String tag = parser.getName(); 930 if (depth == 1) { 931 if (!TAG_ROOT.equals(tag)) { 932 Slog.e(TAG, "Invalid root tag: " + tag); 933 return; 934 } 935 continue; 936 } 937 // Assume depth == 2 938 switch (tag) { 939 case TAG_LAST_RESET_TIME: 940 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE); 941 break; 942 default: 943 Slog.e(TAG, "Invalid tag: " + tag); 944 break; 945 } 946 } 947 } catch (FileNotFoundException e) { 948 // Use the default 949 } catch (IOException | XmlPullParserException e) { 950 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e); 951 952 mRawLastResetTime = 0; 953 } 954 // Adjust the last reset time. 955 getLastResetTimeLocked(); 956 } 957 958 @VisibleForTesting getUserFile(@serIdInt int userId)959 final File getUserFile(@UserIdInt int userId) { 960 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES); 961 } 962 963 @GuardedBy("mLock") saveUserLocked(@serIdInt int userId)964 private void saveUserLocked(@UserIdInt int userId) { 965 final File path = getUserFile(userId); 966 if (DEBUG) { 967 Slog.d(TAG, "Saving to " + path); 968 } 969 970 mShortcutBitmapSaver.waitForAllSavesLocked(); 971 972 path.getParentFile().mkdirs(); 973 final AtomicFile file = new AtomicFile(path); 974 FileOutputStream os = null; 975 try { 976 os = file.startWrite(); 977 978 saveUserInternalLocked(userId, os, /* forBackup= */ false); 979 980 file.finishWrite(os); 981 982 // Remove all dangling bitmap files. 983 cleanupDanglingBitmapDirectoriesLocked(userId); 984 } catch (XmlPullParserException | IOException e) { 985 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e); 986 file.failWrite(os); 987 } 988 989 getUserShortcutsLocked(userId).logSharingShortcutStats(mMetricsLogger); 990 } 991 992 @GuardedBy("mLock") saveUserInternalLocked(@serIdInt int userId, OutputStream os, boolean forBackup)993 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os, 994 boolean forBackup) throws IOException, XmlPullParserException { 995 996 final BufferedOutputStream bos = new BufferedOutputStream(os); 997 998 // Write to XML 999 XmlSerializer out = new FastXmlSerializer(); 1000 out.setOutput(bos, StandardCharsets.UTF_8.name()); 1001 out.startDocument(null, true); 1002 1003 getUserShortcutsLocked(userId).saveToXml(out, forBackup); 1004 1005 out.endDocument(); 1006 1007 bos.flush(); 1008 os.flush(); 1009 } 1010 throwForInvalidTag(int depth, String tag)1011 static IOException throwForInvalidTag(int depth, String tag) throws IOException { 1012 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth)); 1013 } 1014 warnForInvalidTag(int depth, String tag)1015 static void warnForInvalidTag(int depth, String tag) throws IOException { 1016 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth)); 1017 } 1018 1019 @Nullable loadUserLocked(@serIdInt int userId)1020 private ShortcutUser loadUserLocked(@UserIdInt int userId) { 1021 final File path = getUserFile(userId); 1022 if (DEBUG) { 1023 Slog.d(TAG, "Loading from " + path); 1024 } 1025 final AtomicFile file = new AtomicFile(path); 1026 1027 final FileInputStream in; 1028 try { 1029 in = file.openRead(); 1030 } catch (FileNotFoundException e) { 1031 if (DEBUG) { 1032 Slog.d(TAG, "Not found " + path); 1033 } 1034 return null; 1035 } 1036 try { 1037 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false); 1038 return ret; 1039 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) { 1040 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e); 1041 return null; 1042 } finally { 1043 IoUtils.closeQuietly(in); 1044 } 1045 } 1046 loadUserInternal(@serIdInt int userId, InputStream is, boolean fromBackup)1047 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is, 1048 boolean fromBackup) throws XmlPullParserException, IOException, 1049 InvalidFileFormatException { 1050 1051 final BufferedInputStream bis = new BufferedInputStream(is); 1052 1053 ShortcutUser ret = null; 1054 XmlPullParser parser = Xml.newPullParser(); 1055 parser.setInput(bis, StandardCharsets.UTF_8.name()); 1056 1057 int type; 1058 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 1059 if (type != XmlPullParser.START_TAG) { 1060 continue; 1061 } 1062 final int depth = parser.getDepth(); 1063 1064 final String tag = parser.getName(); 1065 if (DEBUG_LOAD) { 1066 Slog.d(TAG, String.format("depth=%d type=%d name=%s", 1067 depth, type, tag)); 1068 } 1069 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) { 1070 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup); 1071 continue; 1072 } 1073 throwForInvalidTag(depth, tag); 1074 } 1075 return ret; 1076 } 1077 scheduleSaveBaseState()1078 private void scheduleSaveBaseState() { 1079 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state. 1080 } 1081 scheduleSaveUser(@serIdInt int userId)1082 void scheduleSaveUser(@UserIdInt int userId) { 1083 scheduleSaveInner(userId); 1084 } 1085 1086 // In order to re-schedule, we need to reuse the same instance, so keep it in final. 1087 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo; 1088 scheduleSaveInner(@serIdInt int userId)1089 private void scheduleSaveInner(@UserIdInt int userId) { 1090 if (DEBUG) { 1091 Slog.d(TAG, "Scheduling to save for " + userId); 1092 } 1093 synchronized (mLock) { 1094 if (!mDirtyUserIds.contains(userId)) { 1095 mDirtyUserIds.add(userId); 1096 } 1097 } 1098 // If already scheduled, remove that and re-schedule in N seconds. 1099 mHandler.removeCallbacks(mSaveDirtyInfoRunner); 1100 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis); 1101 } 1102 1103 @VisibleForTesting saveDirtyInfo()1104 void saveDirtyInfo() { 1105 if (DEBUG) { 1106 Slog.d(TAG, "saveDirtyInfo"); 1107 } 1108 try { 1109 synchronized (mLock) { 1110 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) { 1111 final int userId = mDirtyUserIds.get(i); 1112 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state. 1113 saveBaseStateLocked(); 1114 } else { 1115 saveUserLocked(userId); 1116 } 1117 } 1118 mDirtyUserIds.clear(); 1119 } 1120 } catch (Exception e) { 1121 wtf("Exception in saveDirtyInfo", e); 1122 } 1123 } 1124 1125 /** Return the last reset time. */ 1126 @GuardedBy("mLock") getLastResetTimeLocked()1127 long getLastResetTimeLocked() { 1128 updateTimesLocked(); 1129 return mRawLastResetTime; 1130 } 1131 1132 /** Return the next reset time. */ 1133 @GuardedBy("mLock") getNextResetTimeLocked()1134 long getNextResetTimeLocked() { 1135 updateTimesLocked(); 1136 return mRawLastResetTime + mResetInterval; 1137 } 1138 isClockValid(long time)1139 static boolean isClockValid(long time) { 1140 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT 1141 } 1142 1143 /** 1144 * Update the last reset time. 1145 */ 1146 @GuardedBy("mLock") updateTimesLocked()1147 private void updateTimesLocked() { 1148 1149 final long now = injectCurrentTimeMillis(); 1150 1151 final long prevLastResetTime = mRawLastResetTime; 1152 1153 if (mRawLastResetTime == 0) { // first launch. 1154 // TODO Randomize?? 1155 mRawLastResetTime = now; 1156 } else if (now < mRawLastResetTime) { 1157 // Clock rewound. 1158 if (isClockValid(now)) { 1159 Slog.w(TAG, "Clock rewound"); 1160 // TODO Randomize?? 1161 mRawLastResetTime = now; 1162 } 1163 } else { 1164 if ((mRawLastResetTime + mResetInterval) <= now) { 1165 final long offset = mRawLastResetTime % mResetInterval; 1166 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset; 1167 } 1168 } 1169 if (prevLastResetTime != mRawLastResetTime) { 1170 scheduleSaveBaseState(); 1171 } 1172 } 1173 1174 // Requires mLock held, but "Locked" prefix would look weired so we just say "L". isUserUnlockedL(@serIdInt int userId)1175 protected boolean isUserUnlockedL(@UserIdInt int userId) { 1176 // First, check the local copy. 1177 synchronized (mUnlockedUsers) { 1178 if (mUnlockedUsers.get(userId)) { 1179 return true; 1180 } 1181 } 1182 1183 // If the local copy says the user is locked, check with AM for the actual state, since 1184 // the user might just have been unlocked. 1185 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false 1186 // when the user is STOPPING, which we still want to consider as "unlocked". 1187 return mUserManagerInternal.isUserUnlockingOrUnlocked(userId); 1188 } 1189 1190 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L". throwIfUserLockedL(@serIdInt int userId)1191 void throwIfUserLockedL(@UserIdInt int userId) { 1192 if (!isUserUnlockedL(userId)) { 1193 throw new IllegalStateException("User " + userId + " is locked or not running"); 1194 } 1195 } 1196 1197 @GuardedBy("mLock") 1198 @NonNull isUserLoadedLocked(@serIdInt int userId)1199 private boolean isUserLoadedLocked(@UserIdInt int userId) { 1200 return mUsers.get(userId) != null; 1201 } 1202 1203 /** Return the per-user state. */ 1204 @GuardedBy("mLock") 1205 @NonNull getUserShortcutsLocked(@serIdInt int userId)1206 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) { 1207 if (!isUserUnlockedL(userId)) { 1208 wtf("User still locked"); 1209 } 1210 1211 ShortcutUser userPackages = mUsers.get(userId); 1212 if (userPackages == null) { 1213 userPackages = loadUserLocked(userId); 1214 if (userPackages == null) { 1215 userPackages = new ShortcutUser(this, userId); 1216 } 1217 mUsers.put(userId, userPackages); 1218 1219 // Also when a user's data is first accessed, scan all packages. 1220 checkPackageChanges(userId); 1221 } 1222 return userPackages; 1223 } 1224 1225 /** Return the non-persistent per-user state. */ 1226 @GuardedBy("mLock") 1227 @NonNull getNonPersistentUserLocked(@serIdInt int userId)1228 ShortcutNonPersistentUser getNonPersistentUserLocked(@UserIdInt int userId) { 1229 ShortcutNonPersistentUser ret = mShortcutNonPersistentUsers.get(userId); 1230 if (ret == null) { 1231 ret = new ShortcutNonPersistentUser(this, userId); 1232 mShortcutNonPersistentUsers.put(userId, ret); 1233 } 1234 return ret; 1235 } 1236 1237 @GuardedBy("mLock") forEachLoadedUserLocked(@onNull Consumer<ShortcutUser> c)1238 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) { 1239 for (int i = mUsers.size() - 1; i >= 0; i--) { 1240 c.accept(mUsers.valueAt(i)); 1241 } 1242 } 1243 1244 /** 1245 * Return the per-user per-package state. If the caller is a publisher, use 1246 * {@link #getPackageShortcutsForPublisherLocked} instead. 1247 */ 1248 @GuardedBy("mLock") 1249 @NonNull getPackageShortcutsLocked( @onNull String packageName, @UserIdInt int userId)1250 ShortcutPackage getPackageShortcutsLocked( 1251 @NonNull String packageName, @UserIdInt int userId) { 1252 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName); 1253 } 1254 1255 /** Return the per-user per-package state. Use this when the caller is a publisher. */ 1256 @GuardedBy("mLock") 1257 @NonNull getPackageShortcutsForPublisherLocked( @onNull String packageName, @UserIdInt int userId)1258 ShortcutPackage getPackageShortcutsForPublisherLocked( 1259 @NonNull String packageName, @UserIdInt int userId) { 1260 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName); 1261 ret.getUser().onCalledByPublisher(packageName); 1262 return ret; 1263 } 1264 1265 @GuardedBy("mLock") 1266 @NonNull getLauncherShortcutsLocked( @onNull String packageName, @UserIdInt int ownerUserId, @UserIdInt int launcherUserId)1267 ShortcutLauncher getLauncherShortcutsLocked( 1268 @NonNull String packageName, @UserIdInt int ownerUserId, 1269 @UserIdInt int launcherUserId) { 1270 return getUserShortcutsLocked(ownerUserId) 1271 .getLauncherShortcuts(packageName, launcherUserId); 1272 } 1273 1274 // === Caller validation === 1275 removeIconLocked(ShortcutInfo shortcut)1276 void removeIconLocked(ShortcutInfo shortcut) { 1277 mShortcutBitmapSaver.removeIcon(shortcut); 1278 } 1279 cleanupBitmapsForPackage(@serIdInt int userId, String packageName)1280 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) { 1281 final File packagePath = new File(getUserBitmapFilePath(userId), packageName); 1282 if (!packagePath.isDirectory()) { 1283 return; 1284 } 1285 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) { 1286 Slog.w(TAG, "Unable to remove directory " + packagePath); 1287 } 1288 } 1289 1290 /** 1291 * Remove dangling bitmap files for a user. 1292 * 1293 * Note this method must be called with the lock held after calling 1294 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap 1295 * saves are going on. 1296 */ 1297 @GuardedBy("mLock") cleanupDanglingBitmapDirectoriesLocked(@serIdInt int userId)1298 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) { 1299 if (DEBUG) { 1300 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId); 1301 } 1302 final long start = getStatStartTime(); 1303 1304 final ShortcutUser user = getUserShortcutsLocked(userId); 1305 1306 final File bitmapDir = getUserBitmapFilePath(userId); 1307 final File[] children = bitmapDir.listFiles(); 1308 if (children == null) { 1309 return; 1310 } 1311 for (File child : children) { 1312 if (!child.isDirectory()) { 1313 continue; 1314 } 1315 final String packageName = child.getName(); 1316 if (DEBUG) { 1317 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName); 1318 } 1319 if (!user.hasPackage(packageName)) { 1320 if (DEBUG) { 1321 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName); 1322 } 1323 cleanupBitmapsForPackage(userId, packageName); 1324 } else { 1325 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child); 1326 } 1327 } 1328 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start); 1329 } 1330 1331 /** 1332 * Remove dangling bitmap files for a package. 1333 * 1334 * Note this method must be called with the lock held after calling 1335 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap 1336 * saves are going on. 1337 */ cleanupDanglingBitmapFilesLocked(@serIdInt int userId, @NonNull ShortcutUser user, @NonNull String packageName, @NonNull File path)1338 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user, 1339 @NonNull String packageName, @NonNull File path) { 1340 final ArraySet<String> usedFiles = 1341 user.getPackageShortcuts(packageName).getUsedBitmapFiles(); 1342 1343 for (File child : path.listFiles()) { 1344 if (!child.isFile()) { 1345 continue; 1346 } 1347 final String name = child.getName(); 1348 if (!usedFiles.contains(name)) { 1349 if (DEBUG) { 1350 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath()); 1351 } 1352 child.delete(); 1353 } 1354 } 1355 } 1356 1357 @VisibleForTesting 1358 static class FileOutputStreamWithPath extends FileOutputStream { 1359 private final File mFile; 1360 FileOutputStreamWithPath(File file)1361 public FileOutputStreamWithPath(File file) throws FileNotFoundException { 1362 super(file); 1363 mFile = file; 1364 } 1365 getFile()1366 public File getFile() { 1367 return mFile; 1368 } 1369 } 1370 1371 /** 1372 * Build the cached bitmap filename for a shortcut icon. 1373 * 1374 * The filename will be based on the ID, except certain characters will be escaped. 1375 */ openIconFileForWrite(@serIdInt int userId, ShortcutInfo shortcut)1376 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut) 1377 throws IOException { 1378 final File packagePath = new File(getUserBitmapFilePath(userId), 1379 shortcut.getPackage()); 1380 if (!packagePath.isDirectory()) { 1381 packagePath.mkdirs(); 1382 if (!packagePath.isDirectory()) { 1383 throw new IOException("Unable to create directory " + packagePath); 1384 } 1385 SELinux.restorecon(packagePath); 1386 } 1387 1388 final String baseName = String.valueOf(injectCurrentTimeMillis()); 1389 for (int suffix = 0; ; suffix++) { 1390 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png"; 1391 final File file = new File(packagePath, filename); 1392 if (!file.exists()) { 1393 if (DEBUG) { 1394 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath()); 1395 } 1396 return new FileOutputStreamWithPath(file); 1397 } 1398 } 1399 } 1400 saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut)1401 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) { 1402 if (shortcut.hasIconFile() || shortcut.hasIconResource()) { 1403 return; 1404 } 1405 1406 final long token = injectClearCallingIdentity(); 1407 try { 1408 // Clear icon info on the shortcut. 1409 removeIconLocked(shortcut); 1410 1411 final Icon icon = shortcut.getIcon(); 1412 if (icon == null) { 1413 return; // has no icon 1414 } 1415 int maxIconDimension = mMaxIconDimension; 1416 Bitmap bitmap; 1417 try { 1418 switch (icon.getType()) { 1419 case Icon.TYPE_RESOURCE: { 1420 injectValidateIconResPackage(shortcut, icon); 1421 1422 shortcut.setIconResourceId(icon.getResId()); 1423 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES); 1424 return; 1425 } 1426 case Icon.TYPE_BITMAP: 1427 bitmap = icon.getBitmap(); // Don't recycle in this case. 1428 break; 1429 case Icon.TYPE_ADAPTIVE_BITMAP: { 1430 bitmap = icon.getBitmap(); // Don't recycle in this case. 1431 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction()); 1432 break; 1433 } 1434 default: 1435 // This shouldn't happen because we've already validated the icon, but 1436 // just in case. 1437 throw ShortcutInfo.getInvalidIconException(); 1438 } 1439 mShortcutBitmapSaver.saveBitmapLocked(shortcut, 1440 maxIconDimension, mIconPersistFormat, mIconPersistQuality); 1441 } finally { 1442 // Once saved, we won't use the original icon information, so null it out. 1443 shortcut.clearIcon(); 1444 } 1445 } finally { 1446 injectRestoreCallingIdentity(token); 1447 } 1448 } 1449 1450 // Unfortunately we can't do this check in unit tests because we fake creator package names, 1451 // so override in unit tests. 1452 // TODO CTS this case. injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon)1453 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) { 1454 if (!shortcut.getPackage().equals(icon.getResPackage())) { 1455 throw new IllegalArgumentException( 1456 "Icon resource must reside in shortcut owner package"); 1457 } 1458 } 1459 shrinkBitmap(Bitmap in, int maxSize)1460 static Bitmap shrinkBitmap(Bitmap in, int maxSize) { 1461 // Original width/height. 1462 final int ow = in.getWidth(); 1463 final int oh = in.getHeight(); 1464 if ((ow <= maxSize) && (oh <= maxSize)) { 1465 if (DEBUG) { 1466 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh)); 1467 } 1468 return in; 1469 } 1470 final int longerDimension = Math.max(ow, oh); 1471 1472 // New width and height. 1473 final int nw = ow * maxSize / longerDimension; 1474 final int nh = oh * maxSize / longerDimension; 1475 if (DEBUG) { 1476 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d", 1477 ow, oh, nw, nh)); 1478 } 1479 1480 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888); 1481 final Canvas c = new Canvas(scaledBitmap); 1482 1483 final RectF dst = new RectF(0, 0, nw, nh); 1484 1485 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null); 1486 1487 return scaledBitmap; 1488 } 1489 1490 /** 1491 * For a shortcut, update all resource names from resource IDs, and also update all 1492 * resource-based strings. 1493 */ fixUpShortcutResourceNamesAndValues(ShortcutInfo si)1494 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) { 1495 final Resources publisherRes = injectGetResourcesForApplicationAsUser( 1496 si.getPackage(), si.getUserId()); 1497 if (publisherRes != null) { 1498 final long start = getStatStartTime(); 1499 try { 1500 si.lookupAndFillInResourceNames(publisherRes); 1501 } finally { 1502 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start); 1503 } 1504 si.resolveResourceStrings(publisherRes); 1505 } 1506 } 1507 1508 // === Caller validation === 1509 isCallerSystem()1510 private boolean isCallerSystem() { 1511 final int callingUid = injectBinderCallingUid(); 1512 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID); 1513 } 1514 isCallerShell()1515 private boolean isCallerShell() { 1516 final int callingUid = injectBinderCallingUid(); 1517 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 1518 } 1519 enforceSystemOrShell()1520 private void enforceSystemOrShell() { 1521 if (!(isCallerSystem() || isCallerShell())) { 1522 throw new SecurityException("Caller must be system or shell"); 1523 } 1524 } 1525 enforceShell()1526 private void enforceShell() { 1527 if (!isCallerShell()) { 1528 throw new SecurityException("Caller must be shell"); 1529 } 1530 } 1531 enforceSystem()1532 private void enforceSystem() { 1533 if (!isCallerSystem()) { 1534 throw new SecurityException("Caller must be system"); 1535 } 1536 } 1537 enforceResetThrottlingPermission()1538 private void enforceResetThrottlingPermission() { 1539 if (isCallerSystem()) { 1540 return; 1541 } 1542 enforceCallingOrSelfPermission( 1543 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null); 1544 } 1545 enforceCallingOrSelfPermission( @onNull String permission, @Nullable String message)1546 private void enforceCallingOrSelfPermission( 1547 @NonNull String permission, @Nullable String message) { 1548 if (isCallerSystem()) { 1549 return; 1550 } 1551 injectEnforceCallingPermission(permission, message); 1552 } 1553 1554 /** 1555 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse 1556 * mockito. So instead we extracted it here and override it in the tests. 1557 */ 1558 @VisibleForTesting injectEnforceCallingPermission( @onNull String permission, @Nullable String message)1559 void injectEnforceCallingPermission( 1560 @NonNull String permission, @Nullable String message) { 1561 mContext.enforceCallingPermission(permission, message); 1562 } 1563 verifyCaller(@onNull String packageName, @UserIdInt int userId)1564 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) { 1565 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1566 1567 if (isCallerSystem()) { 1568 return; // no check 1569 } 1570 1571 final int callingUid = injectBinderCallingUid(); 1572 1573 // Otherwise, make sure the arguments are valid. 1574 if (UserHandle.getUserId(callingUid) != userId) { 1575 throw new SecurityException("Invalid user-ID"); 1576 } 1577 if (injectGetPackageUid(packageName, userId) != callingUid) { 1578 throw new SecurityException("Calling package name mismatch"); 1579 } 1580 Preconditions.checkState(!isEphemeralApp(packageName, userId), 1581 "Ephemeral apps can't use ShortcutManager"); 1582 } 1583 verifyShortcutInfoPackage(String callerPackage, ShortcutInfo si)1584 private void verifyShortcutInfoPackage(String callerPackage, ShortcutInfo si) { 1585 if (si == null) { 1586 return; 1587 } 1588 if (!Objects.equals(callerPackage, si.getPackage())) { 1589 android.util.EventLog.writeEvent(0x534e4554, "109824443", -1, ""); 1590 throw new SecurityException("Shortcut package name mismatch"); 1591 } 1592 } 1593 verifyShortcutInfoPackages( String callerPackage, List<ShortcutInfo> list)1594 private void verifyShortcutInfoPackages( 1595 String callerPackage, List<ShortcutInfo> list) { 1596 final int size = list.size(); 1597 for (int i = 0; i < size; i++) { 1598 verifyShortcutInfoPackage(callerPackage, list.get(i)); 1599 } 1600 } 1601 1602 // Overridden in unit tests to execute r synchronously. injectPostToHandler(Runnable r)1603 void injectPostToHandler(Runnable r) { 1604 mHandler.post(r); 1605 } 1606 injectRunOnNewThread(Runnable r)1607 void injectRunOnNewThread(Runnable r) { 1608 new Thread(r).start(); 1609 } 1610 1611 /** 1612 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than 1613 * {@link #getMaxActivityShortcuts()}. 1614 */ enforceMaxActivityShortcuts(int numShortcuts)1615 void enforceMaxActivityShortcuts(int numShortcuts) { 1616 if (numShortcuts > mMaxShortcuts) { 1617 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded"); 1618 } 1619 } 1620 1621 /** 1622 * Return the max number of dynamic + manifest shortcuts for each launcher icon. 1623 */ getMaxActivityShortcuts()1624 int getMaxActivityShortcuts() { 1625 return mMaxShortcuts; 1626 } 1627 1628 /** 1629 * - Sends a notification to LauncherApps 1630 * - Write to file 1631 */ packageShortcutsChanged(@onNull String packageName, @UserIdInt int userId)1632 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) { 1633 notifyListeners(packageName, userId); 1634 scheduleSaveUser(userId); 1635 } 1636 notifyListeners(@onNull String packageName, @UserIdInt int userId)1637 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) { 1638 if (DEBUG) { 1639 Slog.d(TAG, String.format( 1640 "Shortcut changes: package=%s, user=%d", packageName, userId)); 1641 } 1642 injectPostToHandler(() -> { 1643 try { 1644 final ArrayList<ShortcutChangeListener> copy; 1645 synchronized (mLock) { 1646 if (!isUserUnlockedL(userId)) { 1647 return; 1648 } 1649 1650 copy = new ArrayList<>(mListeners); 1651 } 1652 // Note onShortcutChanged() needs to be called with the system service permissions. 1653 for (int i = copy.size() - 1; i >= 0; i--) { 1654 copy.get(i).onShortcutChanged(packageName, userId); 1655 } 1656 } catch (Exception ignore) { 1657 } 1658 }); 1659 } 1660 1661 /** 1662 * Clean up / validate an incoming shortcut. 1663 * - Make sure all mandatory fields are set. 1664 * - Make sure the intent's extras are persistable, and them to set 1665 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras. 1666 * - Clear flags. 1667 */ fixUpIncomingShortcutInfo(@onNull ShortcutInfo shortcut, boolean forUpdate, boolean forPinRequest)1668 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate, 1669 boolean forPinRequest) { 1670 if (shortcut.isReturnedByServer()) { 1671 Log.w(TAG, 1672 "Re-publishing ShortcutInfo returned by server is not supported." 1673 + " Some information such as icon may lost from shortcut."); 1674 } 1675 Preconditions.checkNotNull(shortcut, "Null shortcut detected"); 1676 if (shortcut.getActivity() != null) { 1677 Preconditions.checkState( 1678 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()), 1679 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not" 1680 + " belong to package " + shortcut.getPackage()); 1681 Preconditions.checkState( 1682 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()), 1683 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not" 1684 + " main activity"); 1685 } 1686 1687 if (!forUpdate) { 1688 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest); 1689 if (!forPinRequest) { 1690 Preconditions.checkState(shortcut.getActivity() != null, 1691 "Cannot publish shortcut: target activity is not set"); 1692 } 1693 } 1694 if (shortcut.getIcon() != null) { 1695 ShortcutInfo.validateIcon(shortcut.getIcon()); 1696 } 1697 1698 shortcut.replaceFlags(0); 1699 } 1700 fixUpIncomingShortcutInfo(@onNull ShortcutInfo shortcut, boolean forUpdate)1701 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) { 1702 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false); 1703 } 1704 validateShortcutForPinRequest(@onNull ShortcutInfo shortcut)1705 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) { 1706 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true); 1707 } 1708 1709 /** 1710 * When a shortcut has no target activity, set the default one from the package. 1711 */ fillInDefaultActivity(List<ShortcutInfo> shortcuts)1712 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) { 1713 ComponentName defaultActivity = null; 1714 for (int i = shortcuts.size() - 1; i >= 0; i--) { 1715 final ShortcutInfo si = shortcuts.get(i); 1716 if (si.getActivity() == null) { 1717 if (defaultActivity == null) { 1718 defaultActivity = injectGetDefaultMainActivity( 1719 si.getPackage(), si.getUserId()); 1720 Preconditions.checkState(defaultActivity != null, 1721 "Launcher activity not found for package " + si.getPackage()); 1722 } 1723 si.setActivity(defaultActivity); 1724 } 1725 } 1726 } 1727 assignImplicitRanks(List<ShortcutInfo> shortcuts)1728 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) { 1729 for (int i = shortcuts.size() - 1; i >= 0; i--) { 1730 shortcuts.get(i).setImplicitRank(i); 1731 } 1732 } 1733 setReturnedByServer(List<ShortcutInfo> shortcuts)1734 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) { 1735 for (int i = shortcuts.size() - 1; i >= 0; i--) { 1736 shortcuts.get(i).setReturnedByServer(); 1737 } 1738 return shortcuts; 1739 } 1740 1741 // === APIs === 1742 1743 @Override setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, @UserIdInt int userId)1744 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1745 @UserIdInt int userId) { 1746 verifyCaller(packageName, userId); 1747 1748 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1749 verifyShortcutInfoPackages(packageName, newShortcuts); 1750 final int size = newShortcuts.size(); 1751 1752 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission( 1753 injectBinderCallingPid(), injectBinderCallingUid()); 1754 1755 synchronized (mLock) { 1756 throwIfUserLockedL(userId); 1757 1758 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1759 1760 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true); 1761 1762 fillInDefaultActivity(newShortcuts); 1763 1764 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET); 1765 1766 // Throttling. 1767 if (!ps.tryApiCall(unlimited)) { 1768 return false; 1769 } 1770 1771 // Initialize the implicit ranks for ShortcutPackage.adjustRanks(). 1772 ps.clearAllImplicitRanks(); 1773 assignImplicitRanks(newShortcuts); 1774 1775 for (int i = 0; i < size; i++) { 1776 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false); 1777 } 1778 1779 // First, remove all un-pinned; dynamic shortcuts 1780 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true); 1781 1782 // Then, add/update all. We need to make sure to take over "pinned" flag. 1783 for (int i = 0; i < size; i++) { 1784 final ShortcutInfo newShortcut = newShortcuts.get(i); 1785 ps.addOrReplaceDynamicShortcut(newShortcut); 1786 } 1787 1788 // Lastly, adjust the ranks. 1789 ps.adjustRanks(); 1790 } 1791 packageShortcutsChanged(packageName, userId); 1792 1793 verifyStates(); 1794 1795 return true; 1796 } 1797 1798 @Override updateShortcuts(String packageName, ParceledListSlice shortcutInfoList, @UserIdInt int userId)1799 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1800 @UserIdInt int userId) { 1801 verifyCaller(packageName, userId); 1802 1803 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1804 verifyShortcutInfoPackages(packageName, newShortcuts); 1805 final int size = newShortcuts.size(); 1806 1807 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission( 1808 injectBinderCallingPid(), injectBinderCallingUid()); 1809 1810 synchronized (mLock) { 1811 throwIfUserLockedL(userId); 1812 1813 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1814 1815 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true); 1816 1817 // For update, don't fill in the default activity. Having null activity means 1818 // "don't update the activity" here. 1819 1820 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE); 1821 1822 // Throttling. 1823 if (!ps.tryApiCall(unlimited)) { 1824 return false; 1825 } 1826 1827 // Initialize the implicit ranks for ShortcutPackage.adjustRanks(). 1828 ps.clearAllImplicitRanks(); 1829 assignImplicitRanks(newShortcuts); 1830 1831 for (int i = 0; i < size; i++) { 1832 final ShortcutInfo source = newShortcuts.get(i); 1833 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true); 1834 1835 final ShortcutInfo target = ps.findShortcutById(source.getId()); 1836 1837 // Invisible shortcuts can't be updated. 1838 if (target == null || !target.isVisibleToPublisher()) { 1839 continue; 1840 } 1841 1842 if (target.isEnabled() != source.isEnabled()) { 1843 Slog.w(TAG, 1844 "ShortcutInfo.enabled cannot be changed with updateShortcuts()"); 1845 } 1846 1847 // When updating the rank, we need to insert between existing ranks, so set 1848 // this setRankChanged, and also copy the implicit rank fo adjustRanks(). 1849 if (source.hasRank()) { 1850 target.setRankChanged(); 1851 target.setImplicitRank(source.getImplicitRank()); 1852 } 1853 1854 final boolean replacingIcon = (source.getIcon() != null); 1855 if (replacingIcon) { 1856 removeIconLocked(target); 1857 } 1858 1859 // Note copyNonNullFieldsFrom() does the "updatable with?" check too. 1860 target.copyNonNullFieldsFrom(source); 1861 target.setTimestamp(injectCurrentTimeMillis()); 1862 1863 if (replacingIcon) { 1864 saveIconAndFixUpShortcutLocked(target); 1865 } 1866 1867 // When we're updating any resource related fields, re-extract the res names and 1868 // the values. 1869 if (replacingIcon || source.hasStringResources()) { 1870 fixUpShortcutResourceNamesAndValues(target); 1871 } 1872 } 1873 1874 // Lastly, adjust the ranks. 1875 ps.adjustRanks(); 1876 } 1877 packageShortcutsChanged(packageName, userId); 1878 1879 verifyStates(); 1880 1881 return true; 1882 } 1883 1884 @Override addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, @UserIdInt int userId)1885 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1886 @UserIdInt int userId) { 1887 verifyCaller(packageName, userId); 1888 1889 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1890 verifyShortcutInfoPackages(packageName, newShortcuts); 1891 final int size = newShortcuts.size(); 1892 1893 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission( 1894 injectBinderCallingPid(), injectBinderCallingUid()); 1895 1896 synchronized (mLock) { 1897 throwIfUserLockedL(userId); 1898 1899 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1900 1901 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true); 1902 1903 fillInDefaultActivity(newShortcuts); 1904 1905 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD); 1906 1907 // Initialize the implicit ranks for ShortcutPackage.adjustRanks(). 1908 ps.clearAllImplicitRanks(); 1909 assignImplicitRanks(newShortcuts); 1910 1911 // Throttling. 1912 if (!ps.tryApiCall(unlimited)) { 1913 return false; 1914 } 1915 for (int i = 0; i < size; i++) { 1916 final ShortcutInfo newShortcut = newShortcuts.get(i); 1917 1918 // Validate the shortcut. 1919 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false); 1920 1921 // When ranks are changing, we need to insert between ranks, so set the 1922 // "rank changed" flag. 1923 newShortcut.setRankChanged(); 1924 1925 // Add it. 1926 ps.addOrReplaceDynamicShortcut(newShortcut); 1927 } 1928 1929 // Lastly, adjust the ranks. 1930 ps.adjustRanks(); 1931 } 1932 packageShortcutsChanged(packageName, userId); 1933 1934 verifyStates(); 1935 1936 return true; 1937 } 1938 1939 @Override requestPinShortcut(String packageName, ShortcutInfo shortcut, IntentSender resultIntent, int userId)1940 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut, 1941 IntentSender resultIntent, int userId) { 1942 Preconditions.checkNotNull(shortcut); 1943 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled"); 1944 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent); 1945 } 1946 1947 @Override createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)1948 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId) 1949 throws RemoteException { 1950 Preconditions.checkNotNull(shortcut); 1951 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled"); 1952 verifyCaller(packageName, userId); 1953 verifyShortcutInfoPackage(packageName, shortcut); 1954 1955 final Intent ret; 1956 synchronized (mLock) { 1957 throwIfUserLockedL(userId); 1958 1959 // Send request to the launcher, if supported. 1960 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId); 1961 } 1962 1963 verifyStates(); 1964 return ret; 1965 } 1966 1967 /** 1968 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}. 1969 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}. 1970 * Either {@param shortcut} or {@param appWidget} should be non-null. 1971 */ requestPinItem(String packageName, int userId, ShortcutInfo shortcut, AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent)1972 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut, 1973 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) { 1974 verifyCaller(packageName, userId); 1975 verifyShortcutInfoPackage(packageName, shortcut); 1976 1977 final boolean ret; 1978 synchronized (mLock) { 1979 throwIfUserLockedL(userId); 1980 1981 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()), 1982 "Calling application must have a foreground activity or a foreground service"); 1983 1984 // If it's a pin shortcut request, and there's already a shortcut with the same ID 1985 // that's not visible to the caller (i.e. restore-blocked; meaning it's pinned by 1986 // someone already), then we just replace the existing one with this new one, 1987 // and then proceed the rest of the process. 1988 if (shortcut != null) { 1989 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked( 1990 packageName, userId); 1991 final String id = shortcut.getId(); 1992 if (ps.isShortcutExistsAndInvisibleToPublisher(id)) { 1993 1994 ps.updateInvisibleShortcutForPinRequestWith(shortcut); 1995 1996 packageShortcutsChanged(packageName, userId); 1997 } 1998 } 1999 2000 // Send request to the launcher, if supported. 2001 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras, 2002 userId, resultIntent); 2003 } 2004 2005 verifyStates(); 2006 2007 return ret; 2008 } 2009 2010 @Override disableShortcuts(String packageName, List shortcutIds, CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId)2011 public void disableShortcuts(String packageName, List shortcutIds, 2012 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) { 2013 verifyCaller(packageName, userId); 2014 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided"); 2015 2016 synchronized (mLock) { 2017 throwIfUserLockedL(userId); 2018 2019 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2020 2021 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds, 2022 /*ignoreInvisible=*/ true); 2023 2024 final String disabledMessageString = 2025 (disabledMessage == null) ? null : disabledMessage.toString(); 2026 2027 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 2028 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)); 2029 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) { 2030 continue; 2031 } 2032 ps.disableWithId(id, 2033 disabledMessageString, disabledMessageResId, 2034 /* overrideImmutable=*/ false, /*ignoreInvisible=*/ true, 2035 ShortcutInfo.DISABLED_REASON_BY_APP); 2036 } 2037 2038 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks. 2039 ps.adjustRanks(); 2040 } 2041 packageShortcutsChanged(packageName, userId); 2042 2043 verifyStates(); 2044 } 2045 2046 @Override enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId)2047 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) { 2048 verifyCaller(packageName, userId); 2049 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided"); 2050 2051 synchronized (mLock) { 2052 throwIfUserLockedL(userId); 2053 2054 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2055 2056 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds, 2057 /*ignoreInvisible=*/ true); 2058 2059 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 2060 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)); 2061 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) { 2062 continue; 2063 } 2064 ps.enableWithId(id); 2065 } 2066 } 2067 packageShortcutsChanged(packageName, userId); 2068 2069 verifyStates(); 2070 } 2071 2072 @Override removeDynamicShortcuts(String packageName, List shortcutIds, @UserIdInt int userId)2073 public void removeDynamicShortcuts(String packageName, List shortcutIds, 2074 @UserIdInt int userId) { 2075 verifyCaller(packageName, userId); 2076 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided"); 2077 2078 synchronized (mLock) { 2079 throwIfUserLockedL(userId); 2080 2081 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2082 2083 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds, 2084 /*ignoreInvisible=*/ true); 2085 2086 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 2087 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)); 2088 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) { 2089 continue; 2090 } 2091 ps.deleteDynamicWithId(id, /*ignoreInvisible=*/ true); 2092 } 2093 2094 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks. 2095 ps.adjustRanks(); 2096 } 2097 packageShortcutsChanged(packageName, userId); 2098 2099 verifyStates(); 2100 } 2101 2102 @Override removeAllDynamicShortcuts(String packageName, @UserIdInt int userId)2103 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) { 2104 verifyCaller(packageName, userId); 2105 2106 synchronized (mLock) { 2107 throwIfUserLockedL(userId); 2108 2109 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2110 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true); 2111 } 2112 packageShortcutsChanged(packageName, userId); 2113 2114 verifyStates(); 2115 } 2116 2117 @Override getDynamicShortcuts(String packageName, @UserIdInt int userId)2118 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName, 2119 @UserIdInt int userId) { 2120 verifyCaller(packageName, userId); 2121 2122 synchronized (mLock) { 2123 throwIfUserLockedL(userId); 2124 2125 return getShortcutsWithQueryLocked( 2126 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 2127 ShortcutInfo::isDynamicVisible); 2128 } 2129 } 2130 2131 @Override getManifestShortcuts(String packageName, @UserIdInt int userId)2132 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName, 2133 @UserIdInt int userId) { 2134 verifyCaller(packageName, userId); 2135 2136 synchronized (mLock) { 2137 throwIfUserLockedL(userId); 2138 2139 return getShortcutsWithQueryLocked( 2140 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 2141 ShortcutInfo::isManifestVisible); 2142 } 2143 } 2144 2145 @Override getPinnedShortcuts(String packageName, @UserIdInt int userId)2146 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName, 2147 @UserIdInt int userId) { 2148 verifyCaller(packageName, userId); 2149 2150 synchronized (mLock) { 2151 throwIfUserLockedL(userId); 2152 2153 return getShortcutsWithQueryLocked( 2154 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 2155 ShortcutInfo::isPinnedVisible); 2156 } 2157 } 2158 2159 @Override getShareTargets(String packageName, IntentFilter filter, @UserIdInt int userId)2160 public ParceledListSlice<ShortcutManager.ShareShortcutInfo> getShareTargets(String packageName, 2161 IntentFilter filter, @UserIdInt int userId) { 2162 verifyCaller(packageName, userId); 2163 enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APP_PREDICTIONS, 2164 "getShareTargets"); 2165 2166 synchronized (mLock) { 2167 throwIfUserLockedL(userId); 2168 2169 final List<ShortcutManager.ShareShortcutInfo> shortcutInfoList = new ArrayList<>(); 2170 2171 final ShortcutUser user = getUserShortcutsLocked(userId); 2172 user.forAllPackages(p -> shortcutInfoList.addAll(p.getMatchingShareTargets(filter))); 2173 2174 return new ParceledListSlice<>(shortcutInfoList); 2175 } 2176 } 2177 2178 @Override hasShareTargets(String packageName, String packageToCheck, @UserIdInt int userId)2179 public boolean hasShareTargets(String packageName, String packageToCheck, 2180 @UserIdInt int userId) { 2181 verifyCaller(packageName, userId); 2182 enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APP_PREDICTIONS, 2183 "hasShareTargets"); 2184 2185 synchronized (mLock) { 2186 throwIfUserLockedL(userId); 2187 2188 return getPackageShortcutsLocked(packageToCheck, userId).hasShareTargets(); 2189 } 2190 } 2191 2192 @GuardedBy("mLock") getShortcutsWithQueryLocked(@onNull String packageName, @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query)2193 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName, 2194 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) { 2195 2196 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 2197 2198 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2199 ps.findAll(ret, query, cloneFlags); 2200 2201 return new ParceledListSlice<>(setReturnedByServer(ret)); 2202 } 2203 2204 @Override getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)2205 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId) 2206 throws RemoteException { 2207 verifyCaller(packageName, userId); 2208 2209 return mMaxShortcuts; 2210 } 2211 2212 @Override getRemainingCallCount(String packageName, @UserIdInt int userId)2213 public int getRemainingCallCount(String packageName, @UserIdInt int userId) { 2214 verifyCaller(packageName, userId); 2215 2216 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission( 2217 injectBinderCallingPid(), injectBinderCallingUid()); 2218 2219 synchronized (mLock) { 2220 throwIfUserLockedL(userId); 2221 2222 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2223 return mMaxUpdatesPerInterval - ps.getApiCallCount(unlimited); 2224 } 2225 } 2226 2227 @Override getRateLimitResetTime(String packageName, @UserIdInt int userId)2228 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) { 2229 verifyCaller(packageName, userId); 2230 2231 synchronized (mLock) { 2232 throwIfUserLockedL(userId); 2233 2234 return getNextResetTimeLocked(); 2235 } 2236 } 2237 2238 @Override getIconMaxDimensions(String packageName, int userId)2239 public int getIconMaxDimensions(String packageName, int userId) { 2240 verifyCaller(packageName, userId); 2241 2242 synchronized (mLock) { 2243 return mMaxIconDimension; 2244 } 2245 } 2246 2247 @Override reportShortcutUsed(String packageName, String shortcutId, int userId)2248 public void reportShortcutUsed(String packageName, String shortcutId, int userId) { 2249 verifyCaller(packageName, userId); 2250 2251 Preconditions.checkNotNull(shortcutId); 2252 2253 if (DEBUG) { 2254 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d", 2255 shortcutId, packageName, userId)); 2256 } 2257 2258 synchronized (mLock) { 2259 throwIfUserLockedL(userId); 2260 2261 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2262 2263 if (ps.findShortcutById(shortcutId) == null) { 2264 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s", 2265 packageName, shortcutId)); 2266 return; 2267 } 2268 } 2269 2270 final long token = injectClearCallingIdentity(); 2271 try { 2272 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId); 2273 } finally { 2274 injectRestoreCallingIdentity(token); 2275 } 2276 } 2277 2278 @Override isRequestPinItemSupported(int callingUserId, int requestType)2279 public boolean isRequestPinItemSupported(int callingUserId, int requestType) { 2280 final long token = injectClearCallingIdentity(); 2281 try { 2282 return mShortcutRequestPinProcessor 2283 .isRequestPinItemSupported(callingUserId, requestType); 2284 } finally { 2285 injectRestoreCallingIdentity(token); 2286 } 2287 } 2288 2289 /** 2290 * Reset all throttling, for developer options and command line. Only system/shell can call 2291 * it. 2292 */ 2293 @Override resetThrottling()2294 public void resetThrottling() { 2295 enforceSystemOrShell(); 2296 2297 resetThrottlingInner(getCallingUserId()); 2298 } 2299 resetThrottlingInner(@serIdInt int userId)2300 void resetThrottlingInner(@UserIdInt int userId) { 2301 synchronized (mLock) { 2302 if (!isUserUnlockedL(userId)) { 2303 Log.w(TAG, "User " + userId + " is locked or not running"); 2304 return; 2305 } 2306 2307 getUserShortcutsLocked(userId).resetThrottling(); 2308 } 2309 scheduleSaveUser(userId); 2310 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId); 2311 } 2312 resetAllThrottlingInner()2313 void resetAllThrottlingInner() { 2314 synchronized (mLock) { 2315 mRawLastResetTime = injectCurrentTimeMillis(); 2316 } 2317 scheduleSaveBaseState(); 2318 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users"); 2319 } 2320 2321 @Override onApplicationActive(String packageName, int userId)2322 public void onApplicationActive(String packageName, int userId) { 2323 if (DEBUG) { 2324 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId); 2325 } 2326 enforceResetThrottlingPermission(); 2327 2328 synchronized (mLock) { 2329 if (!isUserUnlockedL(userId)) { 2330 // This is called by system UI, so no need to throw. Just ignore. 2331 return; 2332 } 2333 2334 getPackageShortcutsLocked(packageName, userId) 2335 .resetRateLimitingForCommandLineNoSaving(); 2336 saveUserLocked(userId); 2337 } 2338 } 2339 2340 // We override this method in unit tests to do a simpler check. hasShortcutHostPermission(@onNull String callingPackage, int userId, int callingPid, int callingUid)2341 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId, 2342 int callingPid, int callingUid) { 2343 if (canSeeAnyPinnedShortcut(callingPackage, userId, callingPid, callingUid)) { 2344 return true; 2345 } 2346 final long start = getStatStartTime(); 2347 try { 2348 return hasShortcutHostPermissionInner(callingPackage, userId); 2349 } finally { 2350 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start); 2351 } 2352 } 2353 canSeeAnyPinnedShortcut(@onNull String callingPackage, int userId, int callingPid, int callingUid)2354 boolean canSeeAnyPinnedShortcut(@NonNull String callingPackage, int userId, 2355 int callingPid, int callingUid) { 2356 if (injectHasAccessShortcutsPermission(callingPid, callingUid)) { 2357 return true; 2358 } 2359 synchronized (mLock) { 2360 return getNonPersistentUserLocked(userId).hasHostPackage(callingPackage); 2361 } 2362 } 2363 2364 /** 2365 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission. 2366 */ 2367 @VisibleForTesting injectHasAccessShortcutsPermission(int callingPid, int callingUid)2368 boolean injectHasAccessShortcutsPermission(int callingPid, int callingUid) { 2369 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS, 2370 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; 2371 } 2372 2373 /** 2374 * Returns true if the caller has the "UNLIMITED_SHORTCUTS_API_CALLS" permission. 2375 */ 2376 @VisibleForTesting injectHasUnlimitedShortcutsApiCallsPermission(int callingPid, int callingUid)2377 boolean injectHasUnlimitedShortcutsApiCallsPermission(int callingPid, int callingUid) { 2378 return mContext.checkPermission(permission.UNLIMITED_SHORTCUTS_API_CALLS, 2379 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; 2380 } 2381 2382 // This method is extracted so we can directly call this method from unit tests, 2383 // even when hasShortcutPermission() is overridden. 2384 @VisibleForTesting hasShortcutHostPermissionInner(@onNull String packageName, int userId)2385 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) { 2386 synchronized (mLock) { 2387 throwIfUserLockedL(userId); 2388 2389 final ShortcutUser user = getUserShortcutsLocked(userId); 2390 2391 // Always trust the cached component. 2392 final ComponentName cached = user.getCachedLauncher(); 2393 if (cached != null) { 2394 if (cached.getPackageName().equals(packageName)) { 2395 return true; 2396 } 2397 } 2398 // If the cached one doesn't match, then go ahead 2399 2400 final ComponentName detected = getDefaultLauncher(userId); 2401 2402 // Update the cache. 2403 user.setLauncher(detected); 2404 if (detected != null) { 2405 if (DEBUG) { 2406 Slog.v(TAG, "Detected launcher: " + detected); 2407 } 2408 return detected.getPackageName().equals(packageName); 2409 } else { 2410 // Default launcher not found. 2411 return false; 2412 } 2413 } 2414 } 2415 2416 @Nullable getDefaultLauncher(@serIdInt int userId)2417 ComponentName getDefaultLauncher(@UserIdInt int userId) { 2418 final long start = getStatStartTime(); 2419 final long token = injectClearCallingIdentity(); 2420 try { 2421 synchronized (mLock) { 2422 throwIfUserLockedL(userId); 2423 2424 final ShortcutUser user = getUserShortcutsLocked(userId); 2425 2426 final List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 2427 2428 // Default launcher from package manager. 2429 final long startGetHomeActivitiesAsUser = getStatStartTime(); 2430 final ComponentName defaultLauncher = mPackageManagerInternal 2431 .getHomeActivitiesAsUser(allHomeCandidates, userId); 2432 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser); 2433 2434 ComponentName detected = null; 2435 if (defaultLauncher != null) { 2436 detected = defaultLauncher; 2437 if (DEBUG) { 2438 Slog.v(TAG, "Default launcher from PM: " + detected); 2439 } 2440 } else { 2441 detected = user.getLastKnownLauncher(); 2442 2443 if (detected != null) { 2444 if (injectIsActivityEnabledAndExported(detected, userId)) { 2445 if (DEBUG) { 2446 Slog.v(TAG, "Cached launcher: " + detected); 2447 } 2448 } else { 2449 Slog.w(TAG, "Cached launcher " + detected + " no longer exists"); 2450 detected = null; 2451 user.clearLauncher(); 2452 } 2453 } 2454 } 2455 2456 if (detected == null) { 2457 // If we reach here, that means it's the first check since the user was created, 2458 // and there's already multiple launchers and there's no default set. 2459 // Find the system one with the highest priority. 2460 // (We need to check the priority too because of FallbackHome in Settings.) 2461 // If there's no system launcher yet, then no one can access shortcuts, until 2462 // the user explicitly 2463 final int size = allHomeCandidates.size(); 2464 2465 int lastPriority = Integer.MIN_VALUE; 2466 for (int i = 0; i < size; i++) { 2467 final ResolveInfo ri = allHomeCandidates.get(i); 2468 if (!ri.activityInfo.applicationInfo.isSystemApp()) { 2469 continue; 2470 } 2471 if (DEBUG) { 2472 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d", 2473 ri.activityInfo.getComponentName(), ri.priority)); 2474 } 2475 if (ri.priority < lastPriority) { 2476 continue; 2477 } 2478 detected = ri.activityInfo.getComponentName(); 2479 lastPriority = ri.priority; 2480 } 2481 } 2482 return detected; 2483 } 2484 } finally { 2485 injectRestoreCallingIdentity(token); 2486 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start); 2487 } 2488 } 2489 setShortcutHostPackage(@onNull String type, @Nullable String packageName, int userId)2490 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName, 2491 int userId) { 2492 synchronized (mLock) { 2493 getNonPersistentUserLocked(userId).setShortcutHostPackage(type, packageName); 2494 } 2495 } 2496 2497 // === House keeping === 2498 cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId, boolean appStillExists)2499 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId, 2500 boolean appStillExists) { 2501 synchronized (mLock) { 2502 forEachLoadedUserLocked(user -> 2503 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId, 2504 appStillExists)); 2505 } 2506 } 2507 2508 /** 2509 * Remove all the information associated with a package. This will really remove all the 2510 * information, including the restore information (i.e. it'll remove packages even if they're 2511 * shadow). 2512 * 2513 * This is called when an app is uninstalled, or an app gets "clear data"ed. 2514 */ 2515 @GuardedBy("mLock") 2516 @VisibleForTesting cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId, boolean appStillExists)2517 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId, 2518 boolean appStillExists) { 2519 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId); 2520 2521 final ShortcutUser user = getUserShortcutsLocked(owningUserId); 2522 boolean doNotify = false; 2523 2524 // First, remove the package from the package list (if the package is a publisher). 2525 if (packageUserId == owningUserId) { 2526 if (user.removePackage(packageName) != null) { 2527 doNotify = true; 2528 } 2529 } 2530 2531 // Also remove from the launcher list (if the package is a launcher). 2532 user.removeLauncher(packageUserId, packageName); 2533 2534 // Then remove pinned shortcuts from all launchers. 2535 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId)); 2536 2537 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous 2538 // step. Remove them too. 2539 user.forAllPackages(p -> p.refreshPinnedFlags()); 2540 2541 scheduleSaveUser(owningUserId); 2542 2543 if (doNotify) { 2544 notifyListeners(packageName, owningUserId); 2545 } 2546 2547 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts. 2548 if (appStillExists && (packageUserId == owningUserId)) { 2549 // This will do the notification and save when needed, so do it after the above 2550 // notifyListeners. 2551 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2552 } 2553 2554 if (!wasUserLoaded) { 2555 // Note this will execute the scheduled save. 2556 unloadUserLocked(owningUserId); 2557 } 2558 } 2559 2560 /** 2561 * Entry point from {@link LauncherApps}. 2562 */ 2563 private class LocalService extends ShortcutServiceInternal { 2564 2565 @Override getShortcuts(int launcherUserId, @NonNull String callingPackage, long changedSince, @Nullable String packageName, @Nullable List<String> shortcutIds, @Nullable ComponentName componentName, int queryFlags, int userId, int callingPid, int callingUid)2566 public List<ShortcutInfo> getShortcuts(int launcherUserId, 2567 @NonNull String callingPackage, long changedSince, 2568 @Nullable String packageName, @Nullable List<String> shortcutIds, 2569 @Nullable ComponentName componentName, 2570 int queryFlags, int userId, int callingPid, int callingUid) { 2571 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 2572 2573 final boolean cloneKeyFieldOnly = 2574 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0); 2575 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO 2576 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER; 2577 if (packageName == null) { 2578 shortcutIds = null; // LauncherAppsService already threw for it though. 2579 } 2580 2581 synchronized (mLock) { 2582 throwIfUserLockedL(userId); 2583 throwIfUserLockedL(launcherUserId); 2584 2585 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2586 .attemptToRestoreIfNeededAndSave(); 2587 2588 if (packageName != null) { 2589 getShortcutsInnerLocked(launcherUserId, 2590 callingPackage, packageName, shortcutIds, changedSince, 2591 componentName, queryFlags, userId, ret, cloneFlag, 2592 callingPid, callingUid); 2593 } else { 2594 final List<String> shortcutIdsF = shortcutIds; 2595 getUserShortcutsLocked(userId).forAllPackages(p -> { 2596 getShortcutsInnerLocked(launcherUserId, 2597 callingPackage, p.getPackageName(), shortcutIdsF, changedSince, 2598 componentName, queryFlags, userId, ret, cloneFlag, 2599 callingPid, callingUid); 2600 }); 2601 } 2602 } 2603 return setReturnedByServer(ret); 2604 } 2605 2606 @GuardedBy("ShortcutService.this.mLock") getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage, @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince, @Nullable ComponentName componentName, int queryFlags, int userId, ArrayList<ShortcutInfo> ret, int cloneFlag, int callingPid, int callingUid)2607 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage, 2608 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince, 2609 @Nullable ComponentName componentName, int queryFlags, 2610 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag, 2611 int callingPid, int callingUid) { 2612 final ArraySet<String> ids = shortcutIds == null ? null 2613 : new ArraySet<>(shortcutIds); 2614 2615 final ShortcutUser user = getUserShortcutsLocked(userId); 2616 final ShortcutPackage p = user.getPackageShortcutsIfExists(packageName); 2617 if (p == null) { 2618 return; // No need to instantiate ShortcutPackage. 2619 } 2620 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0; 2621 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0; 2622 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0; 2623 2624 final boolean canAccessAllShortcuts = 2625 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, callingPid, callingUid); 2626 2627 final boolean getPinnedByAnyLauncher = 2628 canAccessAllShortcuts && 2629 ((queryFlags & ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER) != 0); 2630 2631 p.findAll(ret, 2632 (ShortcutInfo si) -> { 2633 if (si.getLastChangedTimestamp() < changedSince) { 2634 return false; 2635 } 2636 if (ids != null && !ids.contains(si.getId())) { 2637 return false; 2638 } 2639 if (componentName != null) { 2640 if (si.getActivity() != null 2641 && !si.getActivity().equals(componentName)) { 2642 return false; 2643 } 2644 } 2645 if (matchDynamic && si.isDynamic()) { 2646 return true; 2647 } 2648 if ((matchPinned || getPinnedByAnyLauncher) && si.isPinned()) { 2649 return true; 2650 } 2651 if (matchManifest && si.isDeclaredInManifest()) { 2652 return true; 2653 } 2654 return false; 2655 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher); 2656 } 2657 2658 @Override isPinnedByCaller(int launcherUserId, @NonNull String callingPackage, @NonNull String packageName, @NonNull String shortcutId, int userId)2659 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage, 2660 @NonNull String packageName, @NonNull String shortcutId, int userId) { 2661 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2662 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId"); 2663 2664 synchronized (mLock) { 2665 throwIfUserLockedL(userId); 2666 throwIfUserLockedL(launcherUserId); 2667 2668 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2669 .attemptToRestoreIfNeededAndSave(); 2670 2671 final ShortcutInfo si = getShortcutInfoLocked( 2672 launcherUserId, callingPackage, packageName, shortcutId, userId, 2673 /*getPinnedByAnyLauncher=*/ false); 2674 return si != null && si.isPinned(); 2675 } 2676 } 2677 2678 @GuardedBy("ShortcutService.this.mLock") getShortcutInfoLocked( int launcherUserId, @NonNull String callingPackage, @NonNull String packageName, @NonNull String shortcutId, int userId, boolean getPinnedByAnyLauncher)2679 private ShortcutInfo getShortcutInfoLocked( 2680 int launcherUserId, @NonNull String callingPackage, 2681 @NonNull String packageName, @NonNull String shortcutId, int userId, 2682 boolean getPinnedByAnyLauncher) { 2683 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2684 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId"); 2685 2686 throwIfUserLockedL(userId); 2687 throwIfUserLockedL(launcherUserId); 2688 2689 final ShortcutPackage p = getUserShortcutsLocked(userId) 2690 .getPackageShortcutsIfExists(packageName); 2691 if (p == null) { 2692 return null; 2693 } 2694 2695 final ArrayList<ShortcutInfo> list = new ArrayList<>(1); 2696 p.findAll(list, 2697 (ShortcutInfo si) -> shortcutId.equals(si.getId()), 2698 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher); 2699 return list.size() == 0 ? null : list.get(0); 2700 } 2701 2702 @Override pinShortcuts(int launcherUserId, @NonNull String callingPackage, @NonNull String packageName, @NonNull List<String> shortcutIds, int userId)2703 public void pinShortcuts(int launcherUserId, 2704 @NonNull String callingPackage, @NonNull String packageName, 2705 @NonNull List<String> shortcutIds, int userId) { 2706 // Calling permission must be checked by LauncherAppsImpl. 2707 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2708 Preconditions.checkNotNull(shortcutIds, "shortcutIds"); 2709 2710 synchronized (mLock) { 2711 throwIfUserLockedL(userId); 2712 throwIfUserLockedL(launcherUserId); 2713 2714 final ShortcutLauncher launcher = 2715 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId); 2716 launcher.attemptToRestoreIfNeededAndSave(); 2717 2718 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false); 2719 } 2720 packageShortcutsChanged(packageName, userId); 2721 2722 verifyStates(); 2723 } 2724 2725 @Override createShortcutIntents(int launcherUserId, @NonNull String callingPackage, @NonNull String packageName, @NonNull String shortcutId, int userId, int callingPid, int callingUid)2726 public Intent[] createShortcutIntents(int launcherUserId, 2727 @NonNull String callingPackage, 2728 @NonNull String packageName, @NonNull String shortcutId, int userId, 2729 int callingPid, int callingUid) { 2730 // Calling permission must be checked by LauncherAppsImpl. 2731 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty"); 2732 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty"); 2733 2734 synchronized (mLock) { 2735 throwIfUserLockedL(userId); 2736 throwIfUserLockedL(launcherUserId); 2737 2738 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2739 .attemptToRestoreIfNeededAndSave(); 2740 2741 final boolean getPinnedByAnyLauncher = 2742 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, 2743 callingPid, callingUid); 2744 2745 // Make sure the shortcut is actually visible to the launcher. 2746 final ShortcutInfo si = getShortcutInfoLocked( 2747 launcherUserId, callingPackage, packageName, shortcutId, userId, 2748 getPinnedByAnyLauncher); 2749 // "si == null" should suffice here, but check the flags too just to make sure. 2750 if (si == null || !si.isEnabled() || !(si.isAlive() || getPinnedByAnyLauncher)) { 2751 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled"); 2752 return null; 2753 } 2754 return si.getIntents(); 2755 } 2756 } 2757 2758 @Override addListener(@onNull ShortcutChangeListener listener)2759 public void addListener(@NonNull ShortcutChangeListener listener) { 2760 synchronized (mLock) { 2761 mListeners.add(Preconditions.checkNotNull(listener)); 2762 } 2763 } 2764 2765 @Override getShortcutIconResId(int launcherUserId, @NonNull String callingPackage, @NonNull String packageName, @NonNull String shortcutId, int userId)2766 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage, 2767 @NonNull String packageName, @NonNull String shortcutId, int userId) { 2768 Preconditions.checkNotNull(callingPackage, "callingPackage"); 2769 Preconditions.checkNotNull(packageName, "packageName"); 2770 Preconditions.checkNotNull(shortcutId, "shortcutId"); 2771 2772 synchronized (mLock) { 2773 throwIfUserLockedL(userId); 2774 throwIfUserLockedL(launcherUserId); 2775 2776 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2777 .attemptToRestoreIfNeededAndSave(); 2778 2779 final ShortcutPackage p = getUserShortcutsLocked(userId) 2780 .getPackageShortcutsIfExists(packageName); 2781 if (p == null) { 2782 return 0; 2783 } 2784 2785 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId); 2786 return (shortcutInfo != null && shortcutInfo.hasIconResource()) 2787 ? shortcutInfo.getIconResourceId() : 0; 2788 } 2789 } 2790 2791 @Override getShortcutIconFd(int launcherUserId, @NonNull String callingPackage, @NonNull String packageName, @NonNull String shortcutId, int userId)2792 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId, 2793 @NonNull String callingPackage, @NonNull String packageName, 2794 @NonNull String shortcutId, int userId) { 2795 Preconditions.checkNotNull(callingPackage, "callingPackage"); 2796 Preconditions.checkNotNull(packageName, "packageName"); 2797 Preconditions.checkNotNull(shortcutId, "shortcutId"); 2798 2799 synchronized (mLock) { 2800 throwIfUserLockedL(userId); 2801 throwIfUserLockedL(launcherUserId); 2802 2803 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2804 .attemptToRestoreIfNeededAndSave(); 2805 2806 final ShortcutPackage p = getUserShortcutsLocked(userId) 2807 .getPackageShortcutsIfExists(packageName); 2808 if (p == null) { 2809 return null; 2810 } 2811 2812 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId); 2813 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) { 2814 return null; 2815 } 2816 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo); 2817 if (path == null) { 2818 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()"); 2819 return null; 2820 } 2821 try { 2822 return ParcelFileDescriptor.open( 2823 new File(path), 2824 ParcelFileDescriptor.MODE_READ_ONLY); 2825 } catch (FileNotFoundException e) { 2826 Slog.e(TAG, "Icon file not found: " + path); 2827 return null; 2828 } 2829 } 2830 } 2831 2832 @Override hasShortcutHostPermission(int launcherUserId, @NonNull String callingPackage, int callingPid, int callingUid)2833 public boolean hasShortcutHostPermission(int launcherUserId, 2834 @NonNull String callingPackage, int callingPid, int callingUid) { 2835 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId, 2836 callingPid, callingUid); 2837 } 2838 2839 @Override setShortcutHostPackage(@onNull String type, @Nullable String packageName, int userId)2840 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName, 2841 int userId) { 2842 ShortcutService.this.setShortcutHostPackage(type, packageName, userId); 2843 } 2844 2845 @Override requestPinAppWidget(@onNull String callingPackage, @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras, @Nullable IntentSender resultIntent, int userId)2846 public boolean requestPinAppWidget(@NonNull String callingPackage, 2847 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras, 2848 @Nullable IntentSender resultIntent, int userId) { 2849 Preconditions.checkNotNull(appWidget); 2850 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent); 2851 } 2852 2853 @Override isRequestPinItemSupported(int callingUserId, int requestType)2854 public boolean isRequestPinItemSupported(int callingUserId, int requestType) { 2855 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType); 2856 } 2857 2858 @Override isForegroundDefaultLauncher(@onNull String callingPackage, int callingUid)2859 public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) { 2860 Preconditions.checkNotNull(callingPackage); 2861 2862 final int userId = UserHandle.getUserId(callingUid); 2863 final ComponentName defaultLauncher = getDefaultLauncher(userId); 2864 if (defaultLauncher == null) { 2865 return false; 2866 } 2867 if (!callingPackage.equals(defaultLauncher.getPackageName())) { 2868 return false; 2869 } 2870 synchronized (mLock) { 2871 if (!isUidForegroundLocked(callingUid)) { 2872 return false; 2873 } 2874 } 2875 return true; 2876 } 2877 } 2878 2879 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 2880 @Override 2881 public void onReceive(Context context, Intent intent) { 2882 if (!mBootCompleted.get()) { 2883 return; // Boot not completed, ignore the broadcast. 2884 } 2885 try { 2886 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) { 2887 handleLocaleChanged(); 2888 } 2889 } catch (Exception e) { 2890 wtf("Exception in mReceiver.onReceive", e); 2891 } 2892 } 2893 }; 2894 handleLocaleChanged()2895 void handleLocaleChanged() { 2896 if (DEBUG) { 2897 Slog.d(TAG, "handleLocaleChanged"); 2898 } 2899 scheduleSaveBaseState(); 2900 2901 synchronized (mLock) { 2902 final long token = injectClearCallingIdentity(); 2903 try { 2904 forEachLoadedUserLocked(user -> user.detectLocaleChange()); 2905 } finally { 2906 injectRestoreCallingIdentity(token); 2907 } 2908 } 2909 } 2910 2911 /** 2912 * Package event callbacks. 2913 */ 2914 @VisibleForTesting 2915 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() { 2916 @Override 2917 public void onReceive(Context context, Intent intent) { 2918 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 2919 if (userId == UserHandle.USER_NULL) { 2920 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent); 2921 return; 2922 } 2923 2924 final String action = intent.getAction(); 2925 2926 // This is normally called on Handler, so clearCallingIdentity() isn't needed, 2927 // but we still check it in unit tests. 2928 final long token = injectClearCallingIdentity(); 2929 try { 2930 synchronized (mLock) { 2931 if (!isUserUnlockedL(userId)) { 2932 if (DEBUG) { 2933 Slog.d(TAG, "Ignoring package broadcast " + action 2934 + " for locked/stopped user " + userId); 2935 } 2936 return; 2937 } 2938 2939 // Whenever we get one of those package broadcasts, or get 2940 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache. 2941 final ShortcutUser user = getUserShortcutsLocked(userId); 2942 user.clearLauncher(); 2943 } 2944 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) { 2945 // Nothing farther to do. 2946 return; 2947 } 2948 2949 final Uri intentUri = intent.getData(); 2950 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart() 2951 : null; 2952 if (packageName == null) { 2953 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent); 2954 return; 2955 } 2956 2957 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 2958 2959 switch (action) { 2960 case Intent.ACTION_PACKAGE_ADDED: 2961 if (replacing) { 2962 handlePackageUpdateFinished(packageName, userId); 2963 } else { 2964 handlePackageAdded(packageName, userId); 2965 } 2966 break; 2967 case Intent.ACTION_PACKAGE_REMOVED: 2968 if (!replacing) { 2969 handlePackageRemoved(packageName, userId); 2970 } 2971 break; 2972 case Intent.ACTION_PACKAGE_CHANGED: 2973 handlePackageChanged(packageName, userId); 2974 2975 break; 2976 case Intent.ACTION_PACKAGE_DATA_CLEARED: 2977 handlePackageDataCleared(packageName, userId); 2978 break; 2979 } 2980 } catch (Exception e) { 2981 wtf("Exception in mPackageMonitor.onReceive", e); 2982 } finally { 2983 injectRestoreCallingIdentity(token); 2984 } 2985 } 2986 }; 2987 2988 /** 2989 * Called when a user is unlocked. 2990 * - Check all known packages still exist, and otherwise perform cleanup. 2991 * - If a package still exists, check the version code. If it's been updated, may need to 2992 * update timestamps of its shortcuts. 2993 */ 2994 @VisibleForTesting checkPackageChanges(@serIdInt int ownerUserId)2995 void checkPackageChanges(@UserIdInt int ownerUserId) { 2996 if (DEBUG) { 2997 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId); 2998 } 2999 if (injectIsSafeModeEnabled()) { 3000 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()"); 3001 return; 3002 } 3003 3004 final long start = getStatStartTime(); 3005 try { 3006 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>(); 3007 3008 synchronized (mLock) { 3009 final ShortcutUser user = getUserShortcutsLocked(ownerUserId); 3010 3011 // Find packages that have been uninstalled. 3012 user.forAllPackageItems(spi -> { 3013 if (spi.getPackageInfo().isShadow()) { 3014 return; // Don't delete shadow information. 3015 } 3016 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) { 3017 if (DEBUG) { 3018 Slog.d(TAG, "Uninstalled: " + spi.getPackageName() 3019 + " user " + spi.getPackageUserId()); 3020 } 3021 gonePackages.add(PackageWithUser.of(spi)); 3022 } 3023 }); 3024 if (gonePackages.size() > 0) { 3025 for (int i = gonePackages.size() - 1; i >= 0; i--) { 3026 final PackageWithUser pu = gonePackages.get(i); 3027 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId, 3028 /* appStillExists = */ false); 3029 } 3030 } 3031 3032 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime()); 3033 } 3034 } finally { 3035 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start); 3036 } 3037 verifyStates(); 3038 } 3039 3040 @GuardedBy("mLock") rescanUpdatedPackagesLocked(@serIdInt int userId, long lastScanTime)3041 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) { 3042 final ShortcutUser user = getUserShortcutsLocked(userId); 3043 3044 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime 3045 // is not reliable. 3046 final long now = injectCurrentTimeMillis(); 3047 final boolean afterOta = 3048 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint()); 3049 3050 // Then for each installed app, publish manifest shortcuts when needed. 3051 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> { 3052 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId); 3053 3054 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true); 3055 }); 3056 3057 // Write the time just before the scan, because there may be apps that have just 3058 // been updated, and we want to catch them in the next time. 3059 user.setLastAppScanTime(now); 3060 user.setLastAppScanOsFingerprint(injectBuildFingerprint()); 3061 scheduleSaveUser(userId); 3062 } 3063 handlePackageAdded(String packageName, @UserIdInt int userId)3064 private void handlePackageAdded(String packageName, @UserIdInt int userId) { 3065 if (DEBUG) { 3066 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId)); 3067 } 3068 synchronized (mLock) { 3069 final ShortcutUser user = getUserShortcutsLocked(userId); 3070 user.attemptToRestoreIfNeededAndSave(this, packageName, userId); 3071 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 3072 } 3073 verifyStates(); 3074 } 3075 handlePackageUpdateFinished(String packageName, @UserIdInt int userId)3076 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) { 3077 if (DEBUG) { 3078 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d", 3079 packageName, userId)); 3080 } 3081 synchronized (mLock) { 3082 final ShortcutUser user = getUserShortcutsLocked(userId); 3083 user.attemptToRestoreIfNeededAndSave(this, packageName, userId); 3084 3085 if (isPackageInstalled(packageName, userId)) { 3086 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 3087 } 3088 } 3089 verifyStates(); 3090 } 3091 handlePackageRemoved(String packageName, @UserIdInt int packageUserId)3092 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) { 3093 if (DEBUG) { 3094 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName, 3095 packageUserId)); 3096 } 3097 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false); 3098 3099 verifyStates(); 3100 } 3101 handlePackageDataCleared(String packageName, int packageUserId)3102 private void handlePackageDataCleared(String packageName, int packageUserId) { 3103 if (DEBUG) { 3104 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName, 3105 packageUserId)); 3106 } 3107 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true); 3108 3109 verifyStates(); 3110 } 3111 handlePackageChanged(String packageName, int packageUserId)3112 private void handlePackageChanged(String packageName, int packageUserId) { 3113 if (!isPackageInstalled(packageName, packageUserId)) { 3114 // Probably disabled, which is the same thing as uninstalled. 3115 handlePackageRemoved(packageName, packageUserId); 3116 return; 3117 } 3118 if (DEBUG) { 3119 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName, 3120 packageUserId)); 3121 } 3122 3123 // Activities may be disabled or enabled. Just rescan the package. 3124 synchronized (mLock) { 3125 final ShortcutUser user = getUserShortcutsLocked(packageUserId); 3126 3127 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 3128 } 3129 3130 verifyStates(); 3131 } 3132 3133 // === PackageManager interaction === 3134 3135 /** 3136 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 3137 */ 3138 @Nullable getPackageInfoWithSignatures(String packageName, @UserIdInt int userId)3139 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) { 3140 return getPackageInfo(packageName, userId, true); 3141 } 3142 3143 /** 3144 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 3145 */ 3146 @Nullable getPackageInfo(String packageName, @UserIdInt int userId)3147 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) { 3148 return getPackageInfo(packageName, userId, false); 3149 } 3150 injectGetPackageUid(@onNull String packageName, @UserIdInt int userId)3151 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) { 3152 final long token = injectClearCallingIdentity(); 3153 try { 3154 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId); 3155 } catch (RemoteException e) { 3156 // Shouldn't happen. 3157 Slog.wtf(TAG, "RemoteException", e); 3158 return -1; 3159 } finally { 3160 injectRestoreCallingIdentity(token); 3161 } 3162 } 3163 3164 /** 3165 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 3166 */ 3167 @Nullable 3168 @VisibleForTesting getPackageInfo(String packageName, @UserIdInt int userId, boolean getSignatures)3169 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId, 3170 boolean getSignatures) { 3171 return isInstalledOrNull(injectPackageInfoWithUninstalled( 3172 packageName, userId, getSignatures)); 3173 } 3174 3175 /** 3176 * Do not use directly; this returns uninstalled packages too. 3177 */ 3178 @Nullable 3179 @VisibleForTesting injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId, boolean getSignatures)3180 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId, 3181 boolean getSignatures) { 3182 final long start = getStatStartTime(); 3183 final long token = injectClearCallingIdentity(); 3184 try { 3185 return mIPackageManager.getPackageInfo( 3186 packageName, PACKAGE_MATCH_FLAGS 3187 | (getSignatures ? PackageManager.GET_SIGNING_CERTIFICATES : 0), 3188 userId); 3189 } catch (RemoteException e) { 3190 // Shouldn't happen. 3191 Slog.wtf(TAG, "RemoteException", e); 3192 return null; 3193 } finally { 3194 injectRestoreCallingIdentity(token); 3195 3196 logDurationStat( 3197 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO), 3198 start); 3199 } 3200 } 3201 3202 /** 3203 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled. 3204 */ 3205 @Nullable 3206 @VisibleForTesting getApplicationInfo(String packageName, @UserIdInt int userId)3207 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) { 3208 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId)); 3209 } 3210 3211 /** 3212 * Do not use directly; this returns uninstalled packages too. 3213 */ 3214 @Nullable 3215 @VisibleForTesting injectApplicationInfoWithUninstalled( String packageName, @UserIdInt int userId)3216 ApplicationInfo injectApplicationInfoWithUninstalled( 3217 String packageName, @UserIdInt int userId) { 3218 final long start = getStatStartTime(); 3219 final long token = injectClearCallingIdentity(); 3220 try { 3221 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId); 3222 } catch (RemoteException e) { 3223 // Shouldn't happen. 3224 Slog.wtf(TAG, "RemoteException", e); 3225 return null; 3226 } finally { 3227 injectRestoreCallingIdentity(token); 3228 3229 logDurationStat(Stats.GET_APPLICATION_INFO, start); 3230 } 3231 } 3232 3233 /** 3234 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled. 3235 */ 3236 @Nullable getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId)3237 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) { 3238 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled( 3239 activity, userId)); 3240 } 3241 3242 /** 3243 * Do not use directly; this returns uninstalled packages too. 3244 */ 3245 @Nullable 3246 @VisibleForTesting injectGetActivityInfoWithMetadataWithUninstalled( ComponentName activity, @UserIdInt int userId)3247 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled( 3248 ComponentName activity, @UserIdInt int userId) { 3249 final long start = getStatStartTime(); 3250 final long token = injectClearCallingIdentity(); 3251 try { 3252 return mIPackageManager.getActivityInfo(activity, 3253 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId); 3254 } catch (RemoteException e) { 3255 // Shouldn't happen. 3256 Slog.wtf(TAG, "RemoteException", e); 3257 return null; 3258 } finally { 3259 injectRestoreCallingIdentity(token); 3260 3261 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start); 3262 } 3263 } 3264 3265 /** 3266 * Return all installed and enabled packages. 3267 */ 3268 @NonNull 3269 @VisibleForTesting getInstalledPackages(@serIdInt int userId)3270 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) { 3271 final long start = getStatStartTime(); 3272 final long token = injectClearCallingIdentity(); 3273 try { 3274 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId); 3275 3276 all.removeIf(PACKAGE_NOT_INSTALLED); 3277 3278 return all; 3279 } catch (RemoteException e) { 3280 // Shouldn't happen. 3281 Slog.wtf(TAG, "RemoteException", e); 3282 return null; 3283 } finally { 3284 injectRestoreCallingIdentity(token); 3285 3286 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start); 3287 } 3288 } 3289 3290 /** 3291 * Do not use directly; this returns uninstalled packages too. 3292 */ 3293 @NonNull 3294 @VisibleForTesting injectGetPackagesWithUninstalled(@serIdInt int userId)3295 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId) 3296 throws RemoteException { 3297 final ParceledListSlice<PackageInfo> parceledList = 3298 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId); 3299 if (parceledList == null) { 3300 return Collections.emptyList(); 3301 } 3302 return parceledList.getList(); 3303 } 3304 forUpdatedPackages(@serIdInt int userId, long lastScanTime, boolean afterOta, Consumer<ApplicationInfo> callback)3305 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta, 3306 Consumer<ApplicationInfo> callback) { 3307 if (DEBUG) { 3308 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime 3309 + " afterOta=" + afterOta); 3310 } 3311 final List<PackageInfo> list = getInstalledPackages(userId); 3312 for (int i = list.size() - 1; i >= 0; i--) { 3313 final PackageInfo pi = list.get(i); 3314 3315 // If the package has been updated since the last scan time, then scan it. 3316 // Also if it's right after an OTA, always re-scan all apps anyway, since the 3317 // shortcut parser might have changed. 3318 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) { 3319 if (DEBUG) { 3320 Slog.d(TAG, "Found updated package " + pi.packageName 3321 + " updateTime=" + pi.lastUpdateTime); 3322 } 3323 callback.accept(pi.applicationInfo); 3324 } 3325 } 3326 } 3327 isApplicationFlagSet(@onNull String packageName, int userId, int flags)3328 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) { 3329 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId); 3330 return (ai != null) && ((ai.flags & flags) == flags); 3331 } 3332 isInstalled(@ullable ApplicationInfo ai)3333 private static boolean isInstalled(@Nullable ApplicationInfo ai) { 3334 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0; 3335 } 3336 isEphemeralApp(@ullable ApplicationInfo ai)3337 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) { 3338 return (ai != null) && ai.isInstantApp(); 3339 } 3340 isInstalled(@ullable PackageInfo pi)3341 private static boolean isInstalled(@Nullable PackageInfo pi) { 3342 return (pi != null) && isInstalled(pi.applicationInfo); 3343 } 3344 isInstalled(@ullable ActivityInfo ai)3345 private static boolean isInstalled(@Nullable ActivityInfo ai) { 3346 return (ai != null) && isInstalled(ai.applicationInfo); 3347 } 3348 isInstalledOrNull(ApplicationInfo ai)3349 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) { 3350 return isInstalled(ai) ? ai : null; 3351 } 3352 isInstalledOrNull(PackageInfo pi)3353 private static PackageInfo isInstalledOrNull(PackageInfo pi) { 3354 return isInstalled(pi) ? pi : null; 3355 } 3356 isInstalledOrNull(ActivityInfo ai)3357 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) { 3358 return isInstalled(ai) ? ai : null; 3359 } 3360 isPackageInstalled(String packageName, int userId)3361 boolean isPackageInstalled(String packageName, int userId) { 3362 return getApplicationInfo(packageName, userId) != null; 3363 } 3364 isEphemeralApp(String packageName, int userId)3365 boolean isEphemeralApp(String packageName, int userId) { 3366 return isEphemeralApp(getApplicationInfo(packageName, userId)); 3367 } 3368 3369 @Nullable injectXmlMetaData(ActivityInfo activityInfo, String key)3370 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) { 3371 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key); 3372 } 3373 3374 @Nullable injectGetResourcesForApplicationAsUser(String packageName, int userId)3375 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) { 3376 final long start = getStatStartTime(); 3377 final long token = injectClearCallingIdentity(); 3378 try { 3379 return mContext.getPackageManager().getResourcesForApplicationAsUser( 3380 packageName, userId); 3381 } catch (NameNotFoundException e) { 3382 Slog.e(TAG, "Resources for package " + packageName + " not found"); 3383 return null; 3384 } finally { 3385 injectRestoreCallingIdentity(token); 3386 3387 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start); 3388 } 3389 } 3390 getMainActivityIntent()3391 private Intent getMainActivityIntent() { 3392 final Intent intent = new Intent(Intent.ACTION_MAIN); 3393 intent.addCategory(LAUNCHER_INTENT_CATEGORY); 3394 return intent; 3395 } 3396 3397 /** 3398 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed, 3399 * and only returns exported activities. 3400 */ 3401 @NonNull 3402 @VisibleForTesting queryActivities(@onNull Intent baseIntent, @NonNull String packageName, @Nullable ComponentName activity, int userId)3403 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent, 3404 @NonNull String packageName, @Nullable ComponentName activity, int userId) { 3405 3406 baseIntent.setPackage(Preconditions.checkNotNull(packageName)); 3407 if (activity != null) { 3408 baseIntent.setComponent(activity); 3409 } 3410 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true); 3411 } 3412 3413 @NonNull queryActivities(@onNull Intent intent, int userId, boolean exportedOnly)3414 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId, 3415 boolean exportedOnly) { 3416 final List<ResolveInfo> resolved; 3417 final long token = injectClearCallingIdentity(); 3418 try { 3419 resolved = 3420 mContext.getPackageManager().queryIntentActivitiesAsUser( 3421 intent, PACKAGE_MATCH_FLAGS, userId); 3422 } finally { 3423 injectRestoreCallingIdentity(token); 3424 } 3425 if (resolved == null || resolved.size() == 0) { 3426 return EMPTY_RESOLVE_INFO; 3427 } 3428 // Make sure the package is installed. 3429 if (!isInstalled(resolved.get(0).activityInfo)) { 3430 return EMPTY_RESOLVE_INFO; 3431 } 3432 if (exportedOnly) { 3433 resolved.removeIf(ACTIVITY_NOT_EXPORTED); 3434 } 3435 return resolved; 3436 } 3437 3438 /** 3439 * Return the main activity that is enabled and exported. If multiple activities are found, 3440 * return the first one. 3441 */ 3442 @Nullable injectGetDefaultMainActivity(@onNull String packageName, int userId)3443 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) { 3444 final long start = getStatStartTime(); 3445 try { 3446 final List<ResolveInfo> resolved = 3447 queryActivities(getMainActivityIntent(), packageName, null, userId); 3448 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName(); 3449 } finally { 3450 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start); 3451 } 3452 } 3453 3454 /** 3455 * Return whether an activity is enabled, exported and main. 3456 */ injectIsMainActivity(@onNull ComponentName activity, int userId)3457 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) { 3458 final long start = getStatStartTime(); 3459 try { 3460 if (activity == null) { 3461 wtf("null activity detected"); 3462 return false; 3463 } 3464 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) { 3465 return true; 3466 } 3467 final List<ResolveInfo> resolved = queryActivities( 3468 getMainActivityIntent(), activity.getPackageName(), activity, userId); 3469 return resolved.size() > 0; 3470 } finally { 3471 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3472 } 3473 } 3474 3475 /** 3476 * Create a dummy "main activity" component name which is used to create a dynamic shortcut 3477 * with no main activity temporarily. 3478 */ 3479 @NonNull getDummyMainActivity(@onNull String packageName)3480 ComponentName getDummyMainActivity(@NonNull String packageName) { 3481 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY); 3482 } 3483 isDummyMainActivity(@ullable ComponentName name)3484 boolean isDummyMainActivity(@Nullable ComponentName name) { 3485 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName()); 3486 } 3487 3488 /** 3489 * Return all the enabled, exported and main activities from a package. 3490 */ 3491 @NonNull injectGetMainActivities(@onNull String packageName, int userId)3492 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) { 3493 final long start = getStatStartTime(); 3494 try { 3495 return queryActivities(getMainActivityIntent(), packageName, null, userId); 3496 } finally { 3497 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3498 } 3499 } 3500 3501 /** 3502 * Return whether an activity is enabled and exported. 3503 */ 3504 @VisibleForTesting injectIsActivityEnabledAndExported( @onNull ComponentName activity, @UserIdInt int userId)3505 boolean injectIsActivityEnabledAndExported( 3506 @NonNull ComponentName activity, @UserIdInt int userId) { 3507 final long start = getStatStartTime(); 3508 try { 3509 return queryActivities(new Intent(), activity.getPackageName(), activity, userId) 3510 .size() > 0; 3511 } finally { 3512 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start); 3513 } 3514 } 3515 3516 /** 3517 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or 3518 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on 3519 * the requestType. 3520 */ 3521 @Nullable injectGetPinConfirmationActivity(@onNull String launcherPackageName, int launcherUserId, int requestType)3522 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName, 3523 int launcherUserId, int requestType) { 3524 Preconditions.checkNotNull(launcherPackageName); 3525 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ? 3526 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT : 3527 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET; 3528 3529 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName); 3530 final List<ResolveInfo> candidates = queryActivities( 3531 confirmIntent, launcherUserId, /* exportedOnly =*/ false); 3532 for (ResolveInfo ri : candidates) { 3533 return ri.activityInfo.getComponentName(); 3534 } 3535 return null; 3536 } 3537 injectIsSafeModeEnabled()3538 boolean injectIsSafeModeEnabled() { 3539 final long token = injectClearCallingIdentity(); 3540 try { 3541 return IWindowManager.Stub 3542 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)) 3543 .isSafeModeEnabled(); 3544 } catch (RemoteException e) { 3545 return false; // Shouldn't happen though. 3546 } finally { 3547 injectRestoreCallingIdentity(token); 3548 } 3549 } 3550 3551 /** 3552 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return 3553 * itself. 3554 */ getParentOrSelfUserId(int userId)3555 int getParentOrSelfUserId(int userId) { 3556 return mUserManagerInternal.getProfileParentId(userId); 3557 } 3558 injectSendIntentSender(IntentSender intentSender, Intent extras)3559 void injectSendIntentSender(IntentSender intentSender, Intent extras) { 3560 if (intentSender == null) { 3561 return; 3562 } 3563 try { 3564 intentSender.sendIntent(mContext, /* code= */ 0, extras, 3565 /* onFinished=*/ null, /* handler= */ null); 3566 } catch (SendIntentException e) { 3567 Slog.w(TAG, "sendIntent failed().", e); 3568 } 3569 } 3570 3571 // === Backup & restore === 3572 shouldBackupApp(String packageName, int userId)3573 boolean shouldBackupApp(String packageName, int userId) { 3574 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP); 3575 } 3576 shouldBackupApp(PackageInfo pi)3577 static boolean shouldBackupApp(PackageInfo pi) { 3578 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0; 3579 } 3580 3581 @Override getBackupPayload(@serIdInt int userId)3582 public byte[] getBackupPayload(@UserIdInt int userId) { 3583 enforceSystem(); 3584 if (DEBUG) { 3585 Slog.d(TAG, "Backing up user " + userId); 3586 } 3587 synchronized (mLock) { 3588 if (!isUserUnlockedL(userId)) { 3589 wtf("Can't backup: user " + userId + " is locked or not running"); 3590 return null; 3591 } 3592 3593 final ShortcutUser user = getUserShortcutsLocked(userId); 3594 if (user == null) { 3595 wtf("Can't backup: user not found: id=" + userId); 3596 return null; 3597 } 3598 3599 // Update the signatures for all packages. 3600 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave()); 3601 3602 // Rescan all apps; this will also update the version codes and "allow-backup". 3603 user.forAllPackages(pkg -> pkg.rescanPackageIfNeeded( 3604 /*isNewApp=*/ false, /*forceRescan=*/ true)); 3605 3606 // Set the version code for the launchers. 3607 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo()); 3608 3609 // Save to the filesystem. 3610 scheduleSaveUser(userId); 3611 saveDirtyInfo(); 3612 3613 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't 3614 // back up bitmaps anyway. 3615 3616 // Then create the backup payload. 3617 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024); 3618 try { 3619 saveUserInternalLocked(userId, os, /* forBackup */ true); 3620 } catch (XmlPullParserException | IOException e) { 3621 // Shouldn't happen. 3622 Slog.w(TAG, "Backup failed.", e); 3623 return null; 3624 } 3625 byte[] payload = os.toByteArray(); 3626 mShortcutDumpFiles.save("backup-1-payload.txt", payload); 3627 return payload; 3628 } 3629 } 3630 3631 @Override applyRestore(byte[] payload, @UserIdInt int userId)3632 public void applyRestore(byte[] payload, @UserIdInt int userId) { 3633 enforceSystem(); 3634 if (DEBUG) { 3635 Slog.d(TAG, "Restoring user " + userId); 3636 } 3637 synchronized (mLock) { 3638 if (!isUserUnlockedL(userId)) { 3639 wtf("Can't restore: user " + userId + " is locked or not running"); 3640 return; 3641 } 3642 3643 // Note we print the file timestamps in dumpsys too, but also printing the timestamp 3644 // in the files anyway. 3645 mShortcutDumpFiles.save("restore-0-start.txt", pw -> { 3646 pw.print("Start time: "); 3647 dumpCurrentTime(pw); 3648 pw.println(); 3649 }); 3650 mShortcutDumpFiles.save("restore-1-payload.xml", payload); 3651 3652 // Actually do restore. 3653 final ShortcutUser restored; 3654 final ByteArrayInputStream is = new ByteArrayInputStream(payload); 3655 try { 3656 restored = loadUserInternal(userId, is, /* fromBackup */ true); 3657 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) { 3658 Slog.w(TAG, "Restoration failed.", e); 3659 return; 3660 } 3661 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner); 3662 3663 getUserShortcutsLocked(userId).mergeRestoredFile(restored); 3664 3665 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner); 3666 3667 // Rescan all packages to re-publish manifest shortcuts and do other checks. 3668 rescanUpdatedPackagesLocked(userId, 3669 0 // lastScanTime = 0; rescan all packages. 3670 ); 3671 3672 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner); 3673 3674 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> { 3675 pw.print("Finish time: "); 3676 dumpCurrentTime(pw); 3677 pw.println(); 3678 }); 3679 3680 saveUserLocked(userId); 3681 } 3682 } 3683 3684 // === Dump === 3685 3686 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)3687 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3688 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 3689 dumpNoCheck(fd, pw, args); 3690 } 3691 3692 @VisibleForTesting dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args)3693 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) { 3694 final DumpFilter filter = parseDumpArgs(args); 3695 3696 if (filter.shouldDumpCheckIn()) { 3697 // Other flags are not supported for checkin. 3698 dumpCheckin(pw, filter.shouldCheckInClear()); 3699 } else { 3700 if (filter.shouldDumpMain()) { 3701 dumpInner(pw, filter); 3702 pw.println(); 3703 } 3704 if (filter.shouldDumpUid()) { 3705 dumpUid(pw); 3706 pw.println(); 3707 } 3708 if (filter.shouldDumpFiles()) { 3709 dumpDumpFiles(pw); 3710 pw.println(); 3711 } 3712 } 3713 } 3714 parseDumpArgs(String[] args)3715 private static DumpFilter parseDumpArgs(String[] args) { 3716 final DumpFilter filter = new DumpFilter(); 3717 if (args == null) { 3718 return filter; 3719 } 3720 3721 int argIndex = 0; 3722 while (argIndex < args.length) { 3723 final String arg = args[argIndex++]; 3724 3725 if ("-c".equals(arg)) { 3726 filter.setDumpCheckIn(true); 3727 continue; 3728 } 3729 if ("--checkin".equals(arg)) { 3730 filter.setDumpCheckIn(true); 3731 filter.setCheckInClear(true); 3732 continue; 3733 } 3734 if ("-a".equals(arg) || "--all".equals(arg)) { 3735 filter.setDumpUid(true); 3736 filter.setDumpFiles(true); 3737 continue; 3738 } 3739 if ("-u".equals(arg) || "--uid".equals(arg)) { 3740 filter.setDumpUid(true); 3741 continue; 3742 } 3743 if ("-f".equals(arg) || "--files".equals(arg)) { 3744 filter.setDumpFiles(true); 3745 continue; 3746 } 3747 if ("-n".equals(arg) || "--no-main".equals(arg)) { 3748 filter.setDumpMain(false); 3749 continue; 3750 } 3751 if ("--user".equals(arg)) { 3752 if (argIndex >= args.length) { 3753 throw new IllegalArgumentException("Missing user ID for --user"); 3754 } 3755 try { 3756 filter.addUser(Integer.parseInt(args[argIndex++])); 3757 } catch (NumberFormatException e) { 3758 throw new IllegalArgumentException("Invalid user ID", e); 3759 } 3760 continue; 3761 } 3762 if ("-p".equals(arg) || "--package".equals(arg)) { 3763 if (argIndex >= args.length) { 3764 throw new IllegalArgumentException("Missing package name for --package"); 3765 } 3766 filter.addPackageRegex(args[argIndex++]); 3767 filter.setDumpDetails(false); 3768 continue; 3769 } 3770 if (arg.startsWith("-")) { 3771 throw new IllegalArgumentException("Unknown option " + arg); 3772 } 3773 break; 3774 } 3775 while (argIndex < args.length) { 3776 filter.addPackage(args[argIndex++]); 3777 } 3778 return filter; 3779 } 3780 3781 static class DumpFilter { 3782 private boolean mDumpCheckIn = false; 3783 private boolean mCheckInClear = false; 3784 3785 private boolean mDumpMain = true; 3786 private boolean mDumpUid = false; 3787 private boolean mDumpFiles = false; 3788 3789 private boolean mDumpDetails = true; 3790 private List<Pattern> mPackagePatterns = new ArrayList<>(); 3791 private List<Integer> mUsers = new ArrayList<>(); 3792 addPackageRegex(String regex)3793 void addPackageRegex(String regex) { 3794 mPackagePatterns.add(Pattern.compile(regex)); 3795 } 3796 addPackage(String packageName)3797 public void addPackage(String packageName) { 3798 addPackageRegex(Pattern.quote(packageName)); 3799 } 3800 addUser(int userId)3801 void addUser(int userId) { 3802 mUsers.add(userId); 3803 } 3804 isPackageMatch(String packageName)3805 boolean isPackageMatch(String packageName) { 3806 if (mPackagePatterns.size() == 0) { 3807 return true; 3808 } 3809 for (int i = 0; i < mPackagePatterns.size(); i++) { 3810 if (mPackagePatterns.get(i).matcher(packageName).find()) { 3811 return true; 3812 } 3813 } 3814 return false; 3815 } 3816 isUserMatch(int userId)3817 boolean isUserMatch(int userId) { 3818 if (mUsers.size() == 0) { 3819 return true; 3820 } 3821 for (int i = 0; i < mUsers.size(); i++) { 3822 if (mUsers.get(i) == userId) { 3823 return true; 3824 } 3825 } 3826 return false; 3827 } 3828 shouldDumpCheckIn()3829 public boolean shouldDumpCheckIn() { 3830 return mDumpCheckIn; 3831 } 3832 setDumpCheckIn(boolean dumpCheckIn)3833 public void setDumpCheckIn(boolean dumpCheckIn) { 3834 mDumpCheckIn = dumpCheckIn; 3835 } 3836 shouldCheckInClear()3837 public boolean shouldCheckInClear() { 3838 return mCheckInClear; 3839 } 3840 setCheckInClear(boolean checkInClear)3841 public void setCheckInClear(boolean checkInClear) { 3842 mCheckInClear = checkInClear; 3843 } 3844 shouldDumpMain()3845 public boolean shouldDumpMain() { 3846 return mDumpMain; 3847 } 3848 setDumpMain(boolean dumpMain)3849 public void setDumpMain(boolean dumpMain) { 3850 mDumpMain = dumpMain; 3851 } 3852 shouldDumpUid()3853 public boolean shouldDumpUid() { 3854 return mDumpUid; 3855 } 3856 setDumpUid(boolean dumpUid)3857 public void setDumpUid(boolean dumpUid) { 3858 mDumpUid = dumpUid; 3859 } 3860 shouldDumpFiles()3861 public boolean shouldDumpFiles() { 3862 return mDumpFiles; 3863 } 3864 setDumpFiles(boolean dumpFiles)3865 public void setDumpFiles(boolean dumpFiles) { 3866 mDumpFiles = dumpFiles; 3867 } 3868 shouldDumpDetails()3869 public boolean shouldDumpDetails() { 3870 return mDumpDetails; 3871 } 3872 setDumpDetails(boolean dumpDetails)3873 public void setDumpDetails(boolean dumpDetails) { 3874 mDumpDetails = dumpDetails; 3875 } 3876 } 3877 dumpInner(PrintWriter pw)3878 private void dumpInner(PrintWriter pw) { 3879 dumpInner(pw, new DumpFilter()); 3880 } 3881 dumpInner(PrintWriter pw, DumpFilter filter)3882 private void dumpInner(PrintWriter pw, DumpFilter filter) { 3883 synchronized (mLock) { 3884 if (filter.shouldDumpDetails()) { 3885 final long now = injectCurrentTimeMillis(); 3886 pw.print("Now: ["); 3887 pw.print(now); 3888 pw.print("] "); 3889 pw.print(formatTime(now)); 3890 3891 pw.print(" Raw last reset: ["); 3892 pw.print(mRawLastResetTime); 3893 pw.print("] "); 3894 pw.print(formatTime(mRawLastResetTime)); 3895 3896 final long last = getLastResetTimeLocked(); 3897 pw.print(" Last reset: ["); 3898 pw.print(last); 3899 pw.print("] "); 3900 pw.print(formatTime(last)); 3901 3902 final long next = getNextResetTimeLocked(); 3903 pw.print(" Next reset: ["); 3904 pw.print(next); 3905 pw.print("] "); 3906 pw.print(formatTime(next)); 3907 pw.println(); 3908 pw.println(); 3909 3910 pw.print(" Config:"); 3911 pw.print(" Max icon dim: "); 3912 pw.println(mMaxIconDimension); 3913 pw.print(" Icon format: "); 3914 pw.println(mIconPersistFormat); 3915 pw.print(" Icon quality: "); 3916 pw.println(mIconPersistQuality); 3917 pw.print(" saveDelayMillis: "); 3918 pw.println(mSaveDelayMillis); 3919 pw.print(" resetInterval: "); 3920 pw.println(mResetInterval); 3921 pw.print(" maxUpdatesPerInterval: "); 3922 pw.println(mMaxUpdatesPerInterval); 3923 pw.print(" maxShortcutsPerActivity: "); 3924 pw.println(mMaxShortcuts); 3925 pw.println(); 3926 3927 mStatLogger.dump(pw, " "); 3928 3929 pw.println(); 3930 pw.print(" #Failures: "); 3931 pw.println(mWtfCount); 3932 3933 if (mLastWtfStacktrace != null) { 3934 pw.print(" Last failure stack trace: "); 3935 pw.println(Log.getStackTraceString(mLastWtfStacktrace)); 3936 } 3937 3938 pw.println(); 3939 mShortcutBitmapSaver.dumpLocked(pw, " "); 3940 3941 pw.println(); 3942 } 3943 3944 for (int i = 0; i < mUsers.size(); i++) { 3945 final ShortcutUser user = mUsers.valueAt(i); 3946 if (filter.isUserMatch(user.getUserId())) { 3947 user.dump(pw, " ", filter); 3948 pw.println(); 3949 } 3950 } 3951 3952 for (int i = 0; i < mShortcutNonPersistentUsers.size(); i++) { 3953 final ShortcutNonPersistentUser user = mShortcutNonPersistentUsers.valueAt(i); 3954 if (filter.isUserMatch(user.getUserId())) { 3955 user.dump(pw, " ", filter); 3956 pw.println(); 3957 } 3958 } 3959 } 3960 } 3961 dumpUid(PrintWriter pw)3962 private void dumpUid(PrintWriter pw) { 3963 synchronized (mLock) { 3964 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)"); 3965 3966 for (int i = 0; i < mUidState.size(); i++) { 3967 final int uid = mUidState.keyAt(i); 3968 final int state = mUidState.valueAt(i); 3969 pw.print(" UID="); 3970 pw.print(uid); 3971 pw.print(" state="); 3972 pw.print(state); 3973 if (isProcessStateForeground(state)) { 3974 pw.print(" [FG]"); 3975 } 3976 pw.print(" last FG="); 3977 pw.print(mUidLastForegroundElapsedTime.get(uid)); 3978 pw.println(); 3979 } 3980 } 3981 } 3982 formatTime(long time)3983 static String formatTime(long time) { 3984 return TimeMigrationUtils.formatMillisWithFixedFormat(time); 3985 } 3986 dumpCurrentTime(PrintWriter pw)3987 private void dumpCurrentTime(PrintWriter pw) { 3988 pw.print(formatTime(injectCurrentTimeMillis())); 3989 } 3990 3991 /** 3992 * Dumpsys for checkin. 3993 * 3994 * @param clear if true, clear the history information. Some other system services have this 3995 * behavior but shortcut service doesn't for now. 3996 */ dumpCheckin(PrintWriter pw, boolean clear)3997 private void dumpCheckin(PrintWriter pw, boolean clear) { 3998 synchronized (mLock) { 3999 try { 4000 final JSONArray users = new JSONArray(); 4001 4002 for (int i = 0; i < mUsers.size(); i++) { 4003 users.put(mUsers.valueAt(i).dumpCheckin(clear)); 4004 } 4005 4006 final JSONObject result = new JSONObject(); 4007 4008 result.put(KEY_SHORTCUT, users); 4009 result.put(KEY_LOW_RAM, injectIsLowRamDevice()); 4010 result.put(KEY_ICON_SIZE, mMaxIconDimension); 4011 4012 pw.println(result.toString(1)); 4013 } catch (JSONException e) { 4014 Slog.e(TAG, "Unable to write in json", e); 4015 } 4016 } 4017 } 4018 dumpDumpFiles(PrintWriter pw)4019 private void dumpDumpFiles(PrintWriter pw) { 4020 synchronized (mLock) { 4021 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)"); 4022 mShortcutDumpFiles.dumpAll(pw); 4023 } 4024 } 4025 4026 // === Shell support === 4027 4028 @Override onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)4029 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 4030 String[] args, ShellCallback callback, ResultReceiver resultReceiver) { 4031 4032 enforceShell(); 4033 4034 final long token = injectClearCallingIdentity(); 4035 try { 4036 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback, 4037 resultReceiver); 4038 resultReceiver.send(status, null); 4039 } finally { 4040 injectRestoreCallingIdentity(token); 4041 } 4042 } 4043 4044 static class CommandException extends Exception { CommandException(String message)4045 public CommandException(String message) { 4046 super(message); 4047 } 4048 } 4049 4050 /** 4051 * Handle "adb shell cmd". 4052 */ 4053 private class MyShellCommand extends ShellCommand { 4054 4055 private int mUserId = UserHandle.USER_SYSTEM; 4056 parseOptionsLocked(boolean takeUser)4057 private void parseOptionsLocked(boolean takeUser) 4058 throws CommandException { 4059 String opt; 4060 while ((opt = getNextOption()) != null) { 4061 switch (opt) { 4062 case "--user": 4063 if (takeUser) { 4064 mUserId = UserHandle.parseUserArg(getNextArgRequired()); 4065 if (!isUserUnlockedL(mUserId)) { 4066 throw new CommandException( 4067 "User " + mUserId + " is not running or locked"); 4068 } 4069 break; 4070 } 4071 // fallthrough 4072 default: 4073 throw new CommandException("Unknown option: " + opt); 4074 } 4075 } 4076 } 4077 4078 @Override onCommand(String cmd)4079 public int onCommand(String cmd) { 4080 if (cmd == null) { 4081 return handleDefaultCommands(cmd); 4082 } 4083 final PrintWriter pw = getOutPrintWriter(); 4084 try { 4085 switch (cmd) { 4086 case "reset-throttling": 4087 handleResetThrottling(); 4088 break; 4089 case "reset-all-throttling": 4090 handleResetAllThrottling(); 4091 break; 4092 case "override-config": 4093 handleOverrideConfig(); 4094 break; 4095 case "reset-config": 4096 handleResetConfig(); 4097 break; 4098 case "clear-default-launcher": 4099 handleClearDefaultLauncher(); 4100 break; 4101 case "get-default-launcher": 4102 handleGetDefaultLauncher(); 4103 break; 4104 case "unload-user": 4105 handleUnloadUser(); 4106 break; 4107 case "clear-shortcuts": 4108 handleClearShortcuts(); 4109 break; 4110 case "verify-states": // hidden command to verify various internal states. 4111 handleVerifyStates(); 4112 break; 4113 default: 4114 return handleDefaultCommands(cmd); 4115 } 4116 } catch (CommandException e) { 4117 pw.println("Error: " + e.getMessage()); 4118 return 1; 4119 } 4120 pw.println("Success"); 4121 return 0; 4122 } 4123 4124 @Override onHelp()4125 public void onHelp() { 4126 final PrintWriter pw = getOutPrintWriter(); 4127 pw.println("Usage: cmd shortcut COMMAND [options ...]"); 4128 pw.println(); 4129 pw.println("cmd shortcut reset-throttling [--user USER_ID]"); 4130 pw.println(" Reset throttling for all packages and users"); 4131 pw.println(); 4132 pw.println("cmd shortcut reset-all-throttling"); 4133 pw.println(" Reset the throttling state for all users"); 4134 pw.println(); 4135 pw.println("cmd shortcut override-config CONFIG"); 4136 pw.println(" Override the configuration for testing (will last until reboot)"); 4137 pw.println(); 4138 pw.println("cmd shortcut reset-config"); 4139 pw.println(" Reset the configuration set with \"update-config\""); 4140 pw.println(); 4141 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]"); 4142 pw.println(" Clear the cached default launcher"); 4143 pw.println(); 4144 pw.println("cmd shortcut get-default-launcher [--user USER_ID]"); 4145 pw.println(" Show the default launcher"); 4146 pw.println(); 4147 pw.println("cmd shortcut unload-user [--user USER_ID]"); 4148 pw.println(" Unload a user from the memory"); 4149 pw.println(" (This should not affect any observable behavior)"); 4150 pw.println(); 4151 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE"); 4152 pw.println(" Remove all shortcuts from a package, including pinned shortcuts"); 4153 pw.println(); 4154 } 4155 handleResetThrottling()4156 private void handleResetThrottling() throws CommandException { 4157 synchronized (mLock) { 4158 parseOptionsLocked(/* takeUser =*/ true); 4159 4160 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId); 4161 4162 resetThrottlingInner(mUserId); 4163 } 4164 } 4165 handleResetAllThrottling()4166 private void handleResetAllThrottling() { 4167 Slog.i(TAG, "cmd: handleResetAllThrottling"); 4168 4169 resetAllThrottlingInner(); 4170 } 4171 handleOverrideConfig()4172 private void handleOverrideConfig() throws CommandException { 4173 final String config = getNextArgRequired(); 4174 4175 Slog.i(TAG, "cmd: handleOverrideConfig: " + config); 4176 4177 synchronized (mLock) { 4178 if (!updateConfigurationLocked(config)) { 4179 throw new CommandException("override-config failed. See logcat for details."); 4180 } 4181 } 4182 } 4183 handleResetConfig()4184 private void handleResetConfig() { 4185 Slog.i(TAG, "cmd: handleResetConfig"); 4186 4187 synchronized (mLock) { 4188 loadConfigurationLocked(); 4189 } 4190 } 4191 clearLauncher()4192 private void clearLauncher() { 4193 synchronized (mLock) { 4194 getUserShortcutsLocked(mUserId).forceClearLauncher(); 4195 } 4196 } 4197 showLauncher()4198 private void showLauncher() { 4199 synchronized (mLock) { 4200 // This ensures to set the cached launcher. Package name doesn't matter. 4201 hasShortcutHostPermissionInner("-", mUserId); 4202 4203 getOutPrintWriter().println("Launcher: " 4204 + getUserShortcutsLocked(mUserId).getLastKnownLauncher()); 4205 } 4206 } 4207 handleClearDefaultLauncher()4208 private void handleClearDefaultLauncher() throws CommandException { 4209 synchronized (mLock) { 4210 parseOptionsLocked(/* takeUser =*/ true); 4211 4212 clearLauncher(); 4213 } 4214 } 4215 handleGetDefaultLauncher()4216 private void handleGetDefaultLauncher() throws CommandException { 4217 synchronized (mLock) { 4218 parseOptionsLocked(/* takeUser =*/ true); 4219 4220 clearLauncher(); 4221 showLauncher(); 4222 } 4223 } 4224 handleUnloadUser()4225 private void handleUnloadUser() throws CommandException { 4226 synchronized (mLock) { 4227 parseOptionsLocked(/* takeUser =*/ true); 4228 4229 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId); 4230 4231 ShortcutService.this.handleStopUser(mUserId); 4232 } 4233 } 4234 handleClearShortcuts()4235 private void handleClearShortcuts() throws CommandException { 4236 synchronized (mLock) { 4237 parseOptionsLocked(/* takeUser =*/ true); 4238 final String packageName = getNextArgRequired(); 4239 4240 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName); 4241 4242 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId, 4243 /* appStillExists = */ true); 4244 } 4245 } 4246 handleVerifyStates()4247 private void handleVerifyStates() throws CommandException { 4248 try { 4249 verifyStatesForce(); // This will throw when there's an issue. 4250 } catch (Throwable th) { 4251 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th)); 4252 } 4253 } 4254 } 4255 4256 // === Unit test support === 4257 4258 // Injection point. 4259 @VisibleForTesting injectCurrentTimeMillis()4260 long injectCurrentTimeMillis() { 4261 return System.currentTimeMillis(); 4262 } 4263 4264 @VisibleForTesting injectElapsedRealtime()4265 long injectElapsedRealtime() { 4266 return SystemClock.elapsedRealtime(); 4267 } 4268 4269 @VisibleForTesting injectUptimeMillis()4270 long injectUptimeMillis() { 4271 return SystemClock.uptimeMillis(); 4272 } 4273 4274 // Injection point. 4275 @VisibleForTesting injectBinderCallingUid()4276 int injectBinderCallingUid() { 4277 return getCallingUid(); 4278 } 4279 4280 @VisibleForTesting injectBinderCallingPid()4281 int injectBinderCallingPid() { 4282 return getCallingPid(); 4283 } 4284 getCallingUserId()4285 private int getCallingUserId() { 4286 return UserHandle.getUserId(injectBinderCallingUid()); 4287 } 4288 4289 // Injection point. 4290 @VisibleForTesting injectClearCallingIdentity()4291 long injectClearCallingIdentity() { 4292 return Binder.clearCallingIdentity(); 4293 } 4294 4295 // Injection point. 4296 @VisibleForTesting injectRestoreCallingIdentity(long token)4297 void injectRestoreCallingIdentity(long token) { 4298 Binder.restoreCallingIdentity(token); 4299 } 4300 4301 // Injection point. injectBuildFingerprint()4302 String injectBuildFingerprint() { 4303 return Build.FINGERPRINT; 4304 } 4305 wtf(String message)4306 final void wtf(String message) { 4307 wtf(message, /* exception= */ null); 4308 } 4309 4310 // Injection point. wtf(String message, Throwable e)4311 void wtf(String message, Throwable e) { 4312 if (e == null) { 4313 e = new RuntimeException("Stacktrace"); 4314 } 4315 synchronized (mLock) { 4316 mWtfCount++; 4317 mLastWtfStacktrace = new Exception("Last failure was logged here:"); 4318 } 4319 Slog.wtf(TAG, message, e); 4320 } 4321 4322 @VisibleForTesting injectSystemDataPath()4323 File injectSystemDataPath() { 4324 return Environment.getDataSystemDirectory(); 4325 } 4326 4327 @VisibleForTesting injectUserDataPath(@serIdInt int userId)4328 File injectUserDataPath(@UserIdInt int userId) { 4329 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER); 4330 } 4331 getDumpPath()4332 public File getDumpPath() { 4333 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP); 4334 } 4335 4336 @VisibleForTesting injectIsLowRamDevice()4337 boolean injectIsLowRamDevice() { 4338 return ActivityManager.isLowRamDeviceStatic(); 4339 } 4340 4341 @VisibleForTesting injectRegisterUidObserver(IUidObserver observer, int which)4342 void injectRegisterUidObserver(IUidObserver observer, int which) { 4343 try { 4344 ActivityManager.getService().registerUidObserver(observer, which, 4345 ActivityManager.PROCESS_STATE_UNKNOWN, null); 4346 } catch (RemoteException shouldntHappen) { 4347 } 4348 } 4349 getUserBitmapFilePath(@serIdInt int userId)4350 File getUserBitmapFilePath(@UserIdInt int userId) { 4351 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS); 4352 } 4353 4354 @VisibleForTesting getShortcutsForTest()4355 SparseArray<ShortcutUser> getShortcutsForTest() { 4356 return mUsers; 4357 } 4358 4359 @VisibleForTesting getMaxShortcutsForTest()4360 int getMaxShortcutsForTest() { 4361 return mMaxShortcuts; 4362 } 4363 4364 @VisibleForTesting getMaxUpdatesPerIntervalForTest()4365 int getMaxUpdatesPerIntervalForTest() { 4366 return mMaxUpdatesPerInterval; 4367 } 4368 4369 @VisibleForTesting getResetIntervalForTest()4370 long getResetIntervalForTest() { 4371 return mResetInterval; 4372 } 4373 4374 @VisibleForTesting getMaxIconDimensionForTest()4375 int getMaxIconDimensionForTest() { 4376 return mMaxIconDimension; 4377 } 4378 4379 @VisibleForTesting getIconPersistFormatForTest()4380 CompressFormat getIconPersistFormatForTest() { 4381 return mIconPersistFormat; 4382 } 4383 4384 @VisibleForTesting getIconPersistQualityForTest()4385 int getIconPersistQualityForTest() { 4386 return mIconPersistQuality; 4387 } 4388 4389 @VisibleForTesting getPackageShortcutForTest(String packageName, int userId)4390 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) { 4391 synchronized (mLock) { 4392 final ShortcutUser user = mUsers.get(userId); 4393 if (user == null) return null; 4394 4395 return user.getAllPackagesForTest().get(packageName); 4396 } 4397 } 4398 4399 @VisibleForTesting getPackageShortcutForTest(String packageName, String shortcutId, int userId)4400 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) { 4401 synchronized (mLock) { 4402 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId); 4403 if (pkg == null) return null; 4404 4405 return pkg.findShortcutById(shortcutId); 4406 } 4407 } 4408 4409 @VisibleForTesting getLauncherShortcutForTest(String packageName, int userId)4410 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) { 4411 synchronized (mLock) { 4412 final ShortcutUser user = mUsers.get(userId); 4413 if (user == null) return null; 4414 4415 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName)); 4416 } 4417 } 4418 4419 @VisibleForTesting getShortcutRequestPinProcessorForTest()4420 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() { 4421 return mShortcutRequestPinProcessor; 4422 } 4423 4424 /** 4425 * Control whether {@link #verifyStates} should be performed. We always perform it during unit 4426 * tests. 4427 */ 4428 @VisibleForTesting injectShouldPerformVerification()4429 boolean injectShouldPerformVerification() { 4430 return DEBUG; 4431 } 4432 4433 /** 4434 * Check various internal states and throws if there's any inconsistency. 4435 * This is normally only enabled during unit tests. 4436 */ verifyStates()4437 final void verifyStates() { 4438 if (injectShouldPerformVerification()) { 4439 verifyStatesInner(); 4440 } 4441 } 4442 verifyStatesForce()4443 private final void verifyStatesForce() { 4444 verifyStatesInner(); 4445 } 4446 verifyStatesInner()4447 private void verifyStatesInner() { 4448 synchronized (mLock) { 4449 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates)); 4450 } 4451 } 4452 4453 @VisibleForTesting waitForBitmapSavesForTest()4454 void waitForBitmapSavesForTest() { 4455 synchronized (mLock) { 4456 mShortcutBitmapSaver.waitForAllSavesLocked(); 4457 } 4458 } 4459 } 4460