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