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