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