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