ShortcutService.java revision 83fa7a82558a41a18d959c7b9fb197b787c52779
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            Preconditions.checkState(
1455                    injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1456                    "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1457                            + " main activity");
1458        }
1459
1460        if (!forUpdate) {
1461            shortcut.enforceMandatoryFields();
1462            Preconditions.checkArgument(
1463                    injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1464                    "Cannot publish shortcut: " + shortcut.getActivity() + " is not main activity");
1465        }
1466        if (shortcut.getIcon() != null) {
1467            ShortcutInfo.validateIcon(shortcut.getIcon());
1468        }
1469
1470        shortcut.replaceFlags(0);
1471    }
1472
1473    /**
1474     * When a shortcut has no target activity, set the default one from the package.
1475     */
1476    private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
1477
1478        ComponentName defaultActivity = null;
1479        for (int i = shortcuts.size() - 1; i >= 0; i--) {
1480            final ShortcutInfo si = shortcuts.get(i);
1481            if (si.getActivity() == null) {
1482                if (defaultActivity == null) {
1483                    defaultActivity = injectGetDefaultMainActivity(
1484                            si.getPackage(), si.getUserId());
1485                    Preconditions.checkState(defaultActivity != null,
1486                            "Launcher activity not found for package " + si.getPackage());
1487                }
1488                si.setActivity(defaultActivity);
1489            }
1490        }
1491    }
1492
1493    private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1494        for (int i = shortcuts.size() - 1; i >= 0; i--) {
1495            shortcuts.get(i).setImplicitRank(i);
1496        }
1497    }
1498
1499    // === APIs ===
1500
1501    @Override
1502    public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1503            @UserIdInt int userId) {
1504        verifyCaller(packageName, userId);
1505
1506        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1507        final int size = newShortcuts.size();
1508
1509        synchronized (mLock) {
1510            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1511            ps.getUser().onCalledByPublisher(packageName);
1512
1513            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1514
1515            fillInDefaultActivity(newShortcuts);
1516
1517            ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1518
1519            // Throttling.
1520            if (!ps.tryApiCall()) {
1521                return false;
1522            }
1523
1524            // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1525            ps.clearAllImplicitRanks();
1526            assignImplicitRanks(newShortcuts);
1527
1528            for (int i = 0; i < size; i++) {
1529                fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1530            }
1531
1532            // First, remove all un-pinned; dynamic shortcuts
1533            ps.deleteAllDynamicShortcuts();
1534
1535            // Then, add/update all.  We need to make sure to take over "pinned" flag.
1536            for (int i = 0; i < size; i++) {
1537                final ShortcutInfo newShortcut = newShortcuts.get(i);
1538                ps.addOrUpdateDynamicShortcut(newShortcut);
1539            }
1540
1541            // Lastly, adjust the ranks.
1542            ps.adjustRanks();
1543        }
1544        packageShortcutsChanged(packageName, userId);
1545
1546        verifyStates();
1547
1548        return true;
1549    }
1550
1551    @Override
1552    public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1553            @UserIdInt int userId) {
1554        verifyCaller(packageName, userId);
1555
1556        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1557        final int size = newShortcuts.size();
1558
1559        synchronized (mLock) {
1560            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1561            ps.getUser().onCalledByPublisher(packageName);
1562
1563            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1564
1565            // For update, don't fill in the default activity.  Having null activity means
1566            // "don't update the activity" here.
1567
1568            ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1569
1570            // Throttling.
1571            if (!ps.tryApiCall()) {
1572                return false;
1573            }
1574
1575            // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1576            ps.clearAllImplicitRanks();
1577            assignImplicitRanks(newShortcuts);
1578
1579            for (int i = 0; i < size; i++) {
1580                final ShortcutInfo source = newShortcuts.get(i);
1581                fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1582
1583                final ShortcutInfo target = ps.findShortcutById(source.getId());
1584                if (target == null) {
1585                    continue;
1586                }
1587
1588                if (target.isEnabled() != source.isEnabled()) {
1589                    Slog.w(TAG,
1590                            "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1591                }
1592
1593                // When updating the rank, we need to insert between existing ranks, so set
1594                // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1595                if (source.hasRank()) {
1596                    target.setRankChanged();
1597                    target.setImplicitRank(source.getImplicitRank());
1598                }
1599
1600                final boolean replacingIcon = (source.getIcon() != null);
1601                if (replacingIcon) {
1602                    removeIcon(userId, target);
1603                }
1604
1605                // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1606                target.copyNonNullFieldsFrom(source);
1607                target.setTimestamp(injectCurrentTimeMillis());
1608
1609                if (replacingIcon) {
1610                    saveIconAndFixUpShortcut(userId, target);
1611                }
1612
1613                // When we're updating any resource related fields, re-extract the res names and
1614                // the values.
1615                if (replacingIcon || source.hasStringResources()) {
1616                    fixUpShortcutResourceNamesAndValues(target);
1617                }
1618            }
1619
1620            // Lastly, adjust the ranks.
1621            ps.adjustRanks();
1622        }
1623        packageShortcutsChanged(packageName, userId);
1624
1625        verifyStates();
1626
1627        return true;
1628    }
1629
1630    @Override
1631    public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1632            @UserIdInt int userId) {
1633        verifyCaller(packageName, userId);
1634
1635        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1636        final int size = newShortcuts.size();
1637
1638        synchronized (mLock) {
1639            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1640            ps.getUser().onCalledByPublisher(packageName);
1641
1642            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1643
1644            fillInDefaultActivity(newShortcuts);
1645
1646            ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1647
1648            // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1649            ps.clearAllImplicitRanks();
1650            assignImplicitRanks(newShortcuts);
1651
1652            // Throttling.
1653            if (!ps.tryApiCall()) {
1654                return false;
1655            }
1656            for (int i = 0; i < size; i++) {
1657                final ShortcutInfo newShortcut = newShortcuts.get(i);
1658
1659                // Validate the shortcut.
1660                fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
1661
1662                // When ranks are changing, we need to insert between ranks, so set the
1663                // "rank changed" flag.
1664                newShortcut.setRankChanged();
1665
1666                // Add it.
1667                ps.addOrUpdateDynamicShortcut(newShortcut);
1668            }
1669
1670            // Lastly, adjust the ranks.
1671            ps.adjustRanks();
1672        }
1673        packageShortcutsChanged(packageName, userId);
1674
1675        verifyStates();
1676
1677        return true;
1678    }
1679
1680    @Override
1681    public void disableShortcuts(String packageName, List shortcutIds,
1682            CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
1683        verifyCaller(packageName, userId);
1684        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1685
1686        synchronized (mLock) {
1687            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1688            ps.getUser().onCalledByPublisher(packageName);
1689
1690            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1691
1692            final String disabledMessageString =
1693                    (disabledMessage == null) ? null : disabledMessage.toString();
1694
1695            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1696                ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
1697                        disabledMessageString, disabledMessageResId,
1698                        /* overrideImmutable=*/ false);
1699            }
1700
1701            // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1702            ps.adjustRanks();
1703        }
1704        packageShortcutsChanged(packageName, userId);
1705
1706        verifyStates();
1707    }
1708
1709    @Override
1710    public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1711        verifyCaller(packageName, userId);
1712        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1713
1714        synchronized (mLock) {
1715            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1716            ps.getUser().onCalledByPublisher(packageName);
1717
1718            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1719
1720            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1721                ps.enableWithId((String) shortcutIds.get(i));
1722            }
1723        }
1724        packageShortcutsChanged(packageName, userId);
1725
1726        verifyStates();
1727    }
1728
1729    @Override
1730    public void removeDynamicShortcuts(String packageName, List shortcutIds,
1731            @UserIdInt int userId) {
1732        verifyCaller(packageName, userId);
1733        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1734
1735        synchronized (mLock) {
1736            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1737            ps.getUser().onCalledByPublisher(packageName);
1738
1739            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1740
1741            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1742                ps.deleteDynamicWithId(
1743                        Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1744            }
1745
1746            // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1747            ps.adjustRanks();
1748        }
1749        packageShortcutsChanged(packageName, userId);
1750
1751        verifyStates();
1752    }
1753
1754    @Override
1755    public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
1756        verifyCaller(packageName, userId);
1757
1758        synchronized (mLock) {
1759            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1760            ps.getUser().onCalledByPublisher(packageName);
1761            ps.deleteAllDynamicShortcuts();
1762        }
1763        packageShortcutsChanged(packageName, userId);
1764
1765        verifyStates();
1766    }
1767
1768    @Override
1769    public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1770            @UserIdInt int userId) {
1771        verifyCaller(packageName, userId);
1772        synchronized (mLock) {
1773            return getShortcutsWithQueryLocked(
1774                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1775                    ShortcutInfo::isDynamic);
1776        }
1777    }
1778
1779    @Override
1780    public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
1781            @UserIdInt int userId) {
1782        verifyCaller(packageName, userId);
1783        synchronized (mLock) {
1784            return getShortcutsWithQueryLocked(
1785                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1786                    ShortcutInfo::isManifestShortcut);
1787        }
1788    }
1789
1790    @Override
1791    public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1792            @UserIdInt int userId) {
1793        verifyCaller(packageName, userId);
1794        synchronized (mLock) {
1795            return getShortcutsWithQueryLocked(
1796                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1797                    ShortcutInfo::isPinned);
1798        }
1799    }
1800
1801    private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1802            @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1803
1804        final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1805
1806        final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1807        ps.getUser().onCalledByPublisher(packageName);
1808        ps.findAll(ret, query, cloneFlags);
1809
1810        return new ParceledListSlice<>(ret);
1811    }
1812
1813    @Override
1814    public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
1815            throws RemoteException {
1816        verifyCaller(packageName, userId);
1817
1818        return mMaxShortcuts;
1819    }
1820
1821    @Override
1822    public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1823        verifyCaller(packageName, userId);
1824
1825        synchronized (mLock) {
1826            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1827            ps.getUser().onCalledByPublisher(packageName);
1828            return mMaxUpdatesPerInterval - ps.getApiCallCount();
1829        }
1830    }
1831
1832    @Override
1833    public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
1834        verifyCaller(packageName, userId);
1835
1836        synchronized (mLock) {
1837            return getNextResetTimeLocked();
1838        }
1839    }
1840
1841    @Override
1842    public int getIconMaxDimensions(String packageName, int userId) {
1843        verifyCaller(packageName, userId);
1844
1845        synchronized (mLock) {
1846            return mMaxIconDimension;
1847        }
1848    }
1849
1850    @Override
1851    public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
1852        verifyCaller(packageName, userId);
1853
1854        Preconditions.checkNotNull(shortcutId);
1855
1856        if (DEBUG) {
1857            Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
1858                    shortcutId, packageName, userId));
1859        }
1860
1861        synchronized (mLock) {
1862            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1863            ps.getUser().onCalledByPublisher(packageName);
1864
1865            if (ps.findShortcutById(shortcutId) == null) {
1866                Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
1867                        packageName, shortcutId));
1868                return;
1869            }
1870        }
1871
1872        final long token = injectClearCallingIdentity();
1873        try {
1874            mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
1875        } finally {
1876            injectRestoreCallingIdentity(token);
1877        }
1878    }
1879
1880    /**
1881     * Reset all throttling, for developer options and command line.  Only system/shell can call
1882     * it.
1883     */
1884    @Override
1885    public void resetThrottling() {
1886        enforceSystemOrShell();
1887
1888        resetThrottlingInner(getCallingUserId());
1889    }
1890
1891    void resetThrottlingInner(@UserIdInt int userId) {
1892        synchronized (mLock) {
1893            getUserShortcutsLocked(userId).resetThrottling();
1894        }
1895        scheduleSaveUser(userId);
1896        Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
1897    }
1898
1899    void resetAllThrottlingInner() {
1900        synchronized (mLock) {
1901            mRawLastResetTime = injectCurrentTimeMillis();
1902        }
1903        scheduleSaveBaseState();
1904        Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
1905    }
1906
1907    void resetPackageThrottling(String packageName, int userId) {
1908        synchronized (mLock) {
1909            getPackageShortcutsLocked(packageName, userId)
1910                    .resetRateLimitingForCommandLineNoSaving();
1911            saveUserLocked(userId);
1912        }
1913    }
1914
1915    @Override
1916    public void onApplicationActive(String packageName, int userId) {
1917        if (DEBUG) {
1918            Slog.d(TAG, "onApplicationActive: package=" + packageName + "  userid=" + userId);
1919        }
1920        enforceResetThrottlingPermission();
1921        resetPackageThrottling(packageName, userId);
1922    }
1923
1924    // We override this method in unit tests to do a simpler check.
1925    boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
1926        return hasShortcutHostPermissionInner(callingPackage, userId);
1927    }
1928
1929    // This method is extracted so we can directly call this method from unit tests,
1930    // even when hasShortcutPermission() is overridden.
1931    @VisibleForTesting
1932    boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
1933        synchronized (mLock) {
1934            final long start = injectElapsedRealtime();
1935
1936            final ShortcutUser user = getUserShortcutsLocked(userId);
1937
1938            final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
1939
1940            // Default launcher from package manager.
1941            final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
1942            final ComponentName defaultLauncher = injectPackageManagerInternal()
1943                    .getHomeActivitiesAsUser(allHomeCandidates, userId);
1944            logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
1945
1946            ComponentName detected;
1947            if (defaultLauncher != null) {
1948                detected = defaultLauncher;
1949                if (DEBUG) {
1950                    Slog.v(TAG, "Default launcher from PM: " + detected);
1951                }
1952            } else {
1953                detected = user.getDefaultLauncherComponent();
1954
1955                if (detected != null) {
1956                    if (injectIsActivityEnabledAndExported(detected, userId)) {
1957                        if (DEBUG) {
1958                            Slog.v(TAG, "Cached launcher: " + detected);
1959                        }
1960                    } else {
1961                        Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
1962                        detected = null;
1963                        user.setDefaultLauncherComponent(null);
1964                    }
1965                }
1966            }
1967
1968            if (detected == null) {
1969                // If we reach here, that means it's the first check since the user was created,
1970                // and there's already multiple launchers and there's no default set.
1971                // Find the system one with the highest priority.
1972                // (We need to check the priority too because of FallbackHome in Settings.)
1973                // If there's no system launcher yet, then no one can access shortcuts, until
1974                // the user explicitly
1975                final int size = allHomeCandidates.size();
1976
1977                int lastPriority = Integer.MIN_VALUE;
1978                for (int i = 0; i < size; i++) {
1979                    final ResolveInfo ri = allHomeCandidates.get(i);
1980                    if (!ri.activityInfo.applicationInfo.isSystemApp()) {
1981                        continue;
1982                    }
1983                    if (DEBUG) {
1984                        Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
1985                                ri.activityInfo.getComponentName(), ri.priority));
1986                    }
1987                    if (ri.priority < lastPriority) {
1988                        continue;
1989                    }
1990                    detected = ri.activityInfo.getComponentName();
1991                    lastPriority = ri.priority;
1992                }
1993            }
1994            logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
1995
1996            if (detected != null) {
1997                if (DEBUG) {
1998                    Slog.v(TAG, "Detected launcher: " + detected);
1999                }
2000                user.setDefaultLauncherComponent(detected);
2001                return detected.getPackageName().equals(callingPackage);
2002            } else {
2003                // Default launcher not found.
2004                return false;
2005            }
2006        }
2007    }
2008
2009    // === House keeping ===
2010
2011    private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2012            boolean appStillExists) {
2013        synchronized (mLock) {
2014            forEachLoadedUserLocked(user ->
2015                    cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2016                            appStillExists));
2017        }
2018    }
2019
2020    /**
2021     * Remove all the information associated with a package.  This will really remove all the
2022     * information, including the restore information (i.e. it'll remove packages even if they're
2023     * shadow).
2024     *
2025     * This is called when an app is uninstalled, or an app gets "clear data"ed.
2026     */
2027    @VisibleForTesting
2028    void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2029            boolean appStillExists) {
2030        final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
2031
2032        final ShortcutUser user = getUserShortcutsLocked(owningUserId);
2033        boolean doNotify = false;
2034
2035        // First, remove the package from the package list (if the package is a publisher).
2036        if (packageUserId == owningUserId) {
2037            if (user.removePackage(packageName) != null) {
2038                doNotify = true;
2039            }
2040        }
2041
2042        // Also remove from the launcher list (if the package is a launcher).
2043        user.removeLauncher(packageUserId, packageName);
2044
2045        // Then remove pinned shortcuts from all launchers.
2046        user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2047
2048        // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
2049        // step.  Remove them too.
2050        user.forAllPackages(p -> p.refreshPinnedFlags());
2051
2052        scheduleSaveUser(owningUserId);
2053
2054        if (doNotify) {
2055            notifyListeners(packageName, owningUserId);
2056        }
2057
2058        // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2059        if (appStillExists && (packageUserId == owningUserId)) {
2060            // This will do the notification and save when needed, so do it after the above
2061            // notifyListeners.
2062            user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2063        }
2064
2065        if (!wasUserLoaded) {
2066            // Note this will execute the scheduled save.
2067            unloadUserLocked(owningUserId);
2068        }
2069    }
2070
2071    /**
2072     * Entry point from {@link LauncherApps}.
2073     */
2074    private class LocalService extends ShortcutServiceInternal {
2075
2076        @Override
2077        public List<ShortcutInfo> getShortcuts(int launcherUserId,
2078                @NonNull String callingPackage, long changedSince,
2079                @Nullable String packageName, @Nullable List<String> shortcutIds,
2080                @Nullable ComponentName componentName,
2081                int queryFlags, int userId) {
2082            final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2083            final boolean cloneKeyFieldOnly =
2084                    ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2085            final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2086                    : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
2087            if (packageName == null) {
2088                shortcutIds = null; // LauncherAppsService already threw for it though.
2089            }
2090
2091            synchronized (mLock) {
2092                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2093                        .attemptToRestoreIfNeededAndSave();
2094
2095                if (packageName != null) {
2096                    getShortcutsInnerLocked(launcherUserId,
2097                            callingPackage, packageName, shortcutIds, changedSince,
2098                            componentName, queryFlags, userId, ret, cloneFlag);
2099                } else {
2100                    final List<String> shortcutIdsF = shortcutIds;
2101                    getUserShortcutsLocked(userId).forAllPackages(p -> {
2102                        getShortcutsInnerLocked(launcherUserId,
2103                                callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
2104                                componentName, queryFlags, userId, ret, cloneFlag);
2105                    });
2106                }
2107            }
2108            return ret;
2109        }
2110
2111        private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
2112                @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
2113                @Nullable ComponentName componentName, int queryFlags,
2114                int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
2115            final ArraySet<String> ids = shortcutIds == null ? null
2116                    : new ArraySet<>(shortcutIds);
2117
2118            final ShortcutPackage p = getUserShortcutsLocked(userId)
2119                    .getPackageShortcutsIfExists(packageName);
2120            if (p == null) {
2121                return; // No need to instantiate ShortcutPackage.
2122            }
2123
2124            p.findAll(ret,
2125                    (ShortcutInfo si) -> {
2126                        if (si.getLastChangedTimestamp() < changedSince) {
2127                            return false;
2128                        }
2129                        if (ids != null && !ids.contains(si.getId())) {
2130                            return false;
2131                        }
2132                        if (componentName != null) {
2133                            if (si.getActivity() != null
2134                                    && !si.getActivity().equals(componentName)) {
2135                                return false;
2136                            }
2137                        }
2138                        if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2139                                && si.isDynamic()) {
2140                            return true;
2141                        }
2142                        if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2143                                && si.isPinned()) {
2144                            return true;
2145                        }
2146                        if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2147                                && si.isManifestShortcut()) {
2148                            return true;
2149                        }
2150                        return false;
2151                    }, cloneFlag, callingPackage, launcherUserId);
2152        }
2153
2154        @Override
2155        public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2156                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2157            Preconditions.checkStringNotEmpty(packageName, "packageName");
2158            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2159
2160            synchronized (mLock) {
2161                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2162                        .attemptToRestoreIfNeededAndSave();
2163
2164                final ShortcutInfo si = getShortcutInfoLocked(
2165                        launcherUserId, callingPackage, packageName, shortcutId, userId);
2166                return si != null && si.isPinned();
2167            }
2168        }
2169
2170        private ShortcutInfo getShortcutInfoLocked(
2171                int launcherUserId, @NonNull String callingPackage,
2172                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2173            Preconditions.checkStringNotEmpty(packageName, "packageName");
2174            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2175
2176            final ShortcutPackage p = getUserShortcutsLocked(userId)
2177                    .getPackageShortcutsIfExists(packageName);
2178            if (p == null) {
2179                return null;
2180            }
2181
2182            final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
2183            p.findAll(list,
2184                    (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2185                    /* clone flags=*/ 0, callingPackage, launcherUserId);
2186            return list.size() == 0 ? null : list.get(0);
2187        }
2188
2189        @Override
2190        public void pinShortcuts(int launcherUserId,
2191                @NonNull String callingPackage, @NonNull String packageName,
2192                @NonNull List<String> shortcutIds, int userId) {
2193            // Calling permission must be checked by LauncherAppsImpl.
2194            Preconditions.checkStringNotEmpty(packageName, "packageName");
2195            Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2196
2197            synchronized (mLock) {
2198                final ShortcutLauncher launcher =
2199                        getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
2200                launcher.attemptToRestoreIfNeededAndSave();
2201
2202                launcher.pinShortcuts(userId, packageName, shortcutIds);
2203            }
2204            packageShortcutsChanged(packageName, userId);
2205
2206            verifyStates();
2207        }
2208
2209        @Override
2210        public Intent createShortcutIntent(int launcherUserId,
2211                @NonNull String callingPackage,
2212                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2213            // Calling permission must be checked by LauncherAppsImpl.
2214            Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2215            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
2216
2217            synchronized (mLock) {
2218                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2219                        .attemptToRestoreIfNeededAndSave();
2220
2221                // Make sure the shortcut is actually visible to the launcher.
2222                final ShortcutInfo si = getShortcutInfoLocked(
2223                        launcherUserId, callingPackage, packageName, shortcutId, userId);
2224                // "si == null" should suffice here, but check the flags too just to make sure.
2225                if (si == null || !si.isEnabled() || !si.isAlive()) {
2226                    Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
2227                    return null;
2228                }
2229                return si.getIntent();
2230            }
2231        }
2232
2233        @Override
2234        public void addListener(@NonNull ShortcutChangeListener listener) {
2235            synchronized (mLock) {
2236                mListeners.add(Preconditions.checkNotNull(listener));
2237            }
2238        }
2239
2240        @Override
2241        public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2242                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2243            Preconditions.checkNotNull(callingPackage, "callingPackage");
2244            Preconditions.checkNotNull(packageName, "packageName");
2245            Preconditions.checkNotNull(shortcutId, "shortcutId");
2246
2247            synchronized (mLock) {
2248                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2249                        .attemptToRestoreIfNeededAndSave();
2250
2251                final ShortcutPackage p = getUserShortcutsLocked(userId)
2252                        .getPackageShortcutsIfExists(packageName);
2253                if (p == null) {
2254                    return 0;
2255                }
2256
2257                final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
2258                return (shortcutInfo != null && shortcutInfo.hasIconResource())
2259                        ? shortcutInfo.getIconResourceId() : 0;
2260            }
2261        }
2262
2263        @Override
2264        public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
2265                @NonNull String callingPackage, @NonNull String packageName,
2266                @NonNull String shortcutId, int userId) {
2267            Preconditions.checkNotNull(callingPackage, "callingPackage");
2268            Preconditions.checkNotNull(packageName, "packageName");
2269            Preconditions.checkNotNull(shortcutId, "shortcutId");
2270
2271            synchronized (mLock) {
2272                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2273                        .attemptToRestoreIfNeededAndSave();
2274
2275                final ShortcutPackage p = getUserShortcutsLocked(userId)
2276                        .getPackageShortcutsIfExists(packageName);
2277                if (p == null) {
2278                    return null;
2279                }
2280
2281                final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
2282                if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2283                    return null;
2284                }
2285                try {
2286                    if (shortcutInfo.getBitmapPath() == null) {
2287                        Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2288                        return null;
2289                    }
2290                    return ParcelFileDescriptor.open(
2291                            new File(shortcutInfo.getBitmapPath()),
2292                            ParcelFileDescriptor.MODE_READ_ONLY);
2293                } catch (FileNotFoundException e) {
2294                    Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2295                    return null;
2296                }
2297            }
2298        }
2299
2300        @Override
2301        public boolean hasShortcutHostPermission(int launcherUserId,
2302                @NonNull String callingPackage) {
2303            return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
2304        }
2305    }
2306
2307    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
2308        @Override
2309        public void onReceive(Context context, Intent intent) {
2310            if (!mBootCompleted.get()) {
2311                return; // Boot not completed, ignore the broadcast.
2312            }
2313            if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2314                handleLocaleChanged();
2315            }
2316        }
2317    };
2318
2319    void handleLocaleChanged() {
2320        if (DEBUG) {
2321            Slog.d(TAG, "handleLocaleChanged");
2322        }
2323        scheduleSaveBaseState();
2324
2325        final long token = injectClearCallingIdentity();
2326        try {
2327            forEachLoadedUserLocked(user -> user.detectLocaleChange());
2328        } finally {
2329            injectRestoreCallingIdentity(token);
2330        }
2331    }
2332
2333    /**
2334     * Package event callbacks.
2335     */
2336    @VisibleForTesting
2337    final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
2338        @Override
2339        public void onReceive(Context context, Intent intent) {
2340            final int userId  = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2341            if (userId == UserHandle.USER_NULL) {
2342                Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2343                return;
2344            }
2345
2346            final String action = intent.getAction();
2347
2348            // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2349            // but we still check it in unit tests.
2350            final long token = injectClearCallingIdentity();
2351            try {
2352
2353                if (!mUserManager.isUserUnlocked(userId)) {
2354                    if (DEBUG) {
2355                        Slog.d(TAG, "Ignoring package broadcast " + action
2356                                + " for locked/stopped user " + userId);
2357                    }
2358                    return;
2359                }
2360
2361                final Uri intentUri = intent.getData();
2362                final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2363                        : null;
2364                if (packageName == null) {
2365                    Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2366                    return;
2367                }
2368
2369                final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2370
2371                switch (action) {
2372                    case Intent.ACTION_PACKAGE_ADDED:
2373                        if (replacing) {
2374                            handlePackageUpdateFinished(packageName, userId);
2375                        } else {
2376                            handlePackageAdded(packageName, userId);
2377                        }
2378                        break;
2379                    case Intent.ACTION_PACKAGE_REMOVED:
2380                        if (!replacing) {
2381                            handlePackageRemoved(packageName, userId);
2382                        }
2383                        break;
2384                    case Intent.ACTION_PACKAGE_CHANGED:
2385                        handlePackageChanged(packageName, userId);
2386
2387                        break;
2388                    case Intent.ACTION_PACKAGE_DATA_CLEARED:
2389                        handlePackageDataCleared(packageName, userId);
2390                        break;
2391                }
2392            } finally {
2393                injectRestoreCallingIdentity(token);
2394            }
2395        }
2396    };
2397
2398    /**
2399     * Called when a user is unlocked.
2400     * - Check all known packages still exist, and otherwise perform cleanup.
2401     * - If a package still exists, check the version code.  If it's been updated, may need to
2402     * update timestamps of its shortcuts.
2403     */
2404    @VisibleForTesting
2405    void checkPackageChanges(@UserIdInt int ownerUserId) {
2406        if (DEBUG) {
2407            Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
2408        }
2409        if (injectIsSafeModeEnabled()) {
2410            Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2411            return;
2412        }
2413
2414        final long start = injectElapsedRealtime();
2415        try {
2416            final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
2417
2418            synchronized (mLock) {
2419                final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2420
2421                // Find packages that have been uninstalled.
2422                user.forAllPackageItems(spi -> {
2423                    if (spi.getPackageInfo().isShadow()) {
2424                        return; // Don't delete shadow information.
2425                    }
2426                    if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
2427                        if (DEBUG) {
2428                            Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2429                                    + " user " + spi.getPackageUserId());
2430                        }
2431                        gonePackages.add(PackageWithUser.of(spi));
2432                    }
2433                });
2434                if (gonePackages.size() > 0) {
2435                    for (int i = gonePackages.size() - 1; i >= 0; i--) {
2436                        final PackageWithUser pu = gonePackages.get(i);
2437                        cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2438                                /* appStillExists = */ false);
2439                    }
2440                }
2441                final long now = injectCurrentTimeMillis();
2442
2443                // Then for each installed app, publish manifest shortcuts when needed.
2444                forUpdatedPackages(ownerUserId, user.getLastAppScanTime(), ai -> {
2445                    user.rescanPackageIfNeeded(ai.packageName, /* forceRescan=*/ false);
2446                });
2447
2448                // Write the time just before the scan, because there may be apps that have just
2449                // been updated, and we want to catch them in the next time.
2450                user.setLastAppScanTime(now);
2451                scheduleSaveUser(ownerUserId);
2452            }
2453        } finally {
2454            logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
2455        }
2456        verifyStates();
2457    }
2458
2459    private void handlePackageAdded(String packageName, @UserIdInt int userId) {
2460        if (DEBUG) {
2461            Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2462        }
2463        synchronized (mLock) {
2464            final ShortcutUser user = getUserShortcutsLocked(userId);
2465            user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
2466            user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ false);
2467        }
2468        verifyStates();
2469    }
2470
2471    private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
2472        if (DEBUG) {
2473            Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2474                    packageName, userId));
2475        }
2476        synchronized (mLock) {
2477            final ShortcutUser user = getUserShortcutsLocked(userId);
2478            user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
2479
2480            if (isPackageInstalled(packageName, userId)) {
2481                user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ false);
2482            }
2483        }
2484        verifyStates();
2485    }
2486
2487    private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
2488        if (DEBUG) {
2489            Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2490                    packageUserId));
2491        }
2492        cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
2493
2494        verifyStates();
2495    }
2496
2497    private void handlePackageDataCleared(String packageName, int packageUserId) {
2498        if (DEBUG) {
2499            Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2500                    packageUserId));
2501        }
2502        cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2503
2504        verifyStates();
2505    }
2506
2507    private void handlePackageChanged(String packageName, int packageUserId) {
2508        if (DEBUG) {
2509            Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2510                    packageUserId));
2511        }
2512
2513        // Activities may be disabled or enabled.  Just rescan the package.
2514        synchronized (mLock) {
2515            final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2516
2517            user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2518        }
2519
2520        verifyStates();
2521    }
2522
2523    // === PackageManager interaction ===
2524
2525    /**
2526     * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2527     */
2528    @Nullable
2529    final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2530        return getPackageInfo(packageName, userId, true);
2531    }
2532
2533    /**
2534     * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2535     */
2536    @Nullable
2537    final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2538        return getPackageInfo(packageName, userId, false);
2539    }
2540
2541    int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
2542        final long token = injectClearCallingIdentity();
2543        try {
2544            return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
2545        } catch (RemoteException e) {
2546            // Shouldn't happen.
2547            Slog.wtf(TAG, "RemoteException", e);
2548            return -1;
2549        } finally {
2550            injectRestoreCallingIdentity(token);
2551        }
2552    }
2553
2554    /**
2555     * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2556     */
2557    @Nullable
2558    @VisibleForTesting
2559    final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2560            boolean getSignatures) {
2561        return isInstalledOrNull(injectPackageInfoWithUninstalled(
2562                packageName, userId, getSignatures));
2563    }
2564
2565    /**
2566     * Do not use directly; this returns uninstalled packages too.
2567     */
2568    @Nullable
2569    @VisibleForTesting
2570    PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
2571            boolean getSignatures) {
2572        final long start = injectElapsedRealtime();
2573        final long token = injectClearCallingIdentity();
2574        try {
2575            return mIPackageManager.getPackageInfo(
2576                    packageName, PACKAGE_MATCH_FLAGS
2577                            | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
2578        } catch (RemoteException e) {
2579            // Shouldn't happen.
2580            Slog.wtf(TAG, "RemoteException", e);
2581            return null;
2582        } finally {
2583            injectRestoreCallingIdentity(token);
2584
2585            logDurationStat(
2586                    (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2587                    start);
2588        }
2589    }
2590
2591    /**
2592     * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2593     */
2594    @Nullable
2595    @VisibleForTesting
2596    final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2597        return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2598    }
2599
2600    /**
2601     * Do not use directly; this returns uninstalled packages too.
2602     */
2603    @Nullable
2604    @VisibleForTesting
2605    ApplicationInfo injectApplicationInfoWithUninstalled(
2606            String packageName, @UserIdInt int userId) {
2607        final long start = injectElapsedRealtime();
2608        final long token = injectClearCallingIdentity();
2609        try {
2610            return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2611        } catch (RemoteException e) {
2612            // Shouldn't happen.
2613            Slog.wtf(TAG, "RemoteException", e);
2614            return null;
2615        } finally {
2616            injectRestoreCallingIdentity(token);
2617
2618            logDurationStat(Stats.GET_APPLICATION_INFO, start);
2619        }
2620    }
2621
2622    /**
2623     * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2624     */
2625    @Nullable
2626    final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2627        return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2628                activity, userId));
2629    }
2630
2631    /**
2632     * Do not use directly; this returns uninstalled packages too.
2633     */
2634    @Nullable
2635    @VisibleForTesting
2636    ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2637            ComponentName activity, @UserIdInt int userId) {
2638        final long start = injectElapsedRealtime();
2639        final long token = injectClearCallingIdentity();
2640        try {
2641            return mIPackageManager.getActivityInfo(activity,
2642                    (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
2643        } catch (RemoteException e) {
2644            // Shouldn't happen.
2645            Slog.wtf(TAG, "RemoteException", e);
2646            return null;
2647        } finally {
2648            injectRestoreCallingIdentity(token);
2649
2650            logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
2651        }
2652    }
2653
2654    /**
2655     * Return all installed and enabled packages.
2656     */
2657    @NonNull
2658    @VisibleForTesting
2659    final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
2660        final long start = injectElapsedRealtime();
2661        final long token = injectClearCallingIdentity();
2662        try {
2663            final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
2664
2665            all.removeIf(PACKAGE_NOT_INSTALLED);
2666
2667            return all;
2668        } catch (RemoteException e) {
2669            // Shouldn't happen.
2670            Slog.wtf(TAG, "RemoteException", e);
2671            return null;
2672        } finally {
2673            injectRestoreCallingIdentity(token);
2674
2675            logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
2676        }
2677    }
2678
2679    /**
2680     * Do not use directly; this returns uninstalled packages too.
2681     */
2682    @NonNull
2683    @VisibleForTesting
2684    List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
2685            throws RemoteException {
2686        final ParceledListSlice<PackageInfo> parceledList =
2687                mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
2688        if (parceledList == null) {
2689            return Collections.emptyList();
2690        }
2691        return parceledList.getList();
2692    }
2693
2694    private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime,
2695            Consumer<ApplicationInfo> callback) {
2696        if (DEBUG) {
2697            Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime);
2698        }
2699        final List<PackageInfo> list = getInstalledPackages(userId);
2700        for (int i = list.size() - 1; i >= 0; i--) {
2701            final PackageInfo pi = list.get(i);
2702
2703            if (pi.lastUpdateTime >= lastScanTime) {
2704                if (DEBUG) {
2705                    Slog.d(TAG, "Found updated package " + pi.packageName);
2706                }
2707                callback.accept(pi.applicationInfo);
2708            }
2709        }
2710    }
2711
2712    private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
2713        final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
2714        return (ai != null) && ((ai.flags & flags) == flags);
2715    }
2716
2717    private static boolean isInstalled(@Nullable ApplicationInfo ai) {
2718        return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
2719    }
2720
2721    private static boolean isInstalled(@Nullable PackageInfo pi) {
2722        return (pi != null) && isInstalled(pi.applicationInfo);
2723    }
2724
2725    private static boolean isInstalled(@Nullable ActivityInfo ai) {
2726        return (ai != null) && isInstalled(ai.applicationInfo);
2727    }
2728
2729    private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
2730        return isInstalled(ai) ? ai : null;
2731    }
2732
2733    private static PackageInfo isInstalledOrNull(PackageInfo pi) {
2734        return isInstalled(pi) ? pi : null;
2735    }
2736
2737    private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
2738        return isInstalled(ai) ? ai : null;
2739    }
2740
2741    boolean isPackageInstalled(String packageName, int userId) {
2742        return getApplicationInfo(packageName, userId) != null;
2743    }
2744
2745    @Nullable
2746    XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
2747        return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
2748    }
2749
2750    @Nullable
2751    Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
2752        final long start = injectElapsedRealtime();
2753        final long token = injectClearCallingIdentity();
2754        try {
2755            return mContext.getPackageManager().getResourcesForApplicationAsUser(
2756                    packageName, userId);
2757        } catch (NameNotFoundException e) {
2758            Slog.e(TAG, "Resources for package " + packageName + " not found");
2759            return null;
2760        } finally {
2761            injectRestoreCallingIdentity(token);
2762
2763            logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
2764        }
2765    }
2766
2767    private Intent getMainActivityIntent() {
2768        final Intent intent = new Intent(Intent.ACTION_MAIN);
2769        intent.addCategory(LAUNCHER_INTENT_CATEGORY);
2770        return intent;
2771    }
2772
2773    /**
2774     * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
2775     * and only returns exported activities.
2776     */
2777    @NonNull
2778    @VisibleForTesting
2779    List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
2780            @NonNull String packageName, @Nullable ComponentName activity, int userId) {
2781
2782        baseIntent.setPackage(Preconditions.checkNotNull(packageName));
2783        if (activity != null) {
2784            baseIntent.setComponent(activity);
2785        }
2786
2787        final List<ResolveInfo> resolved =
2788                mContext.getPackageManager().queryIntentActivitiesAsUser(
2789                        baseIntent, PACKAGE_MATCH_FLAGS, userId);
2790        if (resolved == null || resolved.size() == 0) {
2791            return EMPTY_RESOLVE_INFO;
2792        }
2793        // Make sure the package is installed.
2794        if (!isInstalled(resolved.get(0).activityInfo)) {
2795            return EMPTY_RESOLVE_INFO;
2796        }
2797        resolved.removeIf(ACTIVITY_NOT_EXPORTED);
2798        return resolved;
2799    }
2800
2801    /**
2802     * Return the main activity that is enabled and exported.  If multiple activities are found,
2803     * return the first one.
2804     */
2805    @Nullable
2806    ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
2807        final long start = injectElapsedRealtime();
2808        final long token = injectClearCallingIdentity();
2809        try {
2810            final List<ResolveInfo> resolved =
2811                    queryActivities(getMainActivityIntent(), packageName, null, userId);
2812            return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
2813        } finally {
2814            injectRestoreCallingIdentity(token);
2815
2816            logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
2817        }
2818    }
2819
2820    /**
2821     * Return whether an activity is enabled, exported and main.
2822     */
2823    boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
2824        final long start = injectElapsedRealtime();
2825        final long token = injectClearCallingIdentity();
2826        try {
2827            final List<ResolveInfo> resolved =
2828                    queryActivities(getMainActivityIntent(), activity.getPackageName(),
2829                            activity, userId);
2830            return resolved.size() > 0;
2831        } finally {
2832            injectRestoreCallingIdentity(token);
2833
2834            logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
2835        }
2836    }
2837
2838    /**
2839     * Return all the enabled, exported and main activities from a package.
2840     */
2841    @NonNull
2842    List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
2843        final long start = injectElapsedRealtime();
2844        final long token = injectClearCallingIdentity();
2845        try {
2846            return queryActivities(getMainActivityIntent(), packageName, null, userId);
2847        } finally {
2848            injectRestoreCallingIdentity(token);
2849
2850            logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
2851        }
2852    }
2853
2854    /**
2855     * Return whether an activity is enabled and exported.
2856     */
2857    @VisibleForTesting
2858    boolean injectIsActivityEnabledAndExported(
2859            @NonNull ComponentName activity, @UserIdInt int userId) {
2860        final long start = injectElapsedRealtime();
2861        final long token = injectClearCallingIdentity();
2862        try {
2863            return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
2864                    .size() > 0;
2865        } finally {
2866            injectRestoreCallingIdentity(token);
2867
2868            logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
2869        }
2870    }
2871
2872    boolean injectIsSafeModeEnabled() {
2873        final long token = injectClearCallingIdentity();
2874        try {
2875            return IWindowManager.Stub
2876                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
2877                    .isSafeModeEnabled();
2878        } catch (RemoteException e) {
2879            return false; // Shouldn't happen though.
2880        } finally {
2881            injectRestoreCallingIdentity(token);
2882        }
2883    }
2884
2885    // === Backup & restore ===
2886
2887    boolean shouldBackupApp(String packageName, int userId) {
2888        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
2889    }
2890
2891    boolean shouldBackupApp(PackageInfo pi) {
2892        return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
2893    }
2894
2895    @Override
2896    public byte[] getBackupPayload(@UserIdInt int userId) {
2897        enforceSystem();
2898        if (DEBUG) {
2899            Slog.d(TAG, "Backing up user " + userId);
2900        }
2901        synchronized (mLock) {
2902            final ShortcutUser user = getUserShortcutsLocked(userId);
2903            if (user == null) {
2904                Slog.w(TAG, "Can't backup: user not found: id=" + userId);
2905                return null;
2906            }
2907
2908            user.forAllPackageItems(spi -> spi.refreshPackageInfoAndSave());
2909
2910            // Then save.
2911            final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
2912            try {
2913                saveUserInternalLocked(userId, os, /* forBackup */ true);
2914            } catch (XmlPullParserException | IOException e) {
2915                // Shouldn't happen.
2916                Slog.w(TAG, "Backup failed.", e);
2917                return null;
2918            }
2919            return os.toByteArray();
2920        }
2921    }
2922
2923    @Override
2924    public void applyRestore(byte[] payload, @UserIdInt int userId) {
2925        enforceSystem();
2926        if (DEBUG) {
2927            Slog.d(TAG, "Restoring user " + userId);
2928        }
2929        final ShortcutUser user;
2930        final ByteArrayInputStream is = new ByteArrayInputStream(payload);
2931        try {
2932            user = loadUserInternal(userId, is, /* fromBackup */ true);
2933        } catch (XmlPullParserException | IOException e) {
2934            Slog.w(TAG, "Restoration failed.", e);
2935            return;
2936        }
2937        synchronized (mLock) {
2938            mUsers.put(userId, user);
2939
2940            // Then purge all the save images.
2941            final File bitmapPath = getUserBitmapFilePath(userId);
2942            final boolean success = FileUtils.deleteContents(bitmapPath);
2943            if (!success) {
2944                Slog.w(TAG, "Failed to delete " + bitmapPath);
2945            }
2946
2947            saveUserLocked(userId);
2948        }
2949    }
2950
2951    // === Dump ===
2952
2953    @Override
2954    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2955        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2956                != PackageManager.PERMISSION_GRANTED) {
2957            pw.println("Permission Denial: can't dump UserManager from from pid="
2958                    + Binder.getCallingPid()
2959                    + ", uid=" + Binder.getCallingUid()
2960                    + " without permission "
2961                    + android.Manifest.permission.DUMP);
2962            return;
2963        }
2964        dumpInner(pw, args);
2965    }
2966
2967    @VisibleForTesting
2968    void dumpInner(PrintWriter pw, String[] args) {
2969        synchronized (mLock) {
2970            final long now = injectCurrentTimeMillis();
2971            pw.print("Now: [");
2972            pw.print(now);
2973            pw.print("] ");
2974            pw.print(formatTime(now));
2975
2976            pw.print("  Raw last reset: [");
2977            pw.print(mRawLastResetTime);
2978            pw.print("] ");
2979            pw.print(formatTime(mRawLastResetTime));
2980
2981            final long last = getLastResetTimeLocked();
2982            pw.print("  Last reset: [");
2983            pw.print(last);
2984            pw.print("] ");
2985            pw.print(formatTime(last));
2986
2987            final long next = getNextResetTimeLocked();
2988            pw.print("  Next reset: [");
2989            pw.print(next);
2990            pw.print("] ");
2991            pw.print(formatTime(next));
2992
2993            pw.print("  Config:");
2994            pw.print("    Max icon dim: ");
2995            pw.println(mMaxIconDimension);
2996            pw.print("    Icon format: ");
2997            pw.println(mIconPersistFormat);
2998            pw.print("    Icon quality: ");
2999            pw.println(mIconPersistQuality);
3000            pw.print("    saveDelayMillis: ");
3001            pw.println(mSaveDelayMillis);
3002            pw.print("    resetInterval: ");
3003            pw.println(mResetInterval);
3004            pw.print("    maxUpdatesPerInterval: ");
3005            pw.println(mMaxUpdatesPerInterval);
3006            pw.print("    maxShortcutsPerActivity: ");
3007            pw.println(mMaxShortcuts);
3008            pw.println();
3009
3010            pw.println("  Stats:");
3011            synchronized (mStatLock) {
3012                final String p = "    ";
3013                dumpStatLS(pw, p, Stats.GET_DEFAULT_HOME, "getHomeActivities()");
3014                dumpStatLS(pw, p, Stats.LAUNCHER_PERMISSION_CHECK, "Launcher permission check");
3015
3016                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO, "getPackageInfo()");
3017                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO_WITH_SIG, "getPackageInfo(SIG)");
3018                dumpStatLS(pw, p, Stats.GET_APPLICATION_INFO, "getApplicationInfo");
3019                dumpStatLS(pw, p, Stats.CLEANUP_DANGLING_BITMAPS, "cleanupDanglingBitmaps");
3020                dumpStatLS(pw, p, Stats.GET_ACTIVITY_WITH_METADATA, "getActivity+metadata");
3021                dumpStatLS(pw, p, Stats.GET_INSTALLED_PACKAGES, "getInstalledPackages");
3022                dumpStatLS(pw, p, Stats.CHECK_PACKAGE_CHANGES, "checkPackageChanges");
3023                dumpStatLS(pw, p, Stats.GET_APPLICATION_RESOURCES, "getApplicationResources");
3024                dumpStatLS(pw, p, Stats.RESOURCE_NAME_LOOKUP, "resourceNameLookup");
3025                dumpStatLS(pw, p, Stats.GET_LAUNCHER_ACTIVITY, "getLauncherActivity");
3026                dumpStatLS(pw, p, Stats.CHECK_LAUNCHER_ACTIVITY, "checkLauncherActivity");
3027                dumpStatLS(pw, p, Stats.IS_ACTIVITY_ENABLED, "isActivityEnabled");
3028                dumpStatLS(pw, p, Stats.PACKAGE_UPDATE_CHECK, "packageUpdateCheck");
3029            }
3030
3031            pw.println();
3032            pw.print("  #Failures: ");
3033            pw.println(mWtfCount);
3034
3035            if (mLastWtfStacktrace != null) {
3036                pw.print("  Last failure stack trace: ");
3037                pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3038            }
3039
3040            for (int i = 0; i < mUsers.size(); i++) {
3041                pw.println();
3042                mUsers.valueAt(i).dump(pw, "  ");
3043            }
3044
3045            pw.println();
3046            pw.println("  UID state:");
3047
3048            for (int i = 0; i < mUidState.size(); i++) {
3049                final int uid = mUidState.keyAt(i);
3050                final int state = mUidState.valueAt(i);
3051                pw.print("    UID=");
3052                pw.print(uid);
3053                pw.print(" state=");
3054                pw.print(state);
3055                if (isProcessStateForeground(state)) {
3056                    pw.print("  [FG]");
3057                }
3058                pw.print("  last FG=");
3059                pw.print(mUidLastForegroundElapsedTime.get(uid));
3060                pw.println();
3061            }
3062        }
3063    }
3064
3065    static String formatTime(long time) {
3066        Time tobj = new Time();
3067        tobj.set(time);
3068        return tobj.format("%Y-%m-%d %H:%M:%S");
3069    }
3070
3071    private void dumpStatLS(PrintWriter pw, String prefix, int statId, String label) {
3072        pw.print(prefix);
3073        final int count = mCountStats[statId];
3074        final long dur = mDurationStats[statId];
3075        pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
3076                label, count, dur,
3077                (count == 0 ? 0 : ((double) dur) / count)));
3078    }
3079
3080    // === Shell support ===
3081
3082    @Override
3083    public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
3084            String[] args, ResultReceiver resultReceiver) throws RemoteException {
3085
3086        enforceShell();
3087
3088        final int status = (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
3089
3090        resultReceiver.send(status, null);
3091    }
3092
3093    static class CommandException extends Exception {
3094        public CommandException(String message) {
3095            super(message);
3096        }
3097    }
3098
3099    /**
3100     * Handle "adb shell cmd".
3101     */
3102    private class MyShellCommand extends ShellCommand {
3103
3104        private int mUserId = UserHandle.USER_SYSTEM;
3105
3106        private void parseOptions(boolean takeUser)
3107                throws CommandException {
3108            String opt;
3109            while ((opt = getNextOption()) != null) {
3110                switch (opt) {
3111                    case "--user":
3112                        if (takeUser) {
3113                            mUserId = UserHandle.parseUserArg(getNextArgRequired());
3114                            if (!mUserManager.isUserUnlocked(mUserId)) {
3115                                throw new CommandException(
3116                                        "User " + mUserId + " is not running or locked");
3117                            }
3118                            break;
3119                        }
3120                        // fallthrough
3121                    default:
3122                        throw new CommandException("Unknown option: " + opt);
3123                }
3124            }
3125        }
3126
3127        @Override
3128        public int onCommand(String cmd) {
3129            if (cmd == null) {
3130                return handleDefaultCommands(cmd);
3131            }
3132            final PrintWriter pw = getOutPrintWriter();
3133            try {
3134                switch (cmd) {
3135                    case "reset-package-throttling":
3136                        handleResetPackageThrottling();
3137                        break;
3138                    case "reset-throttling":
3139                        handleResetThrottling();
3140                        break;
3141                    case "reset-all-throttling":
3142                        handleResetAllThrottling();
3143                        break;
3144                    case "override-config":
3145                        handleOverrideConfig();
3146                        break;
3147                    case "reset-config":
3148                        handleResetConfig();
3149                        break;
3150                    case "clear-default-launcher":
3151                        handleClearDefaultLauncher();
3152                        break;
3153                    case "get-default-launcher":
3154                        handleGetDefaultLauncher();
3155                        break;
3156                    case "refresh-default-launcher":
3157                        handleRefreshDefaultLauncher();
3158                        break;
3159                    case "unload-user":
3160                        handleUnloadUser();
3161                        break;
3162                    case "clear-shortcuts":
3163                        handleClearShortcuts();
3164                        break;
3165                    case "verify-states": // hidden command to verify various internal states.
3166                        handleVerifyStates();
3167                        break;
3168                    default:
3169                        return handleDefaultCommands(cmd);
3170                }
3171            } catch (CommandException e) {
3172                pw.println("Error: " + e.getMessage());
3173                return 1;
3174            }
3175            pw.println("Success");
3176            return 0;
3177        }
3178
3179        @Override
3180        public void onHelp() {
3181            final PrintWriter pw = getOutPrintWriter();
3182            pw.println("Usage: cmd shortcut COMMAND [options ...]");
3183            pw.println();
3184            pw.println("cmd shortcut reset-package-throttling [--user USER_ID] PACKAGE");
3185            pw.println("    Reset throttling for a package");
3186            pw.println();
3187            pw.println("cmd shortcut reset-throttling [--user USER_ID]");
3188            pw.println("    Reset throttling for all packages and users");
3189            pw.println();
3190            pw.println("cmd shortcut reset-all-throttling");
3191            pw.println("    Reset the throttling state for all users");
3192            pw.println();
3193            pw.println("cmd shortcut override-config CONFIG");
3194            pw.println("    Override the configuration for testing (will last until reboot)");
3195            pw.println();
3196            pw.println("cmd shortcut reset-config");
3197            pw.println("    Reset the configuration set with \"update-config\"");
3198            pw.println();
3199            pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3200            pw.println("    Clear the cached default launcher");
3201            pw.println();
3202            pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
3203            pw.println("    Show the cached default launcher");
3204            pw.println();
3205            pw.println("cmd shortcut refresh-default-launcher [--user USER_ID]");
3206            pw.println("    Refresh the cached default launcher");
3207            pw.println();
3208            pw.println("cmd shortcut unload-user [--user USER_ID]");
3209            pw.println("    Unload a user from the memory");
3210            pw.println("    (This should not affect any observable behavior)");
3211            pw.println();
3212            pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3213            pw.println("    Remove all shortcuts from a package, including pinned shortcuts");
3214            pw.println();
3215        }
3216
3217        private void handleResetThrottling() throws CommandException {
3218            parseOptions(/* takeUser =*/ true);
3219
3220            Slog.i(TAG, "cmd: handleResetThrottling");
3221
3222            resetThrottlingInner(mUserId);
3223        }
3224
3225        private void handleResetAllThrottling() {
3226            Slog.i(TAG, "cmd: handleResetAllThrottling");
3227
3228            resetAllThrottlingInner();
3229        }
3230
3231        private void handleResetPackageThrottling() throws CommandException {
3232            parseOptions(/* takeUser =*/ true);
3233
3234            final String packageName = getNextArgRequired();
3235
3236            Slog.i(TAG, "cmd: handleResetPackageThrottling: " + packageName);
3237
3238            resetPackageThrottling(packageName, mUserId);
3239        }
3240
3241        private void handleOverrideConfig() throws CommandException {
3242            final String config = getNextArgRequired();
3243
3244            Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3245
3246            synchronized (mLock) {
3247                if (!updateConfigurationLocked(config)) {
3248                    throw new CommandException("override-config failed.  See logcat for details.");
3249                }
3250            }
3251        }
3252
3253        private void handleResetConfig() {
3254            Slog.i(TAG, "cmd: handleResetConfig");
3255
3256            synchronized (mLock) {
3257                loadConfigurationLocked();
3258            }
3259        }
3260
3261        private void clearLauncher() {
3262            synchronized (mLock) {
3263                getUserShortcutsLocked(mUserId).setDefaultLauncherComponent(null);
3264            }
3265        }
3266
3267        private void showLauncher() {
3268            synchronized (mLock) {
3269                // This ensures to set the cached launcher.  Package name doesn't matter.
3270                hasShortcutHostPermissionInner("-", mUserId);
3271
3272                getOutPrintWriter().println("Launcher: "
3273                        + getUserShortcutsLocked(mUserId).getDefaultLauncherComponent());
3274            }
3275        }
3276
3277        private void handleClearDefaultLauncher() throws CommandException {
3278            parseOptions(/* takeUser =*/ true);
3279
3280            clearLauncher();
3281        }
3282
3283        private void handleGetDefaultLauncher() throws CommandException {
3284            parseOptions(/* takeUser =*/ true);
3285
3286            showLauncher();
3287        }
3288
3289        private void handleRefreshDefaultLauncher() throws CommandException {
3290            parseOptions(/* takeUser =*/ true);
3291
3292            clearLauncher();
3293            showLauncher();
3294        }
3295
3296        private void handleUnloadUser() throws CommandException {
3297            parseOptions(/* takeUser =*/ true);
3298
3299            Slog.i(TAG, "cmd: handleUnloadUser: " + mUserId);
3300
3301            ShortcutService.this.handleCleanupUser(mUserId);
3302        }
3303
3304        private void handleClearShortcuts() throws CommandException {
3305            parseOptions(/* takeUser =*/ true);
3306            final String packageName = getNextArgRequired();
3307
3308            Slog.i(TAG, "cmd: handleClearShortcuts: " + mUserId + ", " + packageName);
3309
3310            ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3311                    /* appStillExists = */ true);
3312        }
3313
3314        private void handleVerifyStates() throws CommandException {
3315            try {
3316                verifyStatesForce(); // This will throw when there's an issue.
3317            } catch (Throwable th) {
3318                throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3319            }
3320        }
3321    }
3322
3323    // === Unit test support ===
3324
3325    // Injection point.
3326    @VisibleForTesting
3327    long injectCurrentTimeMillis() {
3328        return System.currentTimeMillis();
3329    }
3330
3331    @VisibleForTesting
3332    long injectElapsedRealtime() {
3333        return SystemClock.elapsedRealtime();
3334    }
3335
3336    // Injection point.
3337    @VisibleForTesting
3338    int injectBinderCallingUid() {
3339        return getCallingUid();
3340    }
3341
3342    private int getCallingUserId() {
3343        return UserHandle.getUserId(injectBinderCallingUid());
3344    }
3345
3346    // Injection point.
3347    @VisibleForTesting
3348    long injectClearCallingIdentity() {
3349        return Binder.clearCallingIdentity();
3350    }
3351
3352    // Injection point.
3353    @VisibleForTesting
3354    void injectRestoreCallingIdentity(long token) {
3355        Binder.restoreCallingIdentity(token);
3356    }
3357
3358    final void wtf(String message) {
3359        wtf(message, /* exception= */ null);
3360    }
3361
3362    // Injection point.
3363    void wtf(String message, Throwable e) {
3364        if (e == null) {
3365            e = new RuntimeException("Stacktrace");
3366        }
3367        synchronized (mLock) {
3368            mWtfCount++;
3369            mLastWtfStacktrace = new Exception("Last failure was logged here:");
3370        }
3371        Slog.wtf(TAG, message, e);
3372    }
3373
3374    @VisibleForTesting
3375    File injectSystemDataPath() {
3376        return Environment.getDataSystemDirectory();
3377    }
3378
3379    @VisibleForTesting
3380    File injectUserDataPath(@UserIdInt int userId) {
3381        return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3382    }
3383
3384    @VisibleForTesting
3385    boolean injectIsLowRamDevice() {
3386        return ActivityManager.isLowRamDeviceStatic();
3387    }
3388
3389    @VisibleForTesting
3390    void injectRegisterUidObserver(IUidObserver observer, int which) {
3391        try {
3392            ActivityManagerNative.getDefault().registerUidObserver(observer, which);
3393        } catch (RemoteException shouldntHappen) {
3394        }
3395    }
3396
3397    @VisibleForTesting
3398    PackageManagerInternal injectPackageManagerInternal() {
3399        return mPackageManagerInternal;
3400    }
3401
3402    File getUserBitmapFilePath(@UserIdInt int userId) {
3403        return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
3404    }
3405
3406    @VisibleForTesting
3407    SparseArray<ShortcutUser> getShortcutsForTest() {
3408        return mUsers;
3409    }
3410
3411    @VisibleForTesting
3412    int getMaxShortcutsForTest() {
3413        return mMaxShortcuts;
3414    }
3415
3416    @VisibleForTesting
3417    int getMaxUpdatesPerIntervalForTest() {
3418        return mMaxUpdatesPerInterval;
3419    }
3420
3421    @VisibleForTesting
3422    long getResetIntervalForTest() {
3423        return mResetInterval;
3424    }
3425
3426    @VisibleForTesting
3427    int getMaxIconDimensionForTest() {
3428        return mMaxIconDimension;
3429    }
3430
3431    @VisibleForTesting
3432    CompressFormat getIconPersistFormatForTest() {
3433        return mIconPersistFormat;
3434    }
3435
3436    @VisibleForTesting
3437    int getIconPersistQualityForTest() {
3438        return mIconPersistQuality;
3439    }
3440
3441    @VisibleForTesting
3442    ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
3443        synchronized (mLock) {
3444            final ShortcutUser user = mUsers.get(userId);
3445            if (user == null) return null;
3446
3447            return user.getAllPackagesForTest().get(packageName);
3448        }
3449    }
3450
3451    @VisibleForTesting
3452    ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3453        synchronized (mLock) {
3454            final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
3455            if (pkg == null) return null;
3456
3457            return pkg.findShortcutById(shortcutId);
3458        }
3459    }
3460
3461    /**
3462     * Control whether {@link #verifyStates} should be performed.  We always perform it during unit
3463     * tests.
3464     */
3465    @VisibleForTesting
3466    boolean injectShouldPerformVerification() {
3467        return DEBUG;
3468    }
3469
3470    /**
3471     * Check various internal states and throws if there's any inconsistency.
3472     * This is normally only enabled during unit tests.
3473     */
3474    final void verifyStates() {
3475        if (injectShouldPerformVerification()) {
3476            verifyStatesInner();
3477        }
3478    }
3479
3480    private final void verifyStatesForce() {
3481        verifyStatesInner();
3482    }
3483
3484    private void verifyStatesInner() {
3485        synchronized (this) {
3486            forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3487        }
3488    }
3489}
3490