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