ShortcutService.java revision 4d36b3a8c5ba1289d851ef337e46709bba333100
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        if (!mUserManager.isUserRunning(userId)) {
1260            return;
1261        }
1262        postToHandler(() -> {
1263            final ArrayList<ShortcutChangeListener> copy;
1264            synchronized (mLock) {
1265                copy = new ArrayList<>(mListeners);
1266            }
1267            // Note onShortcutChanged() needs to be called with the system service permissions.
1268            for (int i = copy.size() - 1; i >= 0; i--) {
1269                copy.get(i).onShortcutChanged(packageName, userId);
1270            }
1271        });
1272    }
1273
1274    /**
1275     * Clean up / validate an incoming shortcut.
1276     * - Make sure all mandatory fields are set.
1277     * - Make sure the intent's extras are persistable, and them to set
1278     *  {@link ShortcutInfo#mIntentPersistableExtras}.  Also clear its extras.
1279     * - Clear flags.
1280     *
1281     * TODO Detailed unit tests
1282     */
1283    private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1284        Preconditions.checkNotNull(shortcut, "Null shortcut detected");
1285        if (shortcut.getActivityComponent() != null) {
1286            Preconditions.checkState(
1287                    shortcut.getPackageName().equals(
1288                            shortcut.getActivityComponent().getPackageName()),
1289                    "Activity package name mismatch");
1290        }
1291
1292        if (!forUpdate) {
1293            shortcut.enforceMandatoryFields();
1294        }
1295        if (shortcut.getIcon() != null) {
1296            ShortcutInfo.validateIcon(shortcut.getIcon());
1297        }
1298
1299        validateForXml(shortcut.getId());
1300        validateForXml(shortcut.getTitle());
1301        validatePersistableBundleForXml(shortcut.getIntentPersistableExtras());
1302        validatePersistableBundleForXml(shortcut.getExtras());
1303
1304        shortcut.replaceFlags(0);
1305    }
1306
1307    // KXmlSerializer is strict and doesn't allow certain characters, so we disallow those
1308    // characters.
1309
1310    private static void validatePersistableBundleForXml(PersistableBundle b) {
1311        if (b == null || b.size() == 0) {
1312            return;
1313        }
1314        for (String key : b.keySet()) {
1315            validateForXml(key);
1316            final Object value = b.get(key);
1317            if (value == null) {
1318                continue;
1319            } else if (value instanceof String) {
1320                validateForXml((String) value);
1321            } else if (value instanceof String[]) {
1322                for (String v : (String[]) value) {
1323                    validateForXml(v);
1324                }
1325            } else if (value instanceof PersistableBundle) {
1326                validatePersistableBundleForXml((PersistableBundle) value);
1327            }
1328        }
1329    }
1330
1331    private static void validateForXml(String s) {
1332        if (TextUtils.isEmpty(s)) {
1333            return;
1334        }
1335        for (int i = s.length() - 1; i >= 0; i--) {
1336            if (!isAllowedInXml(s.charAt(i))) {
1337                throw new IllegalArgumentException("Unsupported character detected in: " + s);
1338            }
1339        }
1340    }
1341
1342    private static boolean isAllowedInXml(char c) {
1343        return (c >= 0x20 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfffd);
1344    }
1345
1346    // === APIs ===
1347
1348    @Override
1349    public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1350            @UserIdInt int userId) {
1351        verifyCaller(packageName, userId);
1352
1353        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1354        final int size = newShortcuts.size();
1355
1356        synchronized (mLock) {
1357            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1358
1359            // Throttling.
1360            if (!ps.tryApiCall(this)) {
1361                return false;
1362            }
1363            enforceMaxDynamicShortcuts(size);
1364
1365            // Validate the shortcuts.
1366            for (int i = 0; i < size; i++) {
1367                fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1368            }
1369
1370            // First, remove all un-pinned; dynamic shortcuts
1371            ps.deleteAllDynamicShortcuts(this);
1372
1373            // Then, add/update all.  We need to make sure to take over "pinned" flag.
1374            for (int i = 0; i < size; i++) {
1375                final ShortcutInfo newShortcut = newShortcuts.get(i);
1376                ps.addDynamicShortcut(this, newShortcut);
1377            }
1378        }
1379        packageShortcutsChanged(packageName, userId);
1380        return true;
1381    }
1382
1383    @Override
1384    public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1385            @UserIdInt int userId) {
1386        verifyCaller(packageName, userId);
1387
1388        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1389        final int size = newShortcuts.size();
1390
1391        synchronized (mLock) {
1392            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1393
1394            // Throttling.
1395            if (!ps.tryApiCall(this)) {
1396                return false;
1397            }
1398
1399            for (int i = 0; i < size; i++) {
1400                final ShortcutInfo source = newShortcuts.get(i);
1401                fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1402
1403                final ShortcutInfo target = ps.findShortcutById(source.getId());
1404                if (target != null) {
1405                    final boolean replacingIcon = (source.getIcon() != null);
1406                    if (replacingIcon) {
1407                        removeIcon(userId, target);
1408                    }
1409
1410                    target.copyNonNullFieldsFrom(source);
1411
1412                    if (replacingIcon) {
1413                        saveIconAndFixUpShortcut(userId, target);
1414                    }
1415                }
1416            }
1417        }
1418        packageShortcutsChanged(packageName, userId);
1419
1420        return true;
1421    }
1422
1423    @Override
1424    public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1425            @UserIdInt int userId) {
1426        verifyCaller(packageName, userId);
1427
1428        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1429        final int size = newShortcuts.size();
1430
1431        synchronized (mLock) {
1432            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1433
1434            // Throttling.
1435            if (!ps.tryApiCall(this)) {
1436                return false;
1437            }
1438            for (int i = 0; i < size; i++) {
1439                final ShortcutInfo newShortcut = newShortcuts.get(i);
1440
1441                // Validate the shortcut.
1442                fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
1443
1444                // Add it.
1445                ps.addDynamicShortcut(this, newShortcut);
1446            }
1447        }
1448        packageShortcutsChanged(packageName, userId);
1449
1450        return true;
1451    }
1452
1453    @Override
1454    public void removeDynamicShortcuts(String packageName, List shortcutIds,
1455            @UserIdInt int userId) {
1456        verifyCaller(packageName, userId);
1457        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1458
1459        synchronized (mLock) {
1460            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1461                getPackageShortcutsLocked(packageName, userId).deleteDynamicWithId(this,
1462                        Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1463            }
1464        }
1465        packageShortcutsChanged(packageName, userId);
1466    }
1467
1468    @Override
1469    public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
1470        verifyCaller(packageName, userId);
1471
1472        synchronized (mLock) {
1473            getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts(this);
1474        }
1475        packageShortcutsChanged(packageName, userId);
1476    }
1477
1478    @Override
1479    public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1480            @UserIdInt int userId) {
1481        verifyCaller(packageName, userId);
1482        synchronized (mLock) {
1483            return getShortcutsWithQueryLocked(
1484                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1485                    ShortcutInfo::isDynamic);
1486        }
1487    }
1488
1489    @Override
1490    public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1491            @UserIdInt int userId) {
1492        verifyCaller(packageName, userId);
1493        synchronized (mLock) {
1494            return getShortcutsWithQueryLocked(
1495                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1496                    ShortcutInfo::isPinned);
1497        }
1498    }
1499
1500    private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1501            @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1502
1503        final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1504
1505        getPackageShortcutsLocked(packageName, userId).findAll(this, ret, query, cloneFlags);
1506
1507        return new ParceledListSlice<>(ret);
1508    }
1509
1510    @Override
1511    public int getMaxDynamicShortcutCount(String packageName, @UserIdInt int userId)
1512            throws RemoteException {
1513        verifyCaller(packageName, userId);
1514
1515        return mMaxDynamicShortcuts;
1516    }
1517
1518    @Override
1519    public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1520        verifyCaller(packageName, userId);
1521
1522        synchronized (mLock) {
1523            return mMaxUpdatesPerInterval
1524                    - getPackageShortcutsLocked(packageName, userId).getApiCallCount(this);
1525        }
1526    }
1527
1528    @Override
1529    public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
1530        verifyCaller(packageName, userId);
1531
1532        synchronized (mLock) {
1533            return getNextResetTimeLocked();
1534        }
1535    }
1536
1537    @Override
1538    public int getIconMaxDimensions(String packageName, int userId) throws RemoteException {
1539        verifyCaller(packageName, userId);
1540
1541        synchronized (mLock) {
1542            return mMaxIconDimension;
1543        }
1544    }
1545
1546    /**
1547     * Reset all throttling, for developer options and command line.  Only system/shell can call it.
1548     */
1549    @Override
1550    public void resetThrottling() {
1551        enforceSystemOrShell();
1552
1553        resetThrottlingInner(getCallingUserId());
1554    }
1555
1556    void resetThrottlingInner(@UserIdInt int userId) {
1557        synchronized (mLock) {
1558            getUserShortcutsLocked(userId).resetThrottling();
1559        }
1560        scheduleSaveUser(userId);
1561        Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
1562    }
1563
1564    void resetAllThrottlingInner() {
1565        synchronized (mLock) {
1566            mRawLastResetTime = injectCurrentTimeMillis();
1567        }
1568        scheduleSaveBaseState();
1569        Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
1570    }
1571
1572    void resetPackageThrottling(String packageName, int userId) {
1573        synchronized (mLock) {
1574            getPackageShortcutsLocked(packageName, userId)
1575                    .resetRateLimitingForCommandLineNoSaving();
1576            saveUserLocked(userId);
1577        }
1578    }
1579
1580    @Override
1581    public void onApplicationActive(String packageName, int userId) {
1582        if (DEBUG) {
1583            Slog.d(TAG, "onApplicationActive: package=" + packageName + "  userid=" + userId);
1584        }
1585        enforceResetThrottlingPermission();
1586        resetPackageThrottling(packageName, userId);
1587    }
1588
1589    // We override this method in unit tests to do a simpler check.
1590    boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
1591        return hasShortcutHostPermissionInner(callingPackage, userId);
1592    }
1593
1594    // This method is extracted so we can directly call this method from unit tests,
1595    // even when hasShortcutPermission() is overridden.
1596    @VisibleForTesting
1597    boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
1598        synchronized (mLock) {
1599            final long start = System.currentTimeMillis();
1600
1601            final ShortcutUser user = getUserShortcutsLocked(userId);
1602
1603            final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
1604
1605            // Default launcher from package manager.
1606            final long startGetHomeActivitiesAsUser = System.currentTimeMillis();
1607            final ComponentName defaultLauncher = injectPackageManagerInternal()
1608                    .getHomeActivitiesAsUser(allHomeCandidates, userId);
1609            logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
1610
1611            ComponentName detected;
1612            if (defaultLauncher != null) {
1613                detected = defaultLauncher;
1614                if (DEBUG) {
1615                    Slog.v(TAG, "Default launcher from PM: " + detected);
1616                }
1617            } else {
1618                detected = user.getLauncherComponent();
1619
1620                // TODO: Make sure it's still enabled.
1621                if (DEBUG) {
1622                    Slog.v(TAG, "Cached launcher: " + detected);
1623                }
1624            }
1625
1626            if (detected == null) {
1627                // If we reach here, that means it's the first check since the user was created,
1628                // and there's already multiple launchers and there's no default set.
1629                // Find the system one with the highest priority.
1630                // (We need to check the priority too because of FallbackHome in Settings.)
1631                // If there's no system launcher yet, then no one can access shortcuts, until
1632                // the user explicitly
1633                final int size = allHomeCandidates.size();
1634
1635                int lastPriority = Integer.MIN_VALUE;
1636                for (int i = 0; i < size; i++) {
1637                    final ResolveInfo ri = allHomeCandidates.get(i);
1638                    if (!ri.activityInfo.applicationInfo.isSystemApp()) {
1639                        continue;
1640                    }
1641                    if (DEBUG) {
1642                        Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
1643                                ri.activityInfo.getComponentName(), ri.priority));
1644                    }
1645                    if (ri.priority < lastPriority) {
1646                        continue;
1647                    }
1648                    detected = ri.activityInfo.getComponentName();
1649                    lastPriority = ri.priority;
1650                }
1651            }
1652            logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
1653
1654            if (detected != null) {
1655                if (DEBUG) {
1656                    Slog.v(TAG, "Detected launcher: " + detected);
1657                }
1658                user.setLauncherComponent(this, detected);
1659                return detected.getPackageName().equals(callingPackage);
1660            } else {
1661                // Default launcher not found.
1662                return false;
1663            }
1664        }
1665    }
1666
1667    // === House keeping ===
1668
1669    private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId) {
1670        synchronized (mLock) {
1671            forEachLoadedUserLocked(user ->
1672                    cleanUpPackageLocked(packageName, user.getUserId(), packageUserId));
1673        }
1674    }
1675
1676    /**
1677     * Remove all the information associated with a package.  This will really remove all the
1678     * information, including the restore information (i.e. it'll remove packages even if they're
1679     * shadow).
1680     *
1681     * This is called when an app is uninstalled, or an app gets "clear data"ed.
1682     */
1683    @VisibleForTesting
1684    void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId) {
1685        final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
1686
1687        final ShortcutUser user = getUserShortcutsLocked(owningUserId);
1688        boolean doNotify = false;
1689
1690        // First, remove the package from the package list (if the package is a publisher).
1691        if (packageUserId == owningUserId) {
1692            if (user.removePackage(this, packageName) != null) {
1693                doNotify = true;
1694            }
1695        }
1696
1697        // Also remove from the launcher list (if the package is a launcher).
1698        user.removeLauncher(packageUserId, packageName);
1699
1700        // Then remove pinned shortcuts from all launchers.
1701        user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
1702
1703        // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
1704        // step.  Remove them too.
1705        user.forAllPackages(p -> p.refreshPinnedFlags(this));
1706
1707        scheduleSaveUser(owningUserId);
1708
1709        if (doNotify) {
1710            notifyListeners(packageName, owningUserId);
1711        }
1712
1713        if (!wasUserLoaded) {
1714            // Note this will execute the scheduled save.
1715            unloadUserLocked(owningUserId);
1716        }
1717    }
1718
1719    /**
1720     * Entry point from {@link LauncherApps}.
1721     */
1722    private class LocalService extends ShortcutServiceInternal {
1723
1724        @Override
1725        public List<ShortcutInfo> getShortcuts(int launcherUserId,
1726                @NonNull String callingPackage, long changedSince,
1727                @Nullable String packageName, @Nullable List<String> shortcutIds,
1728                @Nullable ComponentName componentName,
1729                int queryFlags, int userId) {
1730            final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1731            final int cloneFlag =
1732                    ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) == 0)
1733                            ? ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER
1734                            : ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO;
1735            if (packageName == null) {
1736                shortcutIds = null; // LauncherAppsService already threw for it though.
1737            }
1738
1739            synchronized (mLock) {
1740                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1741                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1742
1743                if (packageName != null) {
1744                    getShortcutsInnerLocked(launcherUserId,
1745                            callingPackage, packageName, shortcutIds, changedSince,
1746                            componentName, queryFlags, userId, ret, cloneFlag);
1747                } else {
1748                    final List<String> shortcutIdsF = shortcutIds;
1749                    getUserShortcutsLocked(userId).forAllPackages(p -> {
1750                        getShortcutsInnerLocked(launcherUserId,
1751                                callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
1752                                componentName, queryFlags, userId, ret, cloneFlag);
1753                    });
1754                }
1755            }
1756            return ret;
1757        }
1758
1759        private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
1760                @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
1761                @Nullable ComponentName componentName, int queryFlags,
1762                int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
1763            final ArraySet<String> ids = shortcutIds == null ? null
1764                    : new ArraySet<>(shortcutIds);
1765
1766            getPackageShortcutsLocked(packageName, userId).findAll(ShortcutService.this, ret,
1767                    (ShortcutInfo si) -> {
1768                        if (si.getLastChangedTimestamp() < changedSince) {
1769                            return false;
1770                        }
1771                        if (ids != null && !ids.contains(si.getId())) {
1772                            return false;
1773                        }
1774                        if (componentName != null
1775                                && !componentName.equals(si.getActivityComponent())) {
1776                            return false;
1777                        }
1778                        final boolean matchDynamic =
1779                                ((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
1780                                        && si.isDynamic();
1781                        final boolean matchPinned =
1782                                ((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
1783                                        && si.isPinned();
1784                        return matchDynamic || matchPinned;
1785                    }, cloneFlag, callingPackage, launcherUserId);
1786        }
1787
1788        @Override
1789        public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
1790                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1791            Preconditions.checkStringNotEmpty(packageName, "packageName");
1792            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
1793
1794            synchronized (mLock) {
1795                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1796                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1797
1798                final ShortcutInfo si = getShortcutInfoLocked(
1799                        launcherUserId, callingPackage, packageName, shortcutId, userId);
1800                return si != null && si.isPinned();
1801            }
1802        }
1803
1804        private ShortcutInfo getShortcutInfoLocked(
1805                int launcherUserId, @NonNull String callingPackage,
1806                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1807            Preconditions.checkStringNotEmpty(packageName, "packageName");
1808            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
1809
1810            final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
1811            getPackageShortcutsLocked(packageName, userId).findAll(
1812                    ShortcutService.this, list,
1813                    (ShortcutInfo si) -> shortcutId.equals(si.getId()),
1814                    /* clone flags=*/ 0, callingPackage, launcherUserId);
1815            return list.size() == 0 ? null : list.get(0);
1816        }
1817
1818        @Override
1819        public void pinShortcuts(int launcherUserId,
1820                @NonNull String callingPackage, @NonNull String packageName,
1821                @NonNull List<String> shortcutIds, int userId) {
1822            // Calling permission must be checked by LauncherAppsImpl.
1823            Preconditions.checkStringNotEmpty(packageName, "packageName");
1824            Preconditions.checkNotNull(shortcutIds, "shortcutIds");
1825
1826            synchronized (mLock) {
1827                final ShortcutLauncher launcher =
1828                        getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
1829                launcher.attemptToRestoreIfNeededAndSave(ShortcutService.this);
1830
1831                launcher.pinShortcuts(
1832                        ShortcutService.this, userId, packageName, shortcutIds);
1833            }
1834            packageShortcutsChanged(packageName, userId);
1835        }
1836
1837        @Override
1838        public Intent createShortcutIntent(int launcherUserId,
1839                @NonNull String callingPackage,
1840                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1841            // Calling permission must be checked by LauncherAppsImpl.
1842            Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
1843            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
1844
1845            synchronized (mLock) {
1846                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1847                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1848
1849                // Make sure the shortcut is actually visible to the launcher.
1850                final ShortcutInfo si = getShortcutInfoLocked(
1851                        launcherUserId, callingPackage, packageName, shortcutId, userId);
1852                // "si == null" should suffice here, but check the flags too just to make sure.
1853                if (si == null || !(si.isDynamic() || si.isPinned())) {
1854                    return null;
1855                }
1856                return si.getIntent();
1857            }
1858        }
1859
1860        @Override
1861        public void addListener(@NonNull ShortcutChangeListener listener) {
1862            synchronized (mLock) {
1863                mListeners.add(Preconditions.checkNotNull(listener));
1864            }
1865        }
1866
1867        @Override
1868        public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
1869                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1870            Preconditions.checkNotNull(callingPackage, "callingPackage");
1871            Preconditions.checkNotNull(packageName, "packageName");
1872            Preconditions.checkNotNull(shortcutId, "shortcutId");
1873
1874            synchronized (mLock) {
1875                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1876                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1877
1878                final ShortcutInfo shortcutInfo = getPackageShortcutsLocked(
1879                        packageName, userId).findShortcutById(shortcutId);
1880                return (shortcutInfo != null && shortcutInfo.hasIconResource())
1881                        ? shortcutInfo.getIconResourceId() : 0;
1882            }
1883        }
1884
1885        @Override
1886        public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
1887                @NonNull String callingPackage, @NonNull String packageName,
1888                @NonNull String shortcutId, int userId) {
1889            Preconditions.checkNotNull(callingPackage, "callingPackage");
1890            Preconditions.checkNotNull(packageName, "packageName");
1891            Preconditions.checkNotNull(shortcutId, "shortcutId");
1892
1893            synchronized (mLock) {
1894                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1895                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1896
1897                final ShortcutInfo shortcutInfo = getPackageShortcutsLocked(
1898                        packageName, userId).findShortcutById(shortcutId);
1899                if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
1900                    return null;
1901                }
1902                try {
1903                    if (shortcutInfo.getBitmapPath() == null) {
1904                        Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
1905                        return null;
1906                    }
1907                    return ParcelFileDescriptor.open(
1908                            new File(shortcutInfo.getBitmapPath()),
1909                            ParcelFileDescriptor.MODE_READ_ONLY);
1910                } catch (FileNotFoundException e) {
1911                    Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
1912                    return null;
1913                }
1914            }
1915        }
1916
1917        @Override
1918        public boolean hasShortcutHostPermission(int launcherUserId,
1919                @NonNull String callingPackage) {
1920            return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
1921        }
1922
1923        /**
1924         * Called by AM when the system locale changes *within the AM lock.  ABSOLUTELY do not take
1925         * any locks in this method.
1926         */
1927        @Override
1928        public void onSystemLocaleChangedNoLock() {
1929            // DO NOT HOLD ANY LOCKS HERE.
1930
1931            // We want to reset throttling for all packages for all users.  But we can't just do so
1932            // here because:
1933            // - We can't load/save users that are locked.
1934            // - Even for loaded users, resetting the counters would require us to hold mLock.
1935            //
1936            // So we use a "pull" model instead.  In here, we just increment the "locale change
1937            // sequence number".  Each ShortcutUser has the "last known locale change sequence".
1938            //
1939            // This allows ShortcutUser's to detect the system locale change, so they can reset
1940            // counters.
1941
1942            mLocaleChangeSequenceNumber.incrementAndGet();
1943            postToHandler(() -> scheduleSaveBaseState());
1944        }
1945    }
1946
1947    /**
1948     * Package event callbacks.
1949     */
1950    @VisibleForTesting
1951    final PackageMonitor mPackageMonitor = new PackageMonitor() {
1952        @Override
1953        public void onPackageAdded(String packageName, int uid) {
1954            handlePackageAdded(packageName, getChangingUserId());
1955        }
1956
1957        @Override
1958        public void onPackageUpdateFinished(String packageName, int uid) {
1959            handlePackageUpdateFinished(packageName, getChangingUserId());
1960        }
1961
1962        @Override
1963        public void onPackageRemoved(String packageName, int uid) {
1964            handlePackageRemoved(packageName, getChangingUserId());
1965        }
1966
1967        @Override
1968        public void onPackageDataCleared(String packageName, int uid) {
1969            handlePackageDataCleared(packageName, getChangingUserId());
1970        }
1971    };
1972
1973    /**
1974     * Called when a user is unlocked.
1975     * - Check all known packages still exist, and otherwise perform cleanup.
1976     * - If a package still exists, check the version code.  If it's been updated, may need to
1977     *   update timestamps of its shortcuts.
1978     */
1979    @VisibleForTesting
1980    void checkPackageChanges(@UserIdInt int ownerUserId) {
1981        if (DEBUG) {
1982            Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
1983        }
1984        final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
1985
1986        synchronized (mLock) {
1987            final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
1988
1989            user.forAllPackageItems(spi -> {
1990                if (spi.getPackageInfo().isShadow()) {
1991                    return; // Don't delete shadow information.
1992                }
1993                final int versionCode = getApplicationVersionCode(
1994                        spi.getPackageName(), spi.getPackageUserId());
1995                if (versionCode >= 0) {
1996                    // Package still installed, see if it's updated.
1997                    getUserShortcutsLocked(ownerUserId).handlePackageUpdated(
1998                            this, spi.getPackageName(), versionCode);
1999                } else {
2000                    gonePackages.add(PackageWithUser.of(spi));
2001                }
2002            });
2003            if (gonePackages.size() > 0) {
2004                for (int i = gonePackages.size() - 1; i >= 0; i--) {
2005                    final PackageWithUser pu = gonePackages.get(i);
2006                    cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId);
2007                }
2008            }
2009        }
2010    }
2011
2012    private void handlePackageAdded(String packageName, @UserIdInt int userId) {
2013        if (DEBUG) {
2014            Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2015        }
2016        synchronized (mLock) {
2017            forEachLoadedUserLocked(user ->
2018                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
2019        }
2020    }
2021
2022    private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
2023        if (DEBUG) {
2024            Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2025                    packageName, userId));
2026        }
2027        synchronized (mLock) {
2028            forEachLoadedUserLocked(user ->
2029                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
2030
2031            final int versionCode = getApplicationVersionCode(packageName, userId);
2032            if (versionCode < 0) {
2033                return; // shouldn't happen
2034            }
2035            getUserShortcutsLocked(userId).handlePackageUpdated(this, packageName, versionCode);
2036        }
2037    }
2038
2039    private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
2040        if (DEBUG) {
2041            Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2042                    packageUserId));
2043        }
2044        cleanUpPackageForAllLoadedUsers(packageName, packageUserId);
2045    }
2046
2047    private void handlePackageDataCleared(String packageName, int packageUserId) {
2048        if (DEBUG) {
2049            Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2050                    packageUserId));
2051        }
2052        cleanUpPackageForAllLoadedUsers(packageName, packageUserId);
2053    }
2054
2055    // === PackageManager interaction ===
2056
2057    PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2058        return injectPackageInfo(packageName, userId, true);
2059    }
2060
2061    int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
2062        final long token = injectClearCallingIdentity();
2063        try {
2064            return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS
2065                    , userId);
2066        } catch (RemoteException e) {
2067            // Shouldn't happen.
2068            Slog.wtf(TAG, "RemoteException", e);
2069            return -1;
2070        } finally {
2071            injectRestoreCallingIdentity(token);
2072        }
2073    }
2074
2075    @VisibleForTesting
2076    PackageInfo injectPackageInfo(String packageName, @UserIdInt int userId,
2077            boolean getSignatures) {
2078        final long start = System.currentTimeMillis();
2079        final long token = injectClearCallingIdentity();
2080        try {
2081            return mIPackageManager.getPackageInfo(packageName, PACKAGE_MATCH_FLAGS
2082                    | (getSignatures ? PackageManager.GET_SIGNATURES : 0)
2083                    , userId);
2084        } catch (RemoteException e) {
2085            // Shouldn't happen.
2086            Slog.wtf(TAG, "RemoteException", e);
2087            return null;
2088        } finally {
2089            injectRestoreCallingIdentity(token);
2090
2091            logDurationStat(
2092                    (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2093                    start);
2094        }
2095    }
2096
2097    @VisibleForTesting
2098    ApplicationInfo injectApplicationInfo(String packageName, @UserIdInt int userId) {
2099        final long start = System.currentTimeMillis();
2100        final long token = injectClearCallingIdentity();
2101        try {
2102            return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2103        } catch (RemoteException e) {
2104            // Shouldn't happen.
2105            Slog.wtf(TAG, "RemoteException", e);
2106            return null;
2107        } finally {
2108            injectRestoreCallingIdentity(token);
2109
2110            logDurationStat(Stats.GET_APPLICATION_INFO, start);
2111        }
2112    }
2113
2114    private boolean isApplicationFlagSet(String packageName, int userId, int flags) {
2115        final ApplicationInfo ai = injectApplicationInfo(packageName, userId);
2116        return (ai != null) && ((ai.flags & flags) == flags);
2117    }
2118
2119    boolean isPackageInstalled(String packageName, int userId) {
2120        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_INSTALLED);
2121    }
2122
2123    /**
2124     * @return the version code of the package, or -1 if the app is not installed.
2125     */
2126    int getApplicationVersionCode(String packageName, int userId) {
2127        final ApplicationInfo ai = injectApplicationInfo(packageName, userId);
2128        if ((ai == null) || ((ai.flags & ApplicationInfo.FLAG_INSTALLED) == 0)) {
2129            return -1;
2130        }
2131        return ai.versionCode;
2132    }
2133
2134    // === Backup & restore ===
2135
2136    boolean shouldBackupApp(String packageName, int userId) {
2137        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
2138    }
2139
2140    boolean shouldBackupApp(PackageInfo pi) {
2141        return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
2142    }
2143
2144    @Override
2145    public byte[] getBackupPayload(@UserIdInt int userId) {
2146        enforceSystem();
2147        if (DEBUG) {
2148            Slog.d(TAG, "Backing up user " + userId);
2149        }
2150        synchronized (mLock) {
2151            final ShortcutUser user = getUserShortcutsLocked(userId);
2152            if (user == null) {
2153                Slog.w(TAG, "Can't backup: user not found: id=" + userId);
2154                return null;
2155            }
2156
2157            user.forAllPackageItems(spi -> spi.refreshPackageInfoAndSave(this));
2158
2159            // Then save.
2160            final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
2161            try {
2162                saveUserInternalLocked(userId, os, /* forBackup */ true);
2163            } catch (XmlPullParserException|IOException e) {
2164                // Shouldn't happen.
2165                Slog.w(TAG, "Backup failed.", e);
2166                return null;
2167            }
2168            return os.toByteArray();
2169        }
2170    }
2171
2172    @Override
2173    public void applyRestore(byte[] payload, @UserIdInt int userId) {
2174        enforceSystem();
2175        if (DEBUG) {
2176            Slog.d(TAG, "Restoring user " + userId);
2177        }
2178        final ShortcutUser user;
2179        final ByteArrayInputStream is = new ByteArrayInputStream(payload);
2180        try {
2181            user = loadUserInternal(userId, is, /* fromBackup */ true);
2182        } catch (XmlPullParserException|IOException e) {
2183            Slog.w(TAG, "Restoration failed.", e);
2184            return;
2185        }
2186        synchronized (mLock) {
2187            mUsers.put(userId, user);
2188
2189            // Then purge all the save images.
2190            final File bitmapPath = getUserBitmapFilePath(userId);
2191            final boolean success = FileUtils.deleteContents(bitmapPath);
2192            if (!success) {
2193                Slog.w(TAG, "Failed to delete " + bitmapPath);
2194            }
2195
2196            saveUserLocked(userId);
2197        }
2198    }
2199
2200    // === Dump ===
2201
2202    @Override
2203    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2204        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2205                != PackageManager.PERMISSION_GRANTED) {
2206            pw.println("Permission Denial: can't dump UserManager from from pid="
2207                    + Binder.getCallingPid()
2208                    + ", uid=" + Binder.getCallingUid()
2209                    + " without permission "
2210                    + android.Manifest.permission.DUMP);
2211            return;
2212        }
2213        dumpInner(pw, args);
2214    }
2215
2216    @VisibleForTesting
2217    void dumpInner(PrintWriter pw, String[] args) {
2218        synchronized (mLock) {
2219            final long now = injectCurrentTimeMillis();
2220            pw.print("Now: [");
2221            pw.print(now);
2222            pw.print("] ");
2223            pw.print(formatTime(now));
2224
2225            pw.print("  Raw last reset: [");
2226            pw.print(mRawLastResetTime);
2227            pw.print("] ");
2228            pw.print(formatTime(mRawLastResetTime));
2229
2230            final long last = getLastResetTimeLocked();
2231            pw.print("  Last reset: [");
2232            pw.print(last);
2233            pw.print("] ");
2234            pw.print(formatTime(last));
2235
2236            final long next = getNextResetTimeLocked();
2237            pw.print("  Next reset: [");
2238            pw.print(next);
2239            pw.print("] ");
2240            pw.print(formatTime(next));
2241
2242            pw.print("  Locale change seq#: ");
2243            pw.print(mLocaleChangeSequenceNumber.get());
2244            pw.println();
2245
2246            pw.print("  Config:");
2247            pw.print("    Max icon dim: ");
2248            pw.println(mMaxIconDimension);
2249            pw.print("    Icon format: ");
2250            pw.println(mIconPersistFormat);
2251            pw.print("    Icon quality: ");
2252            pw.println(mIconPersistQuality);
2253            pw.print("    saveDelayMillis: ");
2254            pw.println(mSaveDelayMillis);
2255            pw.print("    resetInterval: ");
2256            pw.println(mResetInterval);
2257            pw.print("    maxUpdatesPerInterval: ");
2258            pw.println(mMaxUpdatesPerInterval);
2259            pw.print("    maxDynamicShortcuts: ");
2260            pw.println(mMaxDynamicShortcuts);
2261            pw.println();
2262
2263            pw.println("  Stats:");
2264            synchronized (mStatLock) {
2265                final String p = "    ";
2266                dumpStatLS(pw, p, Stats.GET_DEFAULT_HOME, "getHomeActivities()");
2267                dumpStatLS(pw, p, Stats.LAUNCHER_PERMISSION_CHECK, "Launcher permission check");
2268
2269                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO, "getPackageInfo()");
2270                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO_WITH_SIG, "getPackageInfo(SIG)");
2271                dumpStatLS(pw, p, Stats.GET_APPLICATION_INFO, "getApplicationInfo");
2272            }
2273
2274            for (int i = 0; i < mUsers.size(); i++) {
2275                pw.println();
2276                mUsers.valueAt(i).dump(this, pw, "  ");
2277            }
2278
2279            pw.println();
2280            pw.println("  UID state:");
2281
2282            for (int i = 0; i < mUidState.size(); i++) {
2283                final int uid = mUidState.keyAt(i);
2284                final int state = mUidState.valueAt(i);
2285                pw.print("    UID=");
2286                pw.print(uid);
2287                pw.print(" state=");
2288                pw.print(state);
2289                if (isProcessStateForeground(state)) {
2290                    pw.print("  [FG]");
2291                }
2292                pw.print("  last FG=");
2293                pw.print(mUidLastForegroundElapsedTime.get(uid));
2294                pw.println();
2295            }
2296        }
2297    }
2298
2299    static String formatTime(long time) {
2300        Time tobj = new Time();
2301        tobj.set(time);
2302        return tobj.format("%Y-%m-%d %H:%M:%S");
2303    }
2304
2305    private void dumpStatLS(PrintWriter pw, String prefix, int statId, String label) {
2306        pw.print(prefix);
2307        final int count = mCountStats[statId];
2308        final long dur = mDurationStats[statId];
2309        pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
2310                label, count, dur,
2311                (count == 0 ? 0 : ((double) dur) / count)));
2312    }
2313
2314    // === Shell support ===
2315
2316    @Override
2317    public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2318            String[] args, ResultReceiver resultReceiver) throws RemoteException {
2319
2320        enforceShell();
2321
2322        (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
2323    }
2324
2325    static class CommandException extends Exception {
2326        public CommandException(String message) {
2327            super(message);
2328        }
2329    }
2330
2331    /**
2332     * Handle "adb shell cmd".
2333     */
2334    private class MyShellCommand extends ShellCommand {
2335
2336        private int mUserId = UserHandle.USER_SYSTEM;
2337
2338        private void parseOptions(boolean takeUser)
2339                throws CommandException {
2340            String opt;
2341            while ((opt = getNextOption()) != null) {
2342                switch (opt) {
2343                    case "--user":
2344                        if (takeUser) {
2345                            mUserId = UserHandle.parseUserArg(getNextArgRequired());
2346                            break;
2347                        }
2348                        // fallthrough
2349                    default:
2350                        throw new CommandException("Unknown option: " + opt);
2351                }
2352            }
2353        }
2354
2355        @Override
2356        public int onCommand(String cmd) {
2357            if (cmd == null) {
2358                return handleDefaultCommands(cmd);
2359            }
2360            final PrintWriter pw = getOutPrintWriter();
2361            try {
2362                switch (cmd) {
2363                    case "reset-package-throttling":
2364                        handleResetPackageThrottling();
2365                        break;
2366                    case "reset-throttling":
2367                        handleResetThrottling();
2368                        break;
2369                    case "reset-all-throttling":
2370                        handleResetAllThrottling();
2371                        break;
2372                    case "override-config":
2373                        handleOverrideConfig();
2374                        break;
2375                    case "reset-config":
2376                        handleResetConfig();
2377                        break;
2378                    case "clear-default-launcher":
2379                        handleClearDefaultLauncher();
2380                        break;
2381                    case "get-default-launcher":
2382                        handleGetDefaultLauncher();
2383                        break;
2384                    case "refresh-default-launcher":
2385                        handleRefreshDefaultLauncher();
2386                        break;
2387                    case "unload-user":
2388                        handleUnloadUser();
2389                        break;
2390                    case "clear-shortcuts":
2391                        handleClearShortcuts();
2392                        break;
2393                    default:
2394                        return handleDefaultCommands(cmd);
2395                }
2396            } catch (CommandException e) {
2397                pw.println("Error: " + e.getMessage());
2398                return 1;
2399            }
2400            pw.println("Success");
2401            return 0;
2402        }
2403
2404        @Override
2405        public void onHelp() {
2406            final PrintWriter pw = getOutPrintWriter();
2407            pw.println("Usage: cmd shortcut COMMAND [options ...]");
2408            pw.println();
2409            pw.println("cmd shortcut reset-package-throttling [--user USER_ID] PACKAGE");
2410            pw.println("    Reset throttling for a package");
2411            pw.println();
2412            pw.println("cmd shortcut reset-throttling [--user USER_ID]");
2413            pw.println("    Reset throttling for all packages and users");
2414            pw.println();
2415            pw.println("cmd shortcut reset-all-throttling");
2416            pw.println("    Reset the throttling state for all users");
2417            pw.println();
2418            pw.println("cmd shortcut override-config CONFIG");
2419            pw.println("    Override the configuration for testing (will last until reboot)");
2420            pw.println();
2421            pw.println("cmd shortcut reset-config");
2422            pw.println("    Reset the configuration set with \"update-config\"");
2423            pw.println();
2424            pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
2425            pw.println("    Clear the cached default launcher");
2426            pw.println();
2427            pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
2428            pw.println("    Show the cached default launcher");
2429            pw.println();
2430            pw.println("cmd shortcut refresh-default-launcher [--user USER_ID]");
2431            pw.println("    Refresh the cached default launcher");
2432            pw.println();
2433            pw.println("cmd shortcut unload-user [--user USER_ID]");
2434            pw.println("    Unload a user from the memory");
2435            pw.println("    (This should not affect any observable behavior)");
2436            pw.println();
2437            pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
2438            pw.println("    Remove all shortcuts from a package, including pinned shortcuts");
2439            pw.println();
2440        }
2441
2442        private void handleResetThrottling() throws CommandException {
2443            parseOptions(/* takeUser =*/ true);
2444
2445            Slog.i(TAG, "cmd: handleResetThrottling");
2446
2447            resetThrottlingInner(mUserId);
2448        }
2449
2450        private void handleResetAllThrottling() {
2451            Slog.i(TAG, "cmd: handleResetAllThrottling");
2452
2453            resetAllThrottlingInner();
2454        }
2455
2456        private void handleResetPackageThrottling() throws CommandException {
2457            parseOptions(/* takeUser =*/ true);
2458
2459            final String packageName = getNextArgRequired();
2460
2461            Slog.i(TAG, "cmd: handleResetPackageThrottling: " + packageName);
2462
2463            resetPackageThrottling(packageName, mUserId);
2464        }
2465
2466        private void handleOverrideConfig() throws CommandException {
2467            final String config = getNextArgRequired();
2468
2469            Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
2470
2471            synchronized (mLock) {
2472                if (!updateConfigurationLocked(config)) {
2473                    throw new CommandException("override-config failed.  See logcat for details.");
2474                }
2475            }
2476        }
2477
2478        private void handleResetConfig() {
2479            Slog.i(TAG, "cmd: handleResetConfig");
2480
2481            synchronized (mLock) {
2482                loadConfigurationLocked();
2483            }
2484        }
2485
2486        private void clearLauncher() {
2487            synchronized (mLock) {
2488                getUserShortcutsLocked(mUserId).setLauncherComponent(
2489                        ShortcutService.this, null);
2490            }
2491        }
2492
2493        private void showLauncher() {
2494            synchronized (mLock) {
2495                // This ensures to set the cached launcher.  Package name doesn't matter.
2496                hasShortcutHostPermissionInner("-", mUserId);
2497
2498                getOutPrintWriter().println("Launcher: "
2499                        + getUserShortcutsLocked(mUserId).getLauncherComponent());
2500            }
2501        }
2502
2503        private void handleClearDefaultLauncher() throws CommandException {
2504            parseOptions(/* takeUser =*/ true);
2505
2506            clearLauncher();
2507        }
2508
2509        private void handleGetDefaultLauncher() throws CommandException {
2510            parseOptions(/* takeUser =*/ true);
2511
2512            showLauncher();
2513        }
2514
2515        private void handleRefreshDefaultLauncher() throws CommandException {
2516            parseOptions(/* takeUser =*/ true);
2517
2518            clearLauncher();
2519            showLauncher();
2520        }
2521
2522        private void handleUnloadUser() throws CommandException {
2523            parseOptions(/* takeUser =*/ true);
2524
2525            Slog.i(TAG, "cmd: handleUnloadUser: " + mUserId);
2526
2527            ShortcutService.this.handleCleanupUser(mUserId);
2528        }
2529
2530        private void handleClearShortcuts() throws CommandException {
2531            parseOptions(/* takeUser =*/ true);
2532            final String packageName = getNextArgRequired();
2533
2534            Slog.i(TAG, "cmd: handleClearShortcuts: " + mUserId + ", " + packageName);
2535
2536            ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId);
2537        }
2538    }
2539
2540    // === Unit test support ===
2541
2542    // Injection point.
2543    @VisibleForTesting
2544    long injectCurrentTimeMillis() {
2545        return System.currentTimeMillis();
2546    }
2547
2548    @VisibleForTesting
2549    long injectElapsedRealtime() {
2550        return SystemClock.elapsedRealtime();
2551    }
2552
2553    // Injection point.
2554    @VisibleForTesting
2555    int injectBinderCallingUid() {
2556        return getCallingUid();
2557    }
2558
2559    private int getCallingUserId() {
2560        return UserHandle.getUserId(injectBinderCallingUid());
2561    }
2562
2563    // Injection point.
2564    @VisibleForTesting
2565    long injectClearCallingIdentity() {
2566        return Binder.clearCallingIdentity();
2567    }
2568
2569    // Injection point.
2570    @VisibleForTesting
2571    void injectRestoreCallingIdentity(long token) {
2572        Binder.restoreCallingIdentity(token);
2573    }
2574
2575    final void wtf(String message) {
2576        wtf( message, /* exception= */ null);
2577    }
2578
2579    // Injection point.
2580    void wtf(String message, Exception e) {
2581        Slog.wtf(TAG, message, e);
2582    }
2583
2584    @VisibleForTesting
2585    File injectSystemDataPath() {
2586        return Environment.getDataSystemDirectory();
2587    }
2588
2589    @VisibleForTesting
2590    File injectUserDataPath(@UserIdInt int userId) {
2591        return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
2592    }
2593
2594    @VisibleForTesting
2595    boolean injectIsLowRamDevice() {
2596        return ActivityManager.isLowRamDeviceStatic();
2597    }
2598
2599    @VisibleForTesting
2600    void injectRegisterUidObserver(IUidObserver observer, int which) {
2601        try {
2602            ActivityManagerNative.getDefault().registerUidObserver(observer, which);
2603        } catch (RemoteException shouldntHappen) {
2604        }
2605    }
2606
2607    @VisibleForTesting
2608    PackageManagerInternal injectPackageManagerInternal() {
2609        return mPackageManagerInternal;
2610    }
2611
2612    File getUserBitmapFilePath(@UserIdInt int userId) {
2613        return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
2614    }
2615
2616    @VisibleForTesting
2617    SparseArray<ShortcutUser> getShortcutsForTest() {
2618        return mUsers;
2619    }
2620
2621    @VisibleForTesting
2622    int getMaxDynamicShortcutsForTest() {
2623        return mMaxDynamicShortcuts;
2624    }
2625
2626    @VisibleForTesting
2627    int getMaxUpdatesPerIntervalForTest() {
2628        return mMaxUpdatesPerInterval;
2629    }
2630
2631    @VisibleForTesting
2632    long getResetIntervalForTest() {
2633        return mResetInterval;
2634    }
2635
2636    @VisibleForTesting
2637    int getMaxIconDimensionForTest() {
2638        return mMaxIconDimension;
2639    }
2640
2641    @VisibleForTesting
2642    CompressFormat getIconPersistFormatForTest() {
2643        return mIconPersistFormat;
2644    }
2645
2646    @VisibleForTesting
2647    int getIconPersistQualityForTest() {
2648        return mIconPersistQuality;
2649    }
2650
2651    @VisibleForTesting
2652    ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
2653        synchronized (mLock) {
2654            final ShortcutUser user = mUsers.get(userId);
2655            if (user == null) return null;
2656
2657            final ShortcutPackage pkg = user.getAllPackagesForTest().get(packageName);
2658            if (pkg == null) return null;
2659
2660            return pkg.findShortcutById(shortcutId);
2661        }
2662    }
2663}
2664