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