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