ShortcutService.java revision 5ba0d3e3a3035b67d2ce3a59975145b1e0061ef4
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 = 24 * 60 * 60; // 1 day
130
131    @VisibleForTesting
132    static final int DEFAULT_MAX_DAILY_UPDATES = 10;
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_DAILY_UPDATES = "max_daily_updates";
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 a day.
236     */
237    int mMaxDailyUpdates;
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            cleanupGonePackages(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        mMaxDailyUpdates = Math.max(0, (int) parser.getLong(
430                ConfigConstants.KEY_MAX_DAILY_UPDATES, DEFAULT_MAX_DAILY_UPDATES));
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    @VisibleForTesting
911    static class FileOutputStreamWithPath extends FileOutputStream {
912        private final File mFile;
913
914        public FileOutputStreamWithPath(File file) throws FileNotFoundException {
915            super(file);
916            mFile = file;
917        }
918
919        public File getFile() {
920            return mFile;
921        }
922    }
923
924    /**
925     * Build the cached bitmap filename for a shortcut icon.
926     *
927     * The filename will be based on the ID, except certain characters will be escaped.
928     */
929    @VisibleForTesting
930    FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
931            throws IOException {
932        final File packagePath = new File(getUserBitmapFilePath(userId),
933                shortcut.getPackageName());
934        if (!packagePath.isDirectory()) {
935            packagePath.mkdirs();
936            if (!packagePath.isDirectory()) {
937                throw new IOException("Unable to create directory " + packagePath);
938            }
939            SELinux.restorecon(packagePath);
940        }
941
942        final String baseName = String.valueOf(injectCurrentTimeMillis());
943        for (int suffix = 0;; suffix++) {
944            final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
945            final File file = new File(packagePath, filename);
946            if (!file.exists()) {
947                if (DEBUG) {
948                    Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
949                }
950                return new FileOutputStreamWithPath(file);
951            }
952        }
953    }
954
955    void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
956        if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
957            return;
958        }
959
960        final long token = injectClearCallingIdentity();
961        try {
962            // Clear icon info on the shortcut.
963            shortcut.setIconResourceId(0);
964            shortcut.setBitmapPath(null);
965
966            final Icon icon = shortcut.getIcon();
967            if (icon == null) {
968                return; // has no icon
969            }
970
971            Bitmap bitmap;
972            Bitmap bitmapToRecycle = null;
973            try {
974                switch (icon.getType()) {
975                    case Icon.TYPE_RESOURCE: {
976                        injectValidateIconResPackage(shortcut, icon);
977
978                        shortcut.setIconResourceId(icon.getResId());
979                        shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
980                        return;
981                    }
982                    case Icon.TYPE_BITMAP: {
983                        bitmap = icon.getBitmap(); // Don't recycle in this case.
984                        break;
985                    }
986                    case Icon.TYPE_URI: {
987                        final Uri uri = ContentProvider.maybeAddUserId(icon.getUri(), userId);
988
989                        try (InputStream is = mContext.getContentResolver().openInputStream(uri)) {
990
991                            bitmapToRecycle = BitmapFactory.decodeStream(is);
992                            bitmap = bitmapToRecycle;
993
994                        } catch (IOException e) {
995                            Slog.e(TAG, "Unable to load icon from " + uri);
996                            return;
997                        }
998                        break;
999                    }
1000                    default:
1001                        // This shouldn't happen because we've already validated the icon, but
1002                        // just in case.
1003                        throw ShortcutInfo.getInvalidIconException();
1004                }
1005                if (bitmap == null) {
1006                    Slog.e(TAG, "Null bitmap detected");
1007                    return;
1008                }
1009                // Shrink and write to the file.
1010                File path = null;
1011                try {
1012                    final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1013                    try {
1014                        path = out.getFile();
1015
1016                        Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1017                        try {
1018                            shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1019                        } finally {
1020                            if (bitmap != shrunk) {
1021                                shrunk.recycle();
1022                            }
1023                        }
1024
1025                        shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1026                        shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1027                    } finally {
1028                        IoUtils.closeQuietly(out);
1029                    }
1030                } catch (IOException|RuntimeException e) {
1031                    // STOPSHIP Change wtf to e
1032                    Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1033                    if (path != null && path.exists()) {
1034                        path.delete();
1035                    }
1036                }
1037            } finally {
1038                if (bitmapToRecycle != null) {
1039                    bitmapToRecycle.recycle();
1040                }
1041                // Once saved, we won't use the original icon information, so null it out.
1042                shortcut.clearIcon();
1043            }
1044        } finally {
1045            injectRestoreCallingIdentity(token);
1046        }
1047    }
1048
1049    // Unfortunately we can't do this check in unit tests because we fake creator package names,
1050    // so override in unit tests.
1051    // TODO CTS this case.
1052    void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
1053        if (!shortcut.getPackageName().equals(icon.getResPackage())) {
1054            throw new IllegalArgumentException(
1055                    "Icon resource must reside in shortcut owner package");
1056        }
1057    }
1058
1059    @VisibleForTesting
1060    static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1061        // Original width/height.
1062        final int ow = in.getWidth();
1063        final int oh = in.getHeight();
1064        if ((ow <= maxSize) && (oh <= maxSize)) {
1065            if (DEBUG) {
1066                Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1067            }
1068            return in;
1069        }
1070        final int longerDimension = Math.max(ow, oh);
1071
1072        // New width and height.
1073        final int nw = ow * maxSize / longerDimension;
1074        final int nh = oh * maxSize / longerDimension;
1075        if (DEBUG) {
1076            Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1077                    ow, oh, nw, nh));
1078        }
1079
1080        final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1081        final Canvas c = new Canvas(scaledBitmap);
1082
1083        final RectF dst = new RectF(0, 0, nw, nh);
1084
1085        c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1086
1087        return scaledBitmap;
1088    }
1089
1090    // === Caller validation ===
1091
1092    private boolean isCallerSystem() {
1093        final int callingUid = injectBinderCallingUid();
1094         return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
1095    }
1096
1097    private boolean isCallerShell() {
1098        final int callingUid = injectBinderCallingUid();
1099        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1100    }
1101
1102    private void enforceSystemOrShell() {
1103        Preconditions.checkState(isCallerSystem() || isCallerShell(),
1104                "Caller must be system or shell");
1105    }
1106
1107    private void enforceShell() {
1108        Preconditions.checkState(isCallerShell(), "Caller must be shell");
1109    }
1110
1111    private void enforceSystem() {
1112        Preconditions.checkState(isCallerSystem(), "Caller must be system");
1113    }
1114
1115    private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1116        Preconditions.checkStringNotEmpty(packageName, "packageName");
1117
1118        if (isCallerSystem()) {
1119            return; // no check
1120        }
1121
1122        final int callingUid = injectBinderCallingUid();
1123
1124        // Otherwise, make sure the arguments are valid.
1125        if (UserHandle.getUserId(callingUid) != userId) {
1126            throw new SecurityException("Invalid user-ID");
1127        }
1128        if (injectGetPackageUid(packageName, userId) == injectBinderCallingUid()) {
1129            return; // Caller is valid.
1130        }
1131        throw new SecurityException("Calling package name mismatch");
1132    }
1133
1134    void postToHandler(Runnable r) {
1135        mHandler.post(r);
1136    }
1137
1138    /**
1139     * Throw if {@code numShortcuts} is bigger than {@link #mMaxDynamicShortcuts}.
1140     */
1141    void enforceMaxDynamicShortcuts(int numShortcuts) {
1142        if (numShortcuts > mMaxDynamicShortcuts) {
1143            throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1144        }
1145    }
1146
1147    /**
1148     * - Sends a notification to LauncherApps
1149     * - Write to file
1150     */
1151    private void userPackageChanged(@NonNull String packageName, @UserIdInt int userId) {
1152        notifyListeners(packageName, userId);
1153        scheduleSaveUser(userId);
1154    }
1155
1156    private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
1157        if (!mUserManager.isUserRunning(userId)) {
1158            return;
1159        }
1160        postToHandler(() -> {
1161            final ArrayList<ShortcutChangeListener> copy;
1162            synchronized (mLock) {
1163                copy = new ArrayList<>(mListeners);
1164            }
1165            // Note onShortcutChanged() needs to be called with the system service permissions.
1166            for (int i = copy.size() - 1; i >= 0; i--) {
1167                copy.get(i).onShortcutChanged(packageName, userId);
1168            }
1169        });
1170    }
1171
1172    /**
1173     * Clean up / validate an incoming shortcut.
1174     * - Make sure all mandatory fields are set.
1175     * - Make sure the intent's extras are persistable, and them to set
1176     *  {@link ShortcutInfo#mIntentPersistableExtras}.  Also clear its extras.
1177     * - Clear flags.
1178     *
1179     * TODO Detailed unit tests
1180     */
1181    private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1182        Preconditions.checkNotNull(shortcut, "Null shortcut detected");
1183        if (shortcut.getActivityComponent() != null) {
1184            Preconditions.checkState(
1185                    shortcut.getPackageName().equals(
1186                            shortcut.getActivityComponent().getPackageName()),
1187                    "Activity package name mismatch");
1188        }
1189
1190        if (!forUpdate) {
1191            shortcut.enforceMandatoryFields();
1192        }
1193        if (shortcut.getIcon() != null) {
1194            ShortcutInfo.validateIcon(shortcut.getIcon());
1195        }
1196
1197        validateForXml(shortcut.getId());
1198        validateForXml(shortcut.getTitle());
1199        validatePersistableBundleForXml(shortcut.getIntentPersistableExtras());
1200        validatePersistableBundleForXml(shortcut.getExtras());
1201
1202        shortcut.replaceFlags(0);
1203    }
1204
1205    // KXmlSerializer is strict and doesn't allow certain characters, so we disallow those
1206    // characters.
1207
1208    private static void validatePersistableBundleForXml(PersistableBundle b) {
1209        if (b == null || b.size() == 0) {
1210            return;
1211        }
1212        for (String key : b.keySet()) {
1213            validateForXml(key);
1214            final Object value = b.get(key);
1215            if (value == null) {
1216                continue;
1217            } else if (value instanceof String) {
1218                validateForXml((String) value);
1219            } else if (value instanceof String[]) {
1220                for (String v : (String[]) value) {
1221                    validateForXml(v);
1222                }
1223            } else if (value instanceof PersistableBundle) {
1224                validatePersistableBundleForXml((PersistableBundle) value);
1225            }
1226        }
1227    }
1228
1229    private static void validateForXml(String s) {
1230        if (TextUtils.isEmpty(s)) {
1231            return;
1232        }
1233        for (int i = s.length() - 1; i >= 0; i--) {
1234            if (!isAllowedInXml(s.charAt(i))) {
1235                throw new IllegalArgumentException("Unsupported character detected in: " + s);
1236            }
1237        }
1238    }
1239
1240    private static boolean isAllowedInXml(char c) {
1241        return (c >= 0x20 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfffd);
1242    }
1243
1244    // === APIs ===
1245
1246    @Override
1247    public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1248            @UserIdInt int userId) {
1249        verifyCaller(packageName, userId);
1250
1251        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1252        final int size = newShortcuts.size();
1253
1254        synchronized (mLock) {
1255            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1256
1257            // Throttling.
1258            if (!ps.tryApiCall(this)) {
1259                return false;
1260            }
1261            enforceMaxDynamicShortcuts(size);
1262
1263            // Validate the shortcuts.
1264            for (int i = 0; i < size; i++) {
1265                fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1266            }
1267
1268            // First, remove all un-pinned; dynamic shortcuts
1269            ps.deleteAllDynamicShortcuts(this);
1270
1271            // Then, add/update all.  We need to make sure to take over "pinned" flag.
1272            for (int i = 0; i < size; i++) {
1273                final ShortcutInfo newShortcut = newShortcuts.get(i);
1274                ps.addDynamicShortcut(this, newShortcut);
1275            }
1276        }
1277        userPackageChanged(packageName, userId);
1278        return true;
1279    }
1280
1281    @Override
1282    public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1283            @UserIdInt int userId) {
1284        verifyCaller(packageName, userId);
1285
1286        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1287        final int size = newShortcuts.size();
1288
1289        synchronized (mLock) {
1290            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1291
1292            // Throttling.
1293            if (!ps.tryApiCall(this)) {
1294                return false;
1295            }
1296
1297            for (int i = 0; i < size; i++) {
1298                final ShortcutInfo source = newShortcuts.get(i);
1299                fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1300
1301                final ShortcutInfo target = ps.findShortcutById(source.getId());
1302                if (target != null) {
1303                    final boolean replacingIcon = (source.getIcon() != null);
1304                    if (replacingIcon) {
1305                        removeIcon(userId, target);
1306                    }
1307
1308                    target.copyNonNullFieldsFrom(source);
1309
1310                    if (replacingIcon) {
1311                        saveIconAndFixUpShortcut(userId, target);
1312                    }
1313                }
1314            }
1315        }
1316        userPackageChanged(packageName, userId);
1317
1318        return true;
1319    }
1320
1321    @Override
1322    public boolean addDynamicShortcut(String packageName, ShortcutInfo newShortcut,
1323            @UserIdInt int userId) {
1324        verifyCaller(packageName, userId);
1325
1326        synchronized (mLock) {
1327            final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1328
1329            // Throttling.
1330            if (!ps.tryApiCall(this)) {
1331                return false;
1332            }
1333
1334            // Validate the shortcut.
1335            fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
1336
1337            // Add it.
1338            ps.addDynamicShortcut(this, newShortcut);
1339        }
1340        userPackageChanged(packageName, userId);
1341
1342        return true;
1343    }
1344
1345    @Override
1346    public void deleteDynamicShortcut(String packageName, String shortcutId,
1347            @UserIdInt int userId) {
1348        verifyCaller(packageName, userId);
1349        Preconditions.checkStringNotEmpty(shortcutId, "shortcutId must be provided");
1350
1351        synchronized (mLock) {
1352            getPackageShortcutsLocked(packageName, userId).deleteDynamicWithId(this, shortcutId);
1353        }
1354        userPackageChanged(packageName, userId);
1355    }
1356
1357    @Override
1358    public void deleteAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
1359        verifyCaller(packageName, userId);
1360
1361        synchronized (mLock) {
1362            getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts(this);
1363        }
1364        userPackageChanged(packageName, userId);
1365    }
1366
1367    @Override
1368    public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1369            @UserIdInt int userId) {
1370        verifyCaller(packageName, userId);
1371        synchronized (mLock) {
1372            return getShortcutsWithQueryLocked(
1373                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1374                    ShortcutInfo::isDynamic);
1375        }
1376    }
1377
1378    @Override
1379    public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1380            @UserIdInt int userId) {
1381        verifyCaller(packageName, userId);
1382        synchronized (mLock) {
1383            return getShortcutsWithQueryLocked(
1384                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1385                    ShortcutInfo::isPinned);
1386        }
1387    }
1388
1389    private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1390            @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1391
1392        final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1393
1394        getPackageShortcutsLocked(packageName, userId).findAll(this, ret, query, cloneFlags);
1395
1396        return new ParceledListSlice<>(ret);
1397    }
1398
1399    @Override
1400    public int getMaxDynamicShortcutCount(String packageName, @UserIdInt int userId)
1401            throws RemoteException {
1402        verifyCaller(packageName, userId);
1403
1404        return mMaxDynamicShortcuts;
1405    }
1406
1407    @Override
1408    public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1409        verifyCaller(packageName, userId);
1410
1411        synchronized (mLock) {
1412            return mMaxDailyUpdates
1413                    - getPackageShortcutsLocked(packageName, userId).getApiCallCount(this);
1414        }
1415    }
1416
1417    @Override
1418    public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
1419        verifyCaller(packageName, userId);
1420
1421        synchronized (mLock) {
1422            return getNextResetTimeLocked();
1423        }
1424    }
1425
1426    @Override
1427    public int getIconMaxDimensions(String packageName, int userId) throws RemoteException {
1428        verifyCaller(packageName, userId);
1429
1430        synchronized (mLock) {
1431            return mMaxIconDimension;
1432        }
1433    }
1434
1435    /**
1436     * Reset all throttling, for developer options and command line.  Only system/shell can call it.
1437     */
1438    @Override
1439    public void resetThrottling() {
1440        enforceSystemOrShell();
1441
1442        resetThrottlingInner(getCallingUserId());
1443    }
1444
1445    void resetThrottlingInner(@UserIdInt int userId) {
1446        synchronized (mLock) {
1447            getUserShortcutsLocked(userId).resetThrottling();
1448        }
1449        scheduleSaveUser(userId);
1450        Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
1451    }
1452
1453    void resetAllThrottlingInner() {
1454        synchronized (mLock) {
1455            mRawLastResetTime = injectCurrentTimeMillis();
1456        }
1457        scheduleSaveBaseState();
1458        Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
1459    }
1460
1461    // We override this method in unit tests to do a simpler check.
1462    boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
1463        return hasShortcutHostPermissionInner(callingPackage, userId);
1464    }
1465
1466    // This method is extracted so we can directly call this method from unit tests,
1467    // even when hasShortcutPermission() is overridden.
1468    @VisibleForTesting
1469    boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
1470        synchronized (mLock) {
1471            final long start = System.currentTimeMillis();
1472
1473            final ShortcutUser user = getUserShortcutsLocked(userId);
1474
1475            final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
1476
1477            // Default launcher from package manager.
1478            final long startGetHomeActivitiesAsUser = System.currentTimeMillis();
1479            final ComponentName defaultLauncher = injectPackageManagerInternal()
1480                    .getHomeActivitiesAsUser(allHomeCandidates, userId);
1481            logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
1482
1483            ComponentName detected;
1484            if (defaultLauncher != null) {
1485                detected = defaultLauncher;
1486                if (DEBUG) {
1487                    Slog.v(TAG, "Default launcher from PM: " + detected);
1488                }
1489            } else {
1490                detected = user.getLauncherComponent();
1491
1492                // TODO: Make sure it's still enabled.
1493                if (DEBUG) {
1494                    Slog.v(TAG, "Cached launcher: " + detected);
1495                }
1496            }
1497
1498            if (detected == null) {
1499                // If we reach here, that means it's the first check since the user was created,
1500                // and there's already multiple launchers and there's no default set.
1501                // Find the system one with the highest priority.
1502                // (We need to check the priority too because of FallbackHome in Settings.)
1503                // If there's no system launcher yet, then no one can access shortcuts, until
1504                // the user explicitly
1505                final int size = allHomeCandidates.size();
1506
1507                int lastPriority = Integer.MIN_VALUE;
1508                for (int i = 0; i < size; i++) {
1509                    final ResolveInfo ri = allHomeCandidates.get(i);
1510                    if (!ri.activityInfo.applicationInfo.isSystemApp()) {
1511                        continue;
1512                    }
1513                    if (DEBUG) {
1514                        Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
1515                                ri.activityInfo.getComponentName(), ri.priority));
1516                    }
1517                    if (ri.priority < lastPriority) {
1518                        continue;
1519                    }
1520                    detected = ri.activityInfo.getComponentName();
1521                    lastPriority = ri.priority;
1522                }
1523            }
1524            logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
1525
1526            if (detected != null) {
1527                if (DEBUG) {
1528                    Slog.v(TAG, "Detected launcher: " + detected);
1529                }
1530                user.setLauncherComponent(this, detected);
1531                return detected.getPackageName().equals(callingPackage);
1532            } else {
1533                // Default launcher not found.
1534                return false;
1535            }
1536        }
1537    }
1538
1539    // === House keeping ===
1540
1541    @VisibleForTesting
1542    void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId) {
1543        cleanUpPackageLocked(packageName, owningUserId, packageUserId,
1544                /* forceForCommandLine= */ false);
1545    }
1546
1547    /**
1548     * Remove all the information associated with a package.  This will really remove all the
1549     * information, including the restore information (i.e. it'll remove packages even if they're
1550     * shadow).
1551     */
1552    private void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
1553            boolean forceForCommandLine) {
1554        if (!forceForCommandLine && isPackageInstalled(packageName, packageUserId)) {
1555            wtf("Package " + packageName + " is still installed for user " + packageUserId);
1556            return;
1557        }
1558
1559        final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
1560
1561        final ShortcutUser mUser = getUserShortcutsLocked(owningUserId);
1562        boolean doNotify = false;
1563
1564        // First, remove the package from the package list (if the package is a publisher).
1565        if (packageUserId == owningUserId) {
1566            if (mUser.removePackage(packageName) != null) {
1567                doNotify = true;
1568            }
1569        }
1570
1571        // Also remove from the launcher list (if the package is a launcher).
1572        mUser.removeLauncher(packageUserId, packageName);
1573
1574        // Then remove pinned shortcuts from all launchers.
1575        final ArrayMap<PackageWithUser, ShortcutLauncher> launchers = mUser.getAllLaunchers();
1576        for (int i = launchers.size() - 1; i >= 0; i--) {
1577            launchers.valueAt(i).cleanUpPackage(packageName, packageUserId);
1578        }
1579        // Now there may be orphan shortcuts because we removed pinned shortucts at the previous
1580        // step.  Remove them too.
1581        for (int i = mUser.getAllPackages().size() - 1; i >= 0; i--) {
1582            mUser.getAllPackages().valueAt(i).refreshPinnedFlags(this);
1583        }
1584
1585        scheduleSaveUser(owningUserId);
1586
1587        if (doNotify) {
1588            notifyListeners(packageName, owningUserId);
1589        }
1590
1591        if (!wasUserLoaded) {
1592            // Note this will execute the scheduled save.
1593            unloadUserLocked(owningUserId);
1594        }
1595    }
1596
1597    /**
1598     * Entry point from {@link LauncherApps}.
1599     */
1600    private class LocalService extends ShortcutServiceInternal {
1601
1602        @Override
1603        public List<ShortcutInfo> getShortcuts(int launcherUserId,
1604                @NonNull String callingPackage, long changedSince,
1605                @Nullable String packageName, @Nullable List<String> shortcutIds,
1606                @Nullable ComponentName componentName,
1607                int queryFlags, int userId) {
1608            final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1609            final int cloneFlag =
1610                    ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) == 0)
1611                            ? ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER
1612                            : ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO;
1613            if (packageName == null) {
1614                shortcutIds = null; // LauncherAppsService already threw for it though.
1615            }
1616
1617            synchronized (mLock) {
1618                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1619                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1620
1621                if (packageName != null) {
1622                    getShortcutsInnerLocked(launcherUserId,
1623                            callingPackage, packageName, shortcutIds, changedSince,
1624                            componentName, queryFlags, userId, ret, cloneFlag);
1625                } else {
1626                    final ArrayMap<String, ShortcutPackage> packages =
1627                            getUserShortcutsLocked(userId).getAllPackages();
1628                    for (int i = packages.size() - 1; i >= 0; i--) {
1629                        getShortcutsInnerLocked(launcherUserId,
1630                                callingPackage, packages.keyAt(i), shortcutIds, changedSince,
1631                                componentName, queryFlags, userId, ret, cloneFlag);
1632                    }
1633                }
1634            }
1635            return ret;
1636        }
1637
1638        private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
1639                @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
1640                @Nullable ComponentName componentName, int queryFlags,
1641                int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
1642            final ArraySet<String> ids = shortcutIds == null ? null
1643                    : new ArraySet<>(shortcutIds);
1644
1645            getPackageShortcutsLocked(packageName, userId).findAll(ShortcutService.this, ret,
1646                    (ShortcutInfo si) -> {
1647                        if (si.getLastChangedTimestamp() < changedSince) {
1648                            return false;
1649                        }
1650                        if (ids != null && !ids.contains(si.getId())) {
1651                            return false;
1652                        }
1653                        if (componentName != null
1654                                && !componentName.equals(si.getActivityComponent())) {
1655                            return false;
1656                        }
1657                        final boolean matchDynamic =
1658                                ((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
1659                                        && si.isDynamic();
1660                        final boolean matchPinned =
1661                                ((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
1662                                        && si.isPinned();
1663                        return matchDynamic || matchPinned;
1664                    }, cloneFlag, callingPackage, launcherUserId);
1665        }
1666
1667        @Override
1668        public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
1669                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1670            Preconditions.checkStringNotEmpty(packageName, "packageName");
1671            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
1672
1673            synchronized (mLock) {
1674                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1675                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1676
1677                final ShortcutInfo si = getShortcutInfoLocked(
1678                        launcherUserId, callingPackage, packageName, shortcutId, userId);
1679                return si != null && si.isPinned();
1680            }
1681        }
1682
1683        private ShortcutInfo getShortcutInfoLocked(
1684                int launcherUserId, @NonNull String callingPackage,
1685                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1686            Preconditions.checkStringNotEmpty(packageName, "packageName");
1687            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
1688
1689            final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
1690            getPackageShortcutsLocked(packageName, userId).findAll(
1691                    ShortcutService.this, list,
1692                    (ShortcutInfo si) -> shortcutId.equals(si.getId()),
1693                    /* clone flags=*/ 0, callingPackage, launcherUserId);
1694            return list.size() == 0 ? null : list.get(0);
1695        }
1696
1697        @Override
1698        public void pinShortcuts(int launcherUserId,
1699                @NonNull String callingPackage, @NonNull String packageName,
1700                @NonNull List<String> shortcutIds, int userId) {
1701            // Calling permission must be checked by LauncherAppsImpl.
1702            Preconditions.checkStringNotEmpty(packageName, "packageName");
1703            Preconditions.checkNotNull(shortcutIds, "shortcutIds");
1704
1705            synchronized (mLock) {
1706                final ShortcutLauncher launcher =
1707                        getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
1708                launcher.attemptToRestoreIfNeededAndSave(ShortcutService.this);
1709
1710                launcher.pinShortcuts(
1711                        ShortcutService.this, userId, packageName, shortcutIds);
1712            }
1713            userPackageChanged(packageName, userId);
1714        }
1715
1716        @Override
1717        public Intent createShortcutIntent(int launcherUserId,
1718                @NonNull String callingPackage,
1719                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1720            // Calling permission must be checked by LauncherAppsImpl.
1721            Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
1722            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
1723
1724            synchronized (mLock) {
1725                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1726                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1727
1728                // Make sure the shortcut is actually visible to the launcher.
1729                final ShortcutInfo si = getShortcutInfoLocked(
1730                        launcherUserId, callingPackage, packageName, shortcutId, userId);
1731                // "si == null" should suffice here, but check the flags too just to make sure.
1732                if (si == null || !(si.isDynamic() || si.isPinned())) {
1733                    return null;
1734                }
1735                return si.getIntent();
1736            }
1737        }
1738
1739        @Override
1740        public void addListener(@NonNull ShortcutChangeListener listener) {
1741            synchronized (mLock) {
1742                mListeners.add(Preconditions.checkNotNull(listener));
1743            }
1744        }
1745
1746        @Override
1747        public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
1748                @NonNull String packageName, @NonNull String shortcutId, int userId) {
1749            Preconditions.checkNotNull(callingPackage, "callingPackage");
1750            Preconditions.checkNotNull(packageName, "packageName");
1751            Preconditions.checkNotNull(shortcutId, "shortcutId");
1752
1753            synchronized (mLock) {
1754                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1755                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1756
1757                final ShortcutInfo shortcutInfo = getPackageShortcutsLocked(
1758                        packageName, userId).findShortcutById(shortcutId);
1759                return (shortcutInfo != null && shortcutInfo.hasIconResource())
1760                        ? shortcutInfo.getIconResourceId() : 0;
1761            }
1762        }
1763
1764        @Override
1765        public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
1766                @NonNull String callingPackage, @NonNull String packageName,
1767                @NonNull String shortcutId, int userId) {
1768            Preconditions.checkNotNull(callingPackage, "callingPackage");
1769            Preconditions.checkNotNull(packageName, "packageName");
1770            Preconditions.checkNotNull(shortcutId, "shortcutId");
1771
1772            synchronized (mLock) {
1773                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
1774                        .attemptToRestoreIfNeededAndSave(ShortcutService.this);
1775
1776                final ShortcutInfo shortcutInfo = getPackageShortcutsLocked(
1777                        packageName, userId).findShortcutById(shortcutId);
1778                if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
1779                    return null;
1780                }
1781                try {
1782                    if (shortcutInfo.getBitmapPath() == null) {
1783                        Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
1784                        return null;
1785                    }
1786                    return ParcelFileDescriptor.open(
1787                            new File(shortcutInfo.getBitmapPath()),
1788                            ParcelFileDescriptor.MODE_READ_ONLY);
1789                } catch (FileNotFoundException e) {
1790                    Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
1791                    return null;
1792                }
1793            }
1794        }
1795
1796        @Override
1797        public boolean hasShortcutHostPermission(int launcherUserId,
1798                @NonNull String callingPackage) {
1799            return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
1800        }
1801    }
1802
1803    /**
1804     * Package event callbacks.
1805     */
1806    @VisibleForTesting
1807    final PackageMonitor mPackageMonitor = new PackageMonitor() {
1808        @Override
1809        public void onPackageAdded(String packageName, int uid) {
1810            handlePackageAdded(packageName, getChangingUserId());
1811        }
1812
1813        @Override
1814        public void onPackageUpdateFinished(String packageName, int uid) {
1815            handlePackageUpdateFinished(packageName, getChangingUserId());
1816        }
1817
1818        @Override
1819        public void onPackageRemoved(String packageName, int uid) {
1820            handlePackageRemoved(packageName, getChangingUserId());
1821        }
1822    };
1823
1824    /**
1825     * Called when a user is unlocked.  Check all known packages still exist, and otherwise
1826     * perform cleanup.
1827     */
1828    @VisibleForTesting
1829    void cleanupGonePackages(@UserIdInt int ownerUserId) {
1830        if (DEBUG) {
1831            Slog.d(TAG, "cleanupGonePackages() ownerUserId=" + ownerUserId);
1832        }
1833        final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
1834
1835        synchronized (mLock) {
1836            final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
1837
1838            user.forAllPackageItems(spi -> {
1839                if (spi.getPackageInfo().isShadow()) {
1840                    return; // Don't delete shadow information.
1841                }
1842                if (isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
1843                    return; // Package not gone.
1844                }
1845                gonePackages.add(PackageWithUser.of(spi));
1846            });
1847            if (gonePackages.size() > 0) {
1848                for (int i = gonePackages.size() - 1; i >= 0; i--) {
1849                    final PackageWithUser pu = gonePackages.get(i);
1850                    cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId);
1851                }
1852            }
1853        }
1854    }
1855
1856    private void handlePackageAdded(String packageName, @UserIdInt int userId) {
1857        if (DEBUG) {
1858            Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
1859        }
1860        synchronized (mLock) {
1861            forEachLoadedUserLocked(user ->
1862                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
1863        }
1864    }
1865
1866    private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
1867        if (DEBUG) {
1868            Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
1869                    packageName, userId));
1870        }
1871        synchronized (mLock) {
1872            forEachLoadedUserLocked(user ->
1873                    user.attemptToRestoreIfNeededAndSave(this, packageName, userId));
1874        }
1875    }
1876
1877    private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
1878        if (DEBUG) {
1879            Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
1880                    packageUserId));
1881        }
1882        handlePackageRemovedInner(packageName, packageUserId, /* forceForCommandLine =*/ false);
1883    }
1884
1885    private void handlePackageRemovedInner(String packageName, @UserIdInt int packageUserId,
1886            boolean forceForCommandLine) {
1887        synchronized (mLock) {
1888            forEachLoadedUserLocked(user ->
1889                cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
1890                        forceForCommandLine));
1891        }
1892    }
1893
1894    // === PackageManager interaction ===
1895
1896    PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
1897        return injectPackageInfo(packageName, userId, true);
1898    }
1899
1900    int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
1901        final long token = injectClearCallingIdentity();
1902        try {
1903            return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS
1904                    , userId);
1905        } catch (RemoteException e) {
1906            // Shouldn't happen.
1907            Slog.wtf(TAG, "RemoteException", e);
1908            return -1;
1909        } finally {
1910            injectRestoreCallingIdentity(token);
1911        }
1912    }
1913
1914    @VisibleForTesting
1915    PackageInfo injectPackageInfo(String packageName, @UserIdInt int userId,
1916            boolean getSignatures) {
1917        final long start = System.currentTimeMillis();
1918        final long token = injectClearCallingIdentity();
1919        try {
1920            return mIPackageManager.getPackageInfo(packageName, PACKAGE_MATCH_FLAGS
1921                    | (getSignatures ? PackageManager.GET_SIGNATURES : 0)
1922                    , userId);
1923        } catch (RemoteException e) {
1924            // Shouldn't happen.
1925            Slog.wtf(TAG, "RemoteException", e);
1926            return null;
1927        } finally {
1928            injectRestoreCallingIdentity(token);
1929
1930            logDurationStat(
1931                    (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
1932                    start);
1933        }
1934    }
1935
1936    @VisibleForTesting
1937    ApplicationInfo injectApplicationInfo(String packageName, @UserIdInt int userId) {
1938        final long start = System.currentTimeMillis();
1939        final long token = injectClearCallingIdentity();
1940        try {
1941            return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
1942        } catch (RemoteException e) {
1943            // Shouldn't happen.
1944            Slog.wtf(TAG, "RemoteException", e);
1945            return null;
1946        } finally {
1947            injectRestoreCallingIdentity(token);
1948
1949            logDurationStat(Stats.GET_APPLICATION_INFO, start);
1950        }
1951    }
1952
1953    private boolean isApplicationFlagSet(String packageName, int userId, int flags) {
1954        final ApplicationInfo ai = injectApplicationInfo(packageName, userId);
1955        return (ai != null) && ((ai.flags & flags) == flags);
1956    }
1957
1958    boolean isPackageInstalled(String packageName, int userId) {
1959        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_INSTALLED);
1960    }
1961
1962    // === Backup & restore ===
1963
1964    boolean shouldBackupApp(String packageName, int userId) {
1965        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
1966    }
1967
1968    boolean shouldBackupApp(PackageInfo pi) {
1969        return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
1970    }
1971
1972    @Override
1973    public byte[] getBackupPayload(@UserIdInt int userId) {
1974        enforceSystem();
1975        if (DEBUG) {
1976            Slog.d(TAG, "Backing up user " + userId);
1977        }
1978        synchronized (mLock) {
1979            final ShortcutUser user = getUserShortcutsLocked(userId);
1980            if (user == null) {
1981                Slog.w(TAG, "Can't backup: user not found: id=" + userId);
1982                return null;
1983            }
1984
1985            user.forAllPackageItems(spi -> spi.refreshPackageInfoAndSave(this));
1986
1987            // Then save.
1988            final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
1989            try {
1990                saveUserInternalLocked(userId, os, /* forBackup */ true);
1991            } catch (XmlPullParserException|IOException e) {
1992                // Shouldn't happen.
1993                Slog.w(TAG, "Backup failed.", e);
1994                return null;
1995            }
1996            return os.toByteArray();
1997        }
1998    }
1999
2000    @Override
2001    public void applyRestore(byte[] payload, @UserIdInt int userId) {
2002        enforceSystem();
2003        if (DEBUG) {
2004            Slog.d(TAG, "Restoring user " + userId);
2005        }
2006        final ShortcutUser user;
2007        final ByteArrayInputStream is = new ByteArrayInputStream(payload);
2008        try {
2009            user = loadUserInternal(userId, is, /* fromBackup */ true);
2010        } catch (XmlPullParserException|IOException e) {
2011            Slog.w(TAG, "Restoration failed.", e);
2012            return;
2013        }
2014        synchronized (mLock) {
2015            mUsers.put(userId, user);
2016
2017            // Then purge all the save images.
2018            final File bitmapPath = getUserBitmapFilePath(userId);
2019            final boolean success = FileUtils.deleteContents(bitmapPath);
2020            if (!success) {
2021                Slog.w(TAG, "Failed to delete " + bitmapPath);
2022            }
2023
2024            saveUserLocked(userId);
2025        }
2026    }
2027
2028    // === Dump ===
2029
2030    @Override
2031    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2032        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2033                != PackageManager.PERMISSION_GRANTED) {
2034            pw.println("Permission Denial: can't dump UserManager from from pid="
2035                    + Binder.getCallingPid()
2036                    + ", uid=" + Binder.getCallingUid()
2037                    + " without permission "
2038                    + android.Manifest.permission.DUMP);
2039            return;
2040        }
2041        dumpInner(pw);
2042    }
2043
2044    @VisibleForTesting
2045    void dumpInner(PrintWriter pw) {
2046        synchronized (mLock) {
2047            final long now = injectCurrentTimeMillis();
2048            pw.print("Now: [");
2049            pw.print(now);
2050            pw.print("] ");
2051            pw.print(formatTime(now));
2052
2053            pw.print("  Raw last reset: [");
2054            pw.print(mRawLastResetTime);
2055            pw.print("] ");
2056            pw.print(formatTime(mRawLastResetTime));
2057
2058            final long last = getLastResetTimeLocked();
2059            pw.print("  Last reset: [");
2060            pw.print(last);
2061            pw.print("] ");
2062            pw.print(formatTime(last));
2063
2064            final long next = getNextResetTimeLocked();
2065            pw.print("  Next reset: [");
2066            pw.print(next);
2067            pw.print("] ");
2068            pw.print(formatTime(next));
2069            pw.println();
2070
2071            pw.print("  Config:");
2072            pw.print("    Max icon dim: ");
2073            pw.println(mMaxIconDimension);
2074            pw.print("    Icon format: ");
2075            pw.println(mIconPersistFormat);
2076            pw.print("    Icon quality: ");
2077            pw.println(mIconPersistQuality);
2078            pw.print("    saveDelayMillis:");
2079            pw.println(mSaveDelayMillis);
2080            pw.print("    resetInterval:");
2081            pw.println(mResetInterval);
2082            pw.print("    maxDailyUpdates:");
2083            pw.println(mMaxDailyUpdates);
2084            pw.print("    maxDynamicShortcuts:");
2085            pw.println(mMaxDynamicShortcuts);
2086            pw.println();
2087
2088            pw.println("  Stats:");
2089            synchronized (mStatLock) {
2090                final String p = "    ";
2091                dumpStatLS(pw, p, Stats.GET_DEFAULT_HOME, "getHomeActivities()");
2092                dumpStatLS(pw, p, Stats.LAUNCHER_PERMISSION_CHECK, "Launcher permission check");
2093
2094                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO, "getPackageInfo()");
2095                dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO_WITH_SIG, "getPackageInfo(SIG)");
2096                dumpStatLS(pw, p, Stats.GET_APPLICATION_INFO, "getApplicationInfo");
2097            }
2098
2099            for (int i = 0; i < mUsers.size(); i++) {
2100                pw.println();
2101                mUsers.valueAt(i).dump(this, pw, "  ");
2102            }
2103        }
2104    }
2105
2106    static String formatTime(long time) {
2107        Time tobj = new Time();
2108        tobj.set(time);
2109        return tobj.format("%Y-%m-%d %H:%M:%S");
2110    }
2111
2112    private void dumpStatLS(PrintWriter pw, String prefix, int statId, String label) {
2113        pw.print(prefix);
2114        final int count = mCountStats[statId];
2115        final long dur = mDurationStats[statId];
2116        pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
2117                label, count, dur,
2118                (count == 0 ? 0 : ((double) dur) / count)));
2119    }
2120
2121    // === Shell support ===
2122
2123    @Override
2124    public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2125            String[] args, ResultReceiver resultReceiver) throws RemoteException {
2126
2127        enforceShell();
2128
2129        (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
2130    }
2131
2132    static class CommandException extends Exception {
2133        public CommandException(String message) {
2134            super(message);
2135        }
2136    }
2137
2138    /**
2139     * Handle "adb shell cmd".
2140     */
2141    private class MyShellCommand extends ShellCommand {
2142
2143        private int mUserId = UserHandle.USER_SYSTEM;
2144
2145        private void parseOptions(boolean takeUser)
2146                throws CommandException {
2147            String opt;
2148            while ((opt = getNextOption()) != null) {
2149                switch (opt) {
2150                    case "--user":
2151                        if (takeUser) {
2152                            mUserId = UserHandle.parseUserArg(getNextArgRequired());
2153                            break;
2154                        }
2155                        // fallthrough
2156                    default:
2157                        throw new CommandException("Unknown option: " + opt);
2158                }
2159            }
2160        }
2161
2162        @Override
2163        public int onCommand(String cmd) {
2164            if (cmd == null) {
2165                return handleDefaultCommands(cmd);
2166            }
2167            final PrintWriter pw = getOutPrintWriter();
2168            try {
2169                switch (cmd) {
2170                    case "reset-package-throttling":
2171                        handleResetPackageThrottling();
2172                        break;
2173                    case "reset-throttling":
2174                        handleResetThrottling();
2175                        break;
2176                    case "reset-all-throttling":
2177                        handleResetAllThrottling();
2178                        break;
2179                    case "override-config":
2180                        handleOverrideConfig();
2181                        break;
2182                    case "reset-config":
2183                        handleResetConfig();
2184                        break;
2185                    case "clear-default-launcher":
2186                        handleClearDefaultLauncher();
2187                        break;
2188                    case "get-default-launcher":
2189                        handleGetDefaultLauncher();
2190                        break;
2191                    case "refresh-default-launcher":
2192                        handleRefreshDefaultLauncher();
2193                        break;
2194                    case "unload-user":
2195                        handleUnloadUser();
2196                        break;
2197                    case "clear-shortcuts":
2198                        handleClearShortcuts();
2199                        break;
2200                    default:
2201                        return handleDefaultCommands(cmd);
2202                }
2203            } catch (CommandException e) {
2204                pw.println("Error: " + e.getMessage());
2205                return 1;
2206            }
2207            pw.println("Success");
2208            return 0;
2209        }
2210
2211        @Override
2212        public void onHelp() {
2213            final PrintWriter pw = getOutPrintWriter();
2214            pw.println("Usage: cmd shortcut COMMAND [options ...]");
2215            pw.println();
2216            pw.println("cmd shortcut reset-package-throttling [--user USER_ID] PACKAGE");
2217            pw.println("    Reset throttling for a package");
2218            pw.println();
2219            pw.println("cmd shortcut reset-throttling [--user USER_ID]");
2220            pw.println("    Reset throttling for all packages and users");
2221            pw.println();
2222            pw.println("cmd shortcut reset-all-throttling");
2223            pw.println("    Reset the throttling state for all users");
2224            pw.println();
2225            pw.println("cmd shortcut override-config CONFIG");
2226            pw.println("    Override the configuration for testing (will last until reboot)");
2227            pw.println();
2228            pw.println("cmd shortcut reset-config");
2229            pw.println("    Reset the configuration set with \"update-config\"");
2230            pw.println();
2231            pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
2232            pw.println("    Clear the cached default launcher");
2233            pw.println();
2234            pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
2235            pw.println("    Show the cached default launcher");
2236            pw.println();
2237            pw.println("cmd shortcut refresh-default-launcher [--user USER_ID]");
2238            pw.println("    Refresh the cached default launcher");
2239            pw.println();
2240            pw.println("cmd shortcut unload-user [--user USER_ID]");
2241            pw.println("    Unload a user from the memory");
2242            pw.println("    (This should not affect any observable behavior)");
2243            pw.println();
2244            pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
2245            pw.println("    Remove all shortcuts from a package, including pinned shortcuts");
2246            pw.println();
2247        }
2248
2249        private void handleResetThrottling() throws CommandException {
2250            parseOptions(/* takeUser =*/ true);
2251
2252            Slog.i(TAG, "cmd: handleResetThrottling");
2253
2254            resetThrottlingInner(mUserId);
2255        }
2256
2257        private void handleResetAllThrottling() {
2258            Slog.i(TAG, "cmd: handleResetAllThrottling");
2259
2260            resetAllThrottlingInner();
2261        }
2262
2263        private void handleResetPackageThrottling() throws CommandException {
2264            parseOptions(/* takeUser =*/ true);
2265
2266            final String packageName = getNextArgRequired();
2267
2268            Slog.i(TAG, "cmd: handleResetPackageThrottling: " + packageName);
2269
2270            synchronized (mLock) {
2271                getPackageShortcutsLocked(packageName, mUserId).resetRateLimitingForCommandLine();
2272                saveUserLocked(mUserId);
2273            }
2274        }
2275
2276        private void handleOverrideConfig() throws CommandException {
2277            final String config = getNextArgRequired();
2278
2279            Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
2280
2281            synchronized (mLock) {
2282                if (!updateConfigurationLocked(config)) {
2283                    throw new CommandException("override-config failed.  See logcat for details.");
2284                }
2285            }
2286        }
2287
2288        private void handleResetConfig() {
2289            Slog.i(TAG, "cmd: handleResetConfig");
2290
2291            synchronized (mLock) {
2292                loadConfigurationLocked();
2293            }
2294        }
2295
2296        private void clearLauncher() {
2297            synchronized (mLock) {
2298                getUserShortcutsLocked(mUserId).setLauncherComponent(
2299                        ShortcutService.this, null);
2300            }
2301        }
2302
2303        private void showLauncher() {
2304            synchronized (mLock) {
2305                // This ensures to set the cached launcher.  Package name doesn't matter.
2306                hasShortcutHostPermissionInner("-", mUserId);
2307
2308                getOutPrintWriter().println("Launcher: "
2309                        + getUserShortcutsLocked(mUserId).getLauncherComponent());
2310            }
2311        }
2312
2313        private void handleClearDefaultLauncher() throws CommandException {
2314            parseOptions(/* takeUser =*/ true);
2315
2316            clearLauncher();
2317        }
2318
2319        private void handleGetDefaultLauncher() throws CommandException {
2320            parseOptions(/* takeUser =*/ true);
2321
2322            showLauncher();
2323        }
2324
2325        private void handleRefreshDefaultLauncher() throws CommandException {
2326            parseOptions(/* takeUser =*/ true);
2327
2328            clearLauncher();
2329            showLauncher();
2330        }
2331
2332        private void handleUnloadUser() throws CommandException {
2333            parseOptions(/* takeUser =*/ true);
2334
2335            Slog.i(TAG, "cmd: handleUnloadUser: " + mUserId);
2336
2337            ShortcutService.this.handleCleanupUser(mUserId);
2338        }
2339
2340        private void handleClearShortcuts() throws CommandException {
2341            parseOptions(/* takeUser =*/ true);
2342            final String packageName = getNextArgRequired();
2343
2344            Slog.i(TAG, "cmd: handleClearShortcuts: " + mUserId + ", " + packageName);
2345
2346            ShortcutService.this.handlePackageRemovedInner(packageName, mUserId,
2347                    /* forceForCommandLine= */ true);
2348        }
2349    }
2350
2351    // === Unit test support ===
2352
2353    // Injection point.
2354    @VisibleForTesting
2355    long injectCurrentTimeMillis() {
2356        return System.currentTimeMillis();
2357    }
2358
2359    // Injection point.
2360    @VisibleForTesting
2361    int injectBinderCallingUid() {
2362        return getCallingUid();
2363    }
2364
2365    private int getCallingUserId() {
2366        return UserHandle.getUserId(injectBinderCallingUid());
2367    }
2368
2369    // Injection point.
2370    @VisibleForTesting
2371    long injectClearCallingIdentity() {
2372        return Binder.clearCallingIdentity();
2373    }
2374
2375    // Injection point.
2376    @VisibleForTesting
2377    void injectRestoreCallingIdentity(long token) {
2378        Binder.restoreCallingIdentity(token);
2379    }
2380
2381    final void wtf(String message) {
2382        wtf( message, /* exception= */ null);
2383    }
2384
2385    // Injection point.
2386    void wtf(String message, Exception e) {
2387        Slog.wtf(TAG, message, e);
2388    }
2389
2390    @VisibleForTesting
2391    File injectSystemDataPath() {
2392        return Environment.getDataSystemDirectory();
2393    }
2394
2395    @VisibleForTesting
2396    File injectUserDataPath(@UserIdInt int userId) {
2397        return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
2398    }
2399
2400    @VisibleForTesting
2401    boolean injectIsLowRamDevice() {
2402        return ActivityManager.isLowRamDeviceStatic();
2403    }
2404
2405    @VisibleForTesting
2406    PackageManagerInternal injectPackageManagerInternal() {
2407        return mPackageManagerInternal;
2408    }
2409
2410    @VisibleForTesting
2411    File getUserBitmapFilePath(@UserIdInt int userId) {
2412        return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
2413    }
2414
2415    @VisibleForTesting
2416    SparseArray<ShortcutUser> getShortcutsForTest() {
2417        return mUsers;
2418    }
2419
2420    @VisibleForTesting
2421    int getMaxDynamicShortcutsForTest() {
2422        return mMaxDynamicShortcuts;
2423    }
2424
2425    @VisibleForTesting
2426    int getMaxDailyUpdatesForTest() {
2427        return mMaxDailyUpdates;
2428    }
2429
2430    @VisibleForTesting
2431    long getResetIntervalForTest() {
2432        return mResetInterval;
2433    }
2434
2435    @VisibleForTesting
2436    int getMaxIconDimensionForTest() {
2437        return mMaxIconDimension;
2438    }
2439
2440    @VisibleForTesting
2441    CompressFormat getIconPersistFormatForTest() {
2442        return mIconPersistFormat;
2443    }
2444
2445    @VisibleForTesting
2446    int getIconPersistQualityForTest() {
2447        return mIconPersistQuality;
2448    }
2449
2450    @VisibleForTesting
2451    ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
2452        synchronized (mLock) {
2453            final ShortcutUser user = mUsers.get(userId);
2454            if (user == null) return null;
2455
2456            final ShortcutPackage pkg = user.getAllPackages().get(packageName);
2457            if (pkg == null) return null;
2458
2459            return pkg.findShortcutById(shortcutId);
2460        }
2461    }
2462}
2463