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