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