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