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