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