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