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