ShortcutService.java revision 85694526039fb0a80ab74b2dc3ab17bacc1a4a59
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.NonNull;
19import android.annotation.Nullable;
20import android.annotation.UserIdInt;
21import android.app.ActivityManager;
22import android.app.ActivityManagerNative;
23import android.app.AppGlobals;
24import android.app.IUidObserver;
25import android.content.ComponentName;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.IPackageManager;
30import android.content.pm.IShortcutService;
31import android.content.pm.LauncherApps;
32import android.content.pm.LauncherApps.ShortcutQuery;
33import android.content.pm.PackageInfo;
34import android.content.pm.PackageManager;
35import android.content.pm.PackageManagerInternal;
36import android.content.pm.ParceledListSlice;
37import android.content.pm.ResolveInfo;
38import android.content.pm.ShortcutInfo;
39import android.content.pm.ShortcutServiceInternal;
40import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
41import android.graphics.Bitmap;
42import android.graphics.Bitmap.CompressFormat;
43import android.graphics.Canvas;
44import android.graphics.RectF;
45import android.graphics.drawable.Icon;
46import android.os.Binder;
47import android.os.Environment;
48import android.os.FileUtils;
49import android.os.Handler;
50import android.os.Looper;
51import android.os.ParcelFileDescriptor;
52import android.os.PersistableBundle;
53import android.os.Process;
54import android.os.RemoteException;
55import android.os.ResultReceiver;
56import android.os.SELinux;
57import android.os.ShellCommand;
58import android.os.SystemClock;
59import android.os.UserHandle;
60import android.os.UserManager;
61import android.text.TextUtils;
62import android.text.format.Time;
63import android.util.ArraySet;
64import android.util.AtomicFile;
65import android.util.KeyValueListParser;
66import android.util.Slog;
67import android.util.SparseArray;
68import android.util.SparseIntArray;
69import android.util.SparseLongArray;
70import android.util.TypedValue;
71import android.util.Xml;
72
73import com.android.internal.annotations.GuardedBy;
74import com.android.internal.annotations.VisibleForTesting;
75import com.android.internal.content.PackageMonitor;
76import com.android.internal.os.BackgroundThread;
77import com.android.internal.util.ArrayUtils;
78import com.android.internal.util.FastXmlSerializer;
79import com.android.internal.util.Preconditions;
80import com.android.server.LocalServices;
81import com.android.server.SystemService;
82import com.android.server.pm.ShortcutUser.PackageWithUser;
83
84import libcore.io.IoUtils;
85
86import org.xmlpull.v1.XmlPullParser;
87import org.xmlpull.v1.XmlPullParserException;
88import org.xmlpull.v1.XmlSerializer;
89
90import java.io.BufferedInputStream;
91import java.io.BufferedOutputStream;
92import java.io.ByteArrayInputStream;
93import java.io.ByteArrayOutputStream;
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.IOException;
100import java.io.InputStream;
101import java.io.OutputStream;
102import java.io.PrintWriter;
103import java.net.URISyntaxException;
104import java.nio.charset.StandardCharsets;
105import java.util.ArrayList;
106import java.util.List;
107import java.util.concurrent.atomic.AtomicLong;
108import java.util.function.Consumer;
109import java.util.function.Predicate;
110
111/**
112 * TODO:
113 *
114 * - Default launcher check does take a few ms.  Worth caching.
115 *
116 * - Clear data -> remove all dynamic?  but not the pinned?
117 *
118 * - Scan and remove orphan bitmaps (just in case).
119 *
120 * - Detect when already registered instances are passed to APIs again, which might break
121 *   internal bitmap handling.
122 *
123 * - Add more call stats.
124 */
125public class ShortcutService extends IShortcutService.Stub {
126    static final String TAG = "ShortcutService";
127
128    static final boolean DEBUG = false; // STOPSHIP if true
129    static final boolean DEBUG_LOAD = false; // STOPSHIP if true
130    static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
131
132    @VisibleForTesting
133    static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
134
135    @VisibleForTesting
136    static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
137
138    @VisibleForTesting
139    static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
140
141    @VisibleForTesting
142    static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
143
144    @VisibleForTesting
145    static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
146
147    @VisibleForTesting
148    static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
149
150    @VisibleForTesting
151    static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
152
153    @VisibleForTesting
154    static final int DEFAULT_SAVE_DELAY_MS = 3000;
155
156    @VisibleForTesting
157    static final String FILENAME_BASE_STATE = "shortcut_service.xml";
158
159    @VisibleForTesting
160    static final String DIRECTORY_PER_USER = "shortcut_service";
161
162    @VisibleForTesting
163    static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
164
165    static final String DIRECTORY_BITMAPS = "bitmaps";
166
167    private static final String TAG_ROOT = "root";
168    private static final String TAG_LAST_RESET_TIME = "last_reset_time";
169    private static final String TAG_LOCALE_CHANGE_SEQUENCE_NUMBER = "locale_seq_no";
170
171    private static final String ATTR_VALUE = "value";
172
173    @VisibleForTesting
174    interface ConfigConstants {
175        /**
176         * Key name for the save delay, in milliseconds. (int)
177         */
178        String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
179
180        /**
181         * Key name for the throttling reset interval, in seconds. (long)
182         */
183        String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
184
185        /**
186         * Key name for the max number of modifying API calls per app for every interval. (int)
187         */
188        String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
189
190        /**
191         * Key name for the max icon dimensions in DP, for non-low-memory devices.
192         */
193        String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
194
195        /**
196         * Key name for the max icon dimensions in DP, for low-memory devices.
197         */
198        String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
199
200        /**
201         * Key name for the max dynamic shortcuts per app. (int)
202         */
203        String KEY_MAX_SHORTCUTS = "max_shortcuts";
204
205        /**
206         * Key name for icon compression quality, 0-100.
207         */
208        String KEY_ICON_QUALITY = "icon_quality";
209
210        /**
211         * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
212         */
213        String KEY_ICON_FORMAT = "icon_format";
214    }
215
216    final Context mContext;
217
218    private final Object mLock = new Object();
219
220    private final Handler mHandler;
221
222    @GuardedBy("mLock")
223    private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
224
225    @GuardedBy("mLock")
226    private long mRawLastResetTime;
227
228    /**
229     * User ID -> UserShortcuts
230     */
231    @GuardedBy("mLock")
232    private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
233
234    /**
235     * Max number of dynamic shortcuts that each application can have at a time.
236     */
237    private int mMaxDynamicShortcuts;
238
239    /**
240     * Max number of updating API calls that each application can make during the interval.
241     */
242    int mMaxUpdatesPerInterval;
243
244    /**
245     * Actual throttling-reset interval.  By default it's a day.
246     */
247    private long mResetInterval;
248
249    /**
250     * Icon max width/height in pixels.
251     */
252    private int mMaxIconDimension;
253
254    private CompressFormat mIconPersistFormat;
255    private int mIconPersistQuality;
256
257    private int mSaveDelayMillis;
258
259    private final IPackageManager mIPackageManager;
260    private final PackageManagerInternal mPackageManagerInternal;
261    private final UserManager mUserManager;
262
263    @GuardedBy("mLock")
264    final SparseIntArray mUidState = new SparseIntArray();
265
266    @GuardedBy("mLock")
267    final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
268
269    @GuardedBy("mLock")
270    private List<Integer> mDirtyUserIds = new ArrayList<>();
271
272    /**
273     * A counter that increments every time the system locale changes.  We keep track of it to reset
274     * throttling counters on the first call from each package after the last locale change.
275     *
276     * We need this mechanism because we can't do much in the locale change callback, which is
277     * {@link ShortcutServiceInternal#onSystemLocaleChangedNoLock()}.
278     */
279    private final AtomicLong mLocaleChangeSequenceNumber = new AtomicLong();
280
281    private static final int PACKAGE_MATCH_FLAGS =
282            PackageManager.MATCH_DIRECT_BOOT_AWARE
283            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
284            | PackageManager.MATCH_UNINSTALLED_PACKAGES;
285
286    // Stats
287    @VisibleForTesting
288    interface Stats {
289        int GET_DEFAULT_HOME = 0;
290        int GET_PACKAGE_INFO = 1;
291        int GET_PACKAGE_INFO_WITH_SIG = 2;
292        int GET_APPLICATION_INFO = 3;
293        int LAUNCHER_PERMISSION_CHECK = 4;
294
295        int COUNT = LAUNCHER_PERMISSION_CHECK + 1;
296    }
297
298    final Object mStatLock = new Object();
299
300    @GuardedBy("mStatLock")
301    private final int[] mCountStats = new int[Stats.COUNT];
302
303    @GuardedBy("mStatLock")
304    private final long[] mDurationStats = new long[Stats.COUNT];
305
306    private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
307            ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
308
309    public ShortcutService(Context context) {
310        this(context, BackgroundThread.get().getLooper());
311    }
312
313    @VisibleForTesting
314    ShortcutService(Context context, Looper looper) {
315        mContext = Preconditions.checkNotNull(context);
316        LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
317        mHandler = new Handler(looper);
318        mIPackageManager = AppGlobals.getPackageManager();
319        mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
320        mUserManager = context.getSystemService(UserManager.class);
321
322        mPackageMonitor.register(context, looper, UserHandle.ALL, /* externalStorage= */ false);
323
324        injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
325                | ActivityManager.UID_OBSERVER_GONE);
326    }
327
328    void logDurationStat(int statId, long start) {
329        synchronized (mStatLock) {
330            mCountStats[statId]++;
331            mDurationStats[statId] += (System.currentTimeMillis() - start);
332        }
333    }
334
335    public long getLocaleChangeSequenceNumber() {
336        return mLocaleChangeSequenceNumber.get();
337    }
338
339    final private IUidObserver mUidObserver = new IUidObserver.Stub() {
340        @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
341            handleOnUidStateChanged(uid, procState);
342        }
343
344        @Override public void onUidGone(int uid) throws RemoteException {
345            handleOnUidStateChanged(uid, ActivityManager.MAX_PROCESS_STATE);
346        }
347
348        @Override public void onUidActive(int uid) throws RemoteException {
349        }
350
351        @Override public void onUidIdle(int uid) throws RemoteException {
352        }
353    };
354
355    void handleOnUidStateChanged(int uid, int procState) {
356        if (DEBUG_PROCSTATE) {
357            Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
358        }
359        synchronized (mLock) {
360            mUidState.put(uid, procState);
361
362            // We need to keep track of last time an app comes to foreground.
363            // See ShortcutPackage.getApiCallCount() for how it's used.
364            // It doesn't have to be persisted, but it needs to be the elapsed time.
365            if (isProcessStateForeground(procState)) {
366                mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
367            }
368        }
369    }
370
371    private boolean isProcessStateForeground(int processState) {
372        return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
373    }
374
375    boolean isUidForegroundLocked(int uid) {
376        if (uid == Process.SYSTEM_UID) {
377            // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
378            // so it's foreground anyway.
379            return true;
380        }
381        return isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE));
382    }
383
384    long getUidLastForegroundElapsedTimeLocked(int uid) {
385        return mUidLastForegroundElapsedTime.get(uid);
386    }
387
388    /**
389     * System service lifecycle.
390     */
391    public static final class Lifecycle extends SystemService {
392        final ShortcutService mService;
393
394        public Lifecycle(Context context) {
395            super(context);
396            mService = new ShortcutService(context);
397        }
398
399        @Override
400        public void onStart() {
401            publishBinderService(Context.SHORTCUT_SERVICE, mService);
402        }
403
404        @Override
405        public void onBootPhase(int phase) {
406            mService.onBootPhase(phase);
407        }
408
409        @Override
410        public void onCleanupUser(int userHandle) {
411            mService.handleCleanupUser(userHandle);
412        }
413
414        @Override
415        public void onUnlockUser(int userId) {
416            mService.handleUnlockUser(userId);
417        }
418    }
419
420    /** lifecycle event */
421    void onBootPhase(int phase) {
422        if (DEBUG) {
423            Slog.d(TAG, "onBootPhase: " + phase);
424        }
425        switch (phase) {
426            case SystemService.PHASE_LOCK_SETTINGS_READY:
427                initialize();
428                break;
429        }
430    }
431
432    /** lifecycle event */
433    void handleUnlockUser(int userId) {
434        synchronized (mLock) {
435            // Preload
436            getUserShortcutsLocked(userId);
437
438            checkPackageChanges(userId);
439        }
440    }
441
442    /** lifecycle event */
443    void handleCleanupUser(int userId) {
444        synchronized (mLock) {
445            unloadUserLocked(userId);
446        }
447    }
448
449    private void unloadUserLocked(int userId) {
450        if (DEBUG) {
451            Slog.d(TAG, "unloadUserLocked: user=" + userId);
452        }
453        // Save all dirty information.
454        saveDirtyInfo();
455
456        // Unload
457        mUsers.delete(userId);
458    }
459
460    /** Return the base state file name */
461    private AtomicFile getBaseStateFile() {
462        final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
463        path.mkdirs();
464        return new AtomicFile(path);
465    }
466
467    /**
468     * Init the instance. (load the state file, etc)
469     */
470    private void initialize() {
471        synchronized (mLock) {
472            loadConfigurationLocked();
473            loadBaseStateLocked();
474        }
475    }
476
477    /**
478     * Load the configuration from Settings.
479     */
480    private void loadConfigurationLocked() {
481        updateConfigurationLocked(injectShortcutManagerConstants());
482    }
483
484    /**
485     * Load the configuration from Settings.
486     */
487    @VisibleForTesting
488    boolean updateConfigurationLocked(String config) {
489        boolean result = true;
490
491        final KeyValueListParser parser = new KeyValueListParser(',');
492        try {
493            parser.setString(config);
494        } catch (IllegalArgumentException e) {
495            // Failed to parse the settings string, log this and move on
496            // with defaults.
497            Slog.e(TAG, "Bad shortcut manager settings", e);
498            result = false;
499        }
500
501        mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
502                DEFAULT_SAVE_DELAY_MS));
503
504        mResetInterval = Math.max(1, parser.getLong(
505                ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
506                * 1000L);
507
508        mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
509                ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
510
511        mMaxDynamicShortcuts = Math.max(0, (int) parser.getLong(
512                ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
513
514        final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
515                ? (int) parser.getLong(
516                    ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
517                    DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
518                : (int) parser.getLong(
519                    ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
520                    DEFAULT_MAX_ICON_DIMENSION_DP));
521
522        mMaxIconDimension = injectDipToPixel(iconDimensionDp);
523
524        mIconPersistFormat = CompressFormat.valueOf(
525                parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
526
527        mIconPersistQuality = (int) parser.getLong(
528                ConfigConstants.KEY_ICON_QUALITY,
529                DEFAULT_ICON_PERSIST_QUALITY);
530
531        return result;
532    }
533
534    @VisibleForTesting
535    String injectShortcutManagerConstants() {
536        return android.provider.Settings.Global.getString(
537                mContext.getContentResolver(),
538                android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
539    }
540
541    @VisibleForTesting
542    int injectDipToPixel(int dip) {
543        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
544                mContext.getResources().getDisplayMetrics());
545    }
546
547    // === Persisting ===
548
549    @Nullable
550    static String parseStringAttribute(XmlPullParser parser, String attribute) {
551        return parser.getAttributeValue(null, attribute);
552    }
553
554    static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
555        return parseLongAttribute(parser, attribute) == 1;
556    }
557
558    static int parseIntAttribute(XmlPullParser parser, String attribute) {
559        return (int) parseLongAttribute(parser, attribute);
560    }
561
562    static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
563        return (int) parseLongAttribute(parser, attribute, def);
564    }
565
566    static long parseLongAttribute(XmlPullParser parser, String attribute) {
567        return parseLongAttribute(parser, attribute, 0);
568    }
569
570    static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
571        final String value = parseStringAttribute(parser, attribute);
572        if (TextUtils.isEmpty(value)) {
573            return def;
574        }
575        try {
576            return Long.parseLong(value);
577        } catch (NumberFormatException e) {
578            Slog.e(TAG, "Error parsing long " + value);
579            return def;
580        }
581    }
582
583    @Nullable
584    static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
585        final String value = parseStringAttribute(parser, attribute);
586        if (TextUtils.isEmpty(value)) {
587            return null;
588        }
589        return ComponentName.unflattenFromString(value);
590    }
591
592    @Nullable
593    static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
594        final String value = parseStringAttribute(parser, attribute);
595        if (TextUtils.isEmpty(value)) {
596            return null;
597        }
598        try {
599            return Intent.parseUri(value, /* flags =*/ 0);
600        } catch (URISyntaxException e) {
601            Slog.e(TAG, "Error parsing intent", e);
602            return null;
603        }
604    }
605
606    static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
607        if (TextUtils.isEmpty(value)) return;
608
609        out.startTag(null, tag);
610        out.attribute(null, ATTR_VALUE, value);
611        out.endTag(null, tag);
612    }
613
614    static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
615        writeTagValue(out, tag, Long.toString(value));
616    }
617
618    static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
619        if (name == null) return;
620        writeTagValue(out, tag, name.flattenToString());
621    }
622
623    static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
624            throws IOException, XmlPullParserException {
625        if (bundle == null) return;
626
627        out.startTag(null, tag);
628        bundle.saveToXml(out);
629        out.endTag(null, tag);
630    }
631
632    static void writeAttr(XmlSerializer out, String name, String value) throws IOException {
633        if (TextUtils.isEmpty(value)) return;
634
635        out.attribute(null, name, value);
636    }
637
638    static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
639        writeAttr(out, name, String.valueOf(value));
640    }
641
642    static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
643        if (value) {
644            writeAttr(out, name, "1");
645        }
646    }
647
648    static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
649        if (comp == null) return;
650        writeAttr(out, name, comp.flattenToString());
651    }
652
653    static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
654        if (intent == null) return;
655
656        writeAttr(out, name, intent.toUri(/* flags =*/ 0));
657    }
658
659    @VisibleForTesting
660    void saveBaseStateLocked() {
661        final AtomicFile file = getBaseStateFile();
662        if (DEBUG) {
663            Slog.d(TAG, "Saving to " + file.getBaseFile());
664        }
665
666        FileOutputStream outs = null;
667        try {
668            outs = file.startWrite();
669
670            // Write to XML
671            XmlSerializer out = new FastXmlSerializer();
672            out.setOutput(outs, StandardCharsets.UTF_8.name());
673            out.startDocument(null, true);
674            out.startTag(null, TAG_ROOT);
675
676            // Body.
677            writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
678            writeTagValue(out, TAG_LOCALE_CHANGE_SEQUENCE_NUMBER,
679                    mLocaleChangeSequenceNumber.get());
680
681            // Epilogue.
682            out.endTag(null, TAG_ROOT);
683            out.endDocument();
684
685            // Close.
686            file.finishWrite(outs);
687        } catch (IOException e) {
688            Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
689            file.failWrite(outs);
690        }
691    }
692
693    private void loadBaseStateLocked() {
694        mRawLastResetTime = 0;
695
696        final AtomicFile file = getBaseStateFile();
697        if (DEBUG) {
698            Slog.d(TAG, "Loading from " + file.getBaseFile());
699        }
700        try (FileInputStream in = file.openRead()) {
701            XmlPullParser parser = Xml.newPullParser();
702            parser.setInput(in, StandardCharsets.UTF_8.name());
703
704            int type;
705            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
706                if (type != XmlPullParser.START_TAG) {
707                    continue;
708                }
709                final int depth = parser.getDepth();
710                // Check the root tag
711                final String tag = parser.getName();
712                if (depth == 1) {
713                    if (!TAG_ROOT.equals(tag)) {
714                        Slog.e(TAG, "Invalid root tag: " + tag);
715                        return;
716                    }
717                    continue;
718                }
719                // Assume depth == 2
720                switch (tag) {
721                    case TAG_LAST_RESET_TIME:
722                        mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
723                        break;
724                    case TAG_LOCALE_CHANGE_SEQUENCE_NUMBER:
725                        mLocaleChangeSequenceNumber.set(parseLongAttribute(parser, ATTR_VALUE));
726                        break;
727                    default:
728                        Slog.e(TAG, "Invalid tag: " + tag);
729                        break;
730                }
731            }
732        } catch (FileNotFoundException e) {
733            // Use the default
734        } catch (IOException|XmlPullParserException e) {
735            Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
736
737            mRawLastResetTime = 0;
738        }
739        // Adjust the last reset time.
740        getLastResetTimeLocked();
741    }
742
743    private void saveUserLocked(@UserIdInt int userId) {
744        final File path = new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
745        if (DEBUG) {
746            Slog.d(TAG, "Saving to " + path);
747        }
748        path.mkdirs();
749        final AtomicFile file = new AtomicFile(path);
750        FileOutputStream os = null;
751        try {
752            os = file.startWrite();
753
754            saveUserInternalLocked(userId, os, /* forBackup= */ false);
755
756            file.finishWrite(os);
757        } catch (XmlPullParserException|IOException e) {
758            Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
759            file.failWrite(os);
760        }
761    }
762
763    private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
764            boolean forBackup) throws IOException, XmlPullParserException {
765
766        final BufferedOutputStream bos = new BufferedOutputStream(os);
767
768        // Write to XML
769        XmlSerializer out = new FastXmlSerializer();
770        out.setOutput(bos, StandardCharsets.UTF_8.name());
771        out.startDocument(null, true);
772
773        getUserShortcutsLocked(userId).saveToXml(this, out, forBackup);
774
775        out.endDocument();
776
777        bos.flush();
778        os.flush();
779    }
780
781    static IOException throwForInvalidTag(int depth, String tag) throws IOException {
782        throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
783    }
784
785    static void warnForInvalidTag(int depth, String tag) throws IOException {
786        Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
787    }
788
789    @Nullable
790    private ShortcutUser loadUserLocked(@UserIdInt int userId) {
791        final File path = new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
792        if (DEBUG) {
793            Slog.d(TAG, "Loading from " + path);
794        }
795        final AtomicFile file = new AtomicFile(path);
796
797        final FileInputStream in;
798        try {
799            in = file.openRead();
800        } catch (FileNotFoundException e) {
801            if (DEBUG) {
802                Slog.d(TAG, "Not found " + path);
803            }
804            return null;
805        }
806        try {
807            return loadUserInternal(userId, in, /* forBackup= */ false);
808        } catch (IOException|XmlPullParserException e) {
809            Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
810            return null;
811        } finally {
812            IoUtils.closeQuietly(in);
813        }
814    }
815
816    private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
817            boolean fromBackup) throws XmlPullParserException, IOException {
818
819        final BufferedInputStream bis = new BufferedInputStream(is);
820
821        ShortcutUser ret = null;
822        XmlPullParser parser = Xml.newPullParser();
823        parser.setInput(bis, StandardCharsets.UTF_8.name());
824
825        int type;
826        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
827            if (type != XmlPullParser.START_TAG) {
828                continue;
829            }
830            final int depth = parser.getDepth();
831
832            final String tag = parser.getName();
833            if (DEBUG_LOAD) {
834                Slog.d(TAG, String.format("depth=%d type=%d name=%s",
835                        depth, type, tag));
836            }
837            if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
838                ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
839                continue;
840            }
841            throwForInvalidTag(depth, tag);
842        }
843        return ret;
844    }
845
846    private void scheduleSaveBaseState() {
847        scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
848    }
849
850    void scheduleSaveUser(@UserIdInt int userId) {
851        scheduleSaveInner(userId);
852    }
853
854    // In order to re-schedule, we need to reuse the same instance, so keep it in final.
855    private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
856
857    private void scheduleSaveInner(@UserIdInt int userId) {
858        if (DEBUG) {
859            Slog.d(TAG, "Scheduling to save for " + userId);
860        }
861        synchronized (mLock) {
862            if (!mDirtyUserIds.contains(userId)) {
863                mDirtyUserIds.add(userId);
864            }
865        }
866        // If already scheduled, remove that and re-schedule in N seconds.
867        mHandler.removeCallbacks(mSaveDirtyInfoRunner);
868        mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
869    }
870
871    @VisibleForTesting
872    void saveDirtyInfo() {
873        if (DEBUG) {
874            Slog.d(TAG, "saveDirtyInfo");
875        }
876        synchronized (mLock) {
877            for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
878                final int userId = mDirtyUserIds.get(i);
879                if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
880                    saveBaseStateLocked();
881                } else {
882                    saveUserLocked(userId);
883                }
884            }
885            mDirtyUserIds.clear();
886        }
887    }
888
889    /** Return the last reset time. */
890    long getLastResetTimeLocked() {
891        updateTimesLocked();
892        return mRawLastResetTime;
893    }
894
895    /** Return the next reset time. */
896    long getNextResetTimeLocked() {
897        updateTimesLocked();
898        return mRawLastResetTime + mResetInterval;
899    }
900
901    static boolean isClockValid(long time) {
902        return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
903    }
904
905    /**
906     * Update the last reset time.
907     */
908    private void updateTimesLocked() {
909
910        final long now = injectCurrentTimeMillis();
911
912        final long prevLastResetTime = mRawLastResetTime;
913
914        if (mRawLastResetTime == 0) { // first launch.
915            // TODO Randomize??
916            mRawLastResetTime = now;
917        } else if (now < mRawLastResetTime) {
918            // Clock rewound.
919            if (isClockValid(now)) {
920                Slog.w(TAG, "Clock rewound");
921                // TODO Randomize??
922                mRawLastResetTime = now;
923            }
924        } else {
925            if ((mRawLastResetTime + mResetInterval) <= now) {
926                final long offset = mRawLastResetTime % mResetInterval;
927                mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
928            }
929        }
930        if (prevLastResetTime != mRawLastResetTime) {
931            scheduleSaveBaseState();
932        }
933    }
934
935    @GuardedBy("mLock")
936    @NonNull
937    private boolean isUserLoadedLocked(@UserIdInt int userId) {
938        return mUsers.get(userId) != null;
939    }
940
941    /** Return the per-user state. */
942    @GuardedBy("mLock")
943    @NonNull
944    ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
945        ShortcutUser userPackages = mUsers.get(userId);
946        if (userPackages == null) {
947            userPackages = loadUserLocked(userId);
948            if (userPackages == null) {
949                userPackages = new ShortcutUser(userId);
950            }
951            mUsers.put(userId, userPackages);
952        }
953        return userPackages;
954    }
955
956    void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
957        for (int i = mUsers.size() - 1; i >= 0; i--) {
958            c.accept(mUsers.valueAt(i));
959        }
960    }
961
962    /** Return the per-user per-package state. */
963    @GuardedBy("mLock")
964    @NonNull
965    ShortcutPackage getPackageShortcutsLocked(
966            @NonNull String packageName, @UserIdInt int userId) {
967        return getUserShortcutsLocked(userId).getPackageShortcuts(this, packageName);
968    }
969
970    @GuardedBy("mLock")
971    @NonNull
972    ShortcutLauncher getLauncherShortcutsLocked(
973            @NonNull String packageName, @UserIdInt int ownerUserId,
974            @UserIdInt int launcherUserId) {
975        return getUserShortcutsLocked(ownerUserId)
976                .getLauncherShortcuts(this, packageName, launcherUserId);
977    }
978
979    // === Caller validation ===
980
981    void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
982        if (shortcut.getBitmapPath() != null) {
983            if (DEBUG) {
984                Slog.d(TAG, "Removing " + shortcut.getBitmapPath());
985            }
986            new File(shortcut.getBitmapPath()).delete();
987
988            shortcut.setBitmapPath(null);
989            shortcut.setIconResourceId(0);
990            shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES);
991        }
992    }
993
994    public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
995        final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
996        if (!packagePath.isDirectory()) {
997            return;
998        }
999        if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1000            Slog.w(TAG, "Unable to remove directory " + packagePath);
1001        }
1002    }
1003
1004    @VisibleForTesting
1005    static class FileOutputStreamWithPath extends FileOutputStream {
1006        private final File mFile;
1007
1008        public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1009            super(file);
1010            mFile = file;
1011        }
1012
1013        public File getFile() {
1014            return mFile;
1015        }
1016    }
1017
1018    /**
1019     * Build the cached bitmap filename for a shortcut icon.
1020     *
1021     * The filename will be based on the ID, except certain characters will be escaped.
1022     */
1023    @VisibleForTesting
1024    FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1025            throws IOException {
1026        final File packagePath = new File(getUserBitmapFilePath(userId),
1027                shortcut.getPackageName());
1028        if (!packagePath.isDirectory()) {
1029            packagePath.mkdirs();
1030            if (!packagePath.isDirectory()) {
1031                throw new IOException("Unable to create directory " + packagePath);
1032            }
1033            SELinux.restorecon(packagePath);
1034        }
1035
1036        final String baseName = String.valueOf(injectCurrentTimeMillis());
1037        for (int suffix = 0;; suffix++) {
1038            final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1039            final File file = new File(packagePath, filename);
1040            if (!file.exists()) {
1041                if (DEBUG) {
1042                    Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1043                }
1044                return new FileOutputStreamWithPath(file);
1045            }
1046        }
1047    }
1048
1049    void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1050        if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1051            return;
1052        }
1053
1054        final long token = injectClearCallingIdentity();
1055        try {
1056            // Clear icon info on the shortcut.
1057            shortcut.setIconResourceId(0);
1058            shortcut.setBitmapPath(null);
1059
1060            final Icon icon = shortcut.getIcon();
1061            if (icon == null) {
1062                return; // has no icon
1063            }
1064
1065            Bitmap bitmap;
1066            Bitmap bitmapToRecycle = null;
1067            try {
1068                switch (icon.getType()) {
1069                    case Icon.TYPE_RESOURCE: {
1070                        injectValidateIconResPackage(shortcut, icon);
1071
1072                        shortcut.setIconResourceId(icon.getResId());
1073                        shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1074                        return;
1075                    }
1076                    case Icon.TYPE_BITMAP: {
1077                        bitmap = icon.getBitmap(); // Don't recycle in this case.
1078                        break;
1079                    }
1080                    default:
1081                        // This shouldn't happen because we've already validated the icon, but
1082                        // just in case.
1083                        throw ShortcutInfo.getInvalidIconException();
1084                }
1085                if (bitmap == null) {
1086                    Slog.e(TAG, "Null bitmap detected");
1087                    return;
1088                }
1089                // Shrink and write to the file.
1090                File path = null;
1091                try {
1092                    final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1093                    try {
1094                        path = out.getFile();
1095
1096                        Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1097                        try {
1098                            shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1099                        } finally {
1100                            if (bitmap != shrunk) {
1101                                shrunk.recycle();
1102                            }
1103                        }
1104
1105                        shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1106                        shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1107                    } finally {
1108                        IoUtils.closeQuietly(out);
1109                    }
1110                } catch (IOException|RuntimeException e) {
1111                    // STOPSHIP Change wtf to e
1112                    Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1113                    if (path != null && path.exists()) {
1114                        path.delete();
1115                    }
1116                }
1117            } finally {
1118                if (bitmapToRecycle != null) {
1119                    bitmapToRecycle.recycle();
1120                }
1121                // Once saved, we won't use the original icon information, so null it out.
1122                shortcut.clearIcon();
1123            }
1124        } finally {
1125            injectRestoreCallingIdentity(token);
1126        }
1127    }
1128
1129    // Unfortunately we can't do this check in unit tests because we fake creator package names,
1130    // so override in unit tests.
1131    // TODO CTS this case.
1132    void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
1133        if (!shortcut.getPackageName().equals(icon.getResPackage())) {
1134            throw new IllegalArgumentException(
1135                    "Icon resource must reside in shortcut owner package");
1136        }
1137    }
1138
1139    @VisibleForTesting
1140    static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1141        // Original width/height.
1142        final int ow = in.getWidth();
1143        final int oh = in.getHeight();
1144        if ((ow <= maxSize) && (oh <= maxSize)) {
1145            if (DEBUG) {
1146                Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1147            }
1148            return in;
1149        }
1150        final int longerDimension = Math.max(ow, oh);
1151
1152        // New width and height.
1153        final int nw = ow * maxSize / longerDimension;
1154        final int nh = oh * maxSize / longerDimension;
1155        if (DEBUG) {
1156            Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1157                    ow, oh, nw, nh));
1158        }
1159
1160        final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1161        final Canvas c = new Canvas(scaledBitmap);
1162
1163        final RectF dst = new RectF(0, 0, nw, nh);
1164
1165        c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1166
1167        return scaledBitmap;
1168    }
1169
1170    // === Caller validation ===
1171
1172    private boolean isCallerSystem() {
1173        final int callingUid = injectBinderCallingUid();
1174         return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
1175    }
1176
1177    private boolean isCallerShell() {
1178        final int callingUid = injectBinderCallingUid();
1179        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1180    }
1181
1182    private void enforceSystemOrShell() {
1183        Preconditions.checkState(isCallerSystem() || isCallerShell(),
1184                "Caller must be system or shell");
1185    }
1186
1187    private void enforceShell() {
1188        Preconditions.checkState(isCallerShell(), "Caller must be shell");
1189    }
1190
1191    private void enforceSystem() {
1192        Preconditions.checkState(isCallerSystem(), "Caller must be system");
1193    }
1194
1195    private void enforceResetThrottlingPermission() {
1196        if (isCallerSystem()) {
1197            return;
1198        }
1199        injectEnforceCallingPermission(
1200                android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1201    }
1202
1203    /**
1204     * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1205     * mockito.  So instead we extracted it here and override it in the tests.
1206     */
1207    @VisibleForTesting
1208    void injectEnforceCallingPermission(
1209            @NonNull String permission, @Nullable String message) {
1210        mContext.enforceCallingPermission(permission, message);
1211    }
1212
1213    private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1214        Preconditions.checkStringNotEmpty(packageName, "packageName");
1215
1216        if (isCallerSystem()) {
1217            return; // no check
1218        }
1219
1220        final int callingUid = injectBinderCallingUid();
1221
1222        // Otherwise, make sure the arguments are valid.
1223        if (UserHandle.getUserId(callingUid) != userId) {
1224            throw new SecurityException("Invalid user-ID");
1225        }
1226        if (injectGetPackageUid(packageName, userId) == injectBinderCallingUid()) {
1227            return; // Caller is valid.
1228        }
1229        throw new SecurityException("Calling package name mismatch");
1230    }
1231
1232    void postToHandler(Runnable r) {
1233        mHandler.post(r);
1234    }
1235
1236    /**
1237     * Throw if {@code numShortcuts} is bigger than {@link #mMaxDynamicShortcuts}.
1238     */
1239    void enforceMaxDynamicShortcuts(int numShortcuts) {
1240        if (numShortcuts > mMaxDynamicShortcuts) {
1241            throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1242        }
1243    }
1244
1245    /**
1246     * - Sends a notification to LauncherApps
1247     * - Write to file
1248     */
1249    void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1250        if (DEBUG) {
1251            Slog.d(TAG, String.format(
1252                    "Shortcut changes: package=%s, user=%d", packageName, userId));
1253        }
1254        notifyListeners(packageName, userId);
1255        scheduleSaveUser(userId);
1256    }
1257
1258    private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
1259        final long token = injectClearCallingIdentity();
1260        try {
1261            if (!mUserManager.isUserRunning(userId)) {
1262                return;
1263            }
1264        } finally {
1265            injectRestoreCallingIdentity(token);
1266        }
1267        postToHandler(() -> {
1268            final ArrayList<ShortcutChangeListener> copy;
1269            synchronized (mLock) {
1270                copy = new ArrayList<>(mListeners);
1271            }
1272            // Note onShortcutChanged() needs to be called with the system service permissions.
1273            for (int i = copy.size() - 1; i >= 0; i--) {
1274                copy.get(i).onShortcutChanged(packageName, userId);
1275            }
1276        });
1277    }
1278
1279    /**
1280     * Clean up / validate an incoming shortcut.
1281     * - Make sure all mandatory fields are set.
1282     * - Make sure the intent's extras are persistable, and them to set
1283     *  {@link ShortcutInfo#mIntentPersistableExtras}.  Also clear its extras.
1284     * - Clear flags.
1285     *
1286     * TODO Detailed unit tests
1287     */
1288    private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1289        Preconditions.checkNotNull(shortcut, "Null shortcut detected");
1290        if (shortcut.getActivityComponent() != null) {
1291            Preconditions.checkState(
1292                    shortcut.getPackageName().equals(
1293                            shortcut.getActivityComponent().getPackageName()),
1294                    "Activity package name mismatch");
1295        }
1296
1297        if (!forUpdate) {
1298            shortcut.enforceMandatoryFields();
1299        }
1300        if (shortcut.getIcon() != null) {
1301            ShortcutInfo.validateIcon(shortcut.getIcon());
1302        }
1303
1304        validateForXml(shortcut.getId());
1305        validateForXml(shortcut.getTitle());
1306        validatePersistableBundleForXml(shortcut.getIntentPersistableExtras());
1307        validatePersistableBundleForXml(shortcut.getExtras());
1308
1309        shortcut.replaceFlags(0);
1310    }
1311
1312    // KXmlSerializer is strict and doesn't allow certain characters, so we disallow those
1313    // characters.
1314
1315    private static void validatePersistableBundleForXml(PersistableBundle b) {
1316        if (b == null || b.size() == 0) {
1317            return;
1318        }
1319        for (String key : b.keySet()) {
1320            validateForXml(key);
1321            final Object value = b.get(key);
1322            if (value == null) {
1323                continue;
1324            } else if (value instanceof String) {
1325                validateForXml((String) value);
1326            } else if (value instanceof String[]) {
1327                for (String v : (String[]) value) {
1328                    validateForXml(v);
1329                }
1330            } else if (value instanceof PersistableBundle) {
1331                validatePersistableBundleForXml((PersistableBundle) value);
1332            }
1333        }
1334    }
1335
1336    private static void validateForXml(String s) {
1337        if (TextUtils.isEmpty(s)) {
1338            return;
1339        }
1340        for (int i = s.length() - 1; i >= 0; i--) {
1341            if (!isAllowedInXml(s.charAt(i))) {
1342                throw new IllegalArgumentException("Unsupported character detected in: " + s);
1343            }
1344        }
1345    }
1346
1347    private static boolean isAllowedInXml(char c) {
1348        return (c >= 0x20 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfffd);
1349    }
1350
1351    // === APIs ===
1352
1353    @Override
1354    public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1355            @UserIdInt int userId) {
1356        verifyCaller(packageName, userId);
1357
1358        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1359        final int size = newShortcuts.size();
1360
1361        synchronized (mLock) {
1362            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1363
1364            // Throttling.
1365            if (!ps.tryApiCall(this)) {
1366                return false;
1367            }
1368            enforceMaxDynamicShortcuts(size);
1369
1370            // Validate the shortcuts.
1371            for (int i = 0; i < size; i++) {
1372                fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1373            }
1374
1375            // First, remove all un-pinned; dynamic shortcuts
1376            ps.deleteAllDynamicShortcuts(this);
1377
1378            // Then, add/update all.  We need to make sure to take over "pinned" flag.
1379            for (int i = 0; i < size; i++) {
1380                final ShortcutInfo newShortcut = newShortcuts.get(i);
1381                ps.addDynamicShortcut(this, newShortcut);
1382            }
1383        }
1384        packageShortcutsChanged(packageName, userId);
1385        return true;
1386    }
1387
1388    @Override
1389    public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1390            @UserIdInt int userId) {
1391        verifyCaller(packageName, userId);
1392
1393        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1394        final int size = newShortcuts.size();
1395
1396        synchronized (mLock) {
1397            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1398
1399            // Throttling.
1400            if (!ps.tryApiCall(this)) {
1401                return false;
1402            }
1403
1404            for (int i = 0; i < size; i++) {
1405                final ShortcutInfo source = newShortcuts.get(i);
1406                fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1407
1408                final ShortcutInfo target = ps.findShortcutById(source.getId());
1409                if (target != null) {
1410                    final boolean replacingIcon = (source.getIcon() != null);
1411                    if (replacingIcon) {
1412                        removeIcon(userId, target);
1413                    }
1414
1415                    target.copyNonNullFieldsFrom(source);
1416
1417                    if (replacingIcon) {
1418                        saveIconAndFixUpShortcut(userId, target);
1419                    }
1420                }
1421            }
1422        }
1423        packageShortcutsChanged(packageName, userId);
1424
1425        return true;
1426    }
1427
1428    @Override
1429    public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1430            @UserIdInt int userId) {
1431        verifyCaller(packageName, userId);
1432
1433        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1434        final int size = newShortcuts.size();
1435
1436        synchronized (mLock) {
1437            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1438
1439            // Throttling.
1440            if (!ps.tryApiCall(this)) {
1441                return false;
1442            }
1443            for (int i = 0; i < size; i++) {
1444                final ShortcutInfo newShortcut = newShortcuts.get(i);
1445
1446                // Validate the shortcut.
1447                fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
1448
1449                // Add it.
1450                ps.addDynamicShortcut(this, newShortcut);
1451            }
1452        }
1453        packageShortcutsChanged(packageName, userId);
1454
1455        return true;
1456    }
1457
1458    @Override
1459    public void removeDynamicShortcuts(String packageName, List shortcutIds,
1460            @UserIdInt int userId) {
1461        verifyCaller(packageName, userId);
1462        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1463
1464        synchronized (mLock) {
1465            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1466                getPackageShortcutsLocked(packageName, userId).deleteDynamicWithId(this,
1467                        Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1468            }
1469        }
1470        packageShortcutsChanged(packageName, userId);
1471    }
1472
1473    @Override
1474    public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
1475        verifyCaller(packageName, userId);
1476
1477        synchronized (mLock) {
1478            getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts(this);
1479        }
1480        packageShortcutsChanged(packageName, userId);
1481    }
1482
1483    @Override
1484    public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1485            @UserIdInt int userId) {
1486        verifyCaller(packageName, userId);
1487        synchronized (mLock) {
1488            return getShortcutsWithQueryLocked(
1489                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1490                    ShortcutInfo::isDynamic);
1491        }
1492    }
1493
1494    @Override
1495    public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1496            @UserIdInt int userId) {
1497        verifyCaller(packageName, userId);
1498        synchronized (mLock) {
1499            return getShortcutsWithQueryLocked(
1500                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1501                    ShortcutInfo::isPinned);
1502        }
1503    }
1504
1505    private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1506            @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1507
1508        final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1509
1510        getPackageShortcutsLocked(packageName, userId).findAll(this, ret, query, cloneFlags);
1511
1512        return new ParceledListSlice<>(ret);
1513    }
1514
1515    @Override
1516    public int getMaxDynamicShortcutCount(String packageName, @UserIdInt int userId)
1517            throws RemoteException {
1518        verifyCaller(packageName, userId);
1519
1520        return mMaxDynamicShortcuts;
1521    }
1522
1523    @Override
1524    public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1525        verifyCaller(packageName, userId);
1526
1527        synchronized (mLock) {
1528            return mMaxUpdatesPerInterval
1529                    - getPackageShortcutsLocked(packageName, userId).getApiCallCount(this);
1530        }
1531    }
1532
1533    @Override
1534    public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
1535        verifyCaller(packageName, userId);
1536
1537        synchronized (mLock) {
1538            return getNextResetTimeLocked();
1539        }
1540    }
1541
1542    @Override
1543    public int getIconMaxDimensions(String packageName, int userId) throws RemoteException {
1544        verifyCaller(packageName, userId);
1545
1546        synchronized (mLock) {
1547            return mMaxIconDimension;
1548        }
1549    }
1550
1551    /**
1552     * Reset all throttling, for developer options and command line.  Only system/shell can call it.
1553     */
1554    @Override
1555    public void resetThrottling() {
1556        enforceSystemOrShell();
1557
1558        resetThrottlingInner(getCallingUserId());
1559    }
1560
1561    void resetThrottlingInner(@UserIdInt int userId) {
1562        synchronized (mLock) {
1563            getUserShortcutsLocked(userId).resetThrottling();
1564        }
1565        scheduleSaveUser(userId);
1566        Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
1567    }
1568
1569    void resetAllThrottlingInner() {
1570        synchronized (mLock) {
1571            mRawLastResetTime = injectCurrentTimeMillis();
1572        }
1573        scheduleSaveBaseState();
1574        Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
1575    }
1576
1577    void resetPackageThrottling(String packageName, int userId) {
1578        synchronized (mLock) {
1579            getPackageShortcutsLocked(packageName, userId)
1580                    .resetRateLimitingForCommandLineNoSaving();
1581            saveUserLocked(userId);
1582        }
1583    }
1584
1585    @Override
1586    public void onApplicationActive(String packageName, int userId) {
1587        if (DEBUG) {
1588            Slog.d(TAG, "onApplicationActive: package=" + packageName + "  userid=" + userId);
1589        }
1590        enforceResetThrottlingPermission();
1591        resetPackageThrottling(packageName, userId);
1592    }
1593
1594    // We override this method in unit tests to do a simpler check.
1595    boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
1596        return hasShortcutHostPermissionInner(callingPackage, userId);
1597    }
1598
1599    // This method is extracted so we can directly call this method from unit tests,
1600    // even when hasShortcutPermission() is overridden.
1601    @VisibleForTesting
1602    boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
1603        synchronized (mLock) {
1604            final long start = System.currentTimeMillis();
1605
1606            final ShortcutUser user = getUserShortcutsLocked(userId);
1607
1608            final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
1609
1610            // Default launcher from package manager.
1611            final long startGetHomeActivitiesAsUser = System.currentTimeMillis();
1612            final ComponentName defaultLauncher = injectPackageManagerInternal()
1613                    .getHomeActivitiesAsUser(allHomeCandidates, userId);
1614            logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
1615
1616            ComponentName detected;
1617            if (defaultLauncher != null) {
1618                detected = defaultLauncher;
1619                if (DEBUG) {
1620                    Slog.v(TAG, "Default launcher from PM: " + detected);
1621                }
1622            } else {
1623                detected = user.getLauncherComponent();
1624
1625                // TODO: Make sure it's still enabled.
1626                if (DEBUG) {
1627                    Slog.v(TAG, "Cached launcher: " + detected);
1628                }
1629            }
1630
1631            if (detected == null) {
1632                // If we reach here, that means it's the first check since the user was created,
1633                // and there's already multiple launchers and there's no default set.
1634                // Find the system one with the highest priority.
1635                // (We need to check the priority too because of FallbackHome in Settings.)
1636                // If there's no system launcher yet, then no one can access shortcuts, until
1637                // the user explicitly
1638                final int size = allHomeCandidates.size();
1639
1640                int lastPriority = Integer.MIN_VALUE;
1641                for (int i = 0; i < size; i++) {
1642                    final ResolveInfo ri = allHomeCandidates.get(i);
1643                    if (!ri.activityInfo.applicationInfo.isSystemApp()) {
1644                        continue;
1645                    }
1646                    if (DEBUG) {
1647                        Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
1648                                ri.activityInfo.getComponentName(), ri.priority));
1649                    }
1650                    if (ri.priority < lastPriority) {
1651                        continue;
1652                    }
1653                    detected = ri.activityInfo.getComponentName();
1654                    lastPriority = ri.priority;
1655                }
1656            }
1657            logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
1658
1659            if (detected != null) {
1660                if (DEBUG) {
1661                    Slog.v(TAG, "Detected launcher: " + detected);
1662                }
1663                user.setLauncherComponent(this, detected);
1664                return detected.getPackageName().equals(callingPackage);
1665            } else {
1666                // Default launcher not found.
1667                return false;
1668            }
1669        }
1670    }
1671
1672    // === House keeping ===
1673
1674    private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId) {
1675        synchronized (mLock) {
1676            forEachLoadedUserLocked(user ->
1677                    cleanUpPackageLocked(packageName, user.getUserId(), packageUserId));
1678        }
1679    }
1680
1681    /**
1682     * Remove all the information associated with a package.  This will really remove all the
1683     * information, including the restore information (i.e. it'll remove packages even if they're
1684     * shadow).
1685     *
1686     * This is called when an app is uninstalled, or an app gets "clear data"ed.
1687     */
1688    @VisibleForTesting
1689    void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId) {
1690        final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
1691
1692        final ShortcutUser user = getUserShortcutsLocked(owningUserId);
1693        boolean doNotify = false;
1694
1695        // First, remove the package from the package list (if the package is a publisher).
1696        if (packageUserId == owningUserId) {
1697            if (user.removePackage(this, packageName) != null) {
1698                doNotify = true;
1699            }
1700        }
1701
1702        // Also remove from the launcher list (if the package is a launcher).
1703        user.removeLauncher(packageUserId, packageName);
1704
1705        // Then remove pinned shortcuts from all launchers.
1706        user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
1707
1708        // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
1709        // step.  Remove them too.
1710        user.forAllPackages(p -> p.refreshPinnedFlags(this));
1711
1712        scheduleSaveUser(owningUserId);
1713
1714        if (doNotify) {
1715            notifyListeners(packageName, owningUserId);
1716        }
1717
1718        if (!wasUserLoaded) {
1719            // Note this will execute the scheduled save.
1720            unloadUserLocked(owningUserId);
1721        }
1722    }
1723
1724    /**
1725     * Entry point from {@link LauncherApps}.
1726     */
1727    private class LocalService extends ShortcutServiceInternal {
1728
1729        @Override
1730        public List<ShortcutInfo> getShortcuts(int launcherUserId,
1731                @NonNull String callingPackage, long changedSince,
1732                @Nullable String packageName, @Nullable List<String> shortcutIds,
1733                @Nullable ComponentName componentName,
1734                int queryFlags, int userId) {
1735            final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1736            final int cloneFlag =
1737                    ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) == 0)
1738                            ? ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER
1739                            : ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO;
1740            if (packageName == null) {
1741                shortcutIds = null; // LauncherAppsService already threw for it though.
1742            }
1743
1744            synchronized (mLock) {
1745                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1746                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1747
1748                if (packageName != null) {
1749                    getShortcutsInnerLocked(launcherUserId,
1750                            callingPackage, packageName, shortcutIds, changedSince,
1751                            componentName, queryFlags, userId, ret, cloneFlag);
1752                } else {
1753                    final List<String> shortcutIdsF = shortcutIds;
1754                    getUserShortcutsLocked(userId).forAllPackages(p -> {
1755                        getShortcutsInnerLocked(launcherUserId,
1756                                callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
1757                                componentName, queryFlags, userId, ret, cloneFlag);
1758                    });
1759                }
1760            }
1761            return ret;
1762        }
1763
1764        private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
1765                @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
1766                @Nullable ComponentName componentName, int queryFlags,
1767                int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
1768            final ArraySet<String> ids = shortcutIds == null ? null
1769                    : new ArraySet<>(shortcutIds);
1770
1771            getPackageShortcutsLocked(packageName, userId).findAll(ShortcutService.this, ret,
1772                    (ShortcutInfo si) -> {
1773                        if (si.getLastChangedTimestamp() < changedSince) {
1774                            return false;
1775                        }
1776                        if (ids != null && !ids.contains(si.getId())) {
1777                            return false;
1778                        }
1779                        if (componentName != null) {
1780                            if (si.getActivityComponent() != null
1781                                    && !si.getActivityComponent().equals(componentName)) {
1782                                return false;
1783                            }
1784                        }
1785                        final boolean matchDynamic =
1786                                ((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
1787                                        && si.isDynamic();
1788                        final boolean matchPinned =
1789                                ((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
1790                                        && si.isPinned();
1791                        return matchDynamic || matchPinned;
1792                    }, cloneFlag, callingPackage, launcherUserId);
1793        }
1794
1795        @Override
1796        public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
1797                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1798            Preconditions.checkStringNotEmpty(packageName, "packageName");
1799            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
1800
1801            synchronized (mLock) {
1802                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1803                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1804
1805                final ShortcutInfo si = getShortcutInfoLocked(
1806                        launcherUserId, callingPackage, packageName, shortcutId, userId);
1807                return si != null && si.isPinned();
1808            }
1809        }
1810
1811        private ShortcutInfo getShortcutInfoLocked(
1812                int launcherUserId, @NonNull String callingPackage,
1813                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1814            Preconditions.checkStringNotEmpty(packageName, "packageName");
1815            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
1816
1817            final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
1818            getPackageShortcutsLocked(packageName, userId).findAll(
1819                    ShortcutService.this, list,
1820                    (ShortcutInfo si) -> shortcutId.equals(si.getId()),
1821                    /* clone flags=*/ 0, callingPackage, launcherUserId);
1822            return list.size() == 0 ? null : list.get(0);
1823        }
1824
1825        @Override
1826        public void pinShortcuts(int launcherUserId,
1827                @NonNull String callingPackage, @NonNull String packageName,
1828                @NonNull List<String> shortcutIds, int userId) {
1829            // Calling permission must be checked by LauncherAppsImpl.
1830            Preconditions.checkStringNotEmpty(packageName, "packageName");
1831            Preconditions.checkNotNull(shortcutIds, "shortcutIds");
1832
1833            synchronized (mLock) {
1834                final ShortcutLauncher launcher =
1835                        getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
1836                launcher.attemptToRestoreIfNeededAndSave(ShortcutService.this);
1837
1838                launcher.pinShortcuts(
1839                        ShortcutService.this, userId, packageName, shortcutIds);
1840            }
1841            packageShortcutsChanged(packageName, userId);
1842        }
1843
1844        @Override
1845        public Intent createShortcutIntent(int launcherUserId,
1846                @NonNull String callingPackage,
1847                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1848            // Calling permission must be checked by LauncherAppsImpl.
1849            Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
1850            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
1851
1852            synchronized (mLock) {
1853                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1854                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1855
1856                // Make sure the shortcut is actually visible to the launcher.
1857                final ShortcutInfo si = getShortcutInfoLocked(
1858                        launcherUserId, callingPackage, packageName, shortcutId, userId);
1859                // "si == null" should suffice here, but check the flags too just to make sure.
1860                if (si == null || !(si.isDynamic() || si.isPinned())) {
1861                    return null;
1862                }
1863                return si.getIntent();
1864            }
1865        }
1866
1867        @Override
1868        public void addListener(@NonNull ShortcutChangeListener listener) {
1869            synchronized (mLock) {
1870                mListeners.add(Preconditions.checkNotNull(listener));
1871            }
1872        }
1873
1874        @Override
1875        public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
1876                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1877            Preconditions.checkNotNull(callingPackage, "callingPackage");
1878            Preconditions.checkNotNull(packageName, "packageName");
1879            Preconditions.checkNotNull(shortcutId, "shortcutId");
1880
1881            synchronized (mLock) {
1882                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1883                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1884
1885                final ShortcutInfo shortcutInfo = getPackageShortcutsLocked(
1886                        packageName, userId).findShortcutById(shortcutId);
1887                return (shortcutInfo != null && shortcutInfo.hasIconResource())
1888                        ? shortcutInfo.getIconResourceId() : 0;
1889            }
1890        }
1891
1892        @Override
1893        public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
1894                @NonNull String callingPackage, @NonNull String packageName,
1895                @NonNull String shortcutId, int userId) {
1896            Preconditions.checkNotNull(callingPackage, "callingPackage");
1897            Preconditions.checkNotNull(packageName, "packageName");
1898            Preconditions.checkNotNull(shortcutId, "shortcutId");
1899
1900            synchronized (mLock) {
1901                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1902                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1903
1904                final ShortcutInfo shortcutInfo = getPackageShortcutsLocked(
1905                        packageName, userId).findShortcutById(shortcutId);
1906                if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
1907                    return null;
1908                }
1909                try {
1910                    if (shortcutInfo.getBitmapPath() == null) {
1911                        Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
1912                        return null;
1913                    }
1914                    return ParcelFileDescriptor.open(
1915                            new File(shortcutInfo.getBitmapPath()),
1916                            ParcelFileDescriptor.MODE_READ_ONLY);
1917                } catch (FileNotFoundException e) {
1918                    Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
1919                    return null;
1920                }
1921            }
1922        }
1923
1924        @Override
1925        public boolean hasShortcutHostPermission(int launcherUserId,
1926                @NonNull String callingPackage) {
1927            return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
1928        }
1929
1930        /**
1931         * Called by AM when the system locale changes *within the AM lock.  ABSOLUTELY do not take
1932         * any locks in this method.
1933         */
1934        @Override
1935        public void onSystemLocaleChangedNoLock() {
1936            // DO NOT HOLD ANY LOCKS HERE.
1937
1938            // We want to reset throttling for all packages for all users.  But we can't just do so
1939            // here because:
1940            // - We can't load/save users that are locked.
1941            // - Even for loaded users, resetting the counters would require us to hold mLock.
1942            //
1943            // So we use a "pull" model instead.  In here, we just increment the "locale change
1944            // sequence number".  Each ShortcutUser has the "last known locale change sequence".
1945            //
1946            // This allows ShortcutUser's to detect the system locale change, so they can reset
1947            // counters.
1948
1949            mLocaleChangeSequenceNumber.incrementAndGet();
1950            postToHandler(() -> scheduleSaveBaseState());
1951        }
1952    }
1953
1954    /**
1955     * Package event callbacks.
1956     */
1957    @VisibleForTesting
1958    final PackageMonitor mPackageMonitor = new PackageMonitor() {
1959        @Override
1960        public void onPackageAdded(String packageName, int uid) {
1961            handlePackageAdded(packageName, getChangingUserId());
1962        }
1963
1964        @Override
1965        public void onPackageUpdateFinished(String packageName, int uid) {
1966            handlePackageUpdateFinished(packageName, getChangingUserId());
1967        }
1968
1969        @Override
1970        public void onPackageRemoved(String packageName, int uid) {
1971            handlePackageRemoved(packageName, getChangingUserId());
1972        }
1973
1974        @Override
1975        public void onPackageDataCleared(String packageName, int uid) {
1976            handlePackageDataCleared(packageName, getChangingUserId());
1977        }
1978    };
1979
1980    /**
1981     * Called when a user is unlocked.
1982     * - Check all known packages still exist, and otherwise perform cleanup.
1983     * - If a package still exists, check the version code.  If it's been updated, may need to
1984     *   update timestamps of its shortcuts.
1985     */
1986    @VisibleForTesting
1987    void checkPackageChanges(@UserIdInt int ownerUserId) {
1988        if (DEBUG) {
1989            Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
1990        }
1991        final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
1992
1993        synchronized (mLock) {
1994            final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
1995
1996            user.forAllPackageItems(spi -> {
1997                if (spi.getPackageInfo().isShadow()) {
1998                    return; // Don't delete shadow information.
1999                }
2000                final int versionCode = getApplicationVersionCode(
2001                        spi.getPackageName(), spi.getPackageUserId());
2002                if (versionCode >= 0) {
2003                    // Package still installed, see if it's updated.
2004                    getUserShortcutsLocked(ownerUserId).handlePackageUpdated(
2005                            this, spi.getPackageName(), versionCode);
2006                } else {
2007                    gonePackages.add(PackageWithUser.of(spi));
2008                }
2009            });
2010            if (gonePackages.size() > 0) {
2011                for (int i = gonePackages.size() - 1; i >= 0; i--) {
2012                    final PackageWithUser pu = gonePackages.get(i);
2013                    cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId);
2014                }
2015            }
2016        }
2017    }
2018
2019    private void handlePackageAdded(String packageName, @UserIdInt int userId) {
2020        if (DEBUG) {
2021            Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2022        }
2023        synchronized (mLock) {
2024            forEachLoadedUserLocked(user ->
2025                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
2026        }
2027    }
2028
2029    private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
2030        if (DEBUG) {
2031            Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2032                    packageName, userId));
2033        }
2034        synchronized (mLock) {
2035            forEachLoadedUserLocked(user ->
2036                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
2037
2038            final int versionCode = getApplicationVersionCode(packageName, userId);
2039            if (versionCode < 0) {
2040                return; // shouldn't happen
2041            }
2042            getUserShortcutsLocked(userId).handlePackageUpdated(this, packageName, versionCode);
2043        }
2044    }
2045
2046    private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
2047        if (DEBUG) {
2048            Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2049                    packageUserId));
2050        }
2051        cleanUpPackageForAllLoadedUsers(packageName, packageUserId);
2052    }
2053
2054    private void handlePackageDataCleared(String packageName, int packageUserId) {
2055        if (DEBUG) {
2056            Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2057                    packageUserId));
2058        }
2059        cleanUpPackageForAllLoadedUsers(packageName, packageUserId);
2060    }
2061
2062    // === PackageManager interaction ===
2063
2064    PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2065        return injectPackageInfo(packageName, userId, true);
2066    }
2067
2068    int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
2069        final long token = injectClearCallingIdentity();
2070        try {
2071            return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS
2072                    , userId);
2073        } catch (RemoteException e) {
2074            // Shouldn't happen.
2075            Slog.wtf(TAG, "RemoteException", e);
2076            return -1;
2077        } finally {
2078            injectRestoreCallingIdentity(token);
2079        }
2080    }
2081
2082    @VisibleForTesting
2083    PackageInfo injectPackageInfo(String packageName, @UserIdInt int userId,
2084            boolean getSignatures) {
2085        final long start = System.currentTimeMillis();
2086        final long token = injectClearCallingIdentity();
2087        try {
2088            return mIPackageManager.getPackageInfo(packageName, PACKAGE_MATCH_FLAGS
2089                    | (getSignatures ? PackageManager.GET_SIGNATURES : 0)
2090                    , userId);
2091        } catch (RemoteException e) {
2092            // Shouldn't happen.
2093            Slog.wtf(TAG, "RemoteException", e);
2094            return null;
2095        } finally {
2096            injectRestoreCallingIdentity(token);
2097
2098            logDurationStat(
2099                    (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2100                    start);
2101        }
2102    }
2103
2104    @VisibleForTesting
2105    ApplicationInfo injectApplicationInfo(String packageName, @UserIdInt int userId) {
2106        final long start = System.currentTimeMillis();
2107        final long token = injectClearCallingIdentity();
2108        try {
2109            return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2110        } catch (RemoteException e) {
2111            // Shouldn't happen.
2112            Slog.wtf(TAG, "RemoteException", e);
2113            return null;
2114        } finally {
2115            injectRestoreCallingIdentity(token);
2116
2117            logDurationStat(Stats.GET_APPLICATION_INFO, start);
2118        }
2119    }
2120
2121    private boolean isApplicationFlagSet(String packageName, int userId, int flags) {
2122        final ApplicationInfo ai = injectApplicationInfo(packageName, userId);
2123        return (ai != null) && ((ai.flags & flags) == flags);
2124    }
2125
2126    boolean isPackageInstalled(String packageName, int userId) {
2127        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_INSTALLED);
2128    }
2129
2130    /**
2131     * @return the version code of the package, or -1 if the app is not installed.
2132     */
2133    int getApplicationVersionCode(String packageName, int userId) {
2134        final ApplicationInfo ai = injectApplicationInfo(packageName, userId);
2135        if ((ai == null) || ((ai.flags & ApplicationInfo.FLAG_INSTALLED) == 0)) {
2136            return -1;
2137        }
2138        return ai.versionCode;
2139    }
2140
2141    // === Backup & restore ===
2142
2143    boolean shouldBackupApp(String packageName, int userId) {
2144        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
2145    }
2146
2147    boolean shouldBackupApp(PackageInfo pi) {
2148        return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
2149    }
2150
2151    @Override
2152    public byte[] getBackupPayload(@UserIdInt int userId) {
2153        enforceSystem();
2154        if (DEBUG) {
2155            Slog.d(TAG, "Backing up user " + userId);
2156        }
2157        synchronized (mLock) {
2158            final ShortcutUser user = getUserShortcutsLocked(userId);
2159            if (user == null) {
2160                Slog.w(TAG, "Can't backup: user not found: id=" + userId);
2161                return null;
2162            }
2163
2164            user.forAllPackageItems(spi -> spi.refreshPackageInfoAndSave(this));
2165
2166            // Then save.
2167            final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
2168            try {
2169                saveUserInternalLocked(userId, os, /* forBackup */ true);
2170            } catch (XmlPullParserException|IOException e) {
2171                // Shouldn't happen.
2172                Slog.w(TAG, "Backup failed.", e);
2173                return null;
2174            }
2175            return os.toByteArray();
2176        }
2177    }
2178
2179    @Override
2180    public void applyRestore(byte[] payload, @UserIdInt int userId) {
2181        enforceSystem();
2182        if (DEBUG) {
2183            Slog.d(TAG, "Restoring user " + userId);
2184        }
2185        final ShortcutUser user;
2186        final ByteArrayInputStream is = new ByteArrayInputStream(payload);
2187        try {
2188            user = loadUserInternal(userId, is, /* fromBackup */ true);
2189        } catch (XmlPullParserException|IOException e) {
2190            Slog.w(TAG, "Restoration failed.", e);
2191            return;
2192        }
2193        synchronized (mLock) {
2194            mUsers.put(userId, user);
2195
2196            // Then purge all the save images.
2197            final File bitmapPath = getUserBitmapFilePath(userId);
2198            final boolean success = FileUtils.deleteContents(bitmapPath);
2199            if (!success) {
2200                Slog.w(TAG, "Failed to delete " + bitmapPath);
2201            }
2202
2203            saveUserLocked(userId);
2204        }
2205    }
2206
2207    // === Dump ===
2208
2209    @Override
2210    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2211        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2212                != PackageManager.PERMISSION_GRANTED) {
2213            pw.println("Permission Denial: can't dump UserManager from from pid="
2214                    + Binder.getCallingPid()
2215                    + ", uid=" + Binder.getCallingUid()
2216                    + " without permission "
2217                    + android.Manifest.permission.DUMP);
2218            return;
2219        }
2220        dumpInner(pw, args);
2221    }
2222
2223    @VisibleForTesting
2224    void dumpInner(PrintWriter pw, String[] args) {
2225        synchronized (mLock) {
2226            final long now = injectCurrentTimeMillis();
2227            pw.print("Now: [");
2228            pw.print(now);
2229            pw.print("] ");
2230            pw.print(formatTime(now));
2231
2232            pw.print("  Raw last reset: [");
2233            pw.print(mRawLastResetTime);
2234            pw.print("] ");
2235            pw.print(formatTime(mRawLastResetTime));
2236
2237            final long last = getLastResetTimeLocked();
2238            pw.print("  Last reset: [");
2239            pw.print(last);
2240            pw.print("] ");
2241            pw.print(formatTime(last));
2242
2243            final long next = getNextResetTimeLocked();
2244            pw.print("  Next reset: [");
2245            pw.print(next);
2246            pw.print("] ");
2247            pw.print(formatTime(next));
2248
2249            pw.print("  Locale change seq#: ");
2250            pw.print(mLocaleChangeSequenceNumber.get());
2251            pw.println();
2252
2253            pw.print("  Config:");
2254            pw.print("    Max icon dim: ");
2255            pw.println(mMaxIconDimension);
2256            pw.print("    Icon format: ");
2257            pw.println(mIconPersistFormat);
2258            pw.print("    Icon quality: ");
2259            pw.println(mIconPersistQuality);
2260            pw.print("    saveDelayMillis: ");
2261            pw.println(mSaveDelayMillis);
2262            pw.print("    resetInterval: ");
2263            pw.println(mResetInterval);
2264            pw.print("    maxUpdatesPerInterval: ");
2265            pw.println(mMaxUpdatesPerInterval);
2266            pw.print("    maxDynamicShortcuts: ");
2267            pw.println(mMaxDynamicShortcuts);
2268            pw.println();
2269
2270            pw.println("  Stats:");
2271            synchronized (mStatLock) {
2272                final String p = "    ";
2273                dumpStatLS(pw, p, Stats.GET_DEFAULT_HOME, "getHomeActivities()");
2274                dumpStatLS(pw, p, Stats.LAUNCHER_PERMISSION_CHECK, "Launcher permission check");
2275
2276                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO, "getPackageInfo()");
2277                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO_WITH_SIG, "getPackageInfo(SIG)");
2278                dumpStatLS(pw, p, Stats.GET_APPLICATION_INFO, "getApplicationInfo");
2279            }
2280
2281            for (int i = 0; i < mUsers.size(); i++) {
2282                pw.println();
2283                mUsers.valueAt(i).dump(this, pw, "  ");
2284            }
2285
2286            pw.println();
2287            pw.println("  UID state:");
2288
2289            for (int i = 0; i < mUidState.size(); i++) {
2290                final int uid = mUidState.keyAt(i);
2291                final int state = mUidState.valueAt(i);
2292                pw.print("    UID=");
2293                pw.print(uid);
2294                pw.print(" state=");
2295                pw.print(state);
2296                if (isProcessStateForeground(state)) {
2297                    pw.print("  [FG]");
2298                }
2299                pw.print("  last FG=");
2300                pw.print(mUidLastForegroundElapsedTime.get(uid));
2301                pw.println();
2302            }
2303        }
2304    }
2305
2306    static String formatTime(long time) {
2307        Time tobj = new Time();
2308        tobj.set(time);
2309        return tobj.format("%Y-%m-%d %H:%M:%S");
2310    }
2311
2312    private void dumpStatLS(PrintWriter pw, String prefix, int statId, String label) {
2313        pw.print(prefix);
2314        final int count = mCountStats[statId];
2315        final long dur = mDurationStats[statId];
2316        pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
2317                label, count, dur,
2318                (count == 0 ? 0 : ((double) dur) / count)));
2319    }
2320
2321    // === Shell support ===
2322
2323    @Override
2324    public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2325            String[] args, ResultReceiver resultReceiver) throws RemoteException {
2326
2327        enforceShell();
2328
2329        (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
2330    }
2331
2332    static class CommandException extends Exception {
2333        public CommandException(String message) {
2334            super(message);
2335        }
2336    }
2337
2338    /**
2339     * Handle "adb shell cmd".
2340     */
2341    private class MyShellCommand extends ShellCommand {
2342
2343        private int mUserId = UserHandle.USER_SYSTEM;
2344
2345        private void parseOptions(boolean takeUser)
2346                throws CommandException {
2347            String opt;
2348            while ((opt = getNextOption()) != null) {
2349                switch (opt) {
2350                    case "--user":
2351                        if (takeUser) {
2352                            mUserId = UserHandle.parseUserArg(getNextArgRequired());
2353                            break;
2354                        }
2355                        // fallthrough
2356                    default:
2357                        throw new CommandException("Unknown option: " + opt);
2358                }
2359            }
2360        }
2361
2362        @Override
2363        public int onCommand(String cmd) {
2364            if (cmd == null) {
2365                return handleDefaultCommands(cmd);
2366            }
2367            final PrintWriter pw = getOutPrintWriter();
2368            try {
2369                switch (cmd) {
2370                    case "reset-package-throttling":
2371                        handleResetPackageThrottling();
2372                        break;
2373                    case "reset-throttling":
2374                        handleResetThrottling();
2375                        break;
2376                    case "reset-all-throttling":
2377                        handleResetAllThrottling();
2378                        break;
2379                    case "override-config":
2380                        handleOverrideConfig();
2381                        break;
2382                    case "reset-config":
2383                        handleResetConfig();
2384                        break;
2385                    case "clear-default-launcher":
2386                        handleClearDefaultLauncher();
2387                        break;
2388                    case "get-default-launcher":
2389                        handleGetDefaultLauncher();
2390                        break;
2391                    case "refresh-default-launcher":
2392                        handleRefreshDefaultLauncher();
2393                        break;
2394                    case "unload-user":
2395                        handleUnloadUser();
2396                        break;
2397                    case "clear-shortcuts":
2398                        handleClearShortcuts();
2399                        break;
2400                    default:
2401                        return handleDefaultCommands(cmd);
2402                }
2403            } catch (CommandException e) {
2404                pw.println("Error: " + e.getMessage());
2405                return 1;
2406            }
2407            pw.println("Success");
2408            return 0;
2409        }
2410
2411        @Override
2412        public void onHelp() {
2413            final PrintWriter pw = getOutPrintWriter();
2414            pw.println("Usage: cmd shortcut COMMAND [options ...]");
2415            pw.println();
2416            pw.println("cmd shortcut reset-package-throttling [--user USER_ID] PACKAGE");
2417            pw.println("    Reset throttling for a package");
2418            pw.println();
2419            pw.println("cmd shortcut reset-throttling [--user USER_ID]");
2420            pw.println("    Reset throttling for all packages and users");
2421            pw.println();
2422            pw.println("cmd shortcut reset-all-throttling");
2423            pw.println("    Reset the throttling state for all users");
2424            pw.println();
2425            pw.println("cmd shortcut override-config CONFIG");
2426            pw.println("    Override the configuration for testing (will last until reboot)");
2427            pw.println();
2428            pw.println("cmd shortcut reset-config");
2429            pw.println("    Reset the configuration set with \"update-config\"");
2430            pw.println();
2431            pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
2432            pw.println("    Clear the cached default launcher");
2433            pw.println();
2434            pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
2435            pw.println("    Show the cached default launcher");
2436            pw.println();
2437            pw.println("cmd shortcut refresh-default-launcher [--user USER_ID]");
2438            pw.println("    Refresh the cached default launcher");
2439            pw.println();
2440            pw.println("cmd shortcut unload-user [--user USER_ID]");
2441            pw.println("    Unload a user from the memory");
2442            pw.println("    (This should not affect any observable behavior)");
2443            pw.println();
2444            pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
2445            pw.println("    Remove all shortcuts from a package, including pinned shortcuts");
2446            pw.println();
2447        }
2448
2449        private void handleResetThrottling() throws CommandException {
2450            parseOptions(/* takeUser =*/ true);
2451
2452            Slog.i(TAG, "cmd: handleResetThrottling");
2453
2454            resetThrottlingInner(mUserId);
2455        }
2456
2457        private void handleResetAllThrottling() {
2458            Slog.i(TAG, "cmd: handleResetAllThrottling");
2459
2460            resetAllThrottlingInner();
2461        }
2462
2463        private void handleResetPackageThrottling() throws CommandException {
2464            parseOptions(/* takeUser =*/ true);
2465
2466            final String packageName = getNextArgRequired();
2467
2468            Slog.i(TAG, "cmd: handleResetPackageThrottling: " + packageName);
2469
2470            resetPackageThrottling(packageName, mUserId);
2471        }
2472
2473        private void handleOverrideConfig() throws CommandException {
2474            final String config = getNextArgRequired();
2475
2476            Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
2477
2478            synchronized (mLock) {
2479                if (!updateConfigurationLocked(config)) {
2480                    throw new CommandException("override-config failed.  See logcat for details.");
2481                }
2482            }
2483        }
2484
2485        private void handleResetConfig() {
2486            Slog.i(TAG, "cmd: handleResetConfig");
2487
2488            synchronized (mLock) {
2489                loadConfigurationLocked();
2490            }
2491        }
2492
2493        private void clearLauncher() {
2494            synchronized (mLock) {
2495                getUserShortcutsLocked(mUserId).setLauncherComponent(
2496                        ShortcutService.this, null);
2497            }
2498        }
2499
2500        private void showLauncher() {
2501            synchronized (mLock) {
2502                // This ensures to set the cached launcher.  Package name doesn't matter.
2503                hasShortcutHostPermissionInner("-", mUserId);
2504
2505                getOutPrintWriter().println("Launcher: "
2506                        + getUserShortcutsLocked(mUserId).getLauncherComponent());
2507            }
2508        }
2509
2510        private void handleClearDefaultLauncher() throws CommandException {
2511            parseOptions(/* takeUser =*/ true);
2512
2513            clearLauncher();
2514        }
2515
2516        private void handleGetDefaultLauncher() throws CommandException {
2517            parseOptions(/* takeUser =*/ true);
2518
2519            showLauncher();
2520        }
2521
2522        private void handleRefreshDefaultLauncher() throws CommandException {
2523            parseOptions(/* takeUser =*/ true);
2524
2525            clearLauncher();
2526            showLauncher();
2527        }
2528
2529        private void handleUnloadUser() throws CommandException {
2530            parseOptions(/* takeUser =*/ true);
2531
2532            Slog.i(TAG, "cmd: handleUnloadUser: " + mUserId);
2533
2534            ShortcutService.this.handleCleanupUser(mUserId);
2535        }
2536
2537        private void handleClearShortcuts() throws CommandException {
2538            parseOptions(/* takeUser =*/ true);
2539            final String packageName = getNextArgRequired();
2540
2541            Slog.i(TAG, "cmd: handleClearShortcuts: " + mUserId + ", " + packageName);
2542
2543            ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId);
2544        }
2545    }
2546
2547    // === Unit test support ===
2548
2549    // Injection point.
2550    @VisibleForTesting
2551    long injectCurrentTimeMillis() {
2552        return System.currentTimeMillis();
2553    }
2554
2555    @VisibleForTesting
2556    long injectElapsedRealtime() {
2557        return SystemClock.elapsedRealtime();
2558    }
2559
2560    // Injection point.
2561    @VisibleForTesting
2562    int injectBinderCallingUid() {
2563        return getCallingUid();
2564    }
2565
2566    private int getCallingUserId() {
2567        return UserHandle.getUserId(injectBinderCallingUid());
2568    }
2569
2570    // Injection point.
2571    @VisibleForTesting
2572    long injectClearCallingIdentity() {
2573        return Binder.clearCallingIdentity();
2574    }
2575
2576    // Injection point.
2577    @VisibleForTesting
2578    void injectRestoreCallingIdentity(long token) {
2579        Binder.restoreCallingIdentity(token);
2580    }
2581
2582    final void wtf(String message) {
2583        wtf( message, /* exception= */ null);
2584    }
2585
2586    // Injection point.
2587    void wtf(String message, Exception e) {
2588        Slog.wtf(TAG, message, e);
2589    }
2590
2591    @VisibleForTesting
2592    File injectSystemDataPath() {
2593        return Environment.getDataSystemDirectory();
2594    }
2595
2596    @VisibleForTesting
2597    File injectUserDataPath(@UserIdInt int userId) {
2598        return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
2599    }
2600
2601    @VisibleForTesting
2602    boolean injectIsLowRamDevice() {
2603        return ActivityManager.isLowRamDeviceStatic();
2604    }
2605
2606    @VisibleForTesting
2607    void injectRegisterUidObserver(IUidObserver observer, int which) {
2608        try {
2609            ActivityManagerNative.getDefault().registerUidObserver(observer, which);
2610        } catch (RemoteException shouldntHappen) {
2611        }
2612    }
2613
2614    @VisibleForTesting
2615    PackageManagerInternal injectPackageManagerInternal() {
2616        return mPackageManagerInternal;
2617    }
2618
2619    File getUserBitmapFilePath(@UserIdInt int userId) {
2620        return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
2621    }
2622
2623    @VisibleForTesting
2624    SparseArray<ShortcutUser> getShortcutsForTest() {
2625        return mUsers;
2626    }
2627
2628    @VisibleForTesting
2629    int getMaxDynamicShortcutsForTest() {
2630        return mMaxDynamicShortcuts;
2631    }
2632
2633    @VisibleForTesting
2634    int getMaxUpdatesPerIntervalForTest() {
2635        return mMaxUpdatesPerInterval;
2636    }
2637
2638    @VisibleForTesting
2639    long getResetIntervalForTest() {
2640        return mResetInterval;
2641    }
2642
2643    @VisibleForTesting
2644    int getMaxIconDimensionForTest() {
2645        return mMaxIconDimension;
2646    }
2647
2648    @VisibleForTesting
2649    CompressFormat getIconPersistFormatForTest() {
2650        return mIconPersistFormat;
2651    }
2652
2653    @VisibleForTesting
2654    int getIconPersistQualityForTest() {
2655        return mIconPersistQuality;
2656    }
2657
2658    @VisibleForTesting
2659    ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
2660        synchronized (mLock) {
2661            final ShortcutUser user = mUsers.get(userId);
2662            if (user == null) return null;
2663
2664            final ShortcutPackage pkg = user.getAllPackagesForTest().get(packageName);
2665            if (pkg == null) return null;
2666
2667            return pkg.findShortcutById(shortcutId);
2668        }
2669    }
2670}
2671