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