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 */
16
17package com.android.server.pm;
18
19import com.android.server.pm.dex.DexManager;
20import com.android.server.pm.dex.PackageDexUsage;
21
22import static com.android.server.pm.PackageManagerService.DEBUG_DEXOPT;
23import static com.android.server.pm.PackageManagerService.TAG;
24
25import android.annotation.NonNull;
26import android.app.AppGlobals;
27import android.content.Intent;
28import android.content.pm.PackageParser;
29import android.content.pm.ResolveInfo;
30import android.os.Build;
31import android.os.RemoteException;
32import android.os.UserHandle;
33import android.system.ErrnoException;
34import android.util.ArraySet;
35import android.util.Log;
36import dalvik.system.VMRuntime;
37import libcore.io.Libcore;
38
39import java.io.File;
40import java.io.IOException;
41import java.util.ArrayList;
42import java.util.Collection;
43import java.util.Collections;
44import java.util.LinkedList;
45import java.util.List;
46import java.util.function.Predicate;
47
48/**
49 * Class containing helper methods for the PackageManagerService.
50 *
51 * {@hide}
52 */
53public class PackageManagerServiceUtils {
54    private final static long SEVEN_DAYS_IN_MILLISECONDS = 7 * 24 * 60 * 60 * 1000;
55
56    private static ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
57        List<ResolveInfo> ris = null;
58        try {
59            ris = AppGlobals.getPackageManager().queryIntentReceivers(intent, null, 0, userId)
60                    .getList();
61        } catch (RemoteException e) {
62        }
63        ArraySet<String> pkgNames = new ArraySet<String>();
64        if (ris != null) {
65            for (ResolveInfo ri : ris) {
66                pkgNames.add(ri.activityInfo.packageName);
67            }
68        }
69        return pkgNames;
70    }
71
72    // Sort a list of apps by their last usage, most recently used apps first. The order of
73    // packages without usage data is undefined (but they will be sorted after the packages
74    // that do have usage data).
75    public static void sortPackagesByUsageDate(List<PackageParser.Package> pkgs,
76            PackageManagerService packageManagerService) {
77        if (!packageManagerService.isHistoricalPackageUsageAvailable()) {
78            return;
79        }
80
81        Collections.sort(pkgs, (pkg1, pkg2) ->
82                Long.compare(pkg2.getLatestForegroundPackageUseTimeInMills(),
83                        pkg1.getLatestForegroundPackageUseTimeInMills()));
84    }
85
86    // Apply the given {@code filter} to all packages in {@code packages}. If tested positive, the
87    // package will be removed from {@code packages} and added to {@code result} with its
88    // dependencies. If usage data is available, the positive packages will be sorted by usage
89    // data (with {@code sortTemp} as temporary storage).
90    private static void applyPackageFilter(Predicate<PackageParser.Package> filter,
91            Collection<PackageParser.Package> result,
92            Collection<PackageParser.Package> packages,
93            @NonNull List<PackageParser.Package> sortTemp,
94            PackageManagerService packageManagerService) {
95        for (PackageParser.Package pkg : packages) {
96            if (filter.test(pkg)) {
97                sortTemp.add(pkg);
98            }
99        }
100
101        sortPackagesByUsageDate(sortTemp, packageManagerService);
102        packages.removeAll(sortTemp);
103
104        for (PackageParser.Package pkg : sortTemp) {
105            result.add(pkg);
106
107            Collection<PackageParser.Package> deps =
108                    packageManagerService.findSharedNonSystemLibraries(pkg);
109            if (!deps.isEmpty()) {
110                deps.removeAll(result);
111                result.addAll(deps);
112                packages.removeAll(deps);
113            }
114        }
115
116        sortTemp.clear();
117    }
118
119    // Sort apps by importance for dexopt ordering. Important apps are given
120    // more priority in case the device runs out of space.
121    public static List<PackageParser.Package> getPackagesForDexopt(
122            Collection<PackageParser.Package> packages,
123            PackageManagerService packageManagerService) {
124        ArrayList<PackageParser.Package> remainingPkgs = new ArrayList<>(packages);
125        LinkedList<PackageParser.Package> result = new LinkedList<>();
126        ArrayList<PackageParser.Package> sortTemp = new ArrayList<>(remainingPkgs.size());
127
128        // Give priority to core apps.
129        applyPackageFilter((pkg) -> pkg.coreApp, result, remainingPkgs, sortTemp,
130                packageManagerService);
131
132        // Give priority to system apps that listen for pre boot complete.
133        Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
134        final ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
135        applyPackageFilter((pkg) -> pkgNames.contains(pkg.packageName), result, remainingPkgs,
136                sortTemp, packageManagerService);
137
138        // Give priority to apps used by other apps.
139        DexManager dexManager = packageManagerService.getDexManager();
140        applyPackageFilter((pkg) ->
141                dexManager.getPackageUseInfoOrDefault(pkg.packageName)
142                        .isAnyCodePathUsedByOtherApps(),
143                result, remainingPkgs, sortTemp, packageManagerService);
144
145        // Filter out packages that aren't recently used, add all remaining apps.
146        // TODO: add a property to control this?
147        Predicate<PackageParser.Package> remainingPredicate;
148        if (!remainingPkgs.isEmpty() && packageManagerService.isHistoricalPackageUsageAvailable()) {
149            if (DEBUG_DEXOPT) {
150                Log.i(TAG, "Looking at historical package use");
151            }
152            // Get the package that was used last.
153            PackageParser.Package lastUsed = Collections.max(remainingPkgs, (pkg1, pkg2) ->
154                    Long.compare(pkg1.getLatestForegroundPackageUseTimeInMills(),
155                            pkg2.getLatestForegroundPackageUseTimeInMills()));
156            if (DEBUG_DEXOPT) {
157                Log.i(TAG, "Taking package " + lastUsed.packageName + " as reference in time use");
158            }
159            long estimatedPreviousSystemUseTime =
160                    lastUsed.getLatestForegroundPackageUseTimeInMills();
161            // Be defensive if for some reason package usage has bogus data.
162            if (estimatedPreviousSystemUseTime != 0) {
163                final long cutoffTime = estimatedPreviousSystemUseTime - SEVEN_DAYS_IN_MILLISECONDS;
164                remainingPredicate =
165                        (pkg) -> pkg.getLatestForegroundPackageUseTimeInMills() >= cutoffTime;
166            } else {
167                // No meaningful historical info. Take all.
168                remainingPredicate = (pkg) -> true;
169            }
170            sortPackagesByUsageDate(remainingPkgs, packageManagerService);
171        } else {
172            // No historical info. Take all.
173            remainingPredicate = (pkg) -> true;
174        }
175        applyPackageFilter(remainingPredicate, result, remainingPkgs, sortTemp,
176                packageManagerService);
177
178        if (DEBUG_DEXOPT) {
179            Log.i(TAG, "Packages to be dexopted: " + packagesToString(result));
180            Log.i(TAG, "Packages skipped from dexopt: " + packagesToString(remainingPkgs));
181        }
182
183        return result;
184    }
185
186    /**
187     * Checks if the package was inactive during since <code>thresholdTimeinMillis</code>.
188     * Package is considered active, if:
189     * 1) It was active in foreground.
190     * 2) It was active in background and also used by other apps.
191     *
192     * If it doesn't have sufficient information about the package, it return <code>false</code>.
193     */
194    static boolean isUnusedSinceTimeInMillis(long firstInstallTime, long currentTimeInMillis,
195            long thresholdTimeinMillis, PackageDexUsage.PackageUseInfo packageUseInfo,
196            long latestPackageUseTimeInMillis, long latestForegroundPackageUseTimeInMillis) {
197
198        if (currentTimeInMillis - firstInstallTime < thresholdTimeinMillis) {
199            return false;
200        }
201
202        // If the app was active in foreground during the threshold period.
203        boolean isActiveInForeground = (currentTimeInMillis
204                - latestForegroundPackageUseTimeInMillis)
205                < thresholdTimeinMillis;
206
207        if (isActiveInForeground) {
208            return false;
209        }
210
211        // If the app was active in background during the threshold period and was used
212        // by other packages.
213        boolean isActiveInBackgroundAndUsedByOtherPackages = ((currentTimeInMillis
214                - latestPackageUseTimeInMillis)
215                < thresholdTimeinMillis)
216                && packageUseInfo.isAnyCodePathUsedByOtherApps();
217
218        return !isActiveInBackgroundAndUsedByOtherPackages;
219    }
220
221    /**
222     * Returns the canonicalized path of {@code path} as per {@code realpath(3)}
223     * semantics.
224     */
225    public static String realpath(File path) throws IOException {
226        try {
227            return Libcore.os.realpath(path.getAbsolutePath());
228        } catch (ErrnoException ee) {
229            throw ee.rethrowAsIOException();
230        }
231    }
232
233    public static String packagesToString(Collection<PackageParser.Package> c) {
234        StringBuilder sb = new StringBuilder();
235        for (PackageParser.Package pkg : c) {
236            if (sb.length() > 0) {
237                sb.append(", ");
238            }
239            sb.append(pkg.packageName);
240        }
241        return sb.toString();
242    }
243
244    /**
245     * Verifies that the given string {@code isa} is a valid supported isa on
246     * the running device.
247     */
248    public static boolean checkISA(String isa) {
249        for (String abi : Build.SUPPORTED_ABIS) {
250            if (VMRuntime.getInstructionSet(abi).equals(isa)) {
251                return true;
252            }
253        }
254        return false;
255    }
256}
257