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