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