Installer.java revision b62a9045c2dc7f2b373a79e819e7064c88d24bf8
1/*
2 * Copyright (C) 2008 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 android.annotation.AppIdInt;
20import android.annotation.Nullable;
21import android.annotation.UserIdInt;
22import android.content.Context;
23import android.content.pm.PackageStats;
24import android.os.Build;
25import android.os.IBinder;
26import android.os.IBinder.DeathRecipient;
27import android.os.IInstalld;
28import android.os.RemoteException;
29import android.os.ServiceManager;
30import android.text.format.DateUtils;
31import android.util.Slog;
32
33import com.android.internal.os.BackgroundThread;
34import com.android.server.SystemService;
35
36import dalvik.system.VMRuntime;
37
38public class Installer extends SystemService {
39    private static final String TAG = "Installer";
40
41    /* ***************************************************************************
42     * IMPORTANT: These values are passed to native code. Keep them in sync with
43     * frameworks/native/cmds/installd/installd.h
44     * **************************************************************************/
45    /** Application should be visible to everyone */
46    public static final int DEXOPT_PUBLIC         = 1 << 1;
47    /** Application wants to allow debugging of its code */
48    public static final int DEXOPT_DEBUGGABLE     = 1 << 2;
49    /** The system boot has finished */
50    public static final int DEXOPT_BOOTCOMPLETE   = 1 << 3;
51    /** Hint that the dexopt type is profile-guided. */
52    public static final int DEXOPT_PROFILE_GUIDED = 1 << 4;
53    /** The compilation is for a secondary dex file. */
54    public static final int DEXOPT_SECONDARY_DEX  = 1 << 5;
55    /** Ignore the result of dexoptNeeded and force compilation. */
56    public static final int DEXOPT_FORCE          = 1 << 6;
57    /** Indicates that the dex file passed to dexopt in on CE storage. */
58    public static final int DEXOPT_STORAGE_CE     = 1 << 7;
59    /** Indicates that the dex file passed to dexopt in on DE storage. */
60    public static final int DEXOPT_STORAGE_DE     = 1 << 8;
61    /** Indicates that dexopt is invoked from the background service. */
62    public static final int DEXOPT_IDLE_BACKGROUND_JOB = 1 << 9;
63    /** Indicates that dexopt should restrict access to private APIs. */
64    public static final int DEXOPT_ENABLE_HIDDEN_API_CHECKS = 1 << 10;
65
66    // NOTE: keep in sync with installd
67    public static final int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
68    public static final int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
69    public static final int FLAG_USE_QUOTA = 1 << 12;
70    public static final int FLAG_FREE_CACHE_V2 = 1 << 13;
71    public static final int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
72    public static final int FLAG_FREE_CACHE_NOOP = 1 << 15;
73    public static final int FLAG_FORCE = 1 << 16;
74
75    private final boolean mIsolated;
76
77    private volatile IInstalld mInstalld;
78    private volatile Object mWarnIfHeld;
79
80    public Installer(Context context) {
81        this(context, false);
82    }
83
84    /**
85     * @param isolated indicates if this object should <em>not</em> connect to
86     *            the real {@code installd}. All remote calls will be ignored
87     *            unless you extend this class and intercept them.
88     */
89    public Installer(Context context, boolean isolated) {
90        super(context);
91        mIsolated = isolated;
92    }
93
94    /**
95     * Yell loudly if someone tries making future calls while holding a lock on
96     * the given object.
97     */
98    public void setWarnIfHeld(Object warnIfHeld) {
99        mWarnIfHeld = warnIfHeld;
100    }
101
102    @Override
103    public void onStart() {
104        if (mIsolated) {
105            mInstalld = null;
106        } else {
107            connect();
108        }
109    }
110
111    private void connect() {
112        IBinder binder = ServiceManager.getService("installd");
113        if (binder != null) {
114            try {
115                binder.linkToDeath(new DeathRecipient() {
116                    @Override
117                    public void binderDied() {
118                        Slog.w(TAG, "installd died; reconnecting");
119                        connect();
120                    }
121                }, 0);
122            } catch (RemoteException e) {
123                binder = null;
124            }
125        }
126
127        if (binder != null) {
128            mInstalld = IInstalld.Stub.asInterface(binder);
129            try {
130                invalidateMounts();
131            } catch (InstallerException ignored) {
132            }
133        } else {
134            Slog.w(TAG, "installd not found; trying again");
135            BackgroundThread.getHandler().postDelayed(() -> {
136                connect();
137            }, DateUtils.SECOND_IN_MILLIS);
138        }
139    }
140
141    /**
142     * Do several pre-flight checks before making a remote call.
143     *
144     * @return if the remote call should continue.
145     */
146    private boolean checkBeforeRemote() {
147        if (mWarnIfHeld != null && Thread.holdsLock(mWarnIfHeld)) {
148            Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() + " is holding 0x"
149                    + Integer.toHexString(System.identityHashCode(mWarnIfHeld)), new Throwable());
150        }
151        if (mIsolated) {
152            Slog.i(TAG, "Ignoring request because this installer is isolated");
153            return false;
154        } else {
155            return true;
156        }
157    }
158
159    public long createAppData(String uuid, String packageName, int userId, int flags, int appId,
160            String seInfo, int targetSdkVersion) throws InstallerException {
161        if (!checkBeforeRemote()) return -1;
162        try {
163            return mInstalld.createAppData(uuid, packageName, userId, flags, appId, seInfo,
164                    targetSdkVersion);
165        } catch (Exception e) {
166            throw InstallerException.from(e);
167        }
168    }
169
170    public void restoreconAppData(String uuid, String packageName, int userId, int flags, int appId,
171            String seInfo) throws InstallerException {
172        if (!checkBeforeRemote()) return;
173        try {
174            mInstalld.restoreconAppData(uuid, packageName, userId, flags, appId, seInfo);
175        } catch (Exception e) {
176            throw InstallerException.from(e);
177        }
178    }
179
180    public void migrateAppData(String uuid, String packageName, int userId, int flags)
181            throws InstallerException {
182        if (!checkBeforeRemote()) return;
183        try {
184            mInstalld.migrateAppData(uuid, packageName, userId, flags);
185        } catch (Exception e) {
186            throw InstallerException.from(e);
187        }
188    }
189
190    public void clearAppData(String uuid, String packageName, int userId, int flags,
191            long ceDataInode) throws InstallerException {
192        if (!checkBeforeRemote()) return;
193        try {
194            mInstalld.clearAppData(uuid, packageName, userId, flags, ceDataInode);
195        } catch (Exception e) {
196            throw InstallerException.from(e);
197        }
198    }
199
200    public void destroyAppData(String uuid, String packageName, int userId, int flags,
201            long ceDataInode) throws InstallerException {
202        if (!checkBeforeRemote()) return;
203        try {
204            mInstalld.destroyAppData(uuid, packageName, userId, flags, ceDataInode);
205        } catch (Exception e) {
206            throw InstallerException.from(e);
207        }
208    }
209
210    public void fixupAppData(String uuid, int flags) throws InstallerException {
211        if (!checkBeforeRemote()) return;
212        try {
213            mInstalld.fixupAppData(uuid, flags);
214        } catch (Exception e) {
215            throw InstallerException.from(e);
216        }
217    }
218
219    public void moveCompleteApp(String fromUuid, String toUuid, String packageName,
220            String dataAppName, int appId, String seInfo, int targetSdkVersion)
221            throws InstallerException {
222        if (!checkBeforeRemote()) return;
223        try {
224            mInstalld.moveCompleteApp(fromUuid, toUuid, packageName, dataAppName, appId, seInfo,
225                    targetSdkVersion);
226        } catch (Exception e) {
227            throw InstallerException.from(e);
228        }
229    }
230
231    public void getAppSize(String uuid, String[] packageNames, int userId, int flags, int appId,
232            long[] ceDataInodes, String[] codePaths, PackageStats stats)
233            throws InstallerException {
234        if (!checkBeforeRemote()) return;
235        try {
236            final long[] res = mInstalld.getAppSize(uuid, packageNames, userId, flags,
237                    appId, ceDataInodes, codePaths);
238            stats.codeSize += res[0];
239            stats.dataSize += res[1];
240            stats.cacheSize += res[2];
241            stats.externalCodeSize += res[3];
242            stats.externalDataSize += res[4];
243            stats.externalCacheSize += res[5];
244        } catch (Exception e) {
245            throw InstallerException.from(e);
246        }
247    }
248
249    public void getUserSize(String uuid, int userId, int flags, int[] appIds, PackageStats stats)
250            throws InstallerException {
251        if (!checkBeforeRemote()) return;
252        try {
253            final long[] res = mInstalld.getUserSize(uuid, userId, flags, appIds);
254            stats.codeSize += res[0];
255            stats.dataSize += res[1];
256            stats.cacheSize += res[2];
257            stats.externalCodeSize += res[3];
258            stats.externalDataSize += res[4];
259            stats.externalCacheSize += res[5];
260        } catch (Exception e) {
261            throw InstallerException.from(e);
262        }
263    }
264
265    public long[] getExternalSize(String uuid, int userId, int flags, int[] appIds)
266            throws InstallerException {
267        if (!checkBeforeRemote()) return new long[6];
268        try {
269            return mInstalld.getExternalSize(uuid, userId, flags, appIds);
270        } catch (Exception e) {
271            throw InstallerException.from(e);
272        }
273    }
274
275    public void setAppQuota(String uuid, int userId, int appId, long cacheQuota)
276            throws InstallerException {
277        if (!checkBeforeRemote()) return;
278        try {
279            mInstalld.setAppQuota(uuid, userId, appId, cacheQuota);
280        } catch (Exception e) {
281            throw InstallerException.from(e);
282        }
283    }
284
285    public void dexopt(String apkPath, int uid, @Nullable String pkgName, String instructionSet,
286            int dexoptNeeded, @Nullable String outputPath, int dexFlags,
287            String compilerFilter, @Nullable String volumeUuid, @Nullable String sharedLibraries,
288            @Nullable String seInfo, boolean downgrade, int targetSdkVersion)
289            throws InstallerException {
290        assertValidInstructionSet(instructionSet);
291        if (!checkBeforeRemote()) return;
292        try {
293            mInstalld.dexopt(apkPath, uid, pkgName, instructionSet, dexoptNeeded, outputPath,
294                    dexFlags, compilerFilter, volumeUuid, sharedLibraries, seInfo, downgrade,
295                    targetSdkVersion);
296        } catch (Exception e) {
297            throw InstallerException.from(e);
298        }
299    }
300
301    public boolean mergeProfiles(int uid, String packageName) throws InstallerException {
302        if (!checkBeforeRemote()) return false;
303        try {
304            return mInstalld.mergeProfiles(uid, packageName);
305        } catch (Exception e) {
306            throw InstallerException.from(e);
307        }
308    }
309
310    public boolean dumpProfiles(int uid, String packageName, String codePaths)
311            throws InstallerException {
312        if (!checkBeforeRemote()) return false;
313        try {
314            return mInstalld.dumpProfiles(uid, packageName, codePaths);
315        } catch (Exception e) {
316            throw InstallerException.from(e);
317        }
318    }
319
320    public boolean copySystemProfile(String systemProfile, int uid, String packageName)
321            throws InstallerException {
322        if (!checkBeforeRemote()) return false;
323        try {
324            return mInstalld.copySystemProfile(systemProfile, uid, packageName);
325        } catch (Exception e) {
326            throw InstallerException.from(e);
327        }
328    }
329
330    public void idmap(String targetApkPath, String overlayApkPath, int uid)
331            throws InstallerException {
332        if (!checkBeforeRemote()) return;
333        try {
334            mInstalld.idmap(targetApkPath, overlayApkPath, uid);
335        } catch (Exception e) {
336            throw InstallerException.from(e);
337        }
338    }
339
340    public void removeIdmap(String overlayApkPath) throws InstallerException {
341        if (!checkBeforeRemote()) return;
342        try {
343            mInstalld.removeIdmap(overlayApkPath);
344        } catch (Exception e) {
345            throw InstallerException.from(e);
346        }
347    }
348
349    public void rmdex(String codePath, String instructionSet) throws InstallerException {
350        assertValidInstructionSet(instructionSet);
351        if (!checkBeforeRemote()) return;
352        try {
353            mInstalld.rmdex(codePath, instructionSet);
354        } catch (Exception e) {
355            throw InstallerException.from(e);
356        }
357    }
358
359    public void rmPackageDir(String packageDir) throws InstallerException {
360        if (!checkBeforeRemote()) return;
361        try {
362            mInstalld.rmPackageDir(packageDir);
363        } catch (Exception e) {
364            throw InstallerException.from(e);
365        }
366    }
367
368    public void clearAppProfiles(String packageName) throws InstallerException {
369        if (!checkBeforeRemote()) return;
370        try {
371            mInstalld.clearAppProfiles(packageName);
372        } catch (Exception e) {
373            throw InstallerException.from(e);
374        }
375    }
376
377    public void destroyAppProfiles(String packageName) throws InstallerException {
378        if (!checkBeforeRemote()) return;
379        try {
380            mInstalld.destroyAppProfiles(packageName);
381        } catch (Exception e) {
382            throw InstallerException.from(e);
383        }
384    }
385
386    public void createUserData(String uuid, int userId, int userSerial, int flags)
387            throws InstallerException {
388        if (!checkBeforeRemote()) return;
389        try {
390            mInstalld.createUserData(uuid, userId, userSerial, flags);
391        } catch (Exception e) {
392            throw InstallerException.from(e);
393        }
394    }
395
396    public void destroyUserData(String uuid, int userId, int flags) throws InstallerException {
397        if (!checkBeforeRemote()) return;
398        try {
399            mInstalld.destroyUserData(uuid, userId, flags);
400        } catch (Exception e) {
401            throw InstallerException.from(e);
402        }
403    }
404
405    public void markBootComplete(String instructionSet) throws InstallerException {
406        assertValidInstructionSet(instructionSet);
407        if (!checkBeforeRemote()) return;
408        try {
409            mInstalld.markBootComplete(instructionSet);
410        } catch (Exception e) {
411            throw InstallerException.from(e);
412        }
413    }
414
415    public void freeCache(String uuid, long targetFreeBytes, long cacheReservedBytes, int flags)
416            throws InstallerException {
417        if (!checkBeforeRemote()) return;
418        try {
419            mInstalld.freeCache(uuid, targetFreeBytes, cacheReservedBytes, flags);
420        } catch (Exception e) {
421            throw InstallerException.from(e);
422        }
423    }
424
425    /**
426     * Links the 32 bit native library directory in an application's data
427     * directory to the real location for backward compatibility. Note that no
428     * such symlink is created for 64 bit shared libraries.
429     */
430    public void linkNativeLibraryDirectory(String uuid, String packageName, String nativeLibPath32,
431            int userId) throws InstallerException {
432        if (!checkBeforeRemote()) return;
433        try {
434            mInstalld.linkNativeLibraryDirectory(uuid, packageName, nativeLibPath32, userId);
435        } catch (Exception e) {
436            throw InstallerException.from(e);
437        }
438    }
439
440    public void createOatDir(String oatDir, String dexInstructionSet)
441            throws InstallerException {
442        if (!checkBeforeRemote()) return;
443        try {
444            mInstalld.createOatDir(oatDir, dexInstructionSet);
445        } catch (Exception e) {
446            throw InstallerException.from(e);
447        }
448    }
449
450    public void linkFile(String relativePath, String fromBase, String toBase)
451            throws InstallerException {
452        if (!checkBeforeRemote()) return;
453        try {
454            mInstalld.linkFile(relativePath, fromBase, toBase);
455        } catch (Exception e) {
456            throw InstallerException.from(e);
457        }
458    }
459
460    public void moveAb(String apkPath, String instructionSet, String outputPath)
461            throws InstallerException {
462        if (!checkBeforeRemote()) return;
463        try {
464            mInstalld.moveAb(apkPath, instructionSet, outputPath);
465        } catch (Exception e) {
466            throw InstallerException.from(e);
467        }
468    }
469
470    public void deleteOdex(String apkPath, String instructionSet, String outputPath)
471            throws InstallerException {
472        if (!checkBeforeRemote()) return;
473        try {
474            mInstalld.deleteOdex(apkPath, instructionSet, outputPath);
475        } catch (Exception e) {
476            throw InstallerException.from(e);
477        }
478    }
479
480    public boolean reconcileSecondaryDexFile(String apkPath, String packageName, int uid,
481            String[] isas, @Nullable String volumeUuid, int flags) throws InstallerException {
482        for (int i = 0; i < isas.length; i++) {
483            assertValidInstructionSet(isas[i]);
484        }
485        if (!checkBeforeRemote()) return false;
486        try {
487            return mInstalld.reconcileSecondaryDexFile(apkPath, packageName, uid, isas,
488                    volumeUuid, flags);
489        } catch (Exception e) {
490            throw InstallerException.from(e);
491        }
492    }
493
494    public byte[] hashSecondaryDexFile(String dexPath, String packageName, int uid,
495            @Nullable String volumeUuid, int flags) throws InstallerException {
496        if (!checkBeforeRemote()) return new byte[0];
497        try {
498            return mInstalld.hashSecondaryDexFile(dexPath, packageName, uid, volumeUuid, flags);
499        } catch (Exception e) {
500            throw InstallerException.from(e);
501        }
502    }
503
504    public boolean createProfileSnapshot(int appId, String packageName, String codePath)
505            throws InstallerException {
506        if (!checkBeforeRemote()) return false;
507        try {
508            return mInstalld.createProfileSnapshot(appId, packageName, codePath);
509        } catch (Exception e) {
510            throw InstallerException.from(e);
511        }
512    }
513
514    public void destroyProfileSnapshot(String packageName, String codePath)
515            throws InstallerException {
516        if (!checkBeforeRemote()) return;
517        try {
518            mInstalld.destroyProfileSnapshot(packageName, codePath);
519        } catch (Exception e) {
520            throw InstallerException.from(e);
521        }
522    }
523
524    public void invalidateMounts() throws InstallerException {
525        if (!checkBeforeRemote()) return;
526        try {
527            mInstalld.invalidateMounts();
528        } catch (Exception e) {
529            throw InstallerException.from(e);
530        }
531    }
532
533    public boolean isQuotaSupported(String volumeUuid) throws InstallerException {
534        if (!checkBeforeRemote()) return false;
535        try {
536            return mInstalld.isQuotaSupported(volumeUuid);
537        } catch (Exception e) {
538            throw InstallerException.from(e);
539        }
540    }
541
542    public boolean prepareAppProfile(String pkg, @UserIdInt int userId, @AppIdInt int appId,
543            String profileName, String codePath, String dexMetadataPath) throws InstallerException {
544        if (!checkBeforeRemote()) return false;
545        try {
546            return mInstalld.prepareAppProfile(pkg, userId, appId, profileName, codePath,
547                    dexMetadataPath);
548        } catch (Exception e) {
549            throw InstallerException.from(e);
550        }
551    }
552
553    private static void assertValidInstructionSet(String instructionSet)
554            throws InstallerException {
555        for (String abi : Build.SUPPORTED_ABIS) {
556            if (VMRuntime.getInstructionSet(abi).equals(instructionSet)) {
557                return;
558            }
559        }
560        throw new InstallerException("Invalid instruction set: " + instructionSet);
561    }
562
563    public static class InstallerException extends Exception {
564        public InstallerException(String detailMessage) {
565            super(detailMessage);
566        }
567
568        public static InstallerException from(Exception e) throws InstallerException {
569            throw new InstallerException(e.toString());
570        }
571    }
572}
573