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