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