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