PackageManagerService.java revision dda003ffa84f986bfaba4344124eafa533f5039d
1/*
2 * Copyright (C) 2006 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 static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.storage.StorageManager;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteException;
149import android.os.SELinux;
150import android.os.ServiceManager;
151import android.os.SystemClock;
152import android.os.SystemProperties;
153import android.os.UserHandle;
154import android.os.UserManager;
155import android.security.KeyStore;
156import android.security.SystemKeyStore;
157import android.system.ErrnoException;
158import android.system.Os;
159import android.system.StructStat;
160import android.text.TextUtils;
161import android.util.ArraySet;
162import android.util.AtomicFile;
163import android.util.DisplayMetrics;
164import android.util.EventLog;
165import android.util.ExceptionUtils;
166import android.util.Log;
167import android.util.LogPrinter;
168import android.util.PrintStreamPrinter;
169import android.util.Slog;
170import android.util.SparseArray;
171import android.util.SparseBooleanArray;
172import android.view.Display;
173
174import java.io.BufferedInputStream;
175import java.io.BufferedOutputStream;
176import java.io.File;
177import java.io.FileDescriptor;
178import java.io.FileInputStream;
179import java.io.FileNotFoundException;
180import java.io.FileOutputStream;
181import java.io.FilenameFilter;
182import java.io.IOException;
183import java.io.InputStream;
184import java.io.PrintWriter;
185import java.nio.charset.StandardCharsets;
186import java.security.NoSuchAlgorithmException;
187import java.security.PublicKey;
188import java.security.cert.CertificateEncodingException;
189import java.security.cert.CertificateException;
190import java.text.SimpleDateFormat;
191import java.util.ArrayList;
192import java.util.Arrays;
193import java.util.Collection;
194import java.util.Collections;
195import java.util.Comparator;
196import java.util.Date;
197import java.util.HashMap;
198import java.util.HashSet;
199import java.util.Iterator;
200import java.util.List;
201import java.util.Map;
202import java.util.Set;
203import java.util.concurrent.atomic.AtomicBoolean;
204import java.util.concurrent.atomic.AtomicLong;
205
206import dalvik.system.DexFile;
207import dalvik.system.StaleDexCacheError;
208import dalvik.system.VMRuntime;
209
210import libcore.io.IoUtils;
211import libcore.util.EmptyArray;
212
213/**
214 * Keep track of all those .apks everywhere.
215 *
216 * This is very central to the platform's security; please run the unit
217 * tests whenever making modifications here:
218 *
219mmm frameworks/base/tests/AndroidTests
220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
222 *
223 * {@hide}
224 */
225public class PackageManagerService extends IPackageManager.Stub {
226    static final String TAG = "PackageManager";
227    static final boolean DEBUG_SETTINGS = false;
228    static final boolean DEBUG_PREFERRED = false;
229    static final boolean DEBUG_UPGRADE = false;
230    private static final boolean DEBUG_INSTALL = false;
231    private static final boolean DEBUG_REMOVE = false;
232    private static final boolean DEBUG_BROADCASTS = false;
233    private static final boolean DEBUG_SHOW_INFO = false;
234    private static final boolean DEBUG_PACKAGE_INFO = false;
235    private static final boolean DEBUG_INTENT_MATCHING = false;
236    private static final boolean DEBUG_PACKAGE_SCANNING = false;
237    private static final boolean DEBUG_VERIFY = false;
238    private static final boolean DEBUG_DEXOPT = false;
239    private static final boolean DEBUG_ABI_SELECTION = false;
240
241    private static final int RADIO_UID = Process.PHONE_UID;
242    private static final int LOG_UID = Process.LOG_UID;
243    private static final int NFC_UID = Process.NFC_UID;
244    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
245    private static final int SHELL_UID = Process.SHELL_UID;
246
247    // Cap the size of permission trees that 3rd party apps can define
248    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
249
250    // Suffix used during package installation when copying/moving
251    // package apks to install directory.
252    private static final String INSTALL_PACKAGE_SUFFIX = "-";
253
254    static final int SCAN_NO_DEX = 1<<1;
255    static final int SCAN_FORCE_DEX = 1<<2;
256    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
257    static final int SCAN_NEW_INSTALL = 1<<4;
258    static final int SCAN_NO_PATHS = 1<<5;
259    static final int SCAN_UPDATE_TIME = 1<<6;
260    static final int SCAN_DEFER_DEX = 1<<7;
261    static final int SCAN_BOOTING = 1<<8;
262    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
263    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
264    static final int SCAN_REPLACING = 1<<11;
265
266    static final int REMOVE_CHATTY = 1<<16;
267
268    /**
269     * Timeout (in milliseconds) after which the watchdog should declare that
270     * our handler thread is wedged.  The usual default for such things is one
271     * minute but we sometimes do very lengthy I/O operations on this thread,
272     * such as installing multi-gigabyte applications, so ours needs to be longer.
273     */
274    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
275
276    /**
277     * Whether verification is enabled by default.
278     */
279    private static final boolean DEFAULT_VERIFY_ENABLE = true;
280
281    /**
282     * The default maximum time to wait for the verification agent to return in
283     * milliseconds.
284     */
285    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
286
287    /**
288     * The default response for package verification timeout.
289     *
290     * This can be either PackageManager.VERIFICATION_ALLOW or
291     * PackageManager.VERIFICATION_REJECT.
292     */
293    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
294
295    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
296
297    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
298            DEFAULT_CONTAINER_PACKAGE,
299            "com.android.defcontainer.DefaultContainerService");
300
301    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
302
303    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
304
305    private static String sPreferredInstructionSet;
306
307    final ServiceThread mHandlerThread;
308
309    private static final String IDMAP_PREFIX = "/data/resource-cache/";
310    private static final String IDMAP_SUFFIX = "@idmap";
311
312    final PackageHandler mHandler;
313
314    final int mSdkVersion = Build.VERSION.SDK_INT;
315
316    final Context mContext;
317    final boolean mFactoryTest;
318    final boolean mOnlyCore;
319    final DisplayMetrics mMetrics;
320    final int mDefParseFlags;
321    final String[] mSeparateProcesses;
322
323    // This is where all application persistent data goes.
324    final File mAppDataDir;
325
326    // This is where all application persistent data goes for secondary users.
327    final File mUserAppDataDir;
328
329    /** The location for ASEC container files on internal storage. */
330    final String mAsecInternalPath;
331
332    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
333    // LOCK HELD.  Can be called with mInstallLock held.
334    final Installer mInstaller;
335
336    /** Directory where installed third-party apps stored */
337    final File mAppInstallDir;
338
339    /**
340     * Directory to which applications installed internally have their
341     * 32 bit native libraries copied.
342     */
343    private File mAppLib32InstallDir;
344
345    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
346    // apps.
347    final File mDrmAppPrivateInstallDir;
348
349    // ----------------------------------------------------------------
350
351    // Lock for state used when installing and doing other long running
352    // operations.  Methods that must be called with this lock held have
353    // the suffix "LI".
354    final Object mInstallLock = new Object();
355
356    // ----------------------------------------------------------------
357
358    // Keys are String (package name), values are Package.  This also serves
359    // as the lock for the global state.  Methods that must be called with
360    // this lock held have the prefix "LP".
361    final HashMap<String, PackageParser.Package> mPackages =
362            new HashMap<String, PackageParser.Package>();
363
364    // Tracks available target package names -> overlay package paths.
365    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
366        new HashMap<String, HashMap<String, PackageParser.Package>>();
367
368    final Settings mSettings;
369    boolean mRestoredSettings;
370
371    // System configuration read by SystemConfig.
372    final int[] mGlobalGids;
373    final SparseArray<HashSet<String>> mSystemPermissions;
374    final HashMap<String, FeatureInfo> mAvailableFeatures;
375
376    // If mac_permissions.xml was found for seinfo labeling.
377    boolean mFoundPolicyFile;
378
379    // If a recursive restorecon of /data/data/<pkg> is needed.
380    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
381
382    public static final class SharedLibraryEntry {
383        public final String path;
384        public final String apk;
385
386        SharedLibraryEntry(String _path, String _apk) {
387            path = _path;
388            apk = _apk;
389        }
390    }
391
392    // Currently known shared libraries.
393    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
394            new HashMap<String, SharedLibraryEntry>();
395
396    // All available activities, for your resolving pleasure.
397    final ActivityIntentResolver mActivities =
398            new ActivityIntentResolver();
399
400    // All available receivers, for your resolving pleasure.
401    final ActivityIntentResolver mReceivers =
402            new ActivityIntentResolver();
403
404    // All available services, for your resolving pleasure.
405    final ServiceIntentResolver mServices = new ServiceIntentResolver();
406
407    // All available providers, for your resolving pleasure.
408    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
409
410    // Mapping from provider base names (first directory in content URI codePath)
411    // to the provider information.
412    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
413            new HashMap<String, PackageParser.Provider>();
414
415    // Mapping from instrumentation class names to info about them.
416    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
417            new HashMap<ComponentName, PackageParser.Instrumentation>();
418
419    // Mapping from permission names to info about them.
420    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
421            new HashMap<String, PackageParser.PermissionGroup>();
422
423    // Packages whose data we have transfered into another package, thus
424    // should no longer exist.
425    final HashSet<String> mTransferedPackages = new HashSet<String>();
426
427    // Broadcast actions that are only available to the system.
428    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
429
430    /** List of packages waiting for verification. */
431    final SparseArray<PackageVerificationState> mPendingVerification
432            = new SparseArray<PackageVerificationState>();
433
434    /** Set of packages associated with each app op permission. */
435    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
436
437    final PackageInstallerService mInstallerService;
438
439    HashSet<PackageParser.Package> mDeferredDexOpt = null;
440
441    // Cache of users who need badging.
442    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
443
444    /** Token for keys in mPendingVerification. */
445    private int mPendingVerificationToken = 0;
446
447    boolean mSystemReady;
448    boolean mSafeMode;
449    boolean mHasSystemUidErrors;
450
451    ApplicationInfo mAndroidApplication;
452    final ActivityInfo mResolveActivity = new ActivityInfo();
453    final ResolveInfo mResolveInfo = new ResolveInfo();
454    ComponentName mResolveComponentName;
455    PackageParser.Package mPlatformPackage;
456    ComponentName mCustomResolverComponentName;
457
458    boolean mResolverReplaced = false;
459
460    // Set of pending broadcasts for aggregating enable/disable of components.
461    static class PendingPackageBroadcasts {
462        // for each user id, a map of <package name -> components within that package>
463        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
464
465        public PendingPackageBroadcasts() {
466            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
467        }
468
469        public ArrayList<String> get(int userId, String packageName) {
470            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
471            return packages.get(packageName);
472        }
473
474        public void put(int userId, String packageName, ArrayList<String> components) {
475            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
476            packages.put(packageName, components);
477        }
478
479        public void remove(int userId, String packageName) {
480            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
481            if (packages != null) {
482                packages.remove(packageName);
483            }
484        }
485
486        public void remove(int userId) {
487            mUidMap.remove(userId);
488        }
489
490        public int userIdCount() {
491            return mUidMap.size();
492        }
493
494        public int userIdAt(int n) {
495            return mUidMap.keyAt(n);
496        }
497
498        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
499            return mUidMap.get(userId);
500        }
501
502        public int size() {
503            // total number of pending broadcast entries across all userIds
504            int num = 0;
505            for (int i = 0; i< mUidMap.size(); i++) {
506                num += mUidMap.valueAt(i).size();
507            }
508            return num;
509        }
510
511        public void clear() {
512            mUidMap.clear();
513        }
514
515        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
516            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
517            if (map == null) {
518                map = new HashMap<String, ArrayList<String>>();
519                mUidMap.put(userId, map);
520            }
521            return map;
522        }
523    }
524    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
525
526    // Service Connection to remote media container service to copy
527    // package uri's from external media onto secure containers
528    // or internal storage.
529    private IMediaContainerService mContainerService = null;
530
531    static final int SEND_PENDING_BROADCAST = 1;
532    static final int MCS_BOUND = 3;
533    static final int END_COPY = 4;
534    static final int INIT_COPY = 5;
535    static final int MCS_UNBIND = 6;
536    static final int START_CLEANING_PACKAGE = 7;
537    static final int FIND_INSTALL_LOC = 8;
538    static final int POST_INSTALL = 9;
539    static final int MCS_RECONNECT = 10;
540    static final int MCS_GIVE_UP = 11;
541    static final int UPDATED_MEDIA_STATUS = 12;
542    static final int WRITE_SETTINGS = 13;
543    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
544    static final int PACKAGE_VERIFIED = 15;
545    static final int CHECK_PENDING_VERIFICATION = 16;
546
547    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
548
549    // Delay time in millisecs
550    static final int BROADCAST_DELAY = 10 * 1000;
551
552    static UserManagerService sUserManager;
553
554    // Stores a list of users whose package restrictions file needs to be updated
555    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
556
557    final private DefaultContainerConnection mDefContainerConn =
558            new DefaultContainerConnection();
559    class DefaultContainerConnection implements ServiceConnection {
560        public void onServiceConnected(ComponentName name, IBinder service) {
561            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
562            IMediaContainerService imcs =
563                IMediaContainerService.Stub.asInterface(service);
564            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
565        }
566
567        public void onServiceDisconnected(ComponentName name) {
568            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
569        }
570    };
571
572    // Recordkeeping of restore-after-install operations that are currently in flight
573    // between the Package Manager and the Backup Manager
574    class PostInstallData {
575        public InstallArgs args;
576        public PackageInstalledInfo res;
577
578        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
579            args = _a;
580            res = _r;
581        }
582    };
583    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
584    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
585
586    private final String mRequiredVerifierPackage;
587
588    private final PackageUsage mPackageUsage = new PackageUsage();
589
590    private class PackageUsage {
591        private static final int WRITE_INTERVAL
592            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
593
594        private final Object mFileLock = new Object();
595        private final AtomicLong mLastWritten = new AtomicLong(0);
596        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
597
598        private boolean mIsHistoricalPackageUsageAvailable = true;
599
600        boolean isHistoricalPackageUsageAvailable() {
601            return mIsHistoricalPackageUsageAvailable;
602        }
603
604        void write(boolean force) {
605            if (force) {
606                writeInternal();
607                return;
608            }
609            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
610                && !DEBUG_DEXOPT) {
611                return;
612            }
613            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
614                new Thread("PackageUsage_DiskWriter") {
615                    @Override
616                    public void run() {
617                        try {
618                            writeInternal();
619                        } finally {
620                            mBackgroundWriteRunning.set(false);
621                        }
622                    }
623                }.start();
624            }
625        }
626
627        private void writeInternal() {
628            synchronized (mPackages) {
629                synchronized (mFileLock) {
630                    AtomicFile file = getFile();
631                    FileOutputStream f = null;
632                    try {
633                        f = file.startWrite();
634                        BufferedOutputStream out = new BufferedOutputStream(f);
635                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
636                        StringBuilder sb = new StringBuilder();
637                        for (PackageParser.Package pkg : mPackages.values()) {
638                            if (pkg.mLastPackageUsageTimeInMills == 0) {
639                                continue;
640                            }
641                            sb.setLength(0);
642                            sb.append(pkg.packageName);
643                            sb.append(' ');
644                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
645                            sb.append('\n');
646                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
647                        }
648                        out.flush();
649                        file.finishWrite(f);
650                    } catch (IOException e) {
651                        if (f != null) {
652                            file.failWrite(f);
653                        }
654                        Log.e(TAG, "Failed to write package usage times", e);
655                    }
656                }
657            }
658            mLastWritten.set(SystemClock.elapsedRealtime());
659        }
660
661        void readLP() {
662            synchronized (mFileLock) {
663                AtomicFile file = getFile();
664                BufferedInputStream in = null;
665                try {
666                    in = new BufferedInputStream(file.openRead());
667                    StringBuffer sb = new StringBuffer();
668                    while (true) {
669                        String packageName = readToken(in, sb, ' ');
670                        if (packageName == null) {
671                            break;
672                        }
673                        String timeInMillisString = readToken(in, sb, '\n');
674                        if (timeInMillisString == null) {
675                            throw new IOException("Failed to find last usage time for package "
676                                                  + packageName);
677                        }
678                        PackageParser.Package pkg = mPackages.get(packageName);
679                        if (pkg == null) {
680                            continue;
681                        }
682                        long timeInMillis;
683                        try {
684                            timeInMillis = Long.parseLong(timeInMillisString.toString());
685                        } catch (NumberFormatException e) {
686                            throw new IOException("Failed to parse " + timeInMillisString
687                                                  + " as a long.", e);
688                        }
689                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
690                    }
691                } catch (FileNotFoundException expected) {
692                    mIsHistoricalPackageUsageAvailable = false;
693                } catch (IOException e) {
694                    Log.w(TAG, "Failed to read package usage times", e);
695                } finally {
696                    IoUtils.closeQuietly(in);
697                }
698            }
699            mLastWritten.set(SystemClock.elapsedRealtime());
700        }
701
702        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
703                throws IOException {
704            sb.setLength(0);
705            while (true) {
706                int ch = in.read();
707                if (ch == -1) {
708                    if (sb.length() == 0) {
709                        return null;
710                    }
711                    throw new IOException("Unexpected EOF");
712                }
713                if (ch == endOfToken) {
714                    return sb.toString();
715                }
716                sb.append((char)ch);
717            }
718        }
719
720        private AtomicFile getFile() {
721            File dataDir = Environment.getDataDirectory();
722            File systemDir = new File(dataDir, "system");
723            File fname = new File(systemDir, "package-usage.list");
724            return new AtomicFile(fname);
725        }
726    }
727
728    class PackageHandler extends Handler {
729        private boolean mBound = false;
730        final ArrayList<HandlerParams> mPendingInstalls =
731            new ArrayList<HandlerParams>();
732
733        private boolean connectToService() {
734            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
735                    " DefaultContainerService");
736            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
737            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
738            if (mContext.bindServiceAsUser(service, mDefContainerConn,
739                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
740                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
741                mBound = true;
742                return true;
743            }
744            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
745            return false;
746        }
747
748        private void disconnectService() {
749            mContainerService = null;
750            mBound = false;
751            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
752            mContext.unbindService(mDefContainerConn);
753            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754        }
755
756        PackageHandler(Looper looper) {
757            super(looper);
758        }
759
760        public void handleMessage(Message msg) {
761            try {
762                doHandleMessage(msg);
763            } finally {
764                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
765            }
766        }
767
768        void doHandleMessage(Message msg) {
769            switch (msg.what) {
770                case INIT_COPY: {
771                    HandlerParams params = (HandlerParams) msg.obj;
772                    int idx = mPendingInstalls.size();
773                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
774                    // If a bind was already initiated we dont really
775                    // need to do anything. The pending install
776                    // will be processed later on.
777                    if (!mBound) {
778                        // If this is the only one pending we might
779                        // have to bind to the service again.
780                        if (!connectToService()) {
781                            Slog.e(TAG, "Failed to bind to media container service");
782                            params.serviceError();
783                            return;
784                        } else {
785                            // Once we bind to the service, the first
786                            // pending request will be processed.
787                            mPendingInstalls.add(idx, params);
788                        }
789                    } else {
790                        mPendingInstalls.add(idx, params);
791                        // Already bound to the service. Just make
792                        // sure we trigger off processing the first request.
793                        if (idx == 0) {
794                            mHandler.sendEmptyMessage(MCS_BOUND);
795                        }
796                    }
797                    break;
798                }
799                case MCS_BOUND: {
800                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
801                    if (msg.obj != null) {
802                        mContainerService = (IMediaContainerService) msg.obj;
803                    }
804                    if (mContainerService == null) {
805                        // Something seriously wrong. Bail out
806                        Slog.e(TAG, "Cannot bind to media container service");
807                        for (HandlerParams params : mPendingInstalls) {
808                            // Indicate service bind error
809                            params.serviceError();
810                        }
811                        mPendingInstalls.clear();
812                    } else if (mPendingInstalls.size() > 0) {
813                        HandlerParams params = mPendingInstalls.get(0);
814                        if (params != null) {
815                            if (params.startCopy()) {
816                                // We are done...  look for more work or to
817                                // go idle.
818                                if (DEBUG_SD_INSTALL) Log.i(TAG,
819                                        "Checking for more work or unbind...");
820                                // Delete pending install
821                                if (mPendingInstalls.size() > 0) {
822                                    mPendingInstalls.remove(0);
823                                }
824                                if (mPendingInstalls.size() == 0) {
825                                    if (mBound) {
826                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
827                                                "Posting delayed MCS_UNBIND");
828                                        removeMessages(MCS_UNBIND);
829                                        Message ubmsg = obtainMessage(MCS_UNBIND);
830                                        // Unbind after a little delay, to avoid
831                                        // continual thrashing.
832                                        sendMessageDelayed(ubmsg, 10000);
833                                    }
834                                } else {
835                                    // There are more pending requests in queue.
836                                    // Just post MCS_BOUND message to trigger processing
837                                    // of next pending install.
838                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
839                                            "Posting MCS_BOUND for next work");
840                                    mHandler.sendEmptyMessage(MCS_BOUND);
841                                }
842                            }
843                        }
844                    } else {
845                        // Should never happen ideally.
846                        Slog.w(TAG, "Empty queue");
847                    }
848                    break;
849                }
850                case MCS_RECONNECT: {
851                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
852                    if (mPendingInstalls.size() > 0) {
853                        if (mBound) {
854                            disconnectService();
855                        }
856                        if (!connectToService()) {
857                            Slog.e(TAG, "Failed to bind to media container service");
858                            for (HandlerParams params : mPendingInstalls) {
859                                // Indicate service bind error
860                                params.serviceError();
861                            }
862                            mPendingInstalls.clear();
863                        }
864                    }
865                    break;
866                }
867                case MCS_UNBIND: {
868                    // If there is no actual work left, then time to unbind.
869                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
870
871                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
872                        if (mBound) {
873                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
874
875                            disconnectService();
876                        }
877                    } else if (mPendingInstalls.size() > 0) {
878                        // There are more pending requests in queue.
879                        // Just post MCS_BOUND message to trigger processing
880                        // of next pending install.
881                        mHandler.sendEmptyMessage(MCS_BOUND);
882                    }
883
884                    break;
885                }
886                case MCS_GIVE_UP: {
887                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
888                    mPendingInstalls.remove(0);
889                    break;
890                }
891                case SEND_PENDING_BROADCAST: {
892                    String packages[];
893                    ArrayList<String> components[];
894                    int size = 0;
895                    int uids[];
896                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
897                    synchronized (mPackages) {
898                        if (mPendingBroadcasts == null) {
899                            return;
900                        }
901                        size = mPendingBroadcasts.size();
902                        if (size <= 0) {
903                            // Nothing to be done. Just return
904                            return;
905                        }
906                        packages = new String[size];
907                        components = new ArrayList[size];
908                        uids = new int[size];
909                        int i = 0;  // filling out the above arrays
910
911                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
912                            int packageUserId = mPendingBroadcasts.userIdAt(n);
913                            Iterator<Map.Entry<String, ArrayList<String>>> it
914                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
915                                            .entrySet().iterator();
916                            while (it.hasNext() && i < size) {
917                                Map.Entry<String, ArrayList<String>> ent = it.next();
918                                packages[i] = ent.getKey();
919                                components[i] = ent.getValue();
920                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
921                                uids[i] = (ps != null)
922                                        ? UserHandle.getUid(packageUserId, ps.appId)
923                                        : -1;
924                                i++;
925                            }
926                        }
927                        size = i;
928                        mPendingBroadcasts.clear();
929                    }
930                    // Send broadcasts
931                    for (int i = 0; i < size; i++) {
932                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
933                    }
934                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
935                    break;
936                }
937                case START_CLEANING_PACKAGE: {
938                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
939                    final String packageName = (String)msg.obj;
940                    final int userId = msg.arg1;
941                    final boolean andCode = msg.arg2 != 0;
942                    synchronized (mPackages) {
943                        if (userId == UserHandle.USER_ALL) {
944                            int[] users = sUserManager.getUserIds();
945                            for (int user : users) {
946                                mSettings.addPackageToCleanLPw(
947                                        new PackageCleanItem(user, packageName, andCode));
948                            }
949                        } else {
950                            mSettings.addPackageToCleanLPw(
951                                    new PackageCleanItem(userId, packageName, andCode));
952                        }
953                    }
954                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
955                    startCleaningPackages();
956                } break;
957                case POST_INSTALL: {
958                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
959                    PostInstallData data = mRunningInstalls.get(msg.arg1);
960                    mRunningInstalls.delete(msg.arg1);
961                    boolean deleteOld = false;
962
963                    if (data != null) {
964                        InstallArgs args = data.args;
965                        PackageInstalledInfo res = data.res;
966
967                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
968                            res.removedInfo.sendBroadcast(false, true, false);
969                            Bundle extras = new Bundle(1);
970                            extras.putInt(Intent.EXTRA_UID, res.uid);
971                            // Determine the set of users who are adding this
972                            // package for the first time vs. those who are seeing
973                            // an update.
974                            int[] firstUsers;
975                            int[] updateUsers = new int[0];
976                            if (res.origUsers == null || res.origUsers.length == 0) {
977                                firstUsers = res.newUsers;
978                            } else {
979                                firstUsers = new int[0];
980                                for (int i=0; i<res.newUsers.length; i++) {
981                                    int user = res.newUsers[i];
982                                    boolean isNew = true;
983                                    for (int j=0; j<res.origUsers.length; j++) {
984                                        if (res.origUsers[j] == user) {
985                                            isNew = false;
986                                            break;
987                                        }
988                                    }
989                                    if (isNew) {
990                                        int[] newFirst = new int[firstUsers.length+1];
991                                        System.arraycopy(firstUsers, 0, newFirst, 0,
992                                                firstUsers.length);
993                                        newFirst[firstUsers.length] = user;
994                                        firstUsers = newFirst;
995                                    } else {
996                                        int[] newUpdate = new int[updateUsers.length+1];
997                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
998                                                updateUsers.length);
999                                        newUpdate[updateUsers.length] = user;
1000                                        updateUsers = newUpdate;
1001                                    }
1002                                }
1003                            }
1004                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1005                                    res.pkg.applicationInfo.packageName,
1006                                    extras, null, null, firstUsers);
1007                            final boolean update = res.removedInfo.removedPackage != null;
1008                            if (update) {
1009                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1010                            }
1011                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1012                                    res.pkg.applicationInfo.packageName,
1013                                    extras, null, null, updateUsers);
1014                            if (update) {
1015                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1016                                        res.pkg.applicationInfo.packageName,
1017                                        extras, null, null, updateUsers);
1018                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1019                                        null, null,
1020                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1021
1022                                // treat asec-hosted packages like removable media on upgrade
1023                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1024                                    if (DEBUG_INSTALL) {
1025                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1026                                                + " is ASEC-hosted -> AVAILABLE");
1027                                    }
1028                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1029                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1030                                    pkgList.add(res.pkg.applicationInfo.packageName);
1031                                    sendResourcesChangedBroadcast(true, true,
1032                                            pkgList,uidArray, null);
1033                                }
1034                            }
1035                            if (res.removedInfo.args != null) {
1036                                // Remove the replaced package's older resources safely now
1037                                deleteOld = true;
1038                            }
1039
1040                            // Log current value of "unknown sources" setting
1041                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1042                                getUnknownSourcesSettings());
1043                        }
1044                        // Force a gc to clear up things
1045                        Runtime.getRuntime().gc();
1046                        // We delete after a gc for applications  on sdcard.
1047                        if (deleteOld) {
1048                            synchronized (mInstallLock) {
1049                                res.removedInfo.args.doPostDeleteLI(true);
1050                            }
1051                        }
1052                        if (args.observer != null) {
1053                            try {
1054                                Bundle extras = extrasForInstallResult(res);
1055                                args.observer.onPackageInstalled(res.name, res.returnCode,
1056                                        res.returnMsg, extras);
1057                            } catch (RemoteException e) {
1058                                Slog.i(TAG, "Observer no longer exists.");
1059                            }
1060                        }
1061                    } else {
1062                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1063                    }
1064                } break;
1065                case UPDATED_MEDIA_STATUS: {
1066                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1067                    boolean reportStatus = msg.arg1 == 1;
1068                    boolean doGc = msg.arg2 == 1;
1069                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1070                    if (doGc) {
1071                        // Force a gc to clear up stale containers.
1072                        Runtime.getRuntime().gc();
1073                    }
1074                    if (msg.obj != null) {
1075                        @SuppressWarnings("unchecked")
1076                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1077                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1078                        // Unload containers
1079                        unloadAllContainers(args);
1080                    }
1081                    if (reportStatus) {
1082                        try {
1083                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1084                            PackageHelper.getMountService().finishMediaUpdate();
1085                        } catch (RemoteException e) {
1086                            Log.e(TAG, "MountService not running?");
1087                        }
1088                    }
1089                } break;
1090                case WRITE_SETTINGS: {
1091                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1092                    synchronized (mPackages) {
1093                        removeMessages(WRITE_SETTINGS);
1094                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1095                        mSettings.writeLPr();
1096                        mDirtyUsers.clear();
1097                    }
1098                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1099                } break;
1100                case WRITE_PACKAGE_RESTRICTIONS: {
1101                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1102                    synchronized (mPackages) {
1103                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1104                        for (int userId : mDirtyUsers) {
1105                            mSettings.writePackageRestrictionsLPr(userId);
1106                        }
1107                        mDirtyUsers.clear();
1108                    }
1109                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1110                } break;
1111                case CHECK_PENDING_VERIFICATION: {
1112                    final int verificationId = msg.arg1;
1113                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1114
1115                    if ((state != null) && !state.timeoutExtended()) {
1116                        final InstallArgs args = state.getInstallArgs();
1117                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1118
1119                        Slog.i(TAG, "Verification timed out for " + originUri);
1120                        mPendingVerification.remove(verificationId);
1121
1122                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1123
1124                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1125                            Slog.i(TAG, "Continuing with installation of " + originUri);
1126                            state.setVerifierResponse(Binder.getCallingUid(),
1127                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1128                            broadcastPackageVerified(verificationId, originUri,
1129                                    PackageManager.VERIFICATION_ALLOW,
1130                                    state.getInstallArgs().getUser());
1131                            try {
1132                                ret = args.copyApk(mContainerService, true);
1133                            } catch (RemoteException e) {
1134                                Slog.e(TAG, "Could not contact the ContainerService");
1135                            }
1136                        } else {
1137                            broadcastPackageVerified(verificationId, originUri,
1138                                    PackageManager.VERIFICATION_REJECT,
1139                                    state.getInstallArgs().getUser());
1140                        }
1141
1142                        processPendingInstall(args, ret);
1143                        mHandler.sendEmptyMessage(MCS_UNBIND);
1144                    }
1145                    break;
1146                }
1147                case PACKAGE_VERIFIED: {
1148                    final int verificationId = msg.arg1;
1149
1150                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1151                    if (state == null) {
1152                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1153                        break;
1154                    }
1155
1156                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1157
1158                    state.setVerifierResponse(response.callerUid, response.code);
1159
1160                    if (state.isVerificationComplete()) {
1161                        mPendingVerification.remove(verificationId);
1162
1163                        final InstallArgs args = state.getInstallArgs();
1164                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1165
1166                        int ret;
1167                        if (state.isInstallAllowed()) {
1168                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1169                            broadcastPackageVerified(verificationId, originUri,
1170                                    response.code, state.getInstallArgs().getUser());
1171                            try {
1172                                ret = args.copyApk(mContainerService, true);
1173                            } catch (RemoteException e) {
1174                                Slog.e(TAG, "Could not contact the ContainerService");
1175                            }
1176                        } else {
1177                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1178                        }
1179
1180                        processPendingInstall(args, ret);
1181
1182                        mHandler.sendEmptyMessage(MCS_UNBIND);
1183                    }
1184
1185                    break;
1186                }
1187            }
1188        }
1189    }
1190
1191    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1192        Bundle extras = null;
1193        switch (res.returnCode) {
1194            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1195                extras = new Bundle();
1196                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1197                        res.origPermission);
1198                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1199                        res.origPackage);
1200                break;
1201            }
1202        }
1203        return extras;
1204    }
1205
1206    void scheduleWriteSettingsLocked() {
1207        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1208            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1209        }
1210    }
1211
1212    void scheduleWritePackageRestrictionsLocked(int userId) {
1213        if (!sUserManager.exists(userId)) return;
1214        mDirtyUsers.add(userId);
1215        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1216            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1217        }
1218    }
1219
1220    public static final PackageManagerService main(Context context, Installer installer,
1221            boolean factoryTest, boolean onlyCore) {
1222        PackageManagerService m = new PackageManagerService(context, installer,
1223                factoryTest, onlyCore);
1224        ServiceManager.addService("package", m);
1225        return m;
1226    }
1227
1228    static String[] splitString(String str, char sep) {
1229        int count = 1;
1230        int i = 0;
1231        while ((i=str.indexOf(sep, i)) >= 0) {
1232            count++;
1233            i++;
1234        }
1235
1236        String[] res = new String[count];
1237        i=0;
1238        count = 0;
1239        int lastI=0;
1240        while ((i=str.indexOf(sep, i)) >= 0) {
1241            res[count] = str.substring(lastI, i);
1242            count++;
1243            i++;
1244            lastI = i;
1245        }
1246        res[count] = str.substring(lastI, str.length());
1247        return res;
1248    }
1249
1250    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1251        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1252                Context.DISPLAY_SERVICE);
1253        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1254    }
1255
1256    public PackageManagerService(Context context, Installer installer,
1257            boolean factoryTest, boolean onlyCore) {
1258        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1259                SystemClock.uptimeMillis());
1260
1261        if (mSdkVersion <= 0) {
1262            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1263        }
1264
1265        mContext = context;
1266        mFactoryTest = factoryTest;
1267        mOnlyCore = onlyCore;
1268        mMetrics = new DisplayMetrics();
1269        mSettings = new Settings(context);
1270        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1271                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1272        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1273                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1274        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1275                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1276        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1277                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1278        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1279                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1280        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1281                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1282
1283        String separateProcesses = SystemProperties.get("debug.separate_processes");
1284        if (separateProcesses != null && separateProcesses.length() > 0) {
1285            if ("*".equals(separateProcesses)) {
1286                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1287                mSeparateProcesses = null;
1288                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1289            } else {
1290                mDefParseFlags = 0;
1291                mSeparateProcesses = separateProcesses.split(",");
1292                Slog.w(TAG, "Running with debug.separate_processes: "
1293                        + separateProcesses);
1294            }
1295        } else {
1296            mDefParseFlags = 0;
1297            mSeparateProcesses = null;
1298        }
1299
1300        mInstaller = installer;
1301
1302        getDefaultDisplayMetrics(context, mMetrics);
1303
1304        SystemConfig systemConfig = SystemConfig.getInstance();
1305        mGlobalGids = systemConfig.getGlobalGids();
1306        mSystemPermissions = systemConfig.getSystemPermissions();
1307        mAvailableFeatures = systemConfig.getAvailableFeatures();
1308
1309        synchronized (mInstallLock) {
1310        // writer
1311        synchronized (mPackages) {
1312            mHandlerThread = new ServiceThread(TAG,
1313                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1314            mHandlerThread.start();
1315            mHandler = new PackageHandler(mHandlerThread.getLooper());
1316            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1317
1318            File dataDir = Environment.getDataDirectory();
1319            mAppDataDir = new File(dataDir, "data");
1320            mAppInstallDir = new File(dataDir, "app");
1321            mAppLib32InstallDir = new File(dataDir, "app-lib");
1322            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1323            mUserAppDataDir = new File(dataDir, "user");
1324            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1325
1326            sUserManager = new UserManagerService(context, this,
1327                    mInstallLock, mPackages);
1328
1329            // Propagate permission configuration in to package manager.
1330            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1331                    = systemConfig.getPermissions();
1332            for (int i=0; i<permConfig.size(); i++) {
1333                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1334                BasePermission bp = mSettings.mPermissions.get(perm.name);
1335                if (bp == null) {
1336                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1337                    mSettings.mPermissions.put(perm.name, bp);
1338                }
1339                if (perm.gids != null) {
1340                    bp.gids = appendInts(bp.gids, perm.gids);
1341                }
1342            }
1343
1344            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1345            for (int i=0; i<libConfig.size(); i++) {
1346                mSharedLibraries.put(libConfig.keyAt(i),
1347                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1348            }
1349
1350            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1351
1352            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1353                    mSdkVersion, mOnlyCore);
1354
1355            String customResolverActivity = Resources.getSystem().getString(
1356                    R.string.config_customResolverActivity);
1357            if (TextUtils.isEmpty(customResolverActivity)) {
1358                customResolverActivity = null;
1359            } else {
1360                mCustomResolverComponentName = ComponentName.unflattenFromString(
1361                        customResolverActivity);
1362            }
1363
1364            long startTime = SystemClock.uptimeMillis();
1365
1366            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1367                    startTime);
1368
1369            // Set flag to monitor and not change apk file paths when
1370            // scanning install directories.
1371            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1372
1373            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1374
1375            /**
1376             * Add everything in the in the boot class path to the
1377             * list of process files because dexopt will have been run
1378             * if necessary during zygote startup.
1379             */
1380            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1381            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1382
1383            if (bootClassPath != null) {
1384                String[] bootClassPathElements = splitString(bootClassPath, ':');
1385                for (String element : bootClassPathElements) {
1386                    alreadyDexOpted.add(element);
1387                }
1388            } else {
1389                Slog.w(TAG, "No BOOTCLASSPATH found!");
1390            }
1391
1392            if (systemServerClassPath != null) {
1393                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1394                for (String element : systemServerClassPathElements) {
1395                    alreadyDexOpted.add(element);
1396                }
1397            } else {
1398                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1399            }
1400
1401            boolean didDexOptLibraryOrTool = false;
1402
1403            final List<String> allInstructionSets = getAllInstructionSets();
1404            final String[] dexCodeInstructionSets =
1405                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1406
1407            /**
1408             * Ensure all external libraries have had dexopt run on them.
1409             */
1410            if (mSharedLibraries.size() > 0) {
1411                // NOTE: For now, we're compiling these system "shared libraries"
1412                // (and framework jars) into all available architectures. It's possible
1413                // to compile them only when we come across an app that uses them (there's
1414                // already logic for that in scanPackageLI) but that adds some complexity.
1415                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1416                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1417                        final String lib = libEntry.path;
1418                        if (lib == null) {
1419                            continue;
1420                        }
1421
1422                        try {
1423                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1424                                                                                 dexCodeInstructionSet,
1425                                                                                 false);
1426                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1427                                alreadyDexOpted.add(lib);
1428
1429                                // The list of "shared libraries" we have at this point is
1430                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1431                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1432                                } else {
1433                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1434                                }
1435                                didDexOptLibraryOrTool = true;
1436                            }
1437                        } catch (FileNotFoundException e) {
1438                            Slog.w(TAG, "Library not found: " + lib);
1439                        } catch (IOException e) {
1440                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1441                                    + e.getMessage());
1442                        }
1443                    }
1444                }
1445            }
1446
1447            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1448
1449            // Gross hack for now: we know this file doesn't contain any
1450            // code, so don't dexopt it to avoid the resulting log spew.
1451            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1452
1453            // Gross hack for now: we know this file is only part of
1454            // the boot class path for art, so don't dexopt it to
1455            // avoid the resulting log spew.
1456            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1457
1458            /**
1459             * And there are a number of commands implemented in Java, which
1460             * we currently need to do the dexopt on so that they can be
1461             * run from a non-root shell.
1462             */
1463            String[] frameworkFiles = frameworkDir.list();
1464            if (frameworkFiles != null) {
1465                // TODO: We could compile these only for the most preferred ABI. We should
1466                // first double check that the dex files for these commands are not referenced
1467                // by other system apps.
1468                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1469                    for (int i=0; i<frameworkFiles.length; i++) {
1470                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1471                        String path = libPath.getPath();
1472                        // Skip the file if we already did it.
1473                        if (alreadyDexOpted.contains(path)) {
1474                            continue;
1475                        }
1476                        // Skip the file if it is not a type we want to dexopt.
1477                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1478                            continue;
1479                        }
1480                        try {
1481                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1482                                                                                 dexCodeInstructionSet,
1483                                                                                 false);
1484                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1485                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1486                                didDexOptLibraryOrTool = true;
1487                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1488                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1489                                didDexOptLibraryOrTool = true;
1490                            }
1491                        } catch (FileNotFoundException e) {
1492                            Slog.w(TAG, "Jar not found: " + path);
1493                        } catch (IOException e) {
1494                            Slog.w(TAG, "Exception reading jar: " + path, e);
1495                        }
1496                    }
1497                }
1498            }
1499
1500            // Collect vendor overlay packages.
1501            // (Do this before scanning any apps.)
1502            // For security and version matching reason, only consider
1503            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1504            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1505            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1506                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1507
1508            // Find base frameworks (resource packages without code).
1509            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1510                    | PackageParser.PARSE_IS_SYSTEM_DIR
1511                    | PackageParser.PARSE_IS_PRIVILEGED,
1512                    scanFlags | SCAN_NO_DEX, 0);
1513
1514            // Collected privileged system packages.
1515            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1516            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1517                    | PackageParser.PARSE_IS_SYSTEM_DIR
1518                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1519
1520            // Collect ordinary system packages.
1521            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1522            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1523                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1524
1525            // Collect all vendor packages.
1526            File vendorAppDir = new File("/vendor/app");
1527            try {
1528                vendorAppDir = vendorAppDir.getCanonicalFile();
1529            } catch (IOException e) {
1530                // failed to look up canonical path, continue with original one
1531            }
1532            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1533                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1534
1535            // Collect all OEM packages.
1536            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1537            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1538                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1539
1540            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1541            mInstaller.moveFiles();
1542
1543            // Prune any system packages that no longer exist.
1544            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1545            if (!mOnlyCore) {
1546                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1547                while (psit.hasNext()) {
1548                    PackageSetting ps = psit.next();
1549
1550                    /*
1551                     * If this is not a system app, it can't be a
1552                     * disable system app.
1553                     */
1554                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1555                        continue;
1556                    }
1557
1558                    /*
1559                     * If the package is scanned, it's not erased.
1560                     */
1561                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1562                    if (scannedPkg != null) {
1563                        /*
1564                         * If the system app is both scanned and in the
1565                         * disabled packages list, then it must have been
1566                         * added via OTA. Remove it from the currently
1567                         * scanned package so the previously user-installed
1568                         * application can be scanned.
1569                         */
1570                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1571                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1572                                    + "; removing system app");
1573                            removePackageLI(ps, true);
1574                        }
1575
1576                        continue;
1577                    }
1578
1579                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1580                        psit.remove();
1581                        String msg = "System package " + ps.name
1582                                + " no longer exists; wiping its data";
1583                        reportSettingsProblem(Log.WARN, msg);
1584                        removeDataDirsLI(ps.name);
1585                    } else {
1586                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1587                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1588                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1589                        }
1590                    }
1591                }
1592            }
1593
1594            //look for any incomplete package installations
1595            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1596            //clean up list
1597            for(int i = 0; i < deletePkgsList.size(); i++) {
1598                //clean up here
1599                cleanupInstallFailedPackage(deletePkgsList.get(i));
1600            }
1601            //delete tmp files
1602            deleteTempPackageFiles();
1603
1604            // Remove any shared userIDs that have no associated packages
1605            mSettings.pruneSharedUsersLPw();
1606
1607            if (!mOnlyCore) {
1608                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1609                        SystemClock.uptimeMillis());
1610                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1611
1612                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1613                        scanFlags, 0);
1614
1615                /**
1616                 * Remove disable package settings for any updated system
1617                 * apps that were removed via an OTA. If they're not a
1618                 * previously-updated app, remove them completely.
1619                 * Otherwise, just revoke their system-level permissions.
1620                 */
1621                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1622                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1623                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1624
1625                    String msg;
1626                    if (deletedPkg == null) {
1627                        msg = "Updated system package " + deletedAppName
1628                                + " no longer exists; wiping its data";
1629                        removeDataDirsLI(deletedAppName);
1630                    } else {
1631                        msg = "Updated system app + " + deletedAppName
1632                                + " no longer present; removing system privileges for "
1633                                + deletedAppName;
1634
1635                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1636
1637                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1638                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1639                    }
1640                    reportSettingsProblem(Log.WARN, msg);
1641                }
1642            }
1643
1644            // Now that we know all of the shared libraries, update all clients to have
1645            // the correct library paths.
1646            updateAllSharedLibrariesLPw();
1647
1648            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1649                // NOTE: We ignore potential failures here during a system scan (like
1650                // the rest of the commands above) because there's precious little we
1651                // can do about it. A settings error is reported, though.
1652                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1653                        false /* force dexopt */, false /* defer dexopt */);
1654            }
1655
1656            // Now that we know all the packages we are keeping,
1657            // read and update their last usage times.
1658            mPackageUsage.readLP();
1659
1660            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1661                    SystemClock.uptimeMillis());
1662            Slog.i(TAG, "Time to scan packages: "
1663                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1664                    + " seconds");
1665
1666            // If the platform SDK has changed since the last time we booted,
1667            // we need to re-grant app permission to catch any new ones that
1668            // appear.  This is really a hack, and means that apps can in some
1669            // cases get permissions that the user didn't initially explicitly
1670            // allow...  it would be nice to have some better way to handle
1671            // this situation.
1672            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1673                    != mSdkVersion;
1674            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1675                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1676                    + "; regranting permissions for internal storage");
1677            mSettings.mInternalSdkPlatform = mSdkVersion;
1678
1679            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1680                    | (regrantPermissions
1681                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1682                            : 0));
1683
1684            // If this is the first boot, and it is a normal boot, then
1685            // we need to initialize the default preferred apps.
1686            if (!mRestoredSettings && !onlyCore) {
1687                mSettings.readDefaultPreferredAppsLPw(this, 0);
1688            }
1689
1690            // If this is first boot after an OTA, and a normal boot, then
1691            // we need to clear code cache directories.
1692            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1693                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1694                for (String pkgName : mSettings.mPackages.keySet()) {
1695                    deleteCodeCacheDirsLI(pkgName);
1696                }
1697                mSettings.mFingerprint = Build.FINGERPRINT;
1698            }
1699
1700            // All the changes are done during package scanning.
1701            mSettings.updateInternalDatabaseVersion();
1702
1703            // can downgrade to reader
1704            mSettings.writeLPr();
1705
1706            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1707                    SystemClock.uptimeMillis());
1708
1709
1710            mRequiredVerifierPackage = getRequiredVerifierLPr();
1711        } // synchronized (mPackages)
1712        } // synchronized (mInstallLock)
1713
1714        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1715
1716        // Now after opening every single application zip, make sure they
1717        // are all flushed.  Not really needed, but keeps things nice and
1718        // tidy.
1719        Runtime.getRuntime().gc();
1720    }
1721
1722    @Override
1723    public boolean isFirstBoot() {
1724        return !mRestoredSettings;
1725    }
1726
1727    @Override
1728    public boolean isOnlyCoreApps() {
1729        return mOnlyCore;
1730    }
1731
1732    private String getRequiredVerifierLPr() {
1733        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1734        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1735                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1736
1737        String requiredVerifier = null;
1738
1739        final int N = receivers.size();
1740        for (int i = 0; i < N; i++) {
1741            final ResolveInfo info = receivers.get(i);
1742
1743            if (info.activityInfo == null) {
1744                continue;
1745            }
1746
1747            final String packageName = info.activityInfo.packageName;
1748
1749            final PackageSetting ps = mSettings.mPackages.get(packageName);
1750            if (ps == null) {
1751                continue;
1752            }
1753
1754            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1755            if (!gp.grantedPermissions
1756                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1757                continue;
1758            }
1759
1760            if (requiredVerifier != null) {
1761                throw new RuntimeException("There can be only one required verifier");
1762            }
1763
1764            requiredVerifier = packageName;
1765        }
1766
1767        return requiredVerifier;
1768    }
1769
1770    @Override
1771    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1772            throws RemoteException {
1773        try {
1774            return super.onTransact(code, data, reply, flags);
1775        } catch (RuntimeException e) {
1776            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1777                Slog.wtf(TAG, "Package Manager Crash", e);
1778            }
1779            throw e;
1780        }
1781    }
1782
1783    void cleanupInstallFailedPackage(PackageSetting ps) {
1784        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1785        removeDataDirsLI(ps.name);
1786
1787        // TODO: try cleaning up codePath directory contents first, since it
1788        // might be a cluster
1789
1790        if (ps.codePath != null) {
1791            if (!ps.codePath.delete()) {
1792                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1793            }
1794        }
1795        if (ps.resourcePath != null) {
1796            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1797                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1798            }
1799        }
1800        mSettings.removePackageLPw(ps.name);
1801    }
1802
1803    static int[] appendInts(int[] cur, int[] add) {
1804        if (add == null) return cur;
1805        if (cur == null) return add;
1806        final int N = add.length;
1807        for (int i=0; i<N; i++) {
1808            cur = appendInt(cur, add[i]);
1809        }
1810        return cur;
1811    }
1812
1813    static int[] removeInts(int[] cur, int[] rem) {
1814        if (rem == null) return cur;
1815        if (cur == null) return cur;
1816        final int N = rem.length;
1817        for (int i=0; i<N; i++) {
1818            cur = removeInt(cur, rem[i]);
1819        }
1820        return cur;
1821    }
1822
1823    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1824        if (!sUserManager.exists(userId)) return null;
1825        final PackageSetting ps = (PackageSetting) p.mExtras;
1826        if (ps == null) {
1827            return null;
1828        }
1829        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1830        final PackageUserState state = ps.readUserState(userId);
1831        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1832                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1833                state, userId);
1834    }
1835
1836    @Override
1837    public boolean isPackageAvailable(String packageName, int userId) {
1838        if (!sUserManager.exists(userId)) return false;
1839        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1840        synchronized (mPackages) {
1841            PackageParser.Package p = mPackages.get(packageName);
1842            if (p != null) {
1843                final PackageSetting ps = (PackageSetting) p.mExtras;
1844                if (ps != null) {
1845                    final PackageUserState state = ps.readUserState(userId);
1846                    if (state != null) {
1847                        return PackageParser.isAvailable(state);
1848                    }
1849                }
1850            }
1851        }
1852        return false;
1853    }
1854
1855    @Override
1856    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1857        if (!sUserManager.exists(userId)) return null;
1858        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1859        // reader
1860        synchronized (mPackages) {
1861            PackageParser.Package p = mPackages.get(packageName);
1862            if (DEBUG_PACKAGE_INFO)
1863                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1864            if (p != null) {
1865                return generatePackageInfo(p, flags, userId);
1866            }
1867            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1868                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1869            }
1870        }
1871        return null;
1872    }
1873
1874    @Override
1875    public String[] currentToCanonicalPackageNames(String[] names) {
1876        String[] out = new String[names.length];
1877        // reader
1878        synchronized (mPackages) {
1879            for (int i=names.length-1; i>=0; i--) {
1880                PackageSetting ps = mSettings.mPackages.get(names[i]);
1881                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1882            }
1883        }
1884        return out;
1885    }
1886
1887    @Override
1888    public String[] canonicalToCurrentPackageNames(String[] names) {
1889        String[] out = new String[names.length];
1890        // reader
1891        synchronized (mPackages) {
1892            for (int i=names.length-1; i>=0; i--) {
1893                String cur = mSettings.mRenamedPackages.get(names[i]);
1894                out[i] = cur != null ? cur : names[i];
1895            }
1896        }
1897        return out;
1898    }
1899
1900    @Override
1901    public int getPackageUid(String packageName, int userId) {
1902        if (!sUserManager.exists(userId)) return -1;
1903        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1904        // reader
1905        synchronized (mPackages) {
1906            PackageParser.Package p = mPackages.get(packageName);
1907            if(p != null) {
1908                return UserHandle.getUid(userId, p.applicationInfo.uid);
1909            }
1910            PackageSetting ps = mSettings.mPackages.get(packageName);
1911            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1912                return -1;
1913            }
1914            p = ps.pkg;
1915            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1916        }
1917    }
1918
1919    @Override
1920    public int[] getPackageGids(String packageName) {
1921        // reader
1922        synchronized (mPackages) {
1923            PackageParser.Package p = mPackages.get(packageName);
1924            if (DEBUG_PACKAGE_INFO)
1925                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1926            if (p != null) {
1927                final PackageSetting ps = (PackageSetting)p.mExtras;
1928                return ps.getGids();
1929            }
1930        }
1931        // stupid thing to indicate an error.
1932        return new int[0];
1933    }
1934
1935    static final PermissionInfo generatePermissionInfo(
1936            BasePermission bp, int flags) {
1937        if (bp.perm != null) {
1938            return PackageParser.generatePermissionInfo(bp.perm, flags);
1939        }
1940        PermissionInfo pi = new PermissionInfo();
1941        pi.name = bp.name;
1942        pi.packageName = bp.sourcePackage;
1943        pi.nonLocalizedLabel = bp.name;
1944        pi.protectionLevel = bp.protectionLevel;
1945        return pi;
1946    }
1947
1948    @Override
1949    public PermissionInfo getPermissionInfo(String name, int flags) {
1950        // reader
1951        synchronized (mPackages) {
1952            final BasePermission p = mSettings.mPermissions.get(name);
1953            if (p != null) {
1954                return generatePermissionInfo(p, flags);
1955            }
1956            return null;
1957        }
1958    }
1959
1960    @Override
1961    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1962        // reader
1963        synchronized (mPackages) {
1964            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1965            for (BasePermission p : mSettings.mPermissions.values()) {
1966                if (group == null) {
1967                    if (p.perm == null || p.perm.info.group == null) {
1968                        out.add(generatePermissionInfo(p, flags));
1969                    }
1970                } else {
1971                    if (p.perm != null && group.equals(p.perm.info.group)) {
1972                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1973                    }
1974                }
1975            }
1976
1977            if (out.size() > 0) {
1978                return out;
1979            }
1980            return mPermissionGroups.containsKey(group) ? out : null;
1981        }
1982    }
1983
1984    @Override
1985    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1986        // reader
1987        synchronized (mPackages) {
1988            return PackageParser.generatePermissionGroupInfo(
1989                    mPermissionGroups.get(name), flags);
1990        }
1991    }
1992
1993    @Override
1994    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1995        // reader
1996        synchronized (mPackages) {
1997            final int N = mPermissionGroups.size();
1998            ArrayList<PermissionGroupInfo> out
1999                    = new ArrayList<PermissionGroupInfo>(N);
2000            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2001                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2002            }
2003            return out;
2004        }
2005    }
2006
2007    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2008            int userId) {
2009        if (!sUserManager.exists(userId)) return null;
2010        PackageSetting ps = mSettings.mPackages.get(packageName);
2011        if (ps != null) {
2012            if (ps.pkg == null) {
2013                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2014                        flags, userId);
2015                if (pInfo != null) {
2016                    return pInfo.applicationInfo;
2017                }
2018                return null;
2019            }
2020            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2021                    ps.readUserState(userId), userId);
2022        }
2023        return null;
2024    }
2025
2026    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2027            int userId) {
2028        if (!sUserManager.exists(userId)) return null;
2029        PackageSetting ps = mSettings.mPackages.get(packageName);
2030        if (ps != null) {
2031            PackageParser.Package pkg = ps.pkg;
2032            if (pkg == null) {
2033                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2034                    return null;
2035                }
2036                // Only data remains, so we aren't worried about code paths
2037                pkg = new PackageParser.Package(packageName);
2038                pkg.applicationInfo.packageName = packageName;
2039                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2040                pkg.applicationInfo.dataDir =
2041                        getDataPathForPackage(packageName, 0).getPath();
2042                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2043                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2044            }
2045            return generatePackageInfo(pkg, flags, userId);
2046        }
2047        return null;
2048    }
2049
2050    @Override
2051    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2052        if (!sUserManager.exists(userId)) return null;
2053        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2054        // writer
2055        synchronized (mPackages) {
2056            PackageParser.Package p = mPackages.get(packageName);
2057            if (DEBUG_PACKAGE_INFO) Log.v(
2058                    TAG, "getApplicationInfo " + packageName
2059                    + ": " + p);
2060            if (p != null) {
2061                PackageSetting ps = mSettings.mPackages.get(packageName);
2062                if (ps == null) return null;
2063                // Note: isEnabledLP() does not apply here - always return info
2064                return PackageParser.generateApplicationInfo(
2065                        p, flags, ps.readUserState(userId), userId);
2066            }
2067            if ("android".equals(packageName)||"system".equals(packageName)) {
2068                return mAndroidApplication;
2069            }
2070            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2071                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2072            }
2073        }
2074        return null;
2075    }
2076
2077
2078    @Override
2079    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2080        mContext.enforceCallingOrSelfPermission(
2081                android.Manifest.permission.CLEAR_APP_CACHE, null);
2082        // Queue up an async operation since clearing cache may take a little while.
2083        mHandler.post(new Runnable() {
2084            public void run() {
2085                mHandler.removeCallbacks(this);
2086                int retCode = -1;
2087                synchronized (mInstallLock) {
2088                    retCode = mInstaller.freeCache(freeStorageSize);
2089                    if (retCode < 0) {
2090                        Slog.w(TAG, "Couldn't clear application caches");
2091                    }
2092                }
2093                if (observer != null) {
2094                    try {
2095                        observer.onRemoveCompleted(null, (retCode >= 0));
2096                    } catch (RemoteException e) {
2097                        Slog.w(TAG, "RemoveException when invoking call back");
2098                    }
2099                }
2100            }
2101        });
2102    }
2103
2104    @Override
2105    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2106        mContext.enforceCallingOrSelfPermission(
2107                android.Manifest.permission.CLEAR_APP_CACHE, null);
2108        // Queue up an async operation since clearing cache may take a little while.
2109        mHandler.post(new Runnable() {
2110            public void run() {
2111                mHandler.removeCallbacks(this);
2112                int retCode = -1;
2113                synchronized (mInstallLock) {
2114                    retCode = mInstaller.freeCache(freeStorageSize);
2115                    if (retCode < 0) {
2116                        Slog.w(TAG, "Couldn't clear application caches");
2117                    }
2118                }
2119                if(pi != null) {
2120                    try {
2121                        // Callback via pending intent
2122                        int code = (retCode >= 0) ? 1 : 0;
2123                        pi.sendIntent(null, code, null,
2124                                null, null);
2125                    } catch (SendIntentException e1) {
2126                        Slog.i(TAG, "Failed to send pending intent");
2127                    }
2128                }
2129            }
2130        });
2131    }
2132
2133    void freeStorage(long freeStorageSize) throws IOException {
2134        synchronized (mInstallLock) {
2135            if (mInstaller.freeCache(freeStorageSize) < 0) {
2136                throw new IOException("Failed to free enough space");
2137            }
2138        }
2139    }
2140
2141    @Override
2142    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2143        if (!sUserManager.exists(userId)) return null;
2144        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2145        synchronized (mPackages) {
2146            PackageParser.Activity a = mActivities.mActivities.get(component);
2147
2148            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2149            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2150                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2151                if (ps == null) return null;
2152                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2153                        userId);
2154            }
2155            if (mResolveComponentName.equals(component)) {
2156                return mResolveActivity;
2157            }
2158        }
2159        return null;
2160    }
2161
2162    @Override
2163    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2164            String resolvedType) {
2165        synchronized (mPackages) {
2166            PackageParser.Activity a = mActivities.mActivities.get(component);
2167            if (a == null) {
2168                return false;
2169            }
2170            for (int i=0; i<a.intents.size(); i++) {
2171                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2172                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2173                    return true;
2174                }
2175            }
2176            return false;
2177        }
2178    }
2179
2180    @Override
2181    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2182        if (!sUserManager.exists(userId)) return null;
2183        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2184        synchronized (mPackages) {
2185            PackageParser.Activity a = mReceivers.mActivities.get(component);
2186            if (DEBUG_PACKAGE_INFO) Log.v(
2187                TAG, "getReceiverInfo " + component + ": " + a);
2188            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2189                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2190                if (ps == null) return null;
2191                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2192                        userId);
2193            }
2194        }
2195        return null;
2196    }
2197
2198    @Override
2199    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2200        if (!sUserManager.exists(userId)) return null;
2201        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2202        synchronized (mPackages) {
2203            PackageParser.Service s = mServices.mServices.get(component);
2204            if (DEBUG_PACKAGE_INFO) Log.v(
2205                TAG, "getServiceInfo " + component + ": " + s);
2206            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2207                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2208                if (ps == null) return null;
2209                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2210                        userId);
2211            }
2212        }
2213        return null;
2214    }
2215
2216    @Override
2217    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2218        if (!sUserManager.exists(userId)) return null;
2219        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2220        synchronized (mPackages) {
2221            PackageParser.Provider p = mProviders.mProviders.get(component);
2222            if (DEBUG_PACKAGE_INFO) Log.v(
2223                TAG, "getProviderInfo " + component + ": " + p);
2224            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2225                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2226                if (ps == null) return null;
2227                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2228                        userId);
2229            }
2230        }
2231        return null;
2232    }
2233
2234    @Override
2235    public String[] getSystemSharedLibraryNames() {
2236        Set<String> libSet;
2237        synchronized (mPackages) {
2238            libSet = mSharedLibraries.keySet();
2239            int size = libSet.size();
2240            if (size > 0) {
2241                String[] libs = new String[size];
2242                libSet.toArray(libs);
2243                return libs;
2244            }
2245        }
2246        return null;
2247    }
2248
2249    @Override
2250    public FeatureInfo[] getSystemAvailableFeatures() {
2251        Collection<FeatureInfo> featSet;
2252        synchronized (mPackages) {
2253            featSet = mAvailableFeatures.values();
2254            int size = featSet.size();
2255            if (size > 0) {
2256                FeatureInfo[] features = new FeatureInfo[size+1];
2257                featSet.toArray(features);
2258                FeatureInfo fi = new FeatureInfo();
2259                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2260                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2261                features[size] = fi;
2262                return features;
2263            }
2264        }
2265        return null;
2266    }
2267
2268    @Override
2269    public boolean hasSystemFeature(String name) {
2270        synchronized (mPackages) {
2271            return mAvailableFeatures.containsKey(name);
2272        }
2273    }
2274
2275    private void checkValidCaller(int uid, int userId) {
2276        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2277            return;
2278
2279        throw new SecurityException("Caller uid=" + uid
2280                + " is not privileged to communicate with user=" + userId);
2281    }
2282
2283    @Override
2284    public int checkPermission(String permName, String pkgName) {
2285        synchronized (mPackages) {
2286            PackageParser.Package p = mPackages.get(pkgName);
2287            if (p != null && p.mExtras != null) {
2288                PackageSetting ps = (PackageSetting)p.mExtras;
2289                if (ps.sharedUser != null) {
2290                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2291                        return PackageManager.PERMISSION_GRANTED;
2292                    }
2293                } else if (ps.grantedPermissions.contains(permName)) {
2294                    return PackageManager.PERMISSION_GRANTED;
2295                }
2296            }
2297        }
2298        return PackageManager.PERMISSION_DENIED;
2299    }
2300
2301    @Override
2302    public int checkUidPermission(String permName, int uid) {
2303        synchronized (mPackages) {
2304            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2305            if (obj != null) {
2306                GrantedPermissions gp = (GrantedPermissions)obj;
2307                if (gp.grantedPermissions.contains(permName)) {
2308                    return PackageManager.PERMISSION_GRANTED;
2309                }
2310            } else {
2311                HashSet<String> perms = mSystemPermissions.get(uid);
2312                if (perms != null && perms.contains(permName)) {
2313                    return PackageManager.PERMISSION_GRANTED;
2314                }
2315            }
2316        }
2317        return PackageManager.PERMISSION_DENIED;
2318    }
2319
2320    /**
2321     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2322     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2323     * @param message the message to log on security exception
2324     */
2325    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2326            String message) {
2327        if (userId < 0) {
2328            throw new IllegalArgumentException("Invalid userId " + userId);
2329        }
2330        if (userId == UserHandle.getUserId(callingUid)) return;
2331        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2332            if (requireFullPermission) {
2333                mContext.enforceCallingOrSelfPermission(
2334                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2335            } else {
2336                try {
2337                    mContext.enforceCallingOrSelfPermission(
2338                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2339                } catch (SecurityException se) {
2340                    mContext.enforceCallingOrSelfPermission(
2341                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2342                }
2343            }
2344        }
2345    }
2346
2347    private BasePermission findPermissionTreeLP(String permName) {
2348        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2349            if (permName.startsWith(bp.name) &&
2350                    permName.length() > bp.name.length() &&
2351                    permName.charAt(bp.name.length()) == '.') {
2352                return bp;
2353            }
2354        }
2355        return null;
2356    }
2357
2358    private BasePermission checkPermissionTreeLP(String permName) {
2359        if (permName != null) {
2360            BasePermission bp = findPermissionTreeLP(permName);
2361            if (bp != null) {
2362                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2363                    return bp;
2364                }
2365                throw new SecurityException("Calling uid "
2366                        + Binder.getCallingUid()
2367                        + " is not allowed to add to permission tree "
2368                        + bp.name + " owned by uid " + bp.uid);
2369            }
2370        }
2371        throw new SecurityException("No permission tree found for " + permName);
2372    }
2373
2374    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2375        if (s1 == null) {
2376            return s2 == null;
2377        }
2378        if (s2 == null) {
2379            return false;
2380        }
2381        if (s1.getClass() != s2.getClass()) {
2382            return false;
2383        }
2384        return s1.equals(s2);
2385    }
2386
2387    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2388        if (pi1.icon != pi2.icon) return false;
2389        if (pi1.logo != pi2.logo) return false;
2390        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2391        if (!compareStrings(pi1.name, pi2.name)) return false;
2392        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2393        // We'll take care of setting this one.
2394        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2395        // These are not currently stored in settings.
2396        //if (!compareStrings(pi1.group, pi2.group)) return false;
2397        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2398        //if (pi1.labelRes != pi2.labelRes) return false;
2399        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2400        return true;
2401    }
2402
2403    int permissionInfoFootprint(PermissionInfo info) {
2404        int size = info.name.length();
2405        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2406        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2407        return size;
2408    }
2409
2410    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2411        int size = 0;
2412        for (BasePermission perm : mSettings.mPermissions.values()) {
2413            if (perm.uid == tree.uid) {
2414                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2415            }
2416        }
2417        return size;
2418    }
2419
2420    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2421        // We calculate the max size of permissions defined by this uid and throw
2422        // if that plus the size of 'info' would exceed our stated maximum.
2423        if (tree.uid != Process.SYSTEM_UID) {
2424            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2425            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2426                throw new SecurityException("Permission tree size cap exceeded");
2427            }
2428        }
2429    }
2430
2431    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2432        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2433            throw new SecurityException("Label must be specified in permission");
2434        }
2435        BasePermission tree = checkPermissionTreeLP(info.name);
2436        BasePermission bp = mSettings.mPermissions.get(info.name);
2437        boolean added = bp == null;
2438        boolean changed = true;
2439        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2440        if (added) {
2441            enforcePermissionCapLocked(info, tree);
2442            bp = new BasePermission(info.name, tree.sourcePackage,
2443                    BasePermission.TYPE_DYNAMIC);
2444        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2445            throw new SecurityException(
2446                    "Not allowed to modify non-dynamic permission "
2447                    + info.name);
2448        } else {
2449            if (bp.protectionLevel == fixedLevel
2450                    && bp.perm.owner.equals(tree.perm.owner)
2451                    && bp.uid == tree.uid
2452                    && comparePermissionInfos(bp.perm.info, info)) {
2453                changed = false;
2454            }
2455        }
2456        bp.protectionLevel = fixedLevel;
2457        info = new PermissionInfo(info);
2458        info.protectionLevel = fixedLevel;
2459        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2460        bp.perm.info.packageName = tree.perm.info.packageName;
2461        bp.uid = tree.uid;
2462        if (added) {
2463            mSettings.mPermissions.put(info.name, bp);
2464        }
2465        if (changed) {
2466            if (!async) {
2467                mSettings.writeLPr();
2468            } else {
2469                scheduleWriteSettingsLocked();
2470            }
2471        }
2472        return added;
2473    }
2474
2475    @Override
2476    public boolean addPermission(PermissionInfo info) {
2477        synchronized (mPackages) {
2478            return addPermissionLocked(info, false);
2479        }
2480    }
2481
2482    @Override
2483    public boolean addPermissionAsync(PermissionInfo info) {
2484        synchronized (mPackages) {
2485            return addPermissionLocked(info, true);
2486        }
2487    }
2488
2489    @Override
2490    public void removePermission(String name) {
2491        synchronized (mPackages) {
2492            checkPermissionTreeLP(name);
2493            BasePermission bp = mSettings.mPermissions.get(name);
2494            if (bp != null) {
2495                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2496                    throw new SecurityException(
2497                            "Not allowed to modify non-dynamic permission "
2498                            + name);
2499                }
2500                mSettings.mPermissions.remove(name);
2501                mSettings.writeLPr();
2502            }
2503        }
2504    }
2505
2506    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2507        int index = pkg.requestedPermissions.indexOf(bp.name);
2508        if (index == -1) {
2509            throw new SecurityException("Package " + pkg.packageName
2510                    + " has not requested permission " + bp.name);
2511        }
2512        boolean isNormal =
2513                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2514                        == PermissionInfo.PROTECTION_NORMAL);
2515        boolean isDangerous =
2516                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2517                        == PermissionInfo.PROTECTION_DANGEROUS);
2518        boolean isDevelopment =
2519                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2520
2521        if (!isNormal && !isDangerous && !isDevelopment) {
2522            throw new SecurityException("Permission " + bp.name
2523                    + " is not a changeable permission type");
2524        }
2525
2526        if (isNormal || isDangerous) {
2527            if (pkg.requestedPermissionsRequired.get(index)) {
2528                throw new SecurityException("Can't change " + bp.name
2529                        + ". It is required by the application");
2530            }
2531        }
2532    }
2533
2534    @Override
2535    public void grantPermission(String packageName, String permissionName) {
2536        mContext.enforceCallingOrSelfPermission(
2537                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2538        synchronized (mPackages) {
2539            final PackageParser.Package pkg = mPackages.get(packageName);
2540            if (pkg == null) {
2541                throw new IllegalArgumentException("Unknown package: " + packageName);
2542            }
2543            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2544            if (bp == null) {
2545                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2546            }
2547
2548            checkGrantRevokePermissions(pkg, bp);
2549
2550            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2551            if (ps == null) {
2552                return;
2553            }
2554            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2555            if (gp.grantedPermissions.add(permissionName)) {
2556                if (ps.haveGids) {
2557                    gp.gids = appendInts(gp.gids, bp.gids);
2558                }
2559                mSettings.writeLPr();
2560            }
2561        }
2562    }
2563
2564    @Override
2565    public void revokePermission(String packageName, String permissionName) {
2566        int changedAppId = -1;
2567
2568        synchronized (mPackages) {
2569            final PackageParser.Package pkg = mPackages.get(packageName);
2570            if (pkg == null) {
2571                throw new IllegalArgumentException("Unknown package: " + packageName);
2572            }
2573            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2574                mContext.enforceCallingOrSelfPermission(
2575                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2576            }
2577            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2578            if (bp == null) {
2579                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2580            }
2581
2582            checkGrantRevokePermissions(pkg, bp);
2583
2584            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2585            if (ps == null) {
2586                return;
2587            }
2588            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2589            if (gp.grantedPermissions.remove(permissionName)) {
2590                gp.grantedPermissions.remove(permissionName);
2591                if (ps.haveGids) {
2592                    gp.gids = removeInts(gp.gids, bp.gids);
2593                }
2594                mSettings.writeLPr();
2595                changedAppId = ps.appId;
2596            }
2597        }
2598
2599        if (changedAppId >= 0) {
2600            // We changed the perm on someone, kill its processes.
2601            IActivityManager am = ActivityManagerNative.getDefault();
2602            if (am != null) {
2603                final int callingUserId = UserHandle.getCallingUserId();
2604                final long ident = Binder.clearCallingIdentity();
2605                try {
2606                    //XXX we should only revoke for the calling user's app permissions,
2607                    // but for now we impact all users.
2608                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2609                    //        "revoke " + permissionName);
2610                    int[] users = sUserManager.getUserIds();
2611                    for (int user : users) {
2612                        am.killUid(UserHandle.getUid(user, changedAppId),
2613                                "revoke " + permissionName);
2614                    }
2615                } catch (RemoteException e) {
2616                } finally {
2617                    Binder.restoreCallingIdentity(ident);
2618                }
2619            }
2620        }
2621    }
2622
2623    @Override
2624    public boolean isProtectedBroadcast(String actionName) {
2625        synchronized (mPackages) {
2626            return mProtectedBroadcasts.contains(actionName);
2627        }
2628    }
2629
2630    @Override
2631    public int checkSignatures(String pkg1, String pkg2) {
2632        synchronized (mPackages) {
2633            final PackageParser.Package p1 = mPackages.get(pkg1);
2634            final PackageParser.Package p2 = mPackages.get(pkg2);
2635            if (p1 == null || p1.mExtras == null
2636                    || p2 == null || p2.mExtras == null) {
2637                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2638            }
2639            return compareSignatures(p1.mSignatures, p2.mSignatures);
2640        }
2641    }
2642
2643    @Override
2644    public int checkUidSignatures(int uid1, int uid2) {
2645        // Map to base uids.
2646        uid1 = UserHandle.getAppId(uid1);
2647        uid2 = UserHandle.getAppId(uid2);
2648        // reader
2649        synchronized (mPackages) {
2650            Signature[] s1;
2651            Signature[] s2;
2652            Object obj = mSettings.getUserIdLPr(uid1);
2653            if (obj != null) {
2654                if (obj instanceof SharedUserSetting) {
2655                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2656                } else if (obj instanceof PackageSetting) {
2657                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2658                } else {
2659                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2660                }
2661            } else {
2662                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2663            }
2664            obj = mSettings.getUserIdLPr(uid2);
2665            if (obj != null) {
2666                if (obj instanceof SharedUserSetting) {
2667                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2668                } else if (obj instanceof PackageSetting) {
2669                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2670                } else {
2671                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2672                }
2673            } else {
2674                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2675            }
2676            return compareSignatures(s1, s2);
2677        }
2678    }
2679
2680    /**
2681     * Compares two sets of signatures. Returns:
2682     * <br />
2683     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2684     * <br />
2685     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2686     * <br />
2687     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2688     * <br />
2689     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2690     * <br />
2691     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2692     */
2693    static int compareSignatures(Signature[] s1, Signature[] s2) {
2694        if (s1 == null) {
2695            return s2 == null
2696                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2697                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2698        }
2699
2700        if (s2 == null) {
2701            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2702        }
2703
2704        if (s1.length != s2.length) {
2705            return PackageManager.SIGNATURE_NO_MATCH;
2706        }
2707
2708        // Since both signature sets are of size 1, we can compare without HashSets.
2709        if (s1.length == 1) {
2710            return s1[0].equals(s2[0]) ?
2711                    PackageManager.SIGNATURE_MATCH :
2712                    PackageManager.SIGNATURE_NO_MATCH;
2713        }
2714
2715        HashSet<Signature> set1 = new HashSet<Signature>();
2716        for (Signature sig : s1) {
2717            set1.add(sig);
2718        }
2719        HashSet<Signature> set2 = new HashSet<Signature>();
2720        for (Signature sig : s2) {
2721            set2.add(sig);
2722        }
2723        // Make sure s2 contains all signatures in s1.
2724        if (set1.equals(set2)) {
2725            return PackageManager.SIGNATURE_MATCH;
2726        }
2727        return PackageManager.SIGNATURE_NO_MATCH;
2728    }
2729
2730    /**
2731     * If the database version for this type of package (internal storage or
2732     * external storage) is less than the version where package signatures
2733     * were updated, return true.
2734     */
2735    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2736        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2737                DatabaseVersion.SIGNATURE_END_ENTITY))
2738                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2739                        DatabaseVersion.SIGNATURE_END_ENTITY));
2740    }
2741
2742    /**
2743     * Used for backward compatibility to make sure any packages with
2744     * certificate chains get upgraded to the new style. {@code existingSigs}
2745     * will be in the old format (since they were stored on disk from before the
2746     * system upgrade) and {@code scannedSigs} will be in the newer format.
2747     */
2748    private int compareSignaturesCompat(PackageSignatures existingSigs,
2749            PackageParser.Package scannedPkg) {
2750        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2751            return PackageManager.SIGNATURE_NO_MATCH;
2752        }
2753
2754        HashSet<Signature> existingSet = new HashSet<Signature>();
2755        for (Signature sig : existingSigs.mSignatures) {
2756            existingSet.add(sig);
2757        }
2758        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2759        for (Signature sig : scannedPkg.mSignatures) {
2760            try {
2761                Signature[] chainSignatures = sig.getChainSignatures();
2762                for (Signature chainSig : chainSignatures) {
2763                    scannedCompatSet.add(chainSig);
2764                }
2765            } catch (CertificateEncodingException e) {
2766                scannedCompatSet.add(sig);
2767            }
2768        }
2769        /*
2770         * Make sure the expanded scanned set contains all signatures in the
2771         * existing one.
2772         */
2773        if (scannedCompatSet.equals(existingSet)) {
2774            // Migrate the old signatures to the new scheme.
2775            existingSigs.assignSignatures(scannedPkg.mSignatures);
2776            // The new KeySets will be re-added later in the scanning process.
2777            synchronized (mPackages) {
2778                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2779            }
2780            return PackageManager.SIGNATURE_MATCH;
2781        }
2782        return PackageManager.SIGNATURE_NO_MATCH;
2783    }
2784
2785    @Override
2786    public String[] getPackagesForUid(int uid) {
2787        uid = UserHandle.getAppId(uid);
2788        // reader
2789        synchronized (mPackages) {
2790            Object obj = mSettings.getUserIdLPr(uid);
2791            if (obj instanceof SharedUserSetting) {
2792                final SharedUserSetting sus = (SharedUserSetting) obj;
2793                final int N = sus.packages.size();
2794                final String[] res = new String[N];
2795                final Iterator<PackageSetting> it = sus.packages.iterator();
2796                int i = 0;
2797                while (it.hasNext()) {
2798                    res[i++] = it.next().name;
2799                }
2800                return res;
2801            } else if (obj instanceof PackageSetting) {
2802                final PackageSetting ps = (PackageSetting) obj;
2803                return new String[] { ps.name };
2804            }
2805        }
2806        return null;
2807    }
2808
2809    @Override
2810    public String getNameForUid(int uid) {
2811        // reader
2812        synchronized (mPackages) {
2813            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2814            if (obj instanceof SharedUserSetting) {
2815                final SharedUserSetting sus = (SharedUserSetting) obj;
2816                return sus.name + ":" + sus.userId;
2817            } else if (obj instanceof PackageSetting) {
2818                final PackageSetting ps = (PackageSetting) obj;
2819                return ps.name;
2820            }
2821        }
2822        return null;
2823    }
2824
2825    @Override
2826    public int getUidForSharedUser(String sharedUserName) {
2827        if(sharedUserName == null) {
2828            return -1;
2829        }
2830        // reader
2831        synchronized (mPackages) {
2832            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2833            if (suid == null) {
2834                return -1;
2835            }
2836            return suid.userId;
2837        }
2838    }
2839
2840    @Override
2841    public int getFlagsForUid(int uid) {
2842        synchronized (mPackages) {
2843            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2844            if (obj instanceof SharedUserSetting) {
2845                final SharedUserSetting sus = (SharedUserSetting) obj;
2846                return sus.pkgFlags;
2847            } else if (obj instanceof PackageSetting) {
2848                final PackageSetting ps = (PackageSetting) obj;
2849                return ps.pkgFlags;
2850            }
2851        }
2852        return 0;
2853    }
2854
2855    @Override
2856    public String[] getAppOpPermissionPackages(String permissionName) {
2857        synchronized (mPackages) {
2858            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2859            if (pkgs == null) {
2860                return null;
2861            }
2862            return pkgs.toArray(new String[pkgs.size()]);
2863        }
2864    }
2865
2866    @Override
2867    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2868            int flags, int userId) {
2869        if (!sUserManager.exists(userId)) return null;
2870        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2871        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2872        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2873    }
2874
2875    @Override
2876    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2877            IntentFilter filter, int match, ComponentName activity) {
2878        final int userId = UserHandle.getCallingUserId();
2879        if (DEBUG_PREFERRED) {
2880            Log.v(TAG, "setLastChosenActivity intent=" + intent
2881                + " resolvedType=" + resolvedType
2882                + " flags=" + flags
2883                + " filter=" + filter
2884                + " match=" + match
2885                + " activity=" + activity);
2886            filter.dump(new PrintStreamPrinter(System.out), "    ");
2887        }
2888        intent.setComponent(null);
2889        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2890        // Find any earlier preferred or last chosen entries and nuke them
2891        findPreferredActivity(intent, resolvedType,
2892                flags, query, 0, false, true, false, userId);
2893        // Add the new activity as the last chosen for this filter
2894        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2895                "Setting last chosen");
2896    }
2897
2898    @Override
2899    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2900        final int userId = UserHandle.getCallingUserId();
2901        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2902        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2903        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2904                false, false, false, userId);
2905    }
2906
2907    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2908            int flags, List<ResolveInfo> query, int userId) {
2909        if (query != null) {
2910            final int N = query.size();
2911            if (N == 1) {
2912                return query.get(0);
2913            } else if (N > 1) {
2914                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2915                // If there is more than one activity with the same priority,
2916                // then let the user decide between them.
2917                ResolveInfo r0 = query.get(0);
2918                ResolveInfo r1 = query.get(1);
2919                if (DEBUG_INTENT_MATCHING || debug) {
2920                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2921                            + r1.activityInfo.name + "=" + r1.priority);
2922                }
2923                // If the first activity has a higher priority, or a different
2924                // default, then it is always desireable to pick it.
2925                if (r0.priority != r1.priority
2926                        || r0.preferredOrder != r1.preferredOrder
2927                        || r0.isDefault != r1.isDefault) {
2928                    return query.get(0);
2929                }
2930                // If we have saved a preference for a preferred activity for
2931                // this Intent, use that.
2932                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2933                        flags, query, r0.priority, true, false, debug, userId);
2934                if (ri != null) {
2935                    return ri;
2936                }
2937                if (userId != 0) {
2938                    ri = new ResolveInfo(mResolveInfo);
2939                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2940                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2941                            ri.activityInfo.applicationInfo);
2942                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2943                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2944                    return ri;
2945                }
2946                return mResolveInfo;
2947            }
2948        }
2949        return null;
2950    }
2951
2952    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2953            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2954        final int N = query.size();
2955        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2956                .get(userId);
2957        // Get the list of persistent preferred activities that handle the intent
2958        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2959        List<PersistentPreferredActivity> pprefs = ppir != null
2960                ? ppir.queryIntent(intent, resolvedType,
2961                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2962                : null;
2963        if (pprefs != null && pprefs.size() > 0) {
2964            final int M = pprefs.size();
2965            for (int i=0; i<M; i++) {
2966                final PersistentPreferredActivity ppa = pprefs.get(i);
2967                if (DEBUG_PREFERRED || debug) {
2968                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2969                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2970                            + "\n  component=" + ppa.mComponent);
2971                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2972                }
2973                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2974                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2975                if (DEBUG_PREFERRED || debug) {
2976                    Slog.v(TAG, "Found persistent preferred activity:");
2977                    if (ai != null) {
2978                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2979                    } else {
2980                        Slog.v(TAG, "  null");
2981                    }
2982                }
2983                if (ai == null) {
2984                    // This previously registered persistent preferred activity
2985                    // component is no longer known. Ignore it and do NOT remove it.
2986                    continue;
2987                }
2988                for (int j=0; j<N; j++) {
2989                    final ResolveInfo ri = query.get(j);
2990                    if (!ri.activityInfo.applicationInfo.packageName
2991                            .equals(ai.applicationInfo.packageName)) {
2992                        continue;
2993                    }
2994                    if (!ri.activityInfo.name.equals(ai.name)) {
2995                        continue;
2996                    }
2997                    //  Found a persistent preference that can handle the intent.
2998                    if (DEBUG_PREFERRED || debug) {
2999                        Slog.v(TAG, "Returning persistent preferred activity: " +
3000                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3001                    }
3002                    return ri;
3003                }
3004            }
3005        }
3006        return null;
3007    }
3008
3009    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3010            List<ResolveInfo> query, int priority, boolean always,
3011            boolean removeMatches, boolean debug, int userId) {
3012        if (!sUserManager.exists(userId)) return null;
3013        // writer
3014        synchronized (mPackages) {
3015            if (intent.getSelector() != null) {
3016                intent = intent.getSelector();
3017            }
3018            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3019
3020            // Try to find a matching persistent preferred activity.
3021            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3022                    debug, userId);
3023
3024            // If a persistent preferred activity matched, use it.
3025            if (pri != null) {
3026                return pri;
3027            }
3028
3029            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3030            // Get the list of preferred activities that handle the intent
3031            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3032            List<PreferredActivity> prefs = pir != null
3033                    ? pir.queryIntent(intent, resolvedType,
3034                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3035                    : null;
3036            if (prefs != null && prefs.size() > 0) {
3037                // First figure out how good the original match set is.
3038                // We will only allow preferred activities that came
3039                // from the same match quality.
3040                int match = 0;
3041
3042                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3043
3044                final int N = query.size();
3045                for (int j=0; j<N; j++) {
3046                    final ResolveInfo ri = query.get(j);
3047                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3048                            + ": 0x" + Integer.toHexString(match));
3049                    if (ri.match > match) {
3050                        match = ri.match;
3051                    }
3052                }
3053
3054                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3055                        + Integer.toHexString(match));
3056
3057                match &= IntentFilter.MATCH_CATEGORY_MASK;
3058                final int M = prefs.size();
3059                for (int i=0; i<M; i++) {
3060                    final PreferredActivity pa = prefs.get(i);
3061                    if (DEBUG_PREFERRED || debug) {
3062                        Slog.v(TAG, "Checking PreferredActivity ds="
3063                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3064                                + "\n  component=" + pa.mPref.mComponent);
3065                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3066                    }
3067                    if (pa.mPref.mMatch != match) {
3068                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3069                                + Integer.toHexString(pa.mPref.mMatch));
3070                        continue;
3071                    }
3072                    // If it's not an "always" type preferred activity and that's what we're
3073                    // looking for, skip it.
3074                    if (always && !pa.mPref.mAlways) {
3075                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3076                        continue;
3077                    }
3078                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3079                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3080                    if (DEBUG_PREFERRED || debug) {
3081                        Slog.v(TAG, "Found preferred activity:");
3082                        if (ai != null) {
3083                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3084                        } else {
3085                            Slog.v(TAG, "  null");
3086                        }
3087                    }
3088                    if (ai == null) {
3089                        // This previously registered preferred activity
3090                        // component is no longer known.  Most likely an update
3091                        // to the app was installed and in the new version this
3092                        // component no longer exists.  Clean it up by removing
3093                        // it from the preferred activities list, and skip it.
3094                        Slog.w(TAG, "Removing dangling preferred activity: "
3095                                + pa.mPref.mComponent);
3096                        pir.removeFilter(pa);
3097                        continue;
3098                    }
3099                    for (int j=0; j<N; j++) {
3100                        final ResolveInfo ri = query.get(j);
3101                        if (!ri.activityInfo.applicationInfo.packageName
3102                                .equals(ai.applicationInfo.packageName)) {
3103                            continue;
3104                        }
3105                        if (!ri.activityInfo.name.equals(ai.name)) {
3106                            continue;
3107                        }
3108
3109                        if (removeMatches) {
3110                            pir.removeFilter(pa);
3111                            if (DEBUG_PREFERRED) {
3112                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3113                            }
3114                            break;
3115                        }
3116
3117                        // Okay we found a previously set preferred or last chosen app.
3118                        // If the result set is different from when this
3119                        // was created, we need to clear it and re-ask the
3120                        // user their preference, if we're looking for an "always" type entry.
3121                        if (always && !pa.mPref.sameSet(query, priority)) {
3122                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3123                                    + intent + " type " + resolvedType);
3124                            if (DEBUG_PREFERRED) {
3125                                Slog.v(TAG, "Removing preferred activity since set changed "
3126                                        + pa.mPref.mComponent);
3127                            }
3128                            pir.removeFilter(pa);
3129                            // Re-add the filter as a "last chosen" entry (!always)
3130                            PreferredActivity lastChosen = new PreferredActivity(
3131                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3132                            pir.addFilter(lastChosen);
3133                            mSettings.writePackageRestrictionsLPr(userId);
3134                            return null;
3135                        }
3136
3137                        // Yay! Either the set matched or we're looking for the last chosen
3138                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3139                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3140                        mSettings.writePackageRestrictionsLPr(userId);
3141                        return ri;
3142                    }
3143                }
3144            }
3145            mSettings.writePackageRestrictionsLPr(userId);
3146        }
3147        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3148        return null;
3149    }
3150
3151    /*
3152     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3153     */
3154    @Override
3155    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3156            int targetUserId) {
3157        mContext.enforceCallingOrSelfPermission(
3158                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3159        List<CrossProfileIntentFilter> matches =
3160                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3161        if (matches != null) {
3162            int size = matches.size();
3163            for (int i = 0; i < size; i++) {
3164                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3165            }
3166        }
3167        ArrayList<String> packageNames = null;
3168        SparseArray<ArrayList<String>> fromSource =
3169                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3170        if (fromSource != null) {
3171            packageNames = fromSource.get(targetUserId);
3172            if (packageNames != null) {
3173                // We need the package name, so we try to resolve with the loosest flags possible
3174                List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType,
3175                        PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3176                int count = resolveInfos.size();
3177                for (int i = 0; i < count; i++) {
3178                    ResolveInfo resolveInfo = resolveInfos.get(i);
3179                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3180                        return true;
3181                    }
3182                }
3183            }
3184        }
3185        return false;
3186    }
3187
3188    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3189            String resolvedType, int userId) {
3190        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3191        if (resolver != null) {
3192            return resolver.queryIntent(intent, resolvedType, false, userId);
3193        }
3194        return null;
3195    }
3196
3197    @Override
3198    public List<ResolveInfo> queryIntentActivities(Intent intent,
3199            String resolvedType, int flags, int userId) {
3200        if (!sUserManager.exists(userId)) return Collections.emptyList();
3201        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3202        ComponentName comp = intent.getComponent();
3203        if (comp == null) {
3204            if (intent.getSelector() != null) {
3205                intent = intent.getSelector();
3206                comp = intent.getComponent();
3207            }
3208        }
3209
3210        if (comp != null) {
3211            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3212            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3213            if (ai != null) {
3214                final ResolveInfo ri = new ResolveInfo();
3215                ri.activityInfo = ai;
3216                list.add(ri);
3217            }
3218            return list;
3219        }
3220
3221        // reader
3222        synchronized (mPackages) {
3223            final String pkgName = intent.getPackage();
3224            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3225            if (pkgName == null) {
3226                ResolveInfo resolveInfo = null;
3227                if (queryCrossProfile) {
3228                    // Check if the intent needs to be forwarded to another user for this package
3229                    ArrayList<ResolveInfo> crossProfileResult =
3230                            queryIntentActivitiesCrossProfilePackage(
3231                                    intent, resolvedType, flags, userId);
3232                    if (!crossProfileResult.isEmpty()) {
3233                        // Skip the current profile
3234                        return crossProfileResult;
3235                    }
3236                    List<CrossProfileIntentFilter> matchingFilters =
3237                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3238                    // Check for results that need to skip the current profile.
3239                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3240                            resolvedType, flags, userId);
3241                    if (resolveInfo != null) {
3242                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3243                        result.add(resolveInfo);
3244                        return result;
3245                    }
3246                    // Check for cross profile results.
3247                    resolveInfo = queryCrossProfileIntents(
3248                            matchingFilters, intent, resolvedType, flags, userId);
3249                }
3250                // Check for results in the current profile.
3251                List<ResolveInfo> result = mActivities.queryIntent(
3252                        intent, resolvedType, flags, userId);
3253                if (resolveInfo != null) {
3254                    result.add(resolveInfo);
3255                    Collections.sort(result, mResolvePrioritySorter);
3256                }
3257                return result;
3258            }
3259            final PackageParser.Package pkg = mPackages.get(pkgName);
3260            if (pkg != null) {
3261                if (queryCrossProfile) {
3262                    ArrayList<ResolveInfo> crossProfileResult =
3263                            queryIntentActivitiesCrossProfilePackage(
3264                                    intent, resolvedType, flags, userId, pkg, pkgName);
3265                    if (!crossProfileResult.isEmpty()) {
3266                        // Skip the current profile
3267                        return crossProfileResult;
3268                    }
3269                }
3270                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3271                        pkg.activities, userId);
3272            }
3273            return new ArrayList<ResolveInfo>();
3274        }
3275    }
3276
3277    private ResolveInfo querySkipCurrentProfileIntents(
3278            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3279            int flags, int sourceUserId) {
3280        if (matchingFilters != null) {
3281            int size = matchingFilters.size();
3282            for (int i = 0; i < size; i ++) {
3283                CrossProfileIntentFilter filter = matchingFilters.get(i);
3284                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3285                    // Checking if there are activities in the target user that can handle the
3286                    // intent.
3287                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3288                            flags, sourceUserId);
3289                    if (resolveInfo != null) {
3290                        return resolveInfo;
3291                    }
3292                }
3293            }
3294        }
3295        return null;
3296    }
3297
3298    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3299            Intent intent, String resolvedType, int flags, int userId) {
3300        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3301        SparseArray<ArrayList<String>> sourceForwardingInfo =
3302                mSettings.mCrossProfilePackageInfo.get(userId);
3303        if (sourceForwardingInfo != null) {
3304            int NI = sourceForwardingInfo.size();
3305            for (int i = 0; i < NI; i++) {
3306                int targetUserId = sourceForwardingInfo.keyAt(i);
3307                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3308                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3309                        intent, resolvedType, flags, targetUserId);
3310                int NJ = resolveInfos.size();
3311                for (int j = 0; j < NJ; j++) {
3312                    ResolveInfo resolveInfo = resolveInfos.get(j);
3313                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3314                        matchingResolveInfos.add(createForwardingResolveInfo(
3315                                resolveInfo.filter, userId, targetUserId));
3316                    }
3317                }
3318            }
3319        }
3320        return matchingResolveInfos;
3321    }
3322
3323    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3324            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3325            String packageName) {
3326        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3327        SparseArray<ArrayList<String>> sourceForwardingInfo =
3328                mSettings.mCrossProfilePackageInfo.get(userId);
3329        if (sourceForwardingInfo != null) {
3330            int NI = sourceForwardingInfo.size();
3331            for (int i = 0; i < NI; i++) {
3332                int targetUserId = sourceForwardingInfo.keyAt(i);
3333                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3334                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3335                            intent, resolvedType, flags, pkg.activities, targetUserId);
3336                    int NJ = resolveInfos.size();
3337                    for (int j = 0; j < NJ; j++) {
3338                        ResolveInfo resolveInfo = resolveInfos.get(j);
3339                        matchingResolveInfos.add(createForwardingResolveInfo(
3340                                resolveInfo.filter, userId, targetUserId));
3341                    }
3342                }
3343            }
3344        }
3345        return matchingResolveInfos;
3346    }
3347
3348    // Return matching ResolveInfo if any for skip current profile intent filters.
3349    private ResolveInfo queryCrossProfileIntents(
3350            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3351            int flags, int sourceUserId) {
3352        if (matchingFilters != null) {
3353            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3354            // match the same intent. For performance reasons, it is better not to
3355            // run queryIntent twice for the same userId
3356            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3357            int size = matchingFilters.size();
3358            for (int i = 0; i < size; i++) {
3359                CrossProfileIntentFilter filter = matchingFilters.get(i);
3360                int targetUserId = filter.getTargetUserId();
3361                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3362                        && !alreadyTriedUserIds.get(targetUserId)) {
3363                    // Checking if there are activities in the target user that can handle the
3364                    // intent.
3365                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3366                            flags, sourceUserId);
3367                    if (resolveInfo != null) return resolveInfo;
3368                    alreadyTriedUserIds.put(targetUserId, true);
3369                }
3370            }
3371        }
3372        return null;
3373    }
3374
3375    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3376            String resolvedType, int flags, int sourceUserId) {
3377        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3378                resolvedType, flags, filter.getTargetUserId());
3379        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3380            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3381        }
3382        return null;
3383    }
3384
3385    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3386            int sourceUserId, int targetUserId) {
3387        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3388        String className;
3389        if (targetUserId == UserHandle.USER_OWNER) {
3390            className = FORWARD_INTENT_TO_USER_OWNER;
3391        } else {
3392            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3393        }
3394        ComponentName forwardingActivityComponentName = new ComponentName(
3395                mAndroidApplication.packageName, className);
3396        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3397                sourceUserId);
3398        if (targetUserId == UserHandle.USER_OWNER) {
3399            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3400            forwardingResolveInfo.noResourceId = true;
3401        }
3402        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3403        forwardingResolveInfo.priority = 0;
3404        forwardingResolveInfo.preferredOrder = 0;
3405        forwardingResolveInfo.match = 0;
3406        forwardingResolveInfo.isDefault = true;
3407        forwardingResolveInfo.filter = filter;
3408        forwardingResolveInfo.targetUserId = targetUserId;
3409        return forwardingResolveInfo;
3410    }
3411
3412    @Override
3413    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3414            Intent[] specifics, String[] specificTypes, Intent intent,
3415            String resolvedType, int flags, int userId) {
3416        if (!sUserManager.exists(userId)) return Collections.emptyList();
3417        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3418                "query intent activity options");
3419        final String resultsAction = intent.getAction();
3420
3421        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3422                | PackageManager.GET_RESOLVED_FILTER, userId);
3423
3424        if (DEBUG_INTENT_MATCHING) {
3425            Log.v(TAG, "Query " + intent + ": " + results);
3426        }
3427
3428        int specificsPos = 0;
3429        int N;
3430
3431        // todo: note that the algorithm used here is O(N^2).  This
3432        // isn't a problem in our current environment, but if we start running
3433        // into situations where we have more than 5 or 10 matches then this
3434        // should probably be changed to something smarter...
3435
3436        // First we go through and resolve each of the specific items
3437        // that were supplied, taking care of removing any corresponding
3438        // duplicate items in the generic resolve list.
3439        if (specifics != null) {
3440            for (int i=0; i<specifics.length; i++) {
3441                final Intent sintent = specifics[i];
3442                if (sintent == null) {
3443                    continue;
3444                }
3445
3446                if (DEBUG_INTENT_MATCHING) {
3447                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3448                }
3449
3450                String action = sintent.getAction();
3451                if (resultsAction != null && resultsAction.equals(action)) {
3452                    // If this action was explicitly requested, then don't
3453                    // remove things that have it.
3454                    action = null;
3455                }
3456
3457                ResolveInfo ri = null;
3458                ActivityInfo ai = null;
3459
3460                ComponentName comp = sintent.getComponent();
3461                if (comp == null) {
3462                    ri = resolveIntent(
3463                        sintent,
3464                        specificTypes != null ? specificTypes[i] : null,
3465                            flags, userId);
3466                    if (ri == null) {
3467                        continue;
3468                    }
3469                    if (ri == mResolveInfo) {
3470                        // ACK!  Must do something better with this.
3471                    }
3472                    ai = ri.activityInfo;
3473                    comp = new ComponentName(ai.applicationInfo.packageName,
3474                            ai.name);
3475                } else {
3476                    ai = getActivityInfo(comp, flags, userId);
3477                    if (ai == null) {
3478                        continue;
3479                    }
3480                }
3481
3482                // Look for any generic query activities that are duplicates
3483                // of this specific one, and remove them from the results.
3484                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3485                N = results.size();
3486                int j;
3487                for (j=specificsPos; j<N; j++) {
3488                    ResolveInfo sri = results.get(j);
3489                    if ((sri.activityInfo.name.equals(comp.getClassName())
3490                            && sri.activityInfo.applicationInfo.packageName.equals(
3491                                    comp.getPackageName()))
3492                        || (action != null && sri.filter.matchAction(action))) {
3493                        results.remove(j);
3494                        if (DEBUG_INTENT_MATCHING) Log.v(
3495                            TAG, "Removing duplicate item from " + j
3496                            + " due to specific " + specificsPos);
3497                        if (ri == null) {
3498                            ri = sri;
3499                        }
3500                        j--;
3501                        N--;
3502                    }
3503                }
3504
3505                // Add this specific item to its proper place.
3506                if (ri == null) {
3507                    ri = new ResolveInfo();
3508                    ri.activityInfo = ai;
3509                }
3510                results.add(specificsPos, ri);
3511                ri.specificIndex = i;
3512                specificsPos++;
3513            }
3514        }
3515
3516        // Now we go through the remaining generic results and remove any
3517        // duplicate actions that are found here.
3518        N = results.size();
3519        for (int i=specificsPos; i<N-1; i++) {
3520            final ResolveInfo rii = results.get(i);
3521            if (rii.filter == null) {
3522                continue;
3523            }
3524
3525            // Iterate over all of the actions of this result's intent
3526            // filter...  typically this should be just one.
3527            final Iterator<String> it = rii.filter.actionsIterator();
3528            if (it == null) {
3529                continue;
3530            }
3531            while (it.hasNext()) {
3532                final String action = it.next();
3533                if (resultsAction != null && resultsAction.equals(action)) {
3534                    // If this action was explicitly requested, then don't
3535                    // remove things that have it.
3536                    continue;
3537                }
3538                for (int j=i+1; j<N; j++) {
3539                    final ResolveInfo rij = results.get(j);
3540                    if (rij.filter != null && rij.filter.hasAction(action)) {
3541                        results.remove(j);
3542                        if (DEBUG_INTENT_MATCHING) Log.v(
3543                            TAG, "Removing duplicate item from " + j
3544                            + " due to action " + action + " at " + i);
3545                        j--;
3546                        N--;
3547                    }
3548                }
3549            }
3550
3551            // If the caller didn't request filter information, drop it now
3552            // so we don't have to marshall/unmarshall it.
3553            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3554                rii.filter = null;
3555            }
3556        }
3557
3558        // Filter out the caller activity if so requested.
3559        if (caller != null) {
3560            N = results.size();
3561            for (int i=0; i<N; i++) {
3562                ActivityInfo ainfo = results.get(i).activityInfo;
3563                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3564                        && caller.getClassName().equals(ainfo.name)) {
3565                    results.remove(i);
3566                    break;
3567                }
3568            }
3569        }
3570
3571        // If the caller didn't request filter information,
3572        // drop them now so we don't have to
3573        // marshall/unmarshall it.
3574        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3575            N = results.size();
3576            for (int i=0; i<N; i++) {
3577                results.get(i).filter = null;
3578            }
3579        }
3580
3581        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3582        return results;
3583    }
3584
3585    @Override
3586    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3587            int userId) {
3588        if (!sUserManager.exists(userId)) return Collections.emptyList();
3589        ComponentName comp = intent.getComponent();
3590        if (comp == null) {
3591            if (intent.getSelector() != null) {
3592                intent = intent.getSelector();
3593                comp = intent.getComponent();
3594            }
3595        }
3596        if (comp != null) {
3597            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3598            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3599            if (ai != null) {
3600                ResolveInfo ri = new ResolveInfo();
3601                ri.activityInfo = ai;
3602                list.add(ri);
3603            }
3604            return list;
3605        }
3606
3607        // reader
3608        synchronized (mPackages) {
3609            String pkgName = intent.getPackage();
3610            if (pkgName == null) {
3611                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3612            }
3613            final PackageParser.Package pkg = mPackages.get(pkgName);
3614            if (pkg != null) {
3615                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3616                        userId);
3617            }
3618            return null;
3619        }
3620    }
3621
3622    @Override
3623    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3624        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3625        if (!sUserManager.exists(userId)) return null;
3626        if (query != null) {
3627            if (query.size() >= 1) {
3628                // If there is more than one service with the same priority,
3629                // just arbitrarily pick the first one.
3630                return query.get(0);
3631            }
3632        }
3633        return null;
3634    }
3635
3636    @Override
3637    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3638            int userId) {
3639        if (!sUserManager.exists(userId)) return Collections.emptyList();
3640        ComponentName comp = intent.getComponent();
3641        if (comp == null) {
3642            if (intent.getSelector() != null) {
3643                intent = intent.getSelector();
3644                comp = intent.getComponent();
3645            }
3646        }
3647        if (comp != null) {
3648            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3649            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3650            if (si != null) {
3651                final ResolveInfo ri = new ResolveInfo();
3652                ri.serviceInfo = si;
3653                list.add(ri);
3654            }
3655            return list;
3656        }
3657
3658        // reader
3659        synchronized (mPackages) {
3660            String pkgName = intent.getPackage();
3661            if (pkgName == null) {
3662                return mServices.queryIntent(intent, resolvedType, flags, userId);
3663            }
3664            final PackageParser.Package pkg = mPackages.get(pkgName);
3665            if (pkg != null) {
3666                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3667                        userId);
3668            }
3669            return null;
3670        }
3671    }
3672
3673    @Override
3674    public List<ResolveInfo> queryIntentContentProviders(
3675            Intent intent, String resolvedType, int flags, int userId) {
3676        if (!sUserManager.exists(userId)) return Collections.emptyList();
3677        ComponentName comp = intent.getComponent();
3678        if (comp == null) {
3679            if (intent.getSelector() != null) {
3680                intent = intent.getSelector();
3681                comp = intent.getComponent();
3682            }
3683        }
3684        if (comp != null) {
3685            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3686            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3687            if (pi != null) {
3688                final ResolveInfo ri = new ResolveInfo();
3689                ri.providerInfo = pi;
3690                list.add(ri);
3691            }
3692            return list;
3693        }
3694
3695        // reader
3696        synchronized (mPackages) {
3697            String pkgName = intent.getPackage();
3698            if (pkgName == null) {
3699                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3700            }
3701            final PackageParser.Package pkg = mPackages.get(pkgName);
3702            if (pkg != null) {
3703                return mProviders.queryIntentForPackage(
3704                        intent, resolvedType, flags, pkg.providers, userId);
3705            }
3706            return null;
3707        }
3708    }
3709
3710    @Override
3711    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3712        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3713
3714        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3715
3716        // writer
3717        synchronized (mPackages) {
3718            ArrayList<PackageInfo> list;
3719            if (listUninstalled) {
3720                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3721                for (PackageSetting ps : mSettings.mPackages.values()) {
3722                    PackageInfo pi;
3723                    if (ps.pkg != null) {
3724                        pi = generatePackageInfo(ps.pkg, flags, userId);
3725                    } else {
3726                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3727                    }
3728                    if (pi != null) {
3729                        list.add(pi);
3730                    }
3731                }
3732            } else {
3733                list = new ArrayList<PackageInfo>(mPackages.size());
3734                for (PackageParser.Package p : mPackages.values()) {
3735                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3736                    if (pi != null) {
3737                        list.add(pi);
3738                    }
3739                }
3740            }
3741
3742            return new ParceledListSlice<PackageInfo>(list);
3743        }
3744    }
3745
3746    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3747            String[] permissions, boolean[] tmp, int flags, int userId) {
3748        int numMatch = 0;
3749        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3750        for (int i=0; i<permissions.length; i++) {
3751            if (gp.grantedPermissions.contains(permissions[i])) {
3752                tmp[i] = true;
3753                numMatch++;
3754            } else {
3755                tmp[i] = false;
3756            }
3757        }
3758        if (numMatch == 0) {
3759            return;
3760        }
3761        PackageInfo pi;
3762        if (ps.pkg != null) {
3763            pi = generatePackageInfo(ps.pkg, flags, userId);
3764        } else {
3765            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3766        }
3767        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3768            if (numMatch == permissions.length) {
3769                pi.requestedPermissions = permissions;
3770            } else {
3771                pi.requestedPermissions = new String[numMatch];
3772                numMatch = 0;
3773                for (int i=0; i<permissions.length; i++) {
3774                    if (tmp[i]) {
3775                        pi.requestedPermissions[numMatch] = permissions[i];
3776                        numMatch++;
3777                    }
3778                }
3779            }
3780        }
3781        list.add(pi);
3782    }
3783
3784    @Override
3785    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3786            String[] permissions, int flags, int userId) {
3787        if (!sUserManager.exists(userId)) return null;
3788        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3789
3790        // writer
3791        synchronized (mPackages) {
3792            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3793            boolean[] tmpBools = new boolean[permissions.length];
3794            if (listUninstalled) {
3795                for (PackageSetting ps : mSettings.mPackages.values()) {
3796                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3797                }
3798            } else {
3799                for (PackageParser.Package pkg : mPackages.values()) {
3800                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3801                    if (ps != null) {
3802                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3803                                userId);
3804                    }
3805                }
3806            }
3807
3808            return new ParceledListSlice<PackageInfo>(list);
3809        }
3810    }
3811
3812    @Override
3813    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3814        if (!sUserManager.exists(userId)) return null;
3815        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3816
3817        // writer
3818        synchronized (mPackages) {
3819            ArrayList<ApplicationInfo> list;
3820            if (listUninstalled) {
3821                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3822                for (PackageSetting ps : mSettings.mPackages.values()) {
3823                    ApplicationInfo ai;
3824                    if (ps.pkg != null) {
3825                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3826                                ps.readUserState(userId), userId);
3827                    } else {
3828                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3829                    }
3830                    if (ai != null) {
3831                        list.add(ai);
3832                    }
3833                }
3834            } else {
3835                list = new ArrayList<ApplicationInfo>(mPackages.size());
3836                for (PackageParser.Package p : mPackages.values()) {
3837                    if (p.mExtras != null) {
3838                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3839                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3840                        if (ai != null) {
3841                            list.add(ai);
3842                        }
3843                    }
3844                }
3845            }
3846
3847            return new ParceledListSlice<ApplicationInfo>(list);
3848        }
3849    }
3850
3851    public List<ApplicationInfo> getPersistentApplications(int flags) {
3852        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3853
3854        // reader
3855        synchronized (mPackages) {
3856            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3857            final int userId = UserHandle.getCallingUserId();
3858            while (i.hasNext()) {
3859                final PackageParser.Package p = i.next();
3860                if (p.applicationInfo != null
3861                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3862                        && (!mSafeMode || isSystemApp(p))) {
3863                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3864                    if (ps != null) {
3865                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3866                                ps.readUserState(userId), userId);
3867                        if (ai != null) {
3868                            finalList.add(ai);
3869                        }
3870                    }
3871                }
3872            }
3873        }
3874
3875        return finalList;
3876    }
3877
3878    @Override
3879    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3880        if (!sUserManager.exists(userId)) return null;
3881        // reader
3882        synchronized (mPackages) {
3883            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3884            PackageSetting ps = provider != null
3885                    ? mSettings.mPackages.get(provider.owner.packageName)
3886                    : null;
3887            return ps != null
3888                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3889                    && (!mSafeMode || (provider.info.applicationInfo.flags
3890                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3891                    ? PackageParser.generateProviderInfo(provider, flags,
3892                            ps.readUserState(userId), userId)
3893                    : null;
3894        }
3895    }
3896
3897    /**
3898     * @deprecated
3899     */
3900    @Deprecated
3901    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3902        // reader
3903        synchronized (mPackages) {
3904            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3905                    .entrySet().iterator();
3906            final int userId = UserHandle.getCallingUserId();
3907            while (i.hasNext()) {
3908                Map.Entry<String, PackageParser.Provider> entry = i.next();
3909                PackageParser.Provider p = entry.getValue();
3910                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3911
3912                if (ps != null && p.syncable
3913                        && (!mSafeMode || (p.info.applicationInfo.flags
3914                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3915                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3916                            ps.readUserState(userId), userId);
3917                    if (info != null) {
3918                        outNames.add(entry.getKey());
3919                        outInfo.add(info);
3920                    }
3921                }
3922            }
3923        }
3924    }
3925
3926    @Override
3927    public List<ProviderInfo> queryContentProviders(String processName,
3928            int uid, int flags) {
3929        ArrayList<ProviderInfo> finalList = null;
3930        // reader
3931        synchronized (mPackages) {
3932            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3933            final int userId = processName != null ?
3934                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3935            while (i.hasNext()) {
3936                final PackageParser.Provider p = i.next();
3937                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3938                if (ps != null && p.info.authority != null
3939                        && (processName == null
3940                                || (p.info.processName.equals(processName)
3941                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3942                        && mSettings.isEnabledLPr(p.info, flags, userId)
3943                        && (!mSafeMode
3944                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3945                    if (finalList == null) {
3946                        finalList = new ArrayList<ProviderInfo>(3);
3947                    }
3948                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3949                            ps.readUserState(userId), userId);
3950                    if (info != null) {
3951                        finalList.add(info);
3952                    }
3953                }
3954            }
3955        }
3956
3957        if (finalList != null) {
3958            Collections.sort(finalList, mProviderInitOrderSorter);
3959        }
3960
3961        return finalList;
3962    }
3963
3964    @Override
3965    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3966            int flags) {
3967        // reader
3968        synchronized (mPackages) {
3969            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3970            return PackageParser.generateInstrumentationInfo(i, flags);
3971        }
3972    }
3973
3974    @Override
3975    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3976            int flags) {
3977        ArrayList<InstrumentationInfo> finalList =
3978            new ArrayList<InstrumentationInfo>();
3979
3980        // reader
3981        synchronized (mPackages) {
3982            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3983            while (i.hasNext()) {
3984                final PackageParser.Instrumentation p = i.next();
3985                if (targetPackage == null
3986                        || targetPackage.equals(p.info.targetPackage)) {
3987                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3988                            flags);
3989                    if (ii != null) {
3990                        finalList.add(ii);
3991                    }
3992                }
3993            }
3994        }
3995
3996        return finalList;
3997    }
3998
3999    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4000        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4001        if (overlays == null) {
4002            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4003            return;
4004        }
4005        for (PackageParser.Package opkg : overlays.values()) {
4006            // Not much to do if idmap fails: we already logged the error
4007            // and we certainly don't want to abort installation of pkg simply
4008            // because an overlay didn't fit properly. For these reasons,
4009            // ignore the return value of createIdmapForPackagePairLI.
4010            createIdmapForPackagePairLI(pkg, opkg);
4011        }
4012    }
4013
4014    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4015            PackageParser.Package opkg) {
4016        if (!opkg.mTrustedOverlay) {
4017            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4018                    opkg.baseCodePath + ": overlay not trusted");
4019            return false;
4020        }
4021        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4022        if (overlaySet == null) {
4023            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4024                    opkg.baseCodePath + " but target package has no known overlays");
4025            return false;
4026        }
4027        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4028        // TODO: generate idmap for split APKs
4029        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4030            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4031                    + opkg.baseCodePath);
4032            return false;
4033        }
4034        PackageParser.Package[] overlayArray =
4035            overlaySet.values().toArray(new PackageParser.Package[0]);
4036        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4037            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4038                return p1.mOverlayPriority - p2.mOverlayPriority;
4039            }
4040        };
4041        Arrays.sort(overlayArray, cmp);
4042
4043        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4044        int i = 0;
4045        for (PackageParser.Package p : overlayArray) {
4046            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4047        }
4048        return true;
4049    }
4050
4051    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4052        final File[] files = dir.listFiles();
4053        if (ArrayUtils.isEmpty(files)) {
4054            Log.d(TAG, "No files in app dir " + dir);
4055            return;
4056        }
4057
4058        if (DEBUG_PACKAGE_SCANNING) {
4059            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4060                    + " flags=0x" + Integer.toHexString(parseFlags));
4061        }
4062
4063        for (File file : files) {
4064            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4065                    && !PackageInstallerService.isStageName(file.getName());
4066            if (!isPackage) {
4067                // Ignore entries which are not packages
4068                continue;
4069            }
4070            try {
4071                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4072                        scanFlags, currentTime, null);
4073            } catch (PackageManagerException e) {
4074                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4075
4076                // Delete invalid userdata apps
4077                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4078                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4079                    Slog.w(TAG, "Deleting invalid package at " + file);
4080                    if (file.isDirectory()) {
4081                        FileUtils.deleteContents(file);
4082                    }
4083                    file.delete();
4084                }
4085            }
4086        }
4087    }
4088
4089    private static File getSettingsProblemFile() {
4090        File dataDir = Environment.getDataDirectory();
4091        File systemDir = new File(dataDir, "system");
4092        File fname = new File(systemDir, "uiderrors.txt");
4093        return fname;
4094    }
4095
4096    static void reportSettingsProblem(int priority, String msg) {
4097        try {
4098            File fname = getSettingsProblemFile();
4099            FileOutputStream out = new FileOutputStream(fname, true);
4100            PrintWriter pw = new FastPrintWriter(out);
4101            SimpleDateFormat formatter = new SimpleDateFormat();
4102            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4103            pw.println(dateString + ": " + msg);
4104            pw.close();
4105            FileUtils.setPermissions(
4106                    fname.toString(),
4107                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4108                    -1, -1);
4109        } catch (java.io.IOException e) {
4110        }
4111        Slog.println(priority, TAG, msg);
4112    }
4113
4114    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4115            PackageParser.Package pkg, File srcFile, int parseFlags)
4116            throws PackageManagerException {
4117        if (ps != null
4118                && ps.codePath.equals(srcFile)
4119                && ps.timeStamp == srcFile.lastModified()
4120                && !isCompatSignatureUpdateNeeded(pkg)) {
4121            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4122            if (ps.signatures.mSignatures != null
4123                    && ps.signatures.mSignatures.length != 0
4124                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4125                // Optimization: reuse the existing cached certificates
4126                // if the package appears to be unchanged.
4127                pkg.mSignatures = ps.signatures.mSignatures;
4128                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4129                synchronized (mPackages) {
4130                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4131                }
4132                return;
4133            }
4134
4135            Slog.w(TAG, "PackageSetting for " + ps.name
4136                    + " is missing signatures.  Collecting certs again to recover them.");
4137        } else {
4138            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4139        }
4140
4141        try {
4142            pp.collectCertificates(pkg, parseFlags);
4143            pp.collectManifestDigest(pkg);
4144        } catch (PackageParserException e) {
4145            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4146                    + pkg.packageName + ": " + e.getMessage());
4147        }
4148    }
4149
4150    /*
4151     *  Scan a package and return the newly parsed package.
4152     *  Returns null in case of errors and the error code is stored in mLastScanError
4153     */
4154    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4155            long currentTime, UserHandle user) throws PackageManagerException {
4156        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4157        parseFlags |= mDefParseFlags;
4158        PackageParser pp = new PackageParser();
4159        pp.setSeparateProcesses(mSeparateProcesses);
4160        pp.setOnlyCoreApps(mOnlyCore);
4161        pp.setDisplayMetrics(mMetrics);
4162
4163        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4164            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4165        }
4166
4167        final PackageParser.Package pkg;
4168        try {
4169            pkg = pp.parsePackage(scanFile, parseFlags);
4170        } catch (PackageParserException e) {
4171            throw new PackageManagerException(e.error,
4172                    "Failed to scan " + scanFile + ": " + e.getMessage());
4173        }
4174
4175        PackageSetting ps = null;
4176        PackageSetting updatedPkg;
4177        // reader
4178        synchronized (mPackages) {
4179            // Look to see if we already know about this package.
4180            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4181            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4182                // This package has been renamed to its original name.  Let's
4183                // use that.
4184                ps = mSettings.peekPackageLPr(oldName);
4185            }
4186            // If there was no original package, see one for the real package name.
4187            if (ps == null) {
4188                ps = mSettings.peekPackageLPr(pkg.packageName);
4189            }
4190            // Check to see if this package could be hiding/updating a system
4191            // package.  Must look for it either under the original or real
4192            // package name depending on our state.
4193            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4194            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4195        }
4196        boolean updatedPkgBetter = false;
4197        // First check if this is a system package that may involve an update
4198        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4199            if (ps != null && !ps.codePath.equals(scanFile)) {
4200                // The path has changed from what was last scanned...  check the
4201                // version of the new path against what we have stored to determine
4202                // what to do.
4203                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4204                if (pkg.mVersionCode < ps.versionCode) {
4205                    // The system package has been updated and the code path does not match
4206                    // Ignore entry. Skip it.
4207                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4208                            + " ignored: updated version " + ps.versionCode
4209                            + " better than this " + pkg.mVersionCode);
4210                    if (!updatedPkg.codePath.equals(scanFile)) {
4211                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4212                                + ps.name + " changing from " + updatedPkg.codePathString
4213                                + " to " + scanFile);
4214                        updatedPkg.codePath = scanFile;
4215                        updatedPkg.codePathString = scanFile.toString();
4216                        // This is the point at which we know that the system-disk APK
4217                        // for this package has moved during a reboot (e.g. due to an OTA),
4218                        // so we need to reevaluate it for privilege policy.
4219                        if (locationIsPrivileged(scanFile)) {
4220                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4221                        }
4222                    }
4223                    updatedPkg.pkg = pkg;
4224                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4225                } else {
4226                    // The current app on the system partition is better than
4227                    // what we have updated to on the data partition; switch
4228                    // back to the system partition version.
4229                    // At this point, its safely assumed that package installation for
4230                    // apps in system partition will go through. If not there won't be a working
4231                    // version of the app
4232                    // writer
4233                    synchronized (mPackages) {
4234                        // Just remove the loaded entries from package lists.
4235                        mPackages.remove(ps.name);
4236                    }
4237                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4238                            + "reverting from " + ps.codePathString
4239                            + ": new version " + pkg.mVersionCode
4240                            + " better than installed " + ps.versionCode);
4241
4242                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4243                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4244                            getAppDexInstructionSets(ps));
4245                    synchronized (mInstallLock) {
4246                        args.cleanUpResourcesLI();
4247                    }
4248                    synchronized (mPackages) {
4249                        mSettings.enableSystemPackageLPw(ps.name);
4250                    }
4251                    updatedPkgBetter = true;
4252                }
4253            }
4254        }
4255
4256        if (updatedPkg != null) {
4257            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4258            // initially
4259            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4260
4261            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4262            // flag set initially
4263            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4264                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4265            }
4266        }
4267
4268        // Verify certificates against what was last scanned
4269        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4270
4271        /*
4272         * A new system app appeared, but we already had a non-system one of the
4273         * same name installed earlier.
4274         */
4275        boolean shouldHideSystemApp = false;
4276        if (updatedPkg == null && ps != null
4277                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4278            /*
4279             * Check to make sure the signatures match first. If they don't,
4280             * wipe the installed application and its data.
4281             */
4282            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4283                    != PackageManager.SIGNATURE_MATCH) {
4284                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4285                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4286                ps = null;
4287            } else {
4288                /*
4289                 * If the newly-added system app is an older version than the
4290                 * already installed version, hide it. It will be scanned later
4291                 * and re-added like an update.
4292                 */
4293                if (pkg.mVersionCode < ps.versionCode) {
4294                    shouldHideSystemApp = true;
4295                } else {
4296                    /*
4297                     * The newly found system app is a newer version that the
4298                     * one previously installed. Simply remove the
4299                     * already-installed application and replace it with our own
4300                     * while keeping the application data.
4301                     */
4302                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4303                            + ps.codePathString + ": new version " + pkg.mVersionCode
4304                            + " better than installed " + ps.versionCode);
4305                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4306                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4307                            getAppDexInstructionSets(ps));
4308                    synchronized (mInstallLock) {
4309                        args.cleanUpResourcesLI();
4310                    }
4311                }
4312            }
4313        }
4314
4315        // The apk is forward locked (not public) if its code and resources
4316        // are kept in different files. (except for app in either system or
4317        // vendor path).
4318        // TODO grab this value from PackageSettings
4319        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4320            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4321                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4322            }
4323        }
4324
4325        // TODO: extend to support forward-locked splits
4326        String resourcePath = null;
4327        String baseResourcePath = null;
4328        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4329            if (ps != null && ps.resourcePathString != null) {
4330                resourcePath = ps.resourcePathString;
4331                baseResourcePath = ps.resourcePathString;
4332            } else {
4333                // Should not happen at all. Just log an error.
4334                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4335            }
4336        } else {
4337            resourcePath = pkg.codePath;
4338            baseResourcePath = pkg.baseCodePath;
4339        }
4340
4341        // Set application objects path explicitly.
4342        pkg.applicationInfo.setCodePath(pkg.codePath);
4343        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4344        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4345        pkg.applicationInfo.setResourcePath(resourcePath);
4346        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4347        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4348
4349        // Note that we invoke the following method only if we are about to unpack an application
4350        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4351                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4352
4353        /*
4354         * If the system app should be overridden by a previously installed
4355         * data, hide the system app now and let the /data/app scan pick it up
4356         * again.
4357         */
4358        if (shouldHideSystemApp) {
4359            synchronized (mPackages) {
4360                /*
4361                 * We have to grant systems permissions before we hide, because
4362                 * grantPermissions will assume the package update is trying to
4363                 * expand its permissions.
4364                 */
4365                grantPermissionsLPw(pkg, true);
4366                mSettings.disableSystemPackageLPw(pkg.packageName);
4367            }
4368        }
4369
4370        return scannedPkg;
4371    }
4372
4373    private static String fixProcessName(String defProcessName,
4374            String processName, int uid) {
4375        if (processName == null) {
4376            return defProcessName;
4377        }
4378        return processName;
4379    }
4380
4381    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4382            throws PackageManagerException {
4383        if (pkgSetting.signatures.mSignatures != null) {
4384            // Already existing package. Make sure signatures match
4385            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4386                    == PackageManager.SIGNATURE_MATCH;
4387            if (!match) {
4388                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4389                        == PackageManager.SIGNATURE_MATCH;
4390            }
4391            if (!match) {
4392                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4393                        + pkg.packageName + " signatures do not match the "
4394                        + "previously installed version; ignoring!");
4395            }
4396        }
4397
4398        // Check for shared user signatures
4399        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4400            // Already existing package. Make sure signatures match
4401            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4402                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4403            if (!match) {
4404                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4405                        == PackageManager.SIGNATURE_MATCH;
4406            }
4407            if (!match) {
4408                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4409                        "Package " + pkg.packageName
4410                        + " has no signatures that match those in shared user "
4411                        + pkgSetting.sharedUser.name + "; ignoring!");
4412            }
4413        }
4414    }
4415
4416    /**
4417     * Enforces that only the system UID or root's UID can call a method exposed
4418     * via Binder.
4419     *
4420     * @param message used as message if SecurityException is thrown
4421     * @throws SecurityException if the caller is not system or root
4422     */
4423    private static final void enforceSystemOrRoot(String message) {
4424        final int uid = Binder.getCallingUid();
4425        if (uid != Process.SYSTEM_UID && uid != 0) {
4426            throw new SecurityException(message);
4427        }
4428    }
4429
4430    @Override
4431    public void performBootDexOpt() {
4432        enforceSystemOrRoot("Only the system can request dexopt be performed");
4433
4434        final HashSet<PackageParser.Package> pkgs;
4435        synchronized (mPackages) {
4436            pkgs = mDeferredDexOpt;
4437            mDeferredDexOpt = null;
4438        }
4439
4440        if (pkgs != null) {
4441            // Filter out packages that aren't recently used.
4442            //
4443            // The exception is first boot of a non-eng device, which
4444            // should do a full dexopt.
4445            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4446            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4447                // TODO: add a property to control this?
4448                long dexOptLRUThresholdInMinutes;
4449                if (eng) {
4450                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4451                } else {
4452                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4453                }
4454                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4455
4456                int total = pkgs.size();
4457                int skipped = 0;
4458                long now = System.currentTimeMillis();
4459                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4460                    PackageParser.Package pkg = i.next();
4461                    long then = pkg.mLastPackageUsageTimeInMills;
4462                    if (then + dexOptLRUThresholdInMills < now) {
4463                        if (DEBUG_DEXOPT) {
4464                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4465                                  ((then == 0) ? "never" : new Date(then)));
4466                        }
4467                        i.remove();
4468                        skipped++;
4469                    }
4470                }
4471                if (DEBUG_DEXOPT) {
4472                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4473                }
4474            }
4475
4476            int i = 0;
4477            for (PackageParser.Package pkg : pkgs) {
4478                i++;
4479                if (DEBUG_DEXOPT) {
4480                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4481                          + ": " + pkg.packageName);
4482                }
4483                if (!isFirstBoot()) {
4484                    try {
4485                        ActivityManagerNative.getDefault().showBootMessage(
4486                                mContext.getResources().getString(
4487                                        R.string.android_upgrading_apk,
4488                                        i, pkgs.size()), true);
4489                    } catch (RemoteException e) {
4490                    }
4491                }
4492                PackageParser.Package p = pkg;
4493                synchronized (mInstallLock) {
4494                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4495                            true /* include dependencies */);
4496                }
4497            }
4498        }
4499    }
4500
4501    @Override
4502    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4503        return performDexOpt(packageName, instructionSet, true);
4504    }
4505
4506    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4507        if (info.primaryCpuAbi == null) {
4508            return getPreferredInstructionSet();
4509        }
4510
4511        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4512    }
4513
4514    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4515        PackageParser.Package p;
4516        final String targetInstructionSet;
4517        synchronized (mPackages) {
4518            p = mPackages.get(packageName);
4519            if (p == null) {
4520                return false;
4521            }
4522            if (updateUsage) {
4523                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4524            }
4525            mPackageUsage.write(false);
4526
4527            targetInstructionSet = instructionSet != null ? instructionSet :
4528                    getPrimaryInstructionSet(p.applicationInfo);
4529            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4530                return false;
4531            }
4532        }
4533
4534        synchronized (mInstallLock) {
4535            final String[] instructionSets = new String[] { targetInstructionSet };
4536            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4537                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4538        }
4539    }
4540
4541    public HashSet<String> getPackagesThatNeedDexOpt() {
4542        HashSet<String> pkgs = null;
4543        synchronized (mPackages) {
4544            for (PackageParser.Package p : mPackages.values()) {
4545                if (DEBUG_DEXOPT) {
4546                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4547                }
4548                if (!p.mDexOptPerformed.isEmpty()) {
4549                    continue;
4550                }
4551                if (pkgs == null) {
4552                    pkgs = new HashSet<String>();
4553                }
4554                pkgs.add(p.packageName);
4555            }
4556        }
4557        return pkgs;
4558    }
4559
4560    public void shutdown() {
4561        mPackageUsage.write(true);
4562    }
4563
4564    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4565             boolean forceDex, boolean defer, HashSet<String> done) {
4566        for (int i=0; i<libs.size(); i++) {
4567            PackageParser.Package libPkg;
4568            String libName;
4569            synchronized (mPackages) {
4570                libName = libs.get(i);
4571                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4572                if (lib != null && lib.apk != null) {
4573                    libPkg = mPackages.get(lib.apk);
4574                } else {
4575                    libPkg = null;
4576                }
4577            }
4578            if (libPkg != null && !done.contains(libName)) {
4579                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4580            }
4581        }
4582    }
4583
4584    static final int DEX_OPT_SKIPPED = 0;
4585    static final int DEX_OPT_PERFORMED = 1;
4586    static final int DEX_OPT_DEFERRED = 2;
4587    static final int DEX_OPT_FAILED = -1;
4588
4589    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4590            boolean forceDex, boolean defer, HashSet<String> done) {
4591        final String[] instructionSets = targetInstructionSets != null ?
4592                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4593
4594        if (done != null) {
4595            done.add(pkg.packageName);
4596            if (pkg.usesLibraries != null) {
4597                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4598            }
4599            if (pkg.usesOptionalLibraries != null) {
4600                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4601            }
4602        }
4603
4604        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4605            return DEX_OPT_SKIPPED;
4606        }
4607
4608        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4609
4610        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4611        boolean performedDexOpt = false;
4612        // There are three basic cases here:
4613        // 1.) we need to dexopt, either because we are forced or it is needed
4614        // 2.) we are defering a needed dexopt
4615        // 3.) we are skipping an unneeded dexopt
4616        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4617        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4618            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4619                continue;
4620            }
4621
4622            for (String path : paths) {
4623                try {
4624                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4625                    // patckage or the one we find does not match the image checksum (i.e. it was
4626                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4627                    // odex file and it matches the checksum of the image but not its base address,
4628                    // meaning we need to move it.
4629                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4630                            pkg.packageName, dexCodeInstructionSet, defer);
4631                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4632                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4633                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4634                                + " vmSafeMode=" + vmSafeMode);
4635                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4636                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4637                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4638
4639                        if (ret < 0) {
4640                            // Don't bother running dexopt again if we failed, it will probably
4641                            // just result in an error again. Also, don't bother dexopting for other
4642                            // paths & ISAs.
4643                            return DEX_OPT_FAILED;
4644                        }
4645
4646                        performedDexOpt = true;
4647                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4648                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4649                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4650                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4651                                pkg.packageName, dexCodeInstructionSet);
4652
4653                        if (ret < 0) {
4654                            // Don't bother running patchoat again if we failed, it will probably
4655                            // just result in an error again. Also, don't bother dexopting for other
4656                            // paths & ISAs.
4657                            return DEX_OPT_FAILED;
4658                        }
4659
4660                        performedDexOpt = true;
4661                    }
4662
4663                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4664                    // paths and instruction sets. We'll deal with them all together when we process
4665                    // our list of deferred dexopts.
4666                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4667                        if (mDeferredDexOpt == null) {
4668                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4669                        }
4670                        mDeferredDexOpt.add(pkg);
4671                        return DEX_OPT_DEFERRED;
4672                    }
4673                } catch (FileNotFoundException e) {
4674                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4675                    return DEX_OPT_FAILED;
4676                } catch (IOException e) {
4677                    Slog.w(TAG, "IOException reading apk: " + path, e);
4678                    return DEX_OPT_FAILED;
4679                } catch (StaleDexCacheError e) {
4680                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4681                    return DEX_OPT_FAILED;
4682                } catch (Exception e) {
4683                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4684                    return DEX_OPT_FAILED;
4685                }
4686            }
4687
4688            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4689            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4690            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4691            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4692            // it.
4693            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4694        }
4695
4696        // If we've gotten here, we're sure that no error occurred and that we haven't
4697        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4698        // we've skipped all of them because they are up to date. In both cases this
4699        // package doesn't need dexopt any longer.
4700        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4701    }
4702
4703    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4704        if (info.primaryCpuAbi != null) {
4705            if (info.secondaryCpuAbi != null) {
4706                return new String[] {
4707                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4708                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4709            } else {
4710                return new String[] {
4711                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4712            }
4713        }
4714
4715        return new String[] { getPreferredInstructionSet() };
4716    }
4717
4718    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4719        if (ps.primaryCpuAbiString != null) {
4720            if (ps.secondaryCpuAbiString != null) {
4721                return new String[] {
4722                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4723                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4724            } else {
4725                return new String[] {
4726                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4727            }
4728        }
4729
4730        return new String[] { getPreferredInstructionSet() };
4731    }
4732
4733    private static String getPreferredInstructionSet() {
4734        if (sPreferredInstructionSet == null) {
4735            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4736        }
4737
4738        return sPreferredInstructionSet;
4739    }
4740
4741    private static List<String> getAllInstructionSets() {
4742        final String[] allAbis = Build.SUPPORTED_ABIS;
4743        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4744
4745        for (String abi : allAbis) {
4746            final String instructionSet = VMRuntime.getInstructionSet(abi);
4747            if (!allInstructionSets.contains(instructionSet)) {
4748                allInstructionSets.add(instructionSet);
4749            }
4750        }
4751
4752        return allInstructionSets;
4753    }
4754
4755    /**
4756     * Returns the instruction set that should be used to compile dex code. In the presence of
4757     * a native bridge this might be different than the one shared libraries use.
4758     */
4759    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4760        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4761        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4762    }
4763
4764    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4765        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4766        for (String instructionSet : instructionSets) {
4767            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4768        }
4769        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4770    }
4771
4772    @Override
4773    public void forceDexOpt(String packageName) {
4774        enforceSystemOrRoot("forceDexOpt");
4775
4776        PackageParser.Package pkg;
4777        synchronized (mPackages) {
4778            pkg = mPackages.get(packageName);
4779            if (pkg == null) {
4780                throw new IllegalArgumentException("Missing package: " + packageName);
4781            }
4782        }
4783
4784        synchronized (mInstallLock) {
4785            final String[] instructionSets = new String[] {
4786                    getPrimaryInstructionSet(pkg.applicationInfo) };
4787            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4788            if (res != DEX_OPT_PERFORMED) {
4789                throw new IllegalStateException("Failed to dexopt: " + res);
4790            }
4791        }
4792    }
4793
4794    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4795                                boolean forceDex, boolean defer, boolean inclDependencies) {
4796        HashSet<String> done;
4797        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4798            done = new HashSet<String>();
4799            done.add(pkg.packageName);
4800        } else {
4801            done = null;
4802        }
4803        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4804    }
4805
4806    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4807        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4808            Slog.w(TAG, "Unable to update from " + oldPkg.name
4809                    + " to " + newPkg.packageName
4810                    + ": old package not in system partition");
4811            return false;
4812        } else if (mPackages.get(oldPkg.name) != null) {
4813            Slog.w(TAG, "Unable to update from " + oldPkg.name
4814                    + " to " + newPkg.packageName
4815                    + ": old package still exists");
4816            return false;
4817        }
4818        return true;
4819    }
4820
4821    File getDataPathForUser(int userId) {
4822        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4823    }
4824
4825    private File getDataPathForPackage(String packageName, int userId) {
4826        /*
4827         * Until we fully support multiple users, return the directory we
4828         * previously would have. The PackageManagerTests will need to be
4829         * revised when this is changed back..
4830         */
4831        if (userId == 0) {
4832            return new File(mAppDataDir, packageName);
4833        } else {
4834            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4835                + File.separator + packageName);
4836        }
4837    }
4838
4839    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4840        int[] users = sUserManager.getUserIds();
4841        int res = mInstaller.install(packageName, uid, uid, seinfo);
4842        if (res < 0) {
4843            return res;
4844        }
4845        for (int user : users) {
4846            if (user != 0) {
4847                res = mInstaller.createUserData(packageName,
4848                        UserHandle.getUid(user, uid), user, seinfo);
4849                if (res < 0) {
4850                    return res;
4851                }
4852            }
4853        }
4854        return res;
4855    }
4856
4857    private int removeDataDirsLI(String packageName) {
4858        int[] users = sUserManager.getUserIds();
4859        int res = 0;
4860        for (int user : users) {
4861            int resInner = mInstaller.remove(packageName, user);
4862            if (resInner < 0) {
4863                res = resInner;
4864            }
4865        }
4866
4867        return res;
4868    }
4869
4870    private int deleteCodeCacheDirsLI(String packageName) {
4871        int[] users = sUserManager.getUserIds();
4872        int res = 0;
4873        for (int user : users) {
4874            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4875            if (resInner < 0) {
4876                res = resInner;
4877            }
4878        }
4879        return res;
4880    }
4881
4882    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4883            PackageParser.Package changingLib) {
4884        if (file.path != null) {
4885            usesLibraryFiles.add(file.path);
4886            return;
4887        }
4888        PackageParser.Package p = mPackages.get(file.apk);
4889        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4890            // If we are doing this while in the middle of updating a library apk,
4891            // then we need to make sure to use that new apk for determining the
4892            // dependencies here.  (We haven't yet finished committing the new apk
4893            // to the package manager state.)
4894            if (p == null || p.packageName.equals(changingLib.packageName)) {
4895                p = changingLib;
4896            }
4897        }
4898        if (p != null) {
4899            usesLibraryFiles.addAll(p.getAllCodePaths());
4900        }
4901    }
4902
4903    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4904            PackageParser.Package changingLib) throws PackageManagerException {
4905        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4906            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4907            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4908            for (int i=0; i<N; i++) {
4909                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4910                if (file == null) {
4911                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4912                            "Package " + pkg.packageName + " requires unavailable shared library "
4913                            + pkg.usesLibraries.get(i) + "; failing!");
4914                }
4915                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4916            }
4917            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4918            for (int i=0; i<N; i++) {
4919                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4920                if (file == null) {
4921                    Slog.w(TAG, "Package " + pkg.packageName
4922                            + " desires unavailable shared library "
4923                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4924                } else {
4925                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4926                }
4927            }
4928            N = usesLibraryFiles.size();
4929            if (N > 0) {
4930                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4931            } else {
4932                pkg.usesLibraryFiles = null;
4933            }
4934        }
4935    }
4936
4937    private static boolean hasString(List<String> list, List<String> which) {
4938        if (list == null) {
4939            return false;
4940        }
4941        for (int i=list.size()-1; i>=0; i--) {
4942            for (int j=which.size()-1; j>=0; j--) {
4943                if (which.get(j).equals(list.get(i))) {
4944                    return true;
4945                }
4946            }
4947        }
4948        return false;
4949    }
4950
4951    private void updateAllSharedLibrariesLPw() {
4952        for (PackageParser.Package pkg : mPackages.values()) {
4953            try {
4954                updateSharedLibrariesLPw(pkg, null);
4955            } catch (PackageManagerException e) {
4956                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4957            }
4958        }
4959    }
4960
4961    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4962            PackageParser.Package changingPkg) {
4963        ArrayList<PackageParser.Package> res = null;
4964        for (PackageParser.Package pkg : mPackages.values()) {
4965            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4966                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4967                if (res == null) {
4968                    res = new ArrayList<PackageParser.Package>();
4969                }
4970                res.add(pkg);
4971                try {
4972                    updateSharedLibrariesLPw(pkg, changingPkg);
4973                } catch (PackageManagerException e) {
4974                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4975                }
4976            }
4977        }
4978        return res;
4979    }
4980
4981    /**
4982     * Derive the value of the {@code cpuAbiOverride} based on the provided
4983     * value and an optional stored value from the package settings.
4984     */
4985    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4986        String cpuAbiOverride = null;
4987
4988        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4989            cpuAbiOverride = null;
4990        } else if (abiOverride != null) {
4991            cpuAbiOverride = abiOverride;
4992        } else if (settings != null) {
4993            cpuAbiOverride = settings.cpuAbiOverrideString;
4994        }
4995
4996        return cpuAbiOverride;
4997    }
4998
4999    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5000            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5001        final File scanFile = new File(pkg.codePath);
5002        if (pkg.applicationInfo.getCodePath() == null ||
5003                pkg.applicationInfo.getResourcePath() == null) {
5004            // Bail out. The resource and code paths haven't been set.
5005            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5006                    "Code and resource paths haven't been set correctly");
5007        }
5008
5009        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5010            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5011        }
5012
5013        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5014            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5015        }
5016
5017        if (mCustomResolverComponentName != null &&
5018                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5019            setUpCustomResolverActivity(pkg);
5020        }
5021
5022        if (pkg.packageName.equals("android")) {
5023            synchronized (mPackages) {
5024                if (mAndroidApplication != null) {
5025                    Slog.w(TAG, "*************************************************");
5026                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5027                    Slog.w(TAG, " file=" + scanFile);
5028                    Slog.w(TAG, "*************************************************");
5029                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5030                            "Core android package being redefined.  Skipping.");
5031                }
5032
5033                // Set up information for our fall-back user intent resolution activity.
5034                mPlatformPackage = pkg;
5035                pkg.mVersionCode = mSdkVersion;
5036                mAndroidApplication = pkg.applicationInfo;
5037
5038                if (!mResolverReplaced) {
5039                    mResolveActivity.applicationInfo = mAndroidApplication;
5040                    mResolveActivity.name = ResolverActivity.class.getName();
5041                    mResolveActivity.packageName = mAndroidApplication.packageName;
5042                    mResolveActivity.processName = "system:ui";
5043                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5044                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5045                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5046                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5047                    mResolveActivity.exported = true;
5048                    mResolveActivity.enabled = true;
5049                    mResolveInfo.activityInfo = mResolveActivity;
5050                    mResolveInfo.priority = 0;
5051                    mResolveInfo.preferredOrder = 0;
5052                    mResolveInfo.match = 0;
5053                    mResolveComponentName = new ComponentName(
5054                            mAndroidApplication.packageName, mResolveActivity.name);
5055                }
5056            }
5057        }
5058
5059        if (DEBUG_PACKAGE_SCANNING) {
5060            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5061                Log.d(TAG, "Scanning package " + pkg.packageName);
5062        }
5063
5064        if (mPackages.containsKey(pkg.packageName)
5065                || mSharedLibraries.containsKey(pkg.packageName)) {
5066            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5067                    "Application package " + pkg.packageName
5068                    + " already installed.  Skipping duplicate.");
5069        }
5070
5071        // Initialize package source and resource directories
5072        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5073        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5074
5075        SharedUserSetting suid = null;
5076        PackageSetting pkgSetting = null;
5077
5078        if (!isSystemApp(pkg)) {
5079            // Only system apps can use these features.
5080            pkg.mOriginalPackages = null;
5081            pkg.mRealPackage = null;
5082            pkg.mAdoptPermissions = null;
5083        }
5084
5085        // writer
5086        synchronized (mPackages) {
5087            if (pkg.mSharedUserId != null) {
5088                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5089                if (suid == null) {
5090                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5091                            "Creating application package " + pkg.packageName
5092                            + " for shared user failed");
5093                }
5094                if (DEBUG_PACKAGE_SCANNING) {
5095                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5096                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5097                                + "): packages=" + suid.packages);
5098                }
5099            }
5100
5101            // Check if we are renaming from an original package name.
5102            PackageSetting origPackage = null;
5103            String realName = null;
5104            if (pkg.mOriginalPackages != null) {
5105                // This package may need to be renamed to a previously
5106                // installed name.  Let's check on that...
5107                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5108                if (pkg.mOriginalPackages.contains(renamed)) {
5109                    // This package had originally been installed as the
5110                    // original name, and we have already taken care of
5111                    // transitioning to the new one.  Just update the new
5112                    // one to continue using the old name.
5113                    realName = pkg.mRealPackage;
5114                    if (!pkg.packageName.equals(renamed)) {
5115                        // Callers into this function may have already taken
5116                        // care of renaming the package; only do it here if
5117                        // it is not already done.
5118                        pkg.setPackageName(renamed);
5119                    }
5120
5121                } else {
5122                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5123                        if ((origPackage = mSettings.peekPackageLPr(
5124                                pkg.mOriginalPackages.get(i))) != null) {
5125                            // We do have the package already installed under its
5126                            // original name...  should we use it?
5127                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5128                                // New package is not compatible with original.
5129                                origPackage = null;
5130                                continue;
5131                            } else if (origPackage.sharedUser != null) {
5132                                // Make sure uid is compatible between packages.
5133                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5134                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5135                                            + " to " + pkg.packageName + ": old uid "
5136                                            + origPackage.sharedUser.name
5137                                            + " differs from " + pkg.mSharedUserId);
5138                                    origPackage = null;
5139                                    continue;
5140                                }
5141                            } else {
5142                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5143                                        + pkg.packageName + " to old name " + origPackage.name);
5144                            }
5145                            break;
5146                        }
5147                    }
5148                }
5149            }
5150
5151            if (mTransferedPackages.contains(pkg.packageName)) {
5152                Slog.w(TAG, "Package " + pkg.packageName
5153                        + " was transferred to another, but its .apk remains");
5154            }
5155
5156            // Just create the setting, don't add it yet. For already existing packages
5157            // the PkgSetting exists already and doesn't have to be created.
5158            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5159                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5160                    pkg.applicationInfo.primaryCpuAbi,
5161                    pkg.applicationInfo.secondaryCpuAbi,
5162                    pkg.applicationInfo.flags, user, false);
5163            if (pkgSetting == null) {
5164                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5165                        "Creating application package " + pkg.packageName + " failed");
5166            }
5167
5168            if (pkgSetting.origPackage != null) {
5169                // If we are first transitioning from an original package,
5170                // fix up the new package's name now.  We need to do this after
5171                // looking up the package under its new name, so getPackageLP
5172                // can take care of fiddling things correctly.
5173                pkg.setPackageName(origPackage.name);
5174
5175                // File a report about this.
5176                String msg = "New package " + pkgSetting.realName
5177                        + " renamed to replace old package " + pkgSetting.name;
5178                reportSettingsProblem(Log.WARN, msg);
5179
5180                // Make a note of it.
5181                mTransferedPackages.add(origPackage.name);
5182
5183                // No longer need to retain this.
5184                pkgSetting.origPackage = null;
5185            }
5186
5187            if (realName != null) {
5188                // Make a note of it.
5189                mTransferedPackages.add(pkg.packageName);
5190            }
5191
5192            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5193                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5194            }
5195
5196            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5197                // Check all shared libraries and map to their actual file path.
5198                // We only do this here for apps not on a system dir, because those
5199                // are the only ones that can fail an install due to this.  We
5200                // will take care of the system apps by updating all of their
5201                // library paths after the scan is done.
5202                updateSharedLibrariesLPw(pkg, null);
5203            }
5204
5205            if (mFoundPolicyFile) {
5206                SELinuxMMAC.assignSeinfoValue(pkg);
5207            }
5208
5209            pkg.applicationInfo.uid = pkgSetting.appId;
5210            pkg.mExtras = pkgSetting;
5211            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5212                try {
5213                    verifySignaturesLP(pkgSetting, pkg);
5214                } catch (PackageManagerException e) {
5215                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5216                        throw e;
5217                    }
5218                    // The signature has changed, but this package is in the system
5219                    // image...  let's recover!
5220                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5221                    // However...  if this package is part of a shared user, but it
5222                    // doesn't match the signature of the shared user, let's fail.
5223                    // What this means is that you can't change the signatures
5224                    // associated with an overall shared user, which doesn't seem all
5225                    // that unreasonable.
5226                    if (pkgSetting.sharedUser != null) {
5227                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5228                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5229                            throw new PackageManagerException(
5230                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5231                                            "Signature mismatch for shared user : "
5232                                            + pkgSetting.sharedUser);
5233                        }
5234                    }
5235                    // File a report about this.
5236                    String msg = "System package " + pkg.packageName
5237                        + " signature changed; retaining data.";
5238                    reportSettingsProblem(Log.WARN, msg);
5239                }
5240            } else {
5241                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5242                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5243                            + pkg.packageName + " upgrade keys do not match the "
5244                            + "previously installed version");
5245                } else {
5246                    // signatures may have changed as result of upgrade
5247                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5248                }
5249            }
5250            // Verify that this new package doesn't have any content providers
5251            // that conflict with existing packages.  Only do this if the
5252            // package isn't already installed, since we don't want to break
5253            // things that are installed.
5254            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5255                final int N = pkg.providers.size();
5256                int i;
5257                for (i=0; i<N; i++) {
5258                    PackageParser.Provider p = pkg.providers.get(i);
5259                    if (p.info.authority != null) {
5260                        String names[] = p.info.authority.split(";");
5261                        for (int j = 0; j < names.length; j++) {
5262                            if (mProvidersByAuthority.containsKey(names[j])) {
5263                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5264                                final String otherPackageName =
5265                                        ((other != null && other.getComponentName() != null) ?
5266                                                other.getComponentName().getPackageName() : "?");
5267                                throw new PackageManagerException(
5268                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5269                                                "Can't install because provider name " + names[j]
5270                                                + " (in package " + pkg.applicationInfo.packageName
5271                                                + ") is already used by " + otherPackageName);
5272                            }
5273                        }
5274                    }
5275                }
5276            }
5277
5278            if (pkg.mAdoptPermissions != null) {
5279                // This package wants to adopt ownership of permissions from
5280                // another package.
5281                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5282                    final String origName = pkg.mAdoptPermissions.get(i);
5283                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5284                    if (orig != null) {
5285                        if (verifyPackageUpdateLPr(orig, pkg)) {
5286                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5287                                    + pkg.packageName);
5288                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5289                        }
5290                    }
5291                }
5292            }
5293        }
5294
5295        final String pkgName = pkg.packageName;
5296
5297        final long scanFileTime = scanFile.lastModified();
5298        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5299        pkg.applicationInfo.processName = fixProcessName(
5300                pkg.applicationInfo.packageName,
5301                pkg.applicationInfo.processName,
5302                pkg.applicationInfo.uid);
5303
5304        File dataPath;
5305        if (mPlatformPackage == pkg) {
5306            // The system package is special.
5307            dataPath = new File (Environment.getDataDirectory(), "system");
5308            pkg.applicationInfo.dataDir = dataPath.getPath();
5309
5310        } else {
5311            // This is a normal package, need to make its data directory.
5312            dataPath = getDataPathForPackage(pkg.packageName, 0);
5313
5314            boolean uidError = false;
5315
5316            if (dataPath.exists()) {
5317                int currentUid = 0;
5318                try {
5319                    StructStat stat = Os.stat(dataPath.getPath());
5320                    currentUid = stat.st_uid;
5321                } catch (ErrnoException e) {
5322                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5323                }
5324
5325                // If we have mismatched owners for the data path, we have a problem.
5326                if (currentUid != pkg.applicationInfo.uid) {
5327                    boolean recovered = false;
5328                    if (currentUid == 0) {
5329                        // The directory somehow became owned by root.  Wow.
5330                        // This is probably because the system was stopped while
5331                        // installd was in the middle of messing with its libs
5332                        // directory.  Ask installd to fix that.
5333                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5334                                pkg.applicationInfo.uid);
5335                        if (ret >= 0) {
5336                            recovered = true;
5337                            String msg = "Package " + pkg.packageName
5338                                    + " unexpectedly changed to uid 0; recovered to " +
5339                                    + pkg.applicationInfo.uid;
5340                            reportSettingsProblem(Log.WARN, msg);
5341                        }
5342                    }
5343                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5344                            || (scanFlags&SCAN_BOOTING) != 0)) {
5345                        // If this is a system app, we can at least delete its
5346                        // current data so the application will still work.
5347                        int ret = removeDataDirsLI(pkgName);
5348                        if (ret >= 0) {
5349                            // TODO: Kill the processes first
5350                            // Old data gone!
5351                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5352                                    ? "System package " : "Third party package ";
5353                            String msg = prefix + pkg.packageName
5354                                    + " has changed from uid: "
5355                                    + currentUid + " to "
5356                                    + pkg.applicationInfo.uid + "; old data erased";
5357                            reportSettingsProblem(Log.WARN, msg);
5358                            recovered = true;
5359
5360                            // And now re-install the app.
5361                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5362                                                   pkg.applicationInfo.seinfo);
5363                            if (ret == -1) {
5364                                // Ack should not happen!
5365                                msg = prefix + pkg.packageName
5366                                        + " could not have data directory re-created after delete.";
5367                                reportSettingsProblem(Log.WARN, msg);
5368                                throw new PackageManagerException(
5369                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5370                            }
5371                        }
5372                        if (!recovered) {
5373                            mHasSystemUidErrors = true;
5374                        }
5375                    } else if (!recovered) {
5376                        // If we allow this install to proceed, we will be broken.
5377                        // Abort, abort!
5378                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5379                                "scanPackageLI");
5380                    }
5381                    if (!recovered) {
5382                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5383                            + pkg.applicationInfo.uid + "/fs_"
5384                            + currentUid;
5385                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5386                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5387                        String msg = "Package " + pkg.packageName
5388                                + " has mismatched uid: "
5389                                + currentUid + " on disk, "
5390                                + pkg.applicationInfo.uid + " in settings";
5391                        // writer
5392                        synchronized (mPackages) {
5393                            mSettings.mReadMessages.append(msg);
5394                            mSettings.mReadMessages.append('\n');
5395                            uidError = true;
5396                            if (!pkgSetting.uidError) {
5397                                reportSettingsProblem(Log.ERROR, msg);
5398                            }
5399                        }
5400                    }
5401                }
5402                pkg.applicationInfo.dataDir = dataPath.getPath();
5403                if (mShouldRestoreconData) {
5404                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5405                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5406                                pkg.applicationInfo.uid);
5407                }
5408            } else {
5409                if (DEBUG_PACKAGE_SCANNING) {
5410                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5411                        Log.v(TAG, "Want this data dir: " + dataPath);
5412                }
5413                //invoke installer to do the actual installation
5414                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5415                                           pkg.applicationInfo.seinfo);
5416                if (ret < 0) {
5417                    // Error from installer
5418                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5419                            "Unable to create data dirs [errorCode=" + ret + "]");
5420                }
5421
5422                if (dataPath.exists()) {
5423                    pkg.applicationInfo.dataDir = dataPath.getPath();
5424                } else {
5425                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5426                    pkg.applicationInfo.dataDir = null;
5427                }
5428            }
5429
5430            pkgSetting.uidError = uidError;
5431        }
5432
5433        final String path = scanFile.getPath();
5434        final String codePath = pkg.applicationInfo.getCodePath();
5435        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5436        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5437            setBundledAppAbisAndRoots(pkg, pkgSetting);
5438
5439            // If we haven't found any native libraries for the app, check if it has
5440            // renderscript code. We'll need to force the app to 32 bit if it has
5441            // renderscript bitcode.
5442            if (pkg.applicationInfo.primaryCpuAbi == null
5443                    && pkg.applicationInfo.secondaryCpuAbi == null
5444                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5445                NativeLibraryHelper.Handle handle = null;
5446                try {
5447                    handle = NativeLibraryHelper.Handle.create(scanFile);
5448                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5449                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5450                    }
5451                } catch (IOException ioe) {
5452                    Slog.w(TAG, "Error scanning system app : " + ioe);
5453                } finally {
5454                    IoUtils.closeQuietly(handle);
5455                }
5456            }
5457
5458            setNativeLibraryPaths(pkg);
5459        } else {
5460            // TODO: We can probably be smarter about this stuff. For installed apps,
5461            // we can calculate this information at install time once and for all. For
5462            // system apps, we can probably assume that this information doesn't change
5463            // after the first boot scan. As things stand, we do lots of unnecessary work.
5464
5465            // Give ourselves some initial paths; we'll come back for another
5466            // pass once we've determined ABI below.
5467            setNativeLibraryPaths(pkg);
5468
5469            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5470            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5471            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5472
5473            NativeLibraryHelper.Handle handle = null;
5474            try {
5475                handle = NativeLibraryHelper.Handle.create(scanFile);
5476                // TODO(multiArch): This can be null for apps that didn't go through the
5477                // usual installation process. We can calculate it again, like we
5478                // do during install time.
5479                //
5480                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5481                // unnecessary.
5482                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5483
5484                // Null out the abis so that they can be recalculated.
5485                pkg.applicationInfo.primaryCpuAbi = null;
5486                pkg.applicationInfo.secondaryCpuAbi = null;
5487                if (isMultiArch(pkg.applicationInfo)) {
5488                    // Warn if we've set an abiOverride for multi-lib packages..
5489                    // By definition, we need to copy both 32 and 64 bit libraries for
5490                    // such packages.
5491                    if (pkg.cpuAbiOverride != null
5492                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5493                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5494                    }
5495
5496                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5497                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5498                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5499                        if (isAsec) {
5500                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5501                        } else {
5502                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5503                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5504                                    useIsaSpecificSubdirs);
5505                        }
5506                    }
5507
5508                    maybeThrowExceptionForMultiArchCopy(
5509                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5510
5511                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5512                        if (isAsec) {
5513                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5514                        } else {
5515                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5516                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5517                                    useIsaSpecificSubdirs);
5518                        }
5519                    }
5520
5521                    maybeThrowExceptionForMultiArchCopy(
5522                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5523
5524                    if (abi64 >= 0) {
5525                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5526                    }
5527
5528                    if (abi32 >= 0) {
5529                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5530                        if (abi64 >= 0) {
5531                            pkg.applicationInfo.secondaryCpuAbi = abi;
5532                        } else {
5533                            pkg.applicationInfo.primaryCpuAbi = abi;
5534                        }
5535                    }
5536                } else {
5537                    String[] abiList = (cpuAbiOverride != null) ?
5538                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5539
5540                    // Enable gross and lame hacks for apps that are built with old
5541                    // SDK tools. We must scan their APKs for renderscript bitcode and
5542                    // not launch them if it's present. Don't bother checking on devices
5543                    // that don't have 64 bit support.
5544                    boolean needsRenderScriptOverride = false;
5545                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5546                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5547                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5548                        needsRenderScriptOverride = true;
5549                    }
5550
5551                    final int copyRet;
5552                    if (isAsec) {
5553                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5554                    } else {
5555                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5556                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5557                    }
5558
5559                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5560                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5561                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5562                    }
5563
5564                    if (copyRet >= 0) {
5565                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5566                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5567                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5568                    } else if (needsRenderScriptOverride) {
5569                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5570                    }
5571                }
5572            } catch (IOException ioe) {
5573                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5574            } finally {
5575                IoUtils.closeQuietly(handle);
5576            }
5577
5578            // Now that we've calculated the ABIs and determined if it's an internal app,
5579            // we will go ahead and populate the nativeLibraryPath.
5580            setNativeLibraryPaths(pkg);
5581
5582            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5583            final int[] userIds = sUserManager.getUserIds();
5584            synchronized (mInstallLock) {
5585                // Create a native library symlink only if we have native libraries
5586                // and if the native libraries are 32 bit libraries. We do not provide
5587                // this symlink for 64 bit libraries.
5588                if (pkg.applicationInfo.primaryCpuAbi != null &&
5589                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5590                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5591                    for (int userId : userIds) {
5592                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5593                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5594                                    "Failed linking native library dir (user=" + userId + ")");
5595                        }
5596                    }
5597                }
5598            }
5599        }
5600
5601        // This is a special case for the "system" package, where the ABI is
5602        // dictated by the zygote configuration (and init.rc). We should keep track
5603        // of this ABI so that we can deal with "normal" applications that run under
5604        // the same UID correctly.
5605        if (mPlatformPackage == pkg) {
5606            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5607                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5608        }
5609
5610        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5611        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5612        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5613        // Copy the derived override back to the parsed package, so that we can
5614        // update the package settings accordingly.
5615        pkg.cpuAbiOverride = cpuAbiOverride;
5616
5617        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5618                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5619                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5620
5621        // Push the derived path down into PackageSettings so we know what to
5622        // clean up at uninstall time.
5623        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5624
5625        if (DEBUG_ABI_SELECTION) {
5626            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5627                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5628                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5629        }
5630
5631        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5632            // We don't do this here during boot because we can do it all
5633            // at once after scanning all existing packages.
5634            //
5635            // We also do this *before* we perform dexopt on this package, so that
5636            // we can avoid redundant dexopts, and also to make sure we've got the
5637            // code and package path correct.
5638            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5639                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5640        }
5641
5642        if ((scanFlags&SCAN_NO_DEX) == 0) {
5643            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5644                    == DEX_OPT_FAILED) {
5645                if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5646                    removeDataDirsLI(pkg.packageName);
5647                }
5648
5649                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5650            }
5651        }
5652
5653        if (mFactoryTest && pkg.requestedPermissions.contains(
5654                android.Manifest.permission.FACTORY_TEST)) {
5655            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5656        }
5657
5658        ArrayList<PackageParser.Package> clientLibPkgs = null;
5659
5660        // writer
5661        synchronized (mPackages) {
5662            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5663                // Only system apps can add new shared libraries.
5664                if (pkg.libraryNames != null) {
5665                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5666                        String name = pkg.libraryNames.get(i);
5667                        boolean allowed = false;
5668                        if (isUpdatedSystemApp(pkg)) {
5669                            // New library entries can only be added through the
5670                            // system image.  This is important to get rid of a lot
5671                            // of nasty edge cases: for example if we allowed a non-
5672                            // system update of the app to add a library, then uninstalling
5673                            // the update would make the library go away, and assumptions
5674                            // we made such as through app install filtering would now
5675                            // have allowed apps on the device which aren't compatible
5676                            // with it.  Better to just have the restriction here, be
5677                            // conservative, and create many fewer cases that can negatively
5678                            // impact the user experience.
5679                            final PackageSetting sysPs = mSettings
5680                                    .getDisabledSystemPkgLPr(pkg.packageName);
5681                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5682                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5683                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5684                                        allowed = true;
5685                                        allowed = true;
5686                                        break;
5687                                    }
5688                                }
5689                            }
5690                        } else {
5691                            allowed = true;
5692                        }
5693                        if (allowed) {
5694                            if (!mSharedLibraries.containsKey(name)) {
5695                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5696                            } else if (!name.equals(pkg.packageName)) {
5697                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5698                                        + name + " already exists; skipping");
5699                            }
5700                        } else {
5701                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5702                                    + name + " that is not declared on system image; skipping");
5703                        }
5704                    }
5705                    if ((scanFlags&SCAN_BOOTING) == 0) {
5706                        // If we are not booting, we need to update any applications
5707                        // that are clients of our shared library.  If we are booting,
5708                        // this will all be done once the scan is complete.
5709                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5710                    }
5711                }
5712            }
5713        }
5714
5715        // We also need to dexopt any apps that are dependent on this library.  Note that
5716        // if these fail, we should abort the install since installing the library will
5717        // result in some apps being broken.
5718        if (clientLibPkgs != null) {
5719            if ((scanFlags&SCAN_NO_DEX) == 0) {
5720                for (int i=0; i<clientLibPkgs.size(); i++) {
5721                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5722                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5723                            forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5724                            == DEX_OPT_FAILED) {
5725                        if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5726                            removeDataDirsLI(pkg.packageName);
5727                        }
5728
5729                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5730                                "scanPackageLI failed to dexopt clientLibPkgs");
5731                    }
5732                }
5733            }
5734        }
5735
5736        // Request the ActivityManager to kill the process(only for existing packages)
5737        // so that we do not end up in a confused state while the user is still using the older
5738        // version of the application while the new one gets installed.
5739        if ((scanFlags & SCAN_REPLACING) != 0) {
5740            killApplication(pkg.applicationInfo.packageName,
5741                        pkg.applicationInfo.uid, "update pkg");
5742        }
5743
5744        // Also need to kill any apps that are dependent on the library.
5745        if (clientLibPkgs != null) {
5746            for (int i=0; i<clientLibPkgs.size(); i++) {
5747                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5748                killApplication(clientPkg.applicationInfo.packageName,
5749                        clientPkg.applicationInfo.uid, "update lib");
5750            }
5751        }
5752
5753        // writer
5754        synchronized (mPackages) {
5755            // We don't expect installation to fail beyond this point
5756
5757            // Add the new setting to mSettings
5758            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5759            // Add the new setting to mPackages
5760            mPackages.put(pkg.applicationInfo.packageName, pkg);
5761            // Make sure we don't accidentally delete its data.
5762            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5763            while (iter.hasNext()) {
5764                PackageCleanItem item = iter.next();
5765                if (pkgName.equals(item.packageName)) {
5766                    iter.remove();
5767                }
5768            }
5769
5770            // Take care of first install / last update times.
5771            if (currentTime != 0) {
5772                if (pkgSetting.firstInstallTime == 0) {
5773                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5774                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5775                    pkgSetting.lastUpdateTime = currentTime;
5776                }
5777            } else if (pkgSetting.firstInstallTime == 0) {
5778                // We need *something*.  Take time time stamp of the file.
5779                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5780            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5781                if (scanFileTime != pkgSetting.timeStamp) {
5782                    // A package on the system image has changed; consider this
5783                    // to be an update.
5784                    pkgSetting.lastUpdateTime = scanFileTime;
5785                }
5786            }
5787
5788            // Add the package's KeySets to the global KeySetManagerService
5789            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5790            try {
5791                // Old KeySetData no longer valid.
5792                ksms.removeAppKeySetDataLPw(pkg.packageName);
5793                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5794                if (pkg.mKeySetMapping != null) {
5795                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5796                            pkg.mKeySetMapping.entrySet()) {
5797                        if (entry.getValue() != null) {
5798                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5799                                                          entry.getValue(), entry.getKey());
5800                        }
5801                    }
5802                    if (pkg.mUpgradeKeySets != null) {
5803                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5804                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5805                        }
5806                    }
5807                }
5808            } catch (NullPointerException e) {
5809                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5810            } catch (IllegalArgumentException e) {
5811                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5812            }
5813
5814            int N = pkg.providers.size();
5815            StringBuilder r = null;
5816            int i;
5817            for (i=0; i<N; i++) {
5818                PackageParser.Provider p = pkg.providers.get(i);
5819                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5820                        p.info.processName, pkg.applicationInfo.uid);
5821                mProviders.addProvider(p);
5822                p.syncable = p.info.isSyncable;
5823                if (p.info.authority != null) {
5824                    String names[] = p.info.authority.split(";");
5825                    p.info.authority = null;
5826                    for (int j = 0; j < names.length; j++) {
5827                        if (j == 1 && p.syncable) {
5828                            // We only want the first authority for a provider to possibly be
5829                            // syncable, so if we already added this provider using a different
5830                            // authority clear the syncable flag. We copy the provider before
5831                            // changing it because the mProviders object contains a reference
5832                            // to a provider that we don't want to change.
5833                            // Only do this for the second authority since the resulting provider
5834                            // object can be the same for all future authorities for this provider.
5835                            p = new PackageParser.Provider(p);
5836                            p.syncable = false;
5837                        }
5838                        if (!mProvidersByAuthority.containsKey(names[j])) {
5839                            mProvidersByAuthority.put(names[j], p);
5840                            if (p.info.authority == null) {
5841                                p.info.authority = names[j];
5842                            } else {
5843                                p.info.authority = p.info.authority + ";" + names[j];
5844                            }
5845                            if (DEBUG_PACKAGE_SCANNING) {
5846                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5847                                    Log.d(TAG, "Registered content provider: " + names[j]
5848                                            + ", className = " + p.info.name + ", isSyncable = "
5849                                            + p.info.isSyncable);
5850                            }
5851                        } else {
5852                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5853                            Slog.w(TAG, "Skipping provider name " + names[j] +
5854                                    " (in package " + pkg.applicationInfo.packageName +
5855                                    "): name already used by "
5856                                    + ((other != null && other.getComponentName() != null)
5857                                            ? other.getComponentName().getPackageName() : "?"));
5858                        }
5859                    }
5860                }
5861                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5862                    if (r == null) {
5863                        r = new StringBuilder(256);
5864                    } else {
5865                        r.append(' ');
5866                    }
5867                    r.append(p.info.name);
5868                }
5869            }
5870            if (r != null) {
5871                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5872            }
5873
5874            N = pkg.services.size();
5875            r = null;
5876            for (i=0; i<N; i++) {
5877                PackageParser.Service s = pkg.services.get(i);
5878                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5879                        s.info.processName, pkg.applicationInfo.uid);
5880                mServices.addService(s);
5881                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5882                    if (r == null) {
5883                        r = new StringBuilder(256);
5884                    } else {
5885                        r.append(' ');
5886                    }
5887                    r.append(s.info.name);
5888                }
5889            }
5890            if (r != null) {
5891                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5892            }
5893
5894            N = pkg.receivers.size();
5895            r = null;
5896            for (i=0; i<N; i++) {
5897                PackageParser.Activity a = pkg.receivers.get(i);
5898                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5899                        a.info.processName, pkg.applicationInfo.uid);
5900                mReceivers.addActivity(a, "receiver");
5901                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5902                    if (r == null) {
5903                        r = new StringBuilder(256);
5904                    } else {
5905                        r.append(' ');
5906                    }
5907                    r.append(a.info.name);
5908                }
5909            }
5910            if (r != null) {
5911                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5912            }
5913
5914            N = pkg.activities.size();
5915            r = null;
5916            for (i=0; i<N; i++) {
5917                PackageParser.Activity a = pkg.activities.get(i);
5918                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5919                        a.info.processName, pkg.applicationInfo.uid);
5920                mActivities.addActivity(a, "activity");
5921                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5922                    if (r == null) {
5923                        r = new StringBuilder(256);
5924                    } else {
5925                        r.append(' ');
5926                    }
5927                    r.append(a.info.name);
5928                }
5929            }
5930            if (r != null) {
5931                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5932            }
5933
5934            N = pkg.permissionGroups.size();
5935            r = null;
5936            for (i=0; i<N; i++) {
5937                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5938                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5939                if (cur == null) {
5940                    mPermissionGroups.put(pg.info.name, pg);
5941                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5942                        if (r == null) {
5943                            r = new StringBuilder(256);
5944                        } else {
5945                            r.append(' ');
5946                        }
5947                        r.append(pg.info.name);
5948                    }
5949                } else {
5950                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5951                            + pg.info.packageName + " ignored: original from "
5952                            + cur.info.packageName);
5953                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5954                        if (r == null) {
5955                            r = new StringBuilder(256);
5956                        } else {
5957                            r.append(' ');
5958                        }
5959                        r.append("DUP:");
5960                        r.append(pg.info.name);
5961                    }
5962                }
5963            }
5964            if (r != null) {
5965                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5966            }
5967
5968            N = pkg.permissions.size();
5969            r = null;
5970            for (i=0; i<N; i++) {
5971                PackageParser.Permission p = pkg.permissions.get(i);
5972                HashMap<String, BasePermission> permissionMap =
5973                        p.tree ? mSettings.mPermissionTrees
5974                        : mSettings.mPermissions;
5975                p.group = mPermissionGroups.get(p.info.group);
5976                if (p.info.group == null || p.group != null) {
5977                    BasePermission bp = permissionMap.get(p.info.name);
5978                    if (bp == null) {
5979                        bp = new BasePermission(p.info.name, p.info.packageName,
5980                                BasePermission.TYPE_NORMAL);
5981                        permissionMap.put(p.info.name, bp);
5982                    }
5983                    if (bp.perm == null) {
5984                        if (bp.sourcePackage != null
5985                                && !bp.sourcePackage.equals(p.info.packageName)) {
5986                            // If this is a permission that was formerly defined by a non-system
5987                            // app, but is now defined by a system app (following an upgrade),
5988                            // discard the previous declaration and consider the system's to be
5989                            // canonical.
5990                            if (isSystemApp(p.owner)) {
5991                                String msg = "New decl " + p.owner + " of permission  "
5992                                        + p.info.name + " is system";
5993                                reportSettingsProblem(Log.WARN, msg);
5994                                bp.sourcePackage = null;
5995                            }
5996                        }
5997                        if (bp.sourcePackage == null
5998                                || bp.sourcePackage.equals(p.info.packageName)) {
5999                            BasePermission tree = findPermissionTreeLP(p.info.name);
6000                            if (tree == null
6001                                    || tree.sourcePackage.equals(p.info.packageName)) {
6002                                bp.packageSetting = pkgSetting;
6003                                bp.perm = p;
6004                                bp.uid = pkg.applicationInfo.uid;
6005                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6006                                    if (r == null) {
6007                                        r = new StringBuilder(256);
6008                                    } else {
6009                                        r.append(' ');
6010                                    }
6011                                    r.append(p.info.name);
6012                                }
6013                            } else {
6014                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6015                                        + p.info.packageName + " ignored: base tree "
6016                                        + tree.name + " is from package "
6017                                        + tree.sourcePackage);
6018                            }
6019                        } else {
6020                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6021                                    + p.info.packageName + " ignored: original from "
6022                                    + bp.sourcePackage);
6023                        }
6024                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6025                        if (r == null) {
6026                            r = new StringBuilder(256);
6027                        } else {
6028                            r.append(' ');
6029                        }
6030                        r.append("DUP:");
6031                        r.append(p.info.name);
6032                    }
6033                    if (bp.perm == p) {
6034                        bp.protectionLevel = p.info.protectionLevel;
6035                    }
6036                } else {
6037                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6038                            + p.info.packageName + " ignored: no group "
6039                            + p.group);
6040                }
6041            }
6042            if (r != null) {
6043                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6044            }
6045
6046            N = pkg.instrumentation.size();
6047            r = null;
6048            for (i=0; i<N; i++) {
6049                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6050                a.info.packageName = pkg.applicationInfo.packageName;
6051                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6052                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6053                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6054                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6055                a.info.dataDir = pkg.applicationInfo.dataDir;
6056
6057                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6058                // need other information about the application, like the ABI and what not ?
6059                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6060                mInstrumentation.put(a.getComponentName(), a);
6061                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6062                    if (r == null) {
6063                        r = new StringBuilder(256);
6064                    } else {
6065                        r.append(' ');
6066                    }
6067                    r.append(a.info.name);
6068                }
6069            }
6070            if (r != null) {
6071                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6072            }
6073
6074            if (pkg.protectedBroadcasts != null) {
6075                N = pkg.protectedBroadcasts.size();
6076                for (i=0; i<N; i++) {
6077                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6078                }
6079            }
6080
6081            pkgSetting.setTimeStamp(scanFileTime);
6082
6083            // Create idmap files for pairs of (packages, overlay packages).
6084            // Note: "android", ie framework-res.apk, is handled by native layers.
6085            if (pkg.mOverlayTarget != null) {
6086                // This is an overlay package.
6087                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6088                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6089                        mOverlays.put(pkg.mOverlayTarget,
6090                                new HashMap<String, PackageParser.Package>());
6091                    }
6092                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6093                    map.put(pkg.packageName, pkg);
6094                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6095                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6096                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6097                                "scanPackageLI failed to createIdmap");
6098                    }
6099                }
6100            } else if (mOverlays.containsKey(pkg.packageName) &&
6101                    !pkg.packageName.equals("android")) {
6102                // This is a regular package, with one or more known overlay packages.
6103                createIdmapsForPackageLI(pkg);
6104            }
6105        }
6106
6107        return pkg;
6108    }
6109
6110    /**
6111     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6112     * i.e, so that all packages can be run inside a single process if required.
6113     *
6114     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6115     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6116     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6117     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6118     * updating a package that belongs to a shared user.
6119     *
6120     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6121     * adds unnecessary complexity.
6122     */
6123    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6124            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6125        String requiredInstructionSet = null;
6126        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6127            requiredInstructionSet = VMRuntime.getInstructionSet(
6128                     scannedPackage.applicationInfo.primaryCpuAbi);
6129        }
6130
6131        PackageSetting requirer = null;
6132        for (PackageSetting ps : packagesForUser) {
6133            // If packagesForUser contains scannedPackage, we skip it. This will happen
6134            // when scannedPackage is an update of an existing package. Without this check,
6135            // we will never be able to change the ABI of any package belonging to a shared
6136            // user, even if it's compatible with other packages.
6137            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6138                if (ps.primaryCpuAbiString == null) {
6139                    continue;
6140                }
6141
6142                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6143                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6144                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6145                    // this but there's not much we can do.
6146                    String errorMessage = "Instruction set mismatch, "
6147                            + ((requirer == null) ? "[caller]" : requirer)
6148                            + " requires " + requiredInstructionSet + " whereas " + ps
6149                            + " requires " + instructionSet;
6150                    Slog.w(TAG, errorMessage);
6151                }
6152
6153                if (requiredInstructionSet == null) {
6154                    requiredInstructionSet = instructionSet;
6155                    requirer = ps;
6156                }
6157            }
6158        }
6159
6160        if (requiredInstructionSet != null) {
6161            String adjustedAbi;
6162            if (requirer != null) {
6163                // requirer != null implies that either scannedPackage was null or that scannedPackage
6164                // did not require an ABI, in which case we have to adjust scannedPackage to match
6165                // the ABI of the set (which is the same as requirer's ABI)
6166                adjustedAbi = requirer.primaryCpuAbiString;
6167                if (scannedPackage != null) {
6168                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6169                }
6170            } else {
6171                // requirer == null implies that we're updating all ABIs in the set to
6172                // match scannedPackage.
6173                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6174            }
6175
6176            for (PackageSetting ps : packagesForUser) {
6177                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6178                    if (ps.primaryCpuAbiString != null) {
6179                        continue;
6180                    }
6181
6182                    ps.primaryCpuAbiString = adjustedAbi;
6183                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6184                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6185                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6186
6187                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6188                                deferDexOpt, true) == DEX_OPT_FAILED) {
6189                            ps.primaryCpuAbiString = null;
6190                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6191                            return;
6192                        } else {
6193                            mInstaller.rmdex(ps.codePathString,
6194                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6195                        }
6196                    }
6197                }
6198            }
6199        }
6200    }
6201
6202    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6203        synchronized (mPackages) {
6204            mResolverReplaced = true;
6205            // Set up information for custom user intent resolution activity.
6206            mResolveActivity.applicationInfo = pkg.applicationInfo;
6207            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6208            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6209            mResolveActivity.processName = null;
6210            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6211            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6212                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6213            mResolveActivity.theme = 0;
6214            mResolveActivity.exported = true;
6215            mResolveActivity.enabled = true;
6216            mResolveInfo.activityInfo = mResolveActivity;
6217            mResolveInfo.priority = 0;
6218            mResolveInfo.preferredOrder = 0;
6219            mResolveInfo.match = 0;
6220            mResolveComponentName = mCustomResolverComponentName;
6221            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6222                    mResolveComponentName);
6223        }
6224    }
6225
6226    private static String calculateBundledApkRoot(final String codePathString) {
6227        final File codePath = new File(codePathString);
6228        final File codeRoot;
6229        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6230            codeRoot = Environment.getRootDirectory();
6231        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6232            codeRoot = Environment.getOemDirectory();
6233        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6234            codeRoot = Environment.getVendorDirectory();
6235        } else {
6236            // Unrecognized code path; take its top real segment as the apk root:
6237            // e.g. /something/app/blah.apk => /something
6238            try {
6239                File f = codePath.getCanonicalFile();
6240                File parent = f.getParentFile();    // non-null because codePath is a file
6241                File tmp;
6242                while ((tmp = parent.getParentFile()) != null) {
6243                    f = parent;
6244                    parent = tmp;
6245                }
6246                codeRoot = f;
6247                Slog.w(TAG, "Unrecognized code path "
6248                        + codePath + " - using " + codeRoot);
6249            } catch (IOException e) {
6250                // Can't canonicalize the code path -- shenanigans?
6251                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6252                return Environment.getRootDirectory().getPath();
6253            }
6254        }
6255        return codeRoot.getPath();
6256    }
6257
6258    /**
6259     * Derive and set the location of native libraries for the given package,
6260     * which varies depending on where and how the package was installed.
6261     */
6262    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6263        final ApplicationInfo info = pkg.applicationInfo;
6264        final String codePath = pkg.codePath;
6265        final File codeFile = new File(codePath);
6266        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6267        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6268
6269        info.nativeLibraryRootDir = null;
6270        info.nativeLibraryRootRequiresIsa = false;
6271        info.nativeLibraryDir = null;
6272        info.secondaryNativeLibraryDir = null;
6273
6274        if (isApkFile(codeFile)) {
6275            // Monolithic install
6276            if (bundledApp) {
6277                // If "/system/lib64/apkname" exists, assume that is the per-package
6278                // native library directory to use; otherwise use "/system/lib/apkname".
6279                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6280                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6281                        getPrimaryInstructionSet(info));
6282
6283                // This is a bundled system app so choose the path based on the ABI.
6284                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6285                // is just the default path.
6286                final String apkName = deriveCodePathName(codePath);
6287                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6288                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6289                        apkName).getAbsolutePath();
6290
6291                if (info.secondaryCpuAbi != null) {
6292                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6293                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6294                            secondaryLibDir, apkName).getAbsolutePath();
6295                }
6296            } else if (asecApp) {
6297                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6298                        .getAbsolutePath();
6299            } else {
6300                final String apkName = deriveCodePathName(codePath);
6301                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6302                        .getAbsolutePath();
6303            }
6304
6305            info.nativeLibraryRootRequiresIsa = false;
6306            info.nativeLibraryDir = info.nativeLibraryRootDir;
6307        } else {
6308            // Cluster install
6309            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6310            info.nativeLibraryRootRequiresIsa = true;
6311
6312            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6313                    getPrimaryInstructionSet(info)).getAbsolutePath();
6314
6315            if (info.secondaryCpuAbi != null) {
6316                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6317                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6318            }
6319        }
6320    }
6321
6322    /**
6323     * Calculate the abis and roots for a bundled app. These can uniquely
6324     * be determined from the contents of the system partition, i.e whether
6325     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6326     * of this information, and instead assume that the system was built
6327     * sensibly.
6328     */
6329    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6330                                           PackageSetting pkgSetting) {
6331        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6332
6333        // If "/system/lib64/apkname" exists, assume that is the per-package
6334        // native library directory to use; otherwise use "/system/lib/apkname".
6335        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6336        setBundledAppAbi(pkg, apkRoot, apkName);
6337        // pkgSetting might be null during rescan following uninstall of updates
6338        // to a bundled app, so accommodate that possibility.  The settings in
6339        // that case will be established later from the parsed package.
6340        //
6341        // If the settings aren't null, sync them up with what we've just derived.
6342        // note that apkRoot isn't stored in the package settings.
6343        if (pkgSetting != null) {
6344            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6345            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6346        }
6347    }
6348
6349    /**
6350     * Deduces the ABI of a bundled app and sets the relevant fields on the
6351     * parsed pkg object.
6352     *
6353     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6354     *        under which system libraries are installed.
6355     * @param apkName the name of the installed package.
6356     */
6357    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6358        final File codeFile = new File(pkg.codePath);
6359
6360        final boolean has64BitLibs;
6361        final boolean has32BitLibs;
6362        if (isApkFile(codeFile)) {
6363            // Monolithic install
6364            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6365            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6366        } else {
6367            // Cluster install
6368            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6369            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6370                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6371                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6372                has64BitLibs = (new File(rootDir, isa)).exists();
6373            } else {
6374                has64BitLibs = false;
6375            }
6376            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6377                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6378                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6379                has32BitLibs = (new File(rootDir, isa)).exists();
6380            } else {
6381                has32BitLibs = false;
6382            }
6383        }
6384
6385        if (has64BitLibs && !has32BitLibs) {
6386            // The package has 64 bit libs, but not 32 bit libs. Its primary
6387            // ABI should be 64 bit. We can safely assume here that the bundled
6388            // native libraries correspond to the most preferred ABI in the list.
6389
6390            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6391            pkg.applicationInfo.secondaryCpuAbi = null;
6392        } else if (has32BitLibs && !has64BitLibs) {
6393            // The package has 32 bit libs but not 64 bit libs. Its primary
6394            // ABI should be 32 bit.
6395
6396            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6397            pkg.applicationInfo.secondaryCpuAbi = null;
6398        } else if (has32BitLibs && has64BitLibs) {
6399            // The application has both 64 and 32 bit bundled libraries. We check
6400            // here that the app declares multiArch support, and warn if it doesn't.
6401            //
6402            // We will be lenient here and record both ABIs. The primary will be the
6403            // ABI that's higher on the list, i.e, a device that's configured to prefer
6404            // 64 bit apps will see a 64 bit primary ABI,
6405
6406            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6407                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6408            }
6409
6410            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6411                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6412                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6413            } else {
6414                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6415                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6416            }
6417        } else {
6418            pkg.applicationInfo.primaryCpuAbi = null;
6419            pkg.applicationInfo.secondaryCpuAbi = null;
6420        }
6421    }
6422
6423    private void killApplication(String pkgName, int appId, String reason) {
6424        // Request the ActivityManager to kill the process(only for existing packages)
6425        // so that we do not end up in a confused state while the user is still using the older
6426        // version of the application while the new one gets installed.
6427        IActivityManager am = ActivityManagerNative.getDefault();
6428        if (am != null) {
6429            try {
6430                am.killApplicationWithAppId(pkgName, appId, reason);
6431            } catch (RemoteException e) {
6432            }
6433        }
6434    }
6435
6436    void removePackageLI(PackageSetting ps, boolean chatty) {
6437        if (DEBUG_INSTALL) {
6438            if (chatty)
6439                Log.d(TAG, "Removing package " + ps.name);
6440        }
6441
6442        // writer
6443        synchronized (mPackages) {
6444            mPackages.remove(ps.name);
6445            final PackageParser.Package pkg = ps.pkg;
6446            if (pkg != null) {
6447                cleanPackageDataStructuresLILPw(pkg, chatty);
6448            }
6449        }
6450    }
6451
6452    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6453        if (DEBUG_INSTALL) {
6454            if (chatty)
6455                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6456        }
6457
6458        // writer
6459        synchronized (mPackages) {
6460            mPackages.remove(pkg.applicationInfo.packageName);
6461            cleanPackageDataStructuresLILPw(pkg, chatty);
6462        }
6463    }
6464
6465    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6466        int N = pkg.providers.size();
6467        StringBuilder r = null;
6468        int i;
6469        for (i=0; i<N; i++) {
6470            PackageParser.Provider p = pkg.providers.get(i);
6471            mProviders.removeProvider(p);
6472            if (p.info.authority == null) {
6473
6474                /* There was another ContentProvider with this authority when
6475                 * this app was installed so this authority is null,
6476                 * Ignore it as we don't have to unregister the provider.
6477                 */
6478                continue;
6479            }
6480            String names[] = p.info.authority.split(";");
6481            for (int j = 0; j < names.length; j++) {
6482                if (mProvidersByAuthority.get(names[j]) == p) {
6483                    mProvidersByAuthority.remove(names[j]);
6484                    if (DEBUG_REMOVE) {
6485                        if (chatty)
6486                            Log.d(TAG, "Unregistered content provider: " + names[j]
6487                                    + ", className = " + p.info.name + ", isSyncable = "
6488                                    + p.info.isSyncable);
6489                    }
6490                }
6491            }
6492            if (DEBUG_REMOVE && chatty) {
6493                if (r == null) {
6494                    r = new StringBuilder(256);
6495                } else {
6496                    r.append(' ');
6497                }
6498                r.append(p.info.name);
6499            }
6500        }
6501        if (r != null) {
6502            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6503        }
6504
6505        N = pkg.services.size();
6506        r = null;
6507        for (i=0; i<N; i++) {
6508            PackageParser.Service s = pkg.services.get(i);
6509            mServices.removeService(s);
6510            if (chatty) {
6511                if (r == null) {
6512                    r = new StringBuilder(256);
6513                } else {
6514                    r.append(' ');
6515                }
6516                r.append(s.info.name);
6517            }
6518        }
6519        if (r != null) {
6520            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6521        }
6522
6523        N = pkg.receivers.size();
6524        r = null;
6525        for (i=0; i<N; i++) {
6526            PackageParser.Activity a = pkg.receivers.get(i);
6527            mReceivers.removeActivity(a, "receiver");
6528            if (DEBUG_REMOVE && chatty) {
6529                if (r == null) {
6530                    r = new StringBuilder(256);
6531                } else {
6532                    r.append(' ');
6533                }
6534                r.append(a.info.name);
6535            }
6536        }
6537        if (r != null) {
6538            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6539        }
6540
6541        N = pkg.activities.size();
6542        r = null;
6543        for (i=0; i<N; i++) {
6544            PackageParser.Activity a = pkg.activities.get(i);
6545            mActivities.removeActivity(a, "activity");
6546            if (DEBUG_REMOVE && chatty) {
6547                if (r == null) {
6548                    r = new StringBuilder(256);
6549                } else {
6550                    r.append(' ');
6551                }
6552                r.append(a.info.name);
6553            }
6554        }
6555        if (r != null) {
6556            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6557        }
6558
6559        N = pkg.permissions.size();
6560        r = null;
6561        for (i=0; i<N; i++) {
6562            PackageParser.Permission p = pkg.permissions.get(i);
6563            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6564            if (bp == null) {
6565                bp = mSettings.mPermissionTrees.get(p.info.name);
6566            }
6567            if (bp != null && bp.perm == p) {
6568                bp.perm = null;
6569                if (DEBUG_REMOVE && chatty) {
6570                    if (r == null) {
6571                        r = new StringBuilder(256);
6572                    } else {
6573                        r.append(' ');
6574                    }
6575                    r.append(p.info.name);
6576                }
6577            }
6578            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6579                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6580                if (appOpPerms != null) {
6581                    appOpPerms.remove(pkg.packageName);
6582                }
6583            }
6584        }
6585        if (r != null) {
6586            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6587        }
6588
6589        N = pkg.requestedPermissions.size();
6590        r = null;
6591        for (i=0; i<N; i++) {
6592            String perm = pkg.requestedPermissions.get(i);
6593            BasePermission bp = mSettings.mPermissions.get(perm);
6594            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6595                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6596                if (appOpPerms != null) {
6597                    appOpPerms.remove(pkg.packageName);
6598                    if (appOpPerms.isEmpty()) {
6599                        mAppOpPermissionPackages.remove(perm);
6600                    }
6601                }
6602            }
6603        }
6604        if (r != null) {
6605            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6606        }
6607
6608        N = pkg.instrumentation.size();
6609        r = null;
6610        for (i=0; i<N; i++) {
6611            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6612            mInstrumentation.remove(a.getComponentName());
6613            if (DEBUG_REMOVE && chatty) {
6614                if (r == null) {
6615                    r = new StringBuilder(256);
6616                } else {
6617                    r.append(' ');
6618                }
6619                r.append(a.info.name);
6620            }
6621        }
6622        if (r != null) {
6623            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6624        }
6625
6626        r = null;
6627        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6628            // Only system apps can hold shared libraries.
6629            if (pkg.libraryNames != null) {
6630                for (i=0; i<pkg.libraryNames.size(); i++) {
6631                    String name = pkg.libraryNames.get(i);
6632                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6633                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6634                        mSharedLibraries.remove(name);
6635                        if (DEBUG_REMOVE && chatty) {
6636                            if (r == null) {
6637                                r = new StringBuilder(256);
6638                            } else {
6639                                r.append(' ');
6640                            }
6641                            r.append(name);
6642                        }
6643                    }
6644                }
6645            }
6646        }
6647        if (r != null) {
6648            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6649        }
6650    }
6651
6652    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6653        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6654            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6655                return true;
6656            }
6657        }
6658        return false;
6659    }
6660
6661    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6662    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6663    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6664
6665    private void updatePermissionsLPw(String changingPkg,
6666            PackageParser.Package pkgInfo, int flags) {
6667        // Make sure there are no dangling permission trees.
6668        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6669        while (it.hasNext()) {
6670            final BasePermission bp = it.next();
6671            if (bp.packageSetting == null) {
6672                // We may not yet have parsed the package, so just see if
6673                // we still know about its settings.
6674                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6675            }
6676            if (bp.packageSetting == null) {
6677                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6678                        + " from package " + bp.sourcePackage);
6679                it.remove();
6680            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6681                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6682                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6683                            + " from package " + bp.sourcePackage);
6684                    flags |= UPDATE_PERMISSIONS_ALL;
6685                    it.remove();
6686                }
6687            }
6688        }
6689
6690        // Make sure all dynamic permissions have been assigned to a package,
6691        // and make sure there are no dangling permissions.
6692        it = mSettings.mPermissions.values().iterator();
6693        while (it.hasNext()) {
6694            final BasePermission bp = it.next();
6695            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6696                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6697                        + bp.name + " pkg=" + bp.sourcePackage
6698                        + " info=" + bp.pendingInfo);
6699                if (bp.packageSetting == null && bp.pendingInfo != null) {
6700                    final BasePermission tree = findPermissionTreeLP(bp.name);
6701                    if (tree != null && tree.perm != null) {
6702                        bp.packageSetting = tree.packageSetting;
6703                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6704                                new PermissionInfo(bp.pendingInfo));
6705                        bp.perm.info.packageName = tree.perm.info.packageName;
6706                        bp.perm.info.name = bp.name;
6707                        bp.uid = tree.uid;
6708                    }
6709                }
6710            }
6711            if (bp.packageSetting == null) {
6712                // We may not yet have parsed the package, so just see if
6713                // we still know about its settings.
6714                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6715            }
6716            if (bp.packageSetting == null) {
6717                Slog.w(TAG, "Removing dangling permission: " + bp.name
6718                        + " from package " + bp.sourcePackage);
6719                it.remove();
6720            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6721                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6722                    Slog.i(TAG, "Removing old permission: " + bp.name
6723                            + " from package " + bp.sourcePackage);
6724                    flags |= UPDATE_PERMISSIONS_ALL;
6725                    it.remove();
6726                }
6727            }
6728        }
6729
6730        // Now update the permissions for all packages, in particular
6731        // replace the granted permissions of the system packages.
6732        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6733            for (PackageParser.Package pkg : mPackages.values()) {
6734                if (pkg != pkgInfo) {
6735                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6736                }
6737            }
6738        }
6739
6740        if (pkgInfo != null) {
6741            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6742        }
6743    }
6744
6745    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6746        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6747        if (ps == null) {
6748            return;
6749        }
6750        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6751        HashSet<String> origPermissions = gp.grantedPermissions;
6752        boolean changedPermission = false;
6753
6754        if (replace) {
6755            ps.permissionsFixed = false;
6756            if (gp == ps) {
6757                origPermissions = new HashSet<String>(gp.grantedPermissions);
6758                gp.grantedPermissions.clear();
6759                gp.gids = mGlobalGids;
6760            }
6761        }
6762
6763        if (gp.gids == null) {
6764            gp.gids = mGlobalGids;
6765        }
6766
6767        final int N = pkg.requestedPermissions.size();
6768        for (int i=0; i<N; i++) {
6769            final String name = pkg.requestedPermissions.get(i);
6770            final boolean required = pkg.requestedPermissionsRequired.get(i);
6771            final BasePermission bp = mSettings.mPermissions.get(name);
6772            if (DEBUG_INSTALL) {
6773                if (gp != ps) {
6774                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6775                }
6776            }
6777
6778            if (bp == null || bp.packageSetting == null) {
6779                Slog.w(TAG, "Unknown permission " + name
6780                        + " in package " + pkg.packageName);
6781                continue;
6782            }
6783
6784            final String perm = bp.name;
6785            boolean allowed;
6786            boolean allowedSig = false;
6787            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6788                // Keep track of app op permissions.
6789                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6790                if (pkgs == null) {
6791                    pkgs = new ArraySet<>();
6792                    mAppOpPermissionPackages.put(bp.name, pkgs);
6793                }
6794                pkgs.add(pkg.packageName);
6795            }
6796            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6797            if (level == PermissionInfo.PROTECTION_NORMAL
6798                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6799                // We grant a normal or dangerous permission if any of the following
6800                // are true:
6801                // 1) The permission is required
6802                // 2) The permission is optional, but was granted in the past
6803                // 3) The permission is optional, but was requested by an
6804                //    app in /system (not /data)
6805                //
6806                // Otherwise, reject the permission.
6807                allowed = (required || origPermissions.contains(perm)
6808                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6809            } else if (bp.packageSetting == null) {
6810                // This permission is invalid; skip it.
6811                allowed = false;
6812            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6813                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6814                if (allowed) {
6815                    allowedSig = true;
6816                }
6817            } else {
6818                allowed = false;
6819            }
6820            if (DEBUG_INSTALL) {
6821                if (gp != ps) {
6822                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6823                }
6824            }
6825            if (allowed) {
6826                if (!isSystemApp(ps) && ps.permissionsFixed) {
6827                    // If this is an existing, non-system package, then
6828                    // we can't add any new permissions to it.
6829                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6830                        // Except...  if this is a permission that was added
6831                        // to the platform (note: need to only do this when
6832                        // updating the platform).
6833                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6834                    }
6835                }
6836                if (allowed) {
6837                    if (!gp.grantedPermissions.contains(perm)) {
6838                        changedPermission = true;
6839                        gp.grantedPermissions.add(perm);
6840                        gp.gids = appendInts(gp.gids, bp.gids);
6841                    } else if (!ps.haveGids) {
6842                        gp.gids = appendInts(gp.gids, bp.gids);
6843                    }
6844                } else {
6845                    Slog.w(TAG, "Not granting permission " + perm
6846                            + " to package " + pkg.packageName
6847                            + " because it was previously installed without");
6848                }
6849            } else {
6850                if (gp.grantedPermissions.remove(perm)) {
6851                    changedPermission = true;
6852                    gp.gids = removeInts(gp.gids, bp.gids);
6853                    Slog.i(TAG, "Un-granting permission " + perm
6854                            + " from package " + pkg.packageName
6855                            + " (protectionLevel=" + bp.protectionLevel
6856                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6857                            + ")");
6858                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6859                    // Don't print warning for app op permissions, since it is fine for them
6860                    // not to be granted, there is a UI for the user to decide.
6861                    Slog.w(TAG, "Not granting permission " + perm
6862                            + " to package " + pkg.packageName
6863                            + " (protectionLevel=" + bp.protectionLevel
6864                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6865                            + ")");
6866                }
6867            }
6868        }
6869
6870        if ((changedPermission || replace) && !ps.permissionsFixed &&
6871                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6872            // This is the first that we have heard about this package, so the
6873            // permissions we have now selected are fixed until explicitly
6874            // changed.
6875            ps.permissionsFixed = true;
6876        }
6877        ps.haveGids = true;
6878    }
6879
6880    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6881        boolean allowed = false;
6882        final int NP = PackageParser.NEW_PERMISSIONS.length;
6883        for (int ip=0; ip<NP; ip++) {
6884            final PackageParser.NewPermissionInfo npi
6885                    = PackageParser.NEW_PERMISSIONS[ip];
6886            if (npi.name.equals(perm)
6887                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6888                allowed = true;
6889                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6890                        + pkg.packageName);
6891                break;
6892            }
6893        }
6894        return allowed;
6895    }
6896
6897    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6898                                          BasePermission bp, HashSet<String> origPermissions) {
6899        boolean allowed;
6900        allowed = (compareSignatures(
6901                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6902                        == PackageManager.SIGNATURE_MATCH)
6903                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6904                        == PackageManager.SIGNATURE_MATCH);
6905        if (!allowed && (bp.protectionLevel
6906                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6907            if (isSystemApp(pkg)) {
6908                // For updated system applications, a system permission
6909                // is granted only if it had been defined by the original application.
6910                if (isUpdatedSystemApp(pkg)) {
6911                    final PackageSetting sysPs = mSettings
6912                            .getDisabledSystemPkgLPr(pkg.packageName);
6913                    final GrantedPermissions origGp = sysPs.sharedUser != null
6914                            ? sysPs.sharedUser : sysPs;
6915
6916                    if (origGp.grantedPermissions.contains(perm)) {
6917                        // If the original was granted this permission, we take
6918                        // that grant decision as read and propagate it to the
6919                        // update.
6920                        allowed = true;
6921                    } else {
6922                        // The system apk may have been updated with an older
6923                        // version of the one on the data partition, but which
6924                        // granted a new system permission that it didn't have
6925                        // before.  In this case we do want to allow the app to
6926                        // now get the new permission if the ancestral apk is
6927                        // privileged to get it.
6928                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6929                            for (int j=0;
6930                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6931                                if (perm.equals(
6932                                        sysPs.pkg.requestedPermissions.get(j))) {
6933                                    allowed = true;
6934                                    break;
6935                                }
6936                            }
6937                        }
6938                    }
6939                } else {
6940                    allowed = isPrivilegedApp(pkg);
6941                }
6942            }
6943        }
6944        if (!allowed && (bp.protectionLevel
6945                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6946            // For development permissions, a development permission
6947            // is granted only if it was already granted.
6948            allowed = origPermissions.contains(perm);
6949        }
6950        return allowed;
6951    }
6952
6953    final class ActivityIntentResolver
6954            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6955        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6956                boolean defaultOnly, int userId) {
6957            if (!sUserManager.exists(userId)) return null;
6958            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6959            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6960        }
6961
6962        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6963                int userId) {
6964            if (!sUserManager.exists(userId)) return null;
6965            mFlags = flags;
6966            return super.queryIntent(intent, resolvedType,
6967                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6968        }
6969
6970        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6971                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6972            if (!sUserManager.exists(userId)) return null;
6973            if (packageActivities == null) {
6974                return null;
6975            }
6976            mFlags = flags;
6977            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6978            final int N = packageActivities.size();
6979            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6980                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6981
6982            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6983            for (int i = 0; i < N; ++i) {
6984                intentFilters = packageActivities.get(i).intents;
6985                if (intentFilters != null && intentFilters.size() > 0) {
6986                    PackageParser.ActivityIntentInfo[] array =
6987                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6988                    intentFilters.toArray(array);
6989                    listCut.add(array);
6990                }
6991            }
6992            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6993        }
6994
6995        public final void addActivity(PackageParser.Activity a, String type) {
6996            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6997            mActivities.put(a.getComponentName(), a);
6998            if (DEBUG_SHOW_INFO)
6999                Log.v(
7000                TAG, "  " + type + " " +
7001                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7002            if (DEBUG_SHOW_INFO)
7003                Log.v(TAG, "    Class=" + a.info.name);
7004            final int NI = a.intents.size();
7005            for (int j=0; j<NI; j++) {
7006                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7007                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7008                    intent.setPriority(0);
7009                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7010                            + a.className + " with priority > 0, forcing to 0");
7011                }
7012                if (DEBUG_SHOW_INFO) {
7013                    Log.v(TAG, "    IntentFilter:");
7014                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7015                }
7016                if (!intent.debugCheck()) {
7017                    Log.w(TAG, "==> For Activity " + a.info.name);
7018                }
7019                addFilter(intent);
7020            }
7021        }
7022
7023        public final void removeActivity(PackageParser.Activity a, String type) {
7024            mActivities.remove(a.getComponentName());
7025            if (DEBUG_SHOW_INFO) {
7026                Log.v(TAG, "  " + type + " "
7027                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7028                                : a.info.name) + ":");
7029                Log.v(TAG, "    Class=" + a.info.name);
7030            }
7031            final int NI = a.intents.size();
7032            for (int j=0; j<NI; j++) {
7033                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7034                if (DEBUG_SHOW_INFO) {
7035                    Log.v(TAG, "    IntentFilter:");
7036                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7037                }
7038                removeFilter(intent);
7039            }
7040        }
7041
7042        @Override
7043        protected boolean allowFilterResult(
7044                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7045            ActivityInfo filterAi = filter.activity.info;
7046            for (int i=dest.size()-1; i>=0; i--) {
7047                ActivityInfo destAi = dest.get(i).activityInfo;
7048                if (destAi.name == filterAi.name
7049                        && destAi.packageName == filterAi.packageName) {
7050                    return false;
7051                }
7052            }
7053            return true;
7054        }
7055
7056        @Override
7057        protected ActivityIntentInfo[] newArray(int size) {
7058            return new ActivityIntentInfo[size];
7059        }
7060
7061        @Override
7062        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7063            if (!sUserManager.exists(userId)) return true;
7064            PackageParser.Package p = filter.activity.owner;
7065            if (p != null) {
7066                PackageSetting ps = (PackageSetting)p.mExtras;
7067                if (ps != null) {
7068                    // System apps are never considered stopped for purposes of
7069                    // filtering, because there may be no way for the user to
7070                    // actually re-launch them.
7071                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7072                            && ps.getStopped(userId);
7073                }
7074            }
7075            return false;
7076        }
7077
7078        @Override
7079        protected boolean isPackageForFilter(String packageName,
7080                PackageParser.ActivityIntentInfo info) {
7081            return packageName.equals(info.activity.owner.packageName);
7082        }
7083
7084        @Override
7085        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7086                int match, int userId) {
7087            if (!sUserManager.exists(userId)) return null;
7088            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7089                return null;
7090            }
7091            final PackageParser.Activity activity = info.activity;
7092            if (mSafeMode && (activity.info.applicationInfo.flags
7093                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7094                return null;
7095            }
7096            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7097            if (ps == null) {
7098                return null;
7099            }
7100            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7101                    ps.readUserState(userId), userId);
7102            if (ai == null) {
7103                return null;
7104            }
7105            final ResolveInfo res = new ResolveInfo();
7106            res.activityInfo = ai;
7107            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7108                res.filter = info;
7109            }
7110            res.priority = info.getPriority();
7111            res.preferredOrder = activity.owner.mPreferredOrder;
7112            //System.out.println("Result: " + res.activityInfo.className +
7113            //                   " = " + res.priority);
7114            res.match = match;
7115            res.isDefault = info.hasDefault;
7116            res.labelRes = info.labelRes;
7117            res.nonLocalizedLabel = info.nonLocalizedLabel;
7118            if (userNeedsBadging(userId)) {
7119                res.noResourceId = true;
7120            } else {
7121                res.icon = info.icon;
7122            }
7123            res.system = isSystemApp(res.activityInfo.applicationInfo);
7124            return res;
7125        }
7126
7127        @Override
7128        protected void sortResults(List<ResolveInfo> results) {
7129            Collections.sort(results, mResolvePrioritySorter);
7130        }
7131
7132        @Override
7133        protected void dumpFilter(PrintWriter out, String prefix,
7134                PackageParser.ActivityIntentInfo filter) {
7135            out.print(prefix); out.print(
7136                    Integer.toHexString(System.identityHashCode(filter.activity)));
7137                    out.print(' ');
7138                    filter.activity.printComponentShortName(out);
7139                    out.print(" filter ");
7140                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7141        }
7142
7143//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7144//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7145//            final List<ResolveInfo> retList = Lists.newArrayList();
7146//            while (i.hasNext()) {
7147//                final ResolveInfo resolveInfo = i.next();
7148//                if (isEnabledLP(resolveInfo.activityInfo)) {
7149//                    retList.add(resolveInfo);
7150//                }
7151//            }
7152//            return retList;
7153//        }
7154
7155        // Keys are String (activity class name), values are Activity.
7156        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7157                = new HashMap<ComponentName, PackageParser.Activity>();
7158        private int mFlags;
7159    }
7160
7161    private final class ServiceIntentResolver
7162            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7164                boolean defaultOnly, int userId) {
7165            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7166            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7167        }
7168
7169        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7170                int userId) {
7171            if (!sUserManager.exists(userId)) return null;
7172            mFlags = flags;
7173            return super.queryIntent(intent, resolvedType,
7174                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7175        }
7176
7177        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7178                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7179            if (!sUserManager.exists(userId)) return null;
7180            if (packageServices == null) {
7181                return null;
7182            }
7183            mFlags = flags;
7184            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7185            final int N = packageServices.size();
7186            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7187                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7188
7189            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7190            for (int i = 0; i < N; ++i) {
7191                intentFilters = packageServices.get(i).intents;
7192                if (intentFilters != null && intentFilters.size() > 0) {
7193                    PackageParser.ServiceIntentInfo[] array =
7194                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7195                    intentFilters.toArray(array);
7196                    listCut.add(array);
7197                }
7198            }
7199            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7200        }
7201
7202        public final void addService(PackageParser.Service s) {
7203            mServices.put(s.getComponentName(), s);
7204            if (DEBUG_SHOW_INFO) {
7205                Log.v(TAG, "  "
7206                        + (s.info.nonLocalizedLabel != null
7207                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7208                Log.v(TAG, "    Class=" + s.info.name);
7209            }
7210            final int NI = s.intents.size();
7211            int j;
7212            for (j=0; j<NI; j++) {
7213                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7214                if (DEBUG_SHOW_INFO) {
7215                    Log.v(TAG, "    IntentFilter:");
7216                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7217                }
7218                if (!intent.debugCheck()) {
7219                    Log.w(TAG, "==> For Service " + s.info.name);
7220                }
7221                addFilter(intent);
7222            }
7223        }
7224
7225        public final void removeService(PackageParser.Service s) {
7226            mServices.remove(s.getComponentName());
7227            if (DEBUG_SHOW_INFO) {
7228                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7229                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7230                Log.v(TAG, "    Class=" + s.info.name);
7231            }
7232            final int NI = s.intents.size();
7233            int j;
7234            for (j=0; j<NI; j++) {
7235                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7236                if (DEBUG_SHOW_INFO) {
7237                    Log.v(TAG, "    IntentFilter:");
7238                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7239                }
7240                removeFilter(intent);
7241            }
7242        }
7243
7244        @Override
7245        protected boolean allowFilterResult(
7246                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7247            ServiceInfo filterSi = filter.service.info;
7248            for (int i=dest.size()-1; i>=0; i--) {
7249                ServiceInfo destAi = dest.get(i).serviceInfo;
7250                if (destAi.name == filterSi.name
7251                        && destAi.packageName == filterSi.packageName) {
7252                    return false;
7253                }
7254            }
7255            return true;
7256        }
7257
7258        @Override
7259        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7260            return new PackageParser.ServiceIntentInfo[size];
7261        }
7262
7263        @Override
7264        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7265            if (!sUserManager.exists(userId)) return true;
7266            PackageParser.Package p = filter.service.owner;
7267            if (p != null) {
7268                PackageSetting ps = (PackageSetting)p.mExtras;
7269                if (ps != null) {
7270                    // System apps are never considered stopped for purposes of
7271                    // filtering, because there may be no way for the user to
7272                    // actually re-launch them.
7273                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7274                            && ps.getStopped(userId);
7275                }
7276            }
7277            return false;
7278        }
7279
7280        @Override
7281        protected boolean isPackageForFilter(String packageName,
7282                PackageParser.ServiceIntentInfo info) {
7283            return packageName.equals(info.service.owner.packageName);
7284        }
7285
7286        @Override
7287        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7288                int match, int userId) {
7289            if (!sUserManager.exists(userId)) return null;
7290            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7291            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7292                return null;
7293            }
7294            final PackageParser.Service service = info.service;
7295            if (mSafeMode && (service.info.applicationInfo.flags
7296                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7297                return null;
7298            }
7299            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7300            if (ps == null) {
7301                return null;
7302            }
7303            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7304                    ps.readUserState(userId), userId);
7305            if (si == null) {
7306                return null;
7307            }
7308            final ResolveInfo res = new ResolveInfo();
7309            res.serviceInfo = si;
7310            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7311                res.filter = filter;
7312            }
7313            res.priority = info.getPriority();
7314            res.preferredOrder = service.owner.mPreferredOrder;
7315            //System.out.println("Result: " + res.activityInfo.className +
7316            //                   " = " + res.priority);
7317            res.match = match;
7318            res.isDefault = info.hasDefault;
7319            res.labelRes = info.labelRes;
7320            res.nonLocalizedLabel = info.nonLocalizedLabel;
7321            res.icon = info.icon;
7322            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7323            return res;
7324        }
7325
7326        @Override
7327        protected void sortResults(List<ResolveInfo> results) {
7328            Collections.sort(results, mResolvePrioritySorter);
7329        }
7330
7331        @Override
7332        protected void dumpFilter(PrintWriter out, String prefix,
7333                PackageParser.ServiceIntentInfo filter) {
7334            out.print(prefix); out.print(
7335                    Integer.toHexString(System.identityHashCode(filter.service)));
7336                    out.print(' ');
7337                    filter.service.printComponentShortName(out);
7338                    out.print(" filter ");
7339                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7340        }
7341
7342//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7343//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7344//            final List<ResolveInfo> retList = Lists.newArrayList();
7345//            while (i.hasNext()) {
7346//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7347//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7348//                    retList.add(resolveInfo);
7349//                }
7350//            }
7351//            return retList;
7352//        }
7353
7354        // Keys are String (activity class name), values are Activity.
7355        private final HashMap<ComponentName, PackageParser.Service> mServices
7356                = new HashMap<ComponentName, PackageParser.Service>();
7357        private int mFlags;
7358    };
7359
7360    private final class ProviderIntentResolver
7361            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7362        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7363                boolean defaultOnly, int userId) {
7364            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7365            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7366        }
7367
7368        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7369                int userId) {
7370            if (!sUserManager.exists(userId))
7371                return null;
7372            mFlags = flags;
7373            return super.queryIntent(intent, resolvedType,
7374                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7375        }
7376
7377        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7378                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7379            if (!sUserManager.exists(userId))
7380                return null;
7381            if (packageProviders == null) {
7382                return null;
7383            }
7384            mFlags = flags;
7385            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7386            final int N = packageProviders.size();
7387            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7388                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7389
7390            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7391            for (int i = 0; i < N; ++i) {
7392                intentFilters = packageProviders.get(i).intents;
7393                if (intentFilters != null && intentFilters.size() > 0) {
7394                    PackageParser.ProviderIntentInfo[] array =
7395                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7396                    intentFilters.toArray(array);
7397                    listCut.add(array);
7398                }
7399            }
7400            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7401        }
7402
7403        public final void addProvider(PackageParser.Provider p) {
7404            if (mProviders.containsKey(p.getComponentName())) {
7405                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7406                return;
7407            }
7408
7409            mProviders.put(p.getComponentName(), p);
7410            if (DEBUG_SHOW_INFO) {
7411                Log.v(TAG, "  "
7412                        + (p.info.nonLocalizedLabel != null
7413                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7414                Log.v(TAG, "    Class=" + p.info.name);
7415            }
7416            final int NI = p.intents.size();
7417            int j;
7418            for (j = 0; j < NI; j++) {
7419                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7420                if (DEBUG_SHOW_INFO) {
7421                    Log.v(TAG, "    IntentFilter:");
7422                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7423                }
7424                if (!intent.debugCheck()) {
7425                    Log.w(TAG, "==> For Provider " + p.info.name);
7426                }
7427                addFilter(intent);
7428            }
7429        }
7430
7431        public final void removeProvider(PackageParser.Provider p) {
7432            mProviders.remove(p.getComponentName());
7433            if (DEBUG_SHOW_INFO) {
7434                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7435                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7436                Log.v(TAG, "    Class=" + p.info.name);
7437            }
7438            final int NI = p.intents.size();
7439            int j;
7440            for (j = 0; j < NI; j++) {
7441                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7442                if (DEBUG_SHOW_INFO) {
7443                    Log.v(TAG, "    IntentFilter:");
7444                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7445                }
7446                removeFilter(intent);
7447            }
7448        }
7449
7450        @Override
7451        protected boolean allowFilterResult(
7452                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7453            ProviderInfo filterPi = filter.provider.info;
7454            for (int i = dest.size() - 1; i >= 0; i--) {
7455                ProviderInfo destPi = dest.get(i).providerInfo;
7456                if (destPi.name == filterPi.name
7457                        && destPi.packageName == filterPi.packageName) {
7458                    return false;
7459                }
7460            }
7461            return true;
7462        }
7463
7464        @Override
7465        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7466            return new PackageParser.ProviderIntentInfo[size];
7467        }
7468
7469        @Override
7470        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7471            if (!sUserManager.exists(userId))
7472                return true;
7473            PackageParser.Package p = filter.provider.owner;
7474            if (p != null) {
7475                PackageSetting ps = (PackageSetting) p.mExtras;
7476                if (ps != null) {
7477                    // System apps are never considered stopped for purposes of
7478                    // filtering, because there may be no way for the user to
7479                    // actually re-launch them.
7480                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7481                            && ps.getStopped(userId);
7482                }
7483            }
7484            return false;
7485        }
7486
7487        @Override
7488        protected boolean isPackageForFilter(String packageName,
7489                PackageParser.ProviderIntentInfo info) {
7490            return packageName.equals(info.provider.owner.packageName);
7491        }
7492
7493        @Override
7494        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7495                int match, int userId) {
7496            if (!sUserManager.exists(userId))
7497                return null;
7498            final PackageParser.ProviderIntentInfo info = filter;
7499            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7500                return null;
7501            }
7502            final PackageParser.Provider provider = info.provider;
7503            if (mSafeMode && (provider.info.applicationInfo.flags
7504                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7505                return null;
7506            }
7507            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7508            if (ps == null) {
7509                return null;
7510            }
7511            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7512                    ps.readUserState(userId), userId);
7513            if (pi == null) {
7514                return null;
7515            }
7516            final ResolveInfo res = new ResolveInfo();
7517            res.providerInfo = pi;
7518            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7519                res.filter = filter;
7520            }
7521            res.priority = info.getPriority();
7522            res.preferredOrder = provider.owner.mPreferredOrder;
7523            res.match = match;
7524            res.isDefault = info.hasDefault;
7525            res.labelRes = info.labelRes;
7526            res.nonLocalizedLabel = info.nonLocalizedLabel;
7527            res.icon = info.icon;
7528            res.system = isSystemApp(res.providerInfo.applicationInfo);
7529            return res;
7530        }
7531
7532        @Override
7533        protected void sortResults(List<ResolveInfo> results) {
7534            Collections.sort(results, mResolvePrioritySorter);
7535        }
7536
7537        @Override
7538        protected void dumpFilter(PrintWriter out, String prefix,
7539                PackageParser.ProviderIntentInfo filter) {
7540            out.print(prefix);
7541            out.print(
7542                    Integer.toHexString(System.identityHashCode(filter.provider)));
7543            out.print(' ');
7544            filter.provider.printComponentShortName(out);
7545            out.print(" filter ");
7546            out.println(Integer.toHexString(System.identityHashCode(filter)));
7547        }
7548
7549        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7550                = new HashMap<ComponentName, PackageParser.Provider>();
7551        private int mFlags;
7552    };
7553
7554    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7555            new Comparator<ResolveInfo>() {
7556        public int compare(ResolveInfo r1, ResolveInfo r2) {
7557            int v1 = r1.priority;
7558            int v2 = r2.priority;
7559            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7560            if (v1 != v2) {
7561                return (v1 > v2) ? -1 : 1;
7562            }
7563            v1 = r1.preferredOrder;
7564            v2 = r2.preferredOrder;
7565            if (v1 != v2) {
7566                return (v1 > v2) ? -1 : 1;
7567            }
7568            if (r1.isDefault != r2.isDefault) {
7569                return r1.isDefault ? -1 : 1;
7570            }
7571            v1 = r1.match;
7572            v2 = r2.match;
7573            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7574            if (v1 != v2) {
7575                return (v1 > v2) ? -1 : 1;
7576            }
7577            if (r1.system != r2.system) {
7578                return r1.system ? -1 : 1;
7579            }
7580            return 0;
7581        }
7582    };
7583
7584    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7585            new Comparator<ProviderInfo>() {
7586        public int compare(ProviderInfo p1, ProviderInfo p2) {
7587            final int v1 = p1.initOrder;
7588            final int v2 = p2.initOrder;
7589            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7590        }
7591    };
7592
7593    static final void sendPackageBroadcast(String action, String pkg,
7594            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7595            int[] userIds) {
7596        IActivityManager am = ActivityManagerNative.getDefault();
7597        if (am != null) {
7598            try {
7599                if (userIds == null) {
7600                    userIds = am.getRunningUserIds();
7601                }
7602                for (int id : userIds) {
7603                    final Intent intent = new Intent(action,
7604                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7605                    if (extras != null) {
7606                        intent.putExtras(extras);
7607                    }
7608                    if (targetPkg != null) {
7609                        intent.setPackage(targetPkg);
7610                    }
7611                    // Modify the UID when posting to other users
7612                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7613                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7614                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7615                        intent.putExtra(Intent.EXTRA_UID, uid);
7616                    }
7617                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7618                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7619                    if (DEBUG_BROADCASTS) {
7620                        RuntimeException here = new RuntimeException("here");
7621                        here.fillInStackTrace();
7622                        Slog.d(TAG, "Sending to user " + id + ": "
7623                                + intent.toShortString(false, true, false, false)
7624                                + " " + intent.getExtras(), here);
7625                    }
7626                    am.broadcastIntent(null, intent, null, finishedReceiver,
7627                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7628                            finishedReceiver != null, false, id);
7629                }
7630            } catch (RemoteException ex) {
7631            }
7632        }
7633    }
7634
7635    /**
7636     * Check if the external storage media is available. This is true if there
7637     * is a mounted external storage medium or if the external storage is
7638     * emulated.
7639     */
7640    private boolean isExternalMediaAvailable() {
7641        return mMediaMounted || Environment.isExternalStorageEmulated();
7642    }
7643
7644    @Override
7645    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7646        // writer
7647        synchronized (mPackages) {
7648            if (!isExternalMediaAvailable()) {
7649                // If the external storage is no longer mounted at this point,
7650                // the caller may not have been able to delete all of this
7651                // packages files and can not delete any more.  Bail.
7652                return null;
7653            }
7654            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7655            if (lastPackage != null) {
7656                pkgs.remove(lastPackage);
7657            }
7658            if (pkgs.size() > 0) {
7659                return pkgs.get(0);
7660            }
7661        }
7662        return null;
7663    }
7664
7665    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7666        if (false) {
7667            RuntimeException here = new RuntimeException("here");
7668            here.fillInStackTrace();
7669            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7670                    + " andCode=" + andCode, here);
7671        }
7672        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7673                userId, andCode ? 1 : 0, packageName));
7674    }
7675
7676    void startCleaningPackages() {
7677        // reader
7678        synchronized (mPackages) {
7679            if (!isExternalMediaAvailable()) {
7680                return;
7681            }
7682            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7683                return;
7684            }
7685        }
7686        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7687        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7688        IActivityManager am = ActivityManagerNative.getDefault();
7689        if (am != null) {
7690            try {
7691                am.startService(null, intent, null, UserHandle.USER_OWNER);
7692            } catch (RemoteException e) {
7693            }
7694        }
7695    }
7696
7697    @Override
7698    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7699            int installFlags, String installerPackageName, VerificationParams verificationParams,
7700            String packageAbiOverride) {
7701        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7702                packageAbiOverride, UserHandle.getCallingUserId());
7703    }
7704
7705    @Override
7706    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7707            int installFlags, String installerPackageName, VerificationParams verificationParams,
7708            String packageAbiOverride, int userId) {
7709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7710                null);
7711        if (UserHandle.getCallingUserId() != userId) {
7712            mContext.enforceCallingOrSelfPermission(
7713                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7714                    "installPackage " + userId);
7715        }
7716
7717        final File originFile = new File(originPath);
7718        final int uid = Binder.getCallingUid();
7719        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7720            try {
7721                if (observer != null) {
7722                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7723                }
7724            } catch (RemoteException re) {
7725            }
7726            return;
7727        }
7728
7729        UserHandle user;
7730        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7731            user = UserHandle.ALL;
7732        } else {
7733            user = new UserHandle(userId);
7734        }
7735
7736        final int filteredInstallFlags;
7737        if (uid == Process.SHELL_UID || uid == 0) {
7738            if (DEBUG_INSTALL) {
7739                Slog.v(TAG, "Install from ADB");
7740            }
7741            filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB;
7742        } else {
7743            filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB;
7744        }
7745
7746        verificationParams.setInstallerUid(uid);
7747
7748        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7749
7750        final Message msg = mHandler.obtainMessage(INIT_COPY);
7751        msg.obj = new InstallParams(origin, observer, filteredInstallFlags,
7752                installerPackageName, verificationParams, user, packageAbiOverride);
7753        mHandler.sendMessage(msg);
7754    }
7755
7756    void installStage(String packageName, File stagedDir, String stagedCid,
7757            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7758            String installerPackageName, int installerUid, UserHandle user) {
7759        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7760                params.referrerUri, installerUid, null);
7761
7762        final OriginInfo origin;
7763        if (stagedDir != null) {
7764            origin = OriginInfo.fromStagedFile(stagedDir);
7765        } else {
7766            origin = OriginInfo.fromStagedContainer(stagedCid);
7767        }
7768
7769        final Message msg = mHandler.obtainMessage(INIT_COPY);
7770        msg.obj = new InstallParams(origin, observer, params.installFlags,
7771                installerPackageName, verifParams, user, params.abiOverride);
7772        mHandler.sendMessage(msg);
7773    }
7774
7775    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7776        Bundle extras = new Bundle(1);
7777        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7778
7779        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7780                packageName, extras, null, null, new int[] {userId});
7781        try {
7782            IActivityManager am = ActivityManagerNative.getDefault();
7783            final boolean isSystem =
7784                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7785            if (isSystem && am.isUserRunning(userId, false)) {
7786                // The just-installed/enabled app is bundled on the system, so presumed
7787                // to be able to run automatically without needing an explicit launch.
7788                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7789                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7790                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7791                        .setPackage(packageName);
7792                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7793                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7794            }
7795        } catch (RemoteException e) {
7796            // shouldn't happen
7797            Slog.w(TAG, "Unable to bootstrap installed package", e);
7798        }
7799    }
7800
7801    @Override
7802    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7803            int userId) {
7804        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7805        PackageSetting pkgSetting;
7806        final int uid = Binder.getCallingUid();
7807        if (UserHandle.getUserId(uid) != userId) {
7808            mContext.enforceCallingOrSelfPermission(
7809                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7810                    "setApplicationHiddenSetting for user " + userId);
7811        }
7812
7813        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7814            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7815            return false;
7816        }
7817
7818        long callingId = Binder.clearCallingIdentity();
7819        try {
7820            boolean sendAdded = false;
7821            boolean sendRemoved = false;
7822            // writer
7823            synchronized (mPackages) {
7824                pkgSetting = mSettings.mPackages.get(packageName);
7825                if (pkgSetting == null) {
7826                    return false;
7827                }
7828                if (pkgSetting.getHidden(userId) != hidden) {
7829                    pkgSetting.setHidden(hidden, userId);
7830                    mSettings.writePackageRestrictionsLPr(userId);
7831                    if (hidden) {
7832                        sendRemoved = true;
7833                    } else {
7834                        sendAdded = true;
7835                    }
7836                }
7837            }
7838            if (sendAdded) {
7839                sendPackageAddedForUser(packageName, pkgSetting, userId);
7840                return true;
7841            }
7842            if (sendRemoved) {
7843                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7844                        "hiding pkg");
7845                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7846            }
7847        } finally {
7848            Binder.restoreCallingIdentity(callingId);
7849        }
7850        return false;
7851    }
7852
7853    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7854            int userId) {
7855        final PackageRemovedInfo info = new PackageRemovedInfo();
7856        info.removedPackage = packageName;
7857        info.removedUsers = new int[] {userId};
7858        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7859        info.sendBroadcast(false, false, false);
7860    }
7861
7862    /**
7863     * Returns true if application is not found or there was an error. Otherwise it returns
7864     * the hidden state of the package for the given user.
7865     */
7866    @Override
7867    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7868        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7869        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7870                "getApplicationHidden for user " + userId);
7871        PackageSetting pkgSetting;
7872        long callingId = Binder.clearCallingIdentity();
7873        try {
7874            // writer
7875            synchronized (mPackages) {
7876                pkgSetting = mSettings.mPackages.get(packageName);
7877                if (pkgSetting == null) {
7878                    return true;
7879                }
7880                return pkgSetting.getHidden(userId);
7881            }
7882        } finally {
7883            Binder.restoreCallingIdentity(callingId);
7884        }
7885    }
7886
7887    /**
7888     * @hide
7889     */
7890    @Override
7891    public int installExistingPackageAsUser(String packageName, int userId) {
7892        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7893                null);
7894        PackageSetting pkgSetting;
7895        final int uid = Binder.getCallingUid();
7896        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7897        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7898            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7899        }
7900
7901        long callingId = Binder.clearCallingIdentity();
7902        try {
7903            boolean sendAdded = false;
7904            Bundle extras = new Bundle(1);
7905
7906            // writer
7907            synchronized (mPackages) {
7908                pkgSetting = mSettings.mPackages.get(packageName);
7909                if (pkgSetting == null) {
7910                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7911                }
7912                if (!pkgSetting.getInstalled(userId)) {
7913                    pkgSetting.setInstalled(true, userId);
7914                    pkgSetting.setHidden(false, userId);
7915                    mSettings.writePackageRestrictionsLPr(userId);
7916                    sendAdded = true;
7917                }
7918            }
7919
7920            if (sendAdded) {
7921                sendPackageAddedForUser(packageName, pkgSetting, userId);
7922            }
7923        } finally {
7924            Binder.restoreCallingIdentity(callingId);
7925        }
7926
7927        return PackageManager.INSTALL_SUCCEEDED;
7928    }
7929
7930    boolean isUserRestricted(int userId, String restrictionKey) {
7931        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7932        if (restrictions.getBoolean(restrictionKey, false)) {
7933            Log.w(TAG, "User is restricted: " + restrictionKey);
7934            return true;
7935        }
7936        return false;
7937    }
7938
7939    @Override
7940    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7941        mContext.enforceCallingOrSelfPermission(
7942                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7943                "Only package verification agents can verify applications");
7944
7945        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7946        final PackageVerificationResponse response = new PackageVerificationResponse(
7947                verificationCode, Binder.getCallingUid());
7948        msg.arg1 = id;
7949        msg.obj = response;
7950        mHandler.sendMessage(msg);
7951    }
7952
7953    @Override
7954    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7955            long millisecondsToDelay) {
7956        mContext.enforceCallingOrSelfPermission(
7957                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7958                "Only package verification agents can extend verification timeouts");
7959
7960        final PackageVerificationState state = mPendingVerification.get(id);
7961        final PackageVerificationResponse response = new PackageVerificationResponse(
7962                verificationCodeAtTimeout, Binder.getCallingUid());
7963
7964        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7965            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7966        }
7967        if (millisecondsToDelay < 0) {
7968            millisecondsToDelay = 0;
7969        }
7970        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7971                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7972            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7973        }
7974
7975        if ((state != null) && !state.timeoutExtended()) {
7976            state.extendTimeout();
7977
7978            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7979            msg.arg1 = id;
7980            msg.obj = response;
7981            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7982        }
7983    }
7984
7985    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7986            int verificationCode, UserHandle user) {
7987        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7988        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7989        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7990        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7991        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7992
7993        mContext.sendBroadcastAsUser(intent, user,
7994                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7995    }
7996
7997    private ComponentName matchComponentForVerifier(String packageName,
7998            List<ResolveInfo> receivers) {
7999        ActivityInfo targetReceiver = null;
8000
8001        final int NR = receivers.size();
8002        for (int i = 0; i < NR; i++) {
8003            final ResolveInfo info = receivers.get(i);
8004            if (info.activityInfo == null) {
8005                continue;
8006            }
8007
8008            if (packageName.equals(info.activityInfo.packageName)) {
8009                targetReceiver = info.activityInfo;
8010                break;
8011            }
8012        }
8013
8014        if (targetReceiver == null) {
8015            return null;
8016        }
8017
8018        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8019    }
8020
8021    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8022            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8023        if (pkgInfo.verifiers.length == 0) {
8024            return null;
8025        }
8026
8027        final int N = pkgInfo.verifiers.length;
8028        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8029        for (int i = 0; i < N; i++) {
8030            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8031
8032            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8033                    receivers);
8034            if (comp == null) {
8035                continue;
8036            }
8037
8038            final int verifierUid = getUidForVerifier(verifierInfo);
8039            if (verifierUid == -1) {
8040                continue;
8041            }
8042
8043            if (DEBUG_VERIFY) {
8044                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8045                        + " with the correct signature");
8046            }
8047            sufficientVerifiers.add(comp);
8048            verificationState.addSufficientVerifier(verifierUid);
8049        }
8050
8051        return sufficientVerifiers;
8052    }
8053
8054    private int getUidForVerifier(VerifierInfo verifierInfo) {
8055        synchronized (mPackages) {
8056            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8057            if (pkg == null) {
8058                return -1;
8059            } else if (pkg.mSignatures.length != 1) {
8060                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8061                        + " has more than one signature; ignoring");
8062                return -1;
8063            }
8064
8065            /*
8066             * If the public key of the package's signature does not match
8067             * our expected public key, then this is a different package and
8068             * we should skip.
8069             */
8070
8071            final byte[] expectedPublicKey;
8072            try {
8073                final Signature verifierSig = pkg.mSignatures[0];
8074                final PublicKey publicKey = verifierSig.getPublicKey();
8075                expectedPublicKey = publicKey.getEncoded();
8076            } catch (CertificateException e) {
8077                return -1;
8078            }
8079
8080            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8081
8082            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8083                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8084                        + " does not have the expected public key; ignoring");
8085                return -1;
8086            }
8087
8088            return pkg.applicationInfo.uid;
8089        }
8090    }
8091
8092    @Override
8093    public void finishPackageInstall(int token) {
8094        enforceSystemOrRoot("Only the system is allowed to finish installs");
8095
8096        if (DEBUG_INSTALL) {
8097            Slog.v(TAG, "BM finishing package install for " + token);
8098        }
8099
8100        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8101        mHandler.sendMessage(msg);
8102    }
8103
8104    /**
8105     * Get the verification agent timeout.
8106     *
8107     * @return verification timeout in milliseconds
8108     */
8109    private long getVerificationTimeout() {
8110        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8111                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8112                DEFAULT_VERIFICATION_TIMEOUT);
8113    }
8114
8115    /**
8116     * Get the default verification agent response code.
8117     *
8118     * @return default verification response code
8119     */
8120    private int getDefaultVerificationResponse() {
8121        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8122                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8123                DEFAULT_VERIFICATION_RESPONSE);
8124    }
8125
8126    /**
8127     * Check whether or not package verification has been enabled.
8128     *
8129     * @return true if verification should be performed
8130     */
8131    private boolean isVerificationEnabled(int userId, int installFlags) {
8132        if (!DEFAULT_VERIFY_ENABLE) {
8133            return false;
8134        }
8135
8136        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8137
8138        // Check if installing from ADB
8139        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8140            // Do not run verification in a test harness environment
8141            if (ActivityManager.isRunningInTestHarness()) {
8142                return false;
8143            }
8144            if (ensureVerifyAppsEnabled) {
8145                return true;
8146            }
8147            // Check if the developer does not want package verification for ADB installs
8148            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8149                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8150                return false;
8151            }
8152        }
8153
8154        if (ensureVerifyAppsEnabled) {
8155            return true;
8156        }
8157
8158        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8159                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8160    }
8161
8162    /**
8163     * Get the "allow unknown sources" setting.
8164     *
8165     * @return the current "allow unknown sources" setting
8166     */
8167    private int getUnknownSourcesSettings() {
8168        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8169                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8170                -1);
8171    }
8172
8173    @Override
8174    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8175        final int uid = Binder.getCallingUid();
8176        // writer
8177        synchronized (mPackages) {
8178            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8179            if (targetPackageSetting == null) {
8180                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8181            }
8182
8183            PackageSetting installerPackageSetting;
8184            if (installerPackageName != null) {
8185                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8186                if (installerPackageSetting == null) {
8187                    throw new IllegalArgumentException("Unknown installer package: "
8188                            + installerPackageName);
8189                }
8190            } else {
8191                installerPackageSetting = null;
8192            }
8193
8194            Signature[] callerSignature;
8195            Object obj = mSettings.getUserIdLPr(uid);
8196            if (obj != null) {
8197                if (obj instanceof SharedUserSetting) {
8198                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8199                } else if (obj instanceof PackageSetting) {
8200                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8201                } else {
8202                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8203                }
8204            } else {
8205                throw new SecurityException("Unknown calling uid " + uid);
8206            }
8207
8208            // Verify: can't set installerPackageName to a package that is
8209            // not signed with the same cert as the caller.
8210            if (installerPackageSetting != null) {
8211                if (compareSignatures(callerSignature,
8212                        installerPackageSetting.signatures.mSignatures)
8213                        != PackageManager.SIGNATURE_MATCH) {
8214                    throw new SecurityException(
8215                            "Caller does not have same cert as new installer package "
8216                            + installerPackageName);
8217                }
8218            }
8219
8220            // Verify: if target already has an installer package, it must
8221            // be signed with the same cert as the caller.
8222            if (targetPackageSetting.installerPackageName != null) {
8223                PackageSetting setting = mSettings.mPackages.get(
8224                        targetPackageSetting.installerPackageName);
8225                // If the currently set package isn't valid, then it's always
8226                // okay to change it.
8227                if (setting != null) {
8228                    if (compareSignatures(callerSignature,
8229                            setting.signatures.mSignatures)
8230                            != PackageManager.SIGNATURE_MATCH) {
8231                        throw new SecurityException(
8232                                "Caller does not have same cert as old installer package "
8233                                + targetPackageSetting.installerPackageName);
8234                    }
8235                }
8236            }
8237
8238            // Okay!
8239            targetPackageSetting.installerPackageName = installerPackageName;
8240            scheduleWriteSettingsLocked();
8241        }
8242    }
8243
8244    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8245        // Queue up an async operation since the package installation may take a little while.
8246        mHandler.post(new Runnable() {
8247            public void run() {
8248                mHandler.removeCallbacks(this);
8249                 // Result object to be returned
8250                PackageInstalledInfo res = new PackageInstalledInfo();
8251                res.returnCode = currentStatus;
8252                res.uid = -1;
8253                res.pkg = null;
8254                res.removedInfo = new PackageRemovedInfo();
8255                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8256                    args.doPreInstall(res.returnCode);
8257                    synchronized (mInstallLock) {
8258                        installPackageLI(args, res);
8259                    }
8260                    args.doPostInstall(res.returnCode, res.uid);
8261                }
8262
8263                // A restore should be performed at this point if (a) the install
8264                // succeeded, (b) the operation is not an update, and (c) the new
8265                // package has not opted out of backup participation.
8266                final boolean update = res.removedInfo.removedPackage != null;
8267                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8268                boolean doRestore = !update
8269                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8270
8271                // Set up the post-install work request bookkeeping.  This will be used
8272                // and cleaned up by the post-install event handling regardless of whether
8273                // there's a restore pass performed.  Token values are >= 1.
8274                int token;
8275                if (mNextInstallToken < 0) mNextInstallToken = 1;
8276                token = mNextInstallToken++;
8277
8278                PostInstallData data = new PostInstallData(args, res);
8279                mRunningInstalls.put(token, data);
8280                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8281
8282                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8283                    // Pass responsibility to the Backup Manager.  It will perform a
8284                    // restore if appropriate, then pass responsibility back to the
8285                    // Package Manager to run the post-install observer callbacks
8286                    // and broadcasts.
8287                    IBackupManager bm = IBackupManager.Stub.asInterface(
8288                            ServiceManager.getService(Context.BACKUP_SERVICE));
8289                    if (bm != null) {
8290                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8291                                + " to BM for possible restore");
8292                        try {
8293                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8294                        } catch (RemoteException e) {
8295                            // can't happen; the backup manager is local
8296                        } catch (Exception e) {
8297                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8298                            doRestore = false;
8299                        }
8300                    } else {
8301                        Slog.e(TAG, "Backup Manager not found!");
8302                        doRestore = false;
8303                    }
8304                }
8305
8306                if (!doRestore) {
8307                    // No restore possible, or the Backup Manager was mysteriously not
8308                    // available -- just fire the post-install work request directly.
8309                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8310                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8311                    mHandler.sendMessage(msg);
8312                }
8313            }
8314        });
8315    }
8316
8317    private abstract class HandlerParams {
8318        private static final int MAX_RETRIES = 4;
8319
8320        /**
8321         * Number of times startCopy() has been attempted and had a non-fatal
8322         * error.
8323         */
8324        private int mRetries = 0;
8325
8326        /** User handle for the user requesting the information or installation. */
8327        private final UserHandle mUser;
8328
8329        HandlerParams(UserHandle user) {
8330            mUser = user;
8331        }
8332
8333        UserHandle getUser() {
8334            return mUser;
8335        }
8336
8337        final boolean startCopy() {
8338            boolean res;
8339            try {
8340                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8341
8342                if (++mRetries > MAX_RETRIES) {
8343                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8344                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8345                    handleServiceError();
8346                    return false;
8347                } else {
8348                    handleStartCopy();
8349                    res = true;
8350                }
8351            } catch (RemoteException e) {
8352                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8353                mHandler.sendEmptyMessage(MCS_RECONNECT);
8354                res = false;
8355            }
8356            handleReturnCode();
8357            return res;
8358        }
8359
8360        final void serviceError() {
8361            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8362            handleServiceError();
8363            handleReturnCode();
8364        }
8365
8366        abstract void handleStartCopy() throws RemoteException;
8367        abstract void handleServiceError();
8368        abstract void handleReturnCode();
8369    }
8370
8371    class MeasureParams extends HandlerParams {
8372        private final PackageStats mStats;
8373        private boolean mSuccess;
8374
8375        private final IPackageStatsObserver mObserver;
8376
8377        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8378            super(new UserHandle(stats.userHandle));
8379            mObserver = observer;
8380            mStats = stats;
8381        }
8382
8383        @Override
8384        public String toString() {
8385            return "MeasureParams{"
8386                + Integer.toHexString(System.identityHashCode(this))
8387                + " " + mStats.packageName + "}";
8388        }
8389
8390        @Override
8391        void handleStartCopy() throws RemoteException {
8392            synchronized (mInstallLock) {
8393                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8394            }
8395
8396            if (mSuccess) {
8397                final boolean mounted;
8398                if (Environment.isExternalStorageEmulated()) {
8399                    mounted = true;
8400                } else {
8401                    final String status = Environment.getExternalStorageState();
8402                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8403                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8404                }
8405
8406                if (mounted) {
8407                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8408
8409                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8410                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8411
8412                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8413                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8414
8415                    // Always subtract cache size, since it's a subdirectory
8416                    mStats.externalDataSize -= mStats.externalCacheSize;
8417
8418                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8419                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8420
8421                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8422                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8423                }
8424            }
8425        }
8426
8427        @Override
8428        void handleReturnCode() {
8429            if (mObserver != null) {
8430                try {
8431                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8432                } catch (RemoteException e) {
8433                    Slog.i(TAG, "Observer no longer exists.");
8434                }
8435            }
8436        }
8437
8438        @Override
8439        void handleServiceError() {
8440            Slog.e(TAG, "Could not measure application " + mStats.packageName
8441                            + " external storage");
8442        }
8443    }
8444
8445    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8446            throws RemoteException {
8447        long result = 0;
8448        for (File path : paths) {
8449            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8450        }
8451        return result;
8452    }
8453
8454    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8455        for (File path : paths) {
8456            try {
8457                mcs.clearDirectory(path.getAbsolutePath());
8458            } catch (RemoteException e) {
8459            }
8460        }
8461    }
8462
8463    static class OriginInfo {
8464        /**
8465         * Location where install is coming from, before it has been
8466         * copied/renamed into place. This could be a single monolithic APK
8467         * file, or a cluster directory. This location may be untrusted.
8468         */
8469        final File file;
8470        final String cid;
8471
8472        /**
8473         * Flag indicating that {@link #file} or {@link #cid} has already been
8474         * staged, meaning downstream users don't need to defensively copy the
8475         * contents.
8476         */
8477        final boolean staged;
8478
8479        /**
8480         * Flag indicating that {@link #file} or {@link #cid} is an already
8481         * installed app that is being moved.
8482         */
8483        final boolean existing;
8484
8485        final String resolvedPath;
8486        final File resolvedFile;
8487
8488        static OriginInfo fromNothing() {
8489            return new OriginInfo(null, null, false, false);
8490        }
8491
8492        static OriginInfo fromUntrustedFile(File file) {
8493            return new OriginInfo(file, null, false, false);
8494        }
8495
8496        static OriginInfo fromExistingFile(File file) {
8497            return new OriginInfo(file, null, false, true);
8498        }
8499
8500        static OriginInfo fromStagedFile(File file) {
8501            return new OriginInfo(file, null, true, false);
8502        }
8503
8504        static OriginInfo fromStagedContainer(String cid) {
8505            return new OriginInfo(null, cid, true, false);
8506        }
8507
8508        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8509            this.file = file;
8510            this.cid = cid;
8511            this.staged = staged;
8512            this.existing = existing;
8513
8514            if (cid != null) {
8515                resolvedPath = PackageHelper.getSdDir(cid);
8516                resolvedFile = new File(resolvedPath);
8517            } else if (file != null) {
8518                resolvedPath = file.getAbsolutePath();
8519                resolvedFile = file;
8520            } else {
8521                resolvedPath = null;
8522                resolvedFile = null;
8523            }
8524        }
8525    }
8526
8527    class InstallParams extends HandlerParams {
8528        final OriginInfo origin;
8529        final IPackageInstallObserver2 observer;
8530        int installFlags;
8531        final String installerPackageName;
8532        final VerificationParams verificationParams;
8533        private InstallArgs mArgs;
8534        private int mRet;
8535        final String packageAbiOverride;
8536
8537        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8538                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8539                String packageAbiOverride) {
8540            super(user);
8541            this.origin = origin;
8542            this.observer = observer;
8543            this.installFlags = installFlags;
8544            this.installerPackageName = installerPackageName;
8545            this.verificationParams = verificationParams;
8546            this.packageAbiOverride = packageAbiOverride;
8547        }
8548
8549        @Override
8550        public String toString() {
8551            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8552                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8553        }
8554
8555        public ManifestDigest getManifestDigest() {
8556            if (verificationParams == null) {
8557                return null;
8558            }
8559            return verificationParams.getManifestDigest();
8560        }
8561
8562        private int installLocationPolicy(PackageInfoLite pkgLite) {
8563            String packageName = pkgLite.packageName;
8564            int installLocation = pkgLite.installLocation;
8565            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8566            // reader
8567            synchronized (mPackages) {
8568                PackageParser.Package pkg = mPackages.get(packageName);
8569                if (pkg != null) {
8570                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8571                        // Check for downgrading.
8572                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8573                            if (pkgLite.versionCode < pkg.mVersionCode) {
8574                                Slog.w(TAG, "Can't install update of " + packageName
8575                                        + " update version " + pkgLite.versionCode
8576                                        + " is older than installed version "
8577                                        + pkg.mVersionCode);
8578                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8579                            }
8580                        }
8581                        // Check for updated system application.
8582                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8583                            if (onSd) {
8584                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8585                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8586                            }
8587                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8588                        } else {
8589                            if (onSd) {
8590                                // Install flag overrides everything.
8591                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8592                            }
8593                            // If current upgrade specifies particular preference
8594                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8595                                // Application explicitly specified internal.
8596                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8597                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8598                                // App explictly prefers external. Let policy decide
8599                            } else {
8600                                // Prefer previous location
8601                                if (isExternal(pkg)) {
8602                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8603                                }
8604                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8605                            }
8606                        }
8607                    } else {
8608                        // Invalid install. Return error code
8609                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8610                    }
8611                }
8612            }
8613            // All the special cases have been taken care of.
8614            // Return result based on recommended install location.
8615            if (onSd) {
8616                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8617            }
8618            return pkgLite.recommendedInstallLocation;
8619        }
8620
8621        /*
8622         * Invoke remote method to get package information and install
8623         * location values. Override install location based on default
8624         * policy if needed and then create install arguments based
8625         * on the install location.
8626         */
8627        public void handleStartCopy() throws RemoteException {
8628            int ret = PackageManager.INSTALL_SUCCEEDED;
8629
8630            // If we're already staged, we've firmly committed to an install location
8631            if (origin.staged) {
8632                if (origin.file != null) {
8633                    installFlags |= PackageManager.INSTALL_INTERNAL;
8634                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8635                } else if (origin.cid != null) {
8636                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8637                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8638                } else {
8639                    throw new IllegalStateException("Invalid stage location");
8640                }
8641            }
8642
8643            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8644            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8645
8646            PackageInfoLite pkgLite = null;
8647
8648            if (onInt && onSd) {
8649                // Check if both bits are set.
8650                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8651                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8652            } else {
8653                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8654                        packageAbiOverride);
8655
8656                /*
8657                 * If we have too little free space, try to free cache
8658                 * before giving up.
8659                 */
8660                if (!origin.staged && pkgLite.recommendedInstallLocation
8661                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8662                    // TODO: focus freeing disk space on the target device
8663                    final StorageManager storage = StorageManager.from(mContext);
8664                    final long lowThreshold = storage.getStorageLowBytes(
8665                            Environment.getDataDirectory());
8666
8667                    final long sizeBytes = mContainerService.calculateInstalledSize(
8668                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8669
8670                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8671                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8672                                installFlags, packageAbiOverride);
8673                    }
8674
8675                    /*
8676                     * The cache free must have deleted the file we
8677                     * downloaded to install.
8678                     *
8679                     * TODO: fix the "freeCache" call to not delete
8680                     *       the file we care about.
8681                     */
8682                    if (pkgLite.recommendedInstallLocation
8683                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8684                        pkgLite.recommendedInstallLocation
8685                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8686                    }
8687                }
8688            }
8689
8690            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8691                int loc = pkgLite.recommendedInstallLocation;
8692                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8693                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8694                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8695                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8696                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8697                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8698                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8699                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8700                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8701                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8702                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8703                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8704                } else {
8705                    // Override with defaults if needed.
8706                    loc = installLocationPolicy(pkgLite);
8707                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8708                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8709                    } else if (!onSd && !onInt) {
8710                        // Override install location with flags
8711                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8712                            // Set the flag to install on external media.
8713                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8714                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8715                        } else {
8716                            // Make sure the flag for installing on external
8717                            // media is unset
8718                            installFlags |= PackageManager.INSTALL_INTERNAL;
8719                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8720                        }
8721                    }
8722                }
8723            }
8724
8725            final InstallArgs args = createInstallArgs(this);
8726            mArgs = args;
8727
8728            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8729                 /*
8730                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8731                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8732                 */
8733                int userIdentifier = getUser().getIdentifier();
8734                if (userIdentifier == UserHandle.USER_ALL
8735                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8736                    userIdentifier = UserHandle.USER_OWNER;
8737                }
8738
8739                /*
8740                 * Determine if we have any installed package verifiers. If we
8741                 * do, then we'll defer to them to verify the packages.
8742                 */
8743                final int requiredUid = mRequiredVerifierPackage == null ? -1
8744                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8745                if (!origin.existing && requiredUid != -1
8746                        && isVerificationEnabled(userIdentifier, installFlags)) {
8747                    final Intent verification = new Intent(
8748                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8749                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8750                            PACKAGE_MIME_TYPE);
8751                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8752
8753                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8754                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8755                            0 /* TODO: Which userId? */);
8756
8757                    if (DEBUG_VERIFY) {
8758                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8759                                + verification.toString() + " with " + pkgLite.verifiers.length
8760                                + " optional verifiers");
8761                    }
8762
8763                    final int verificationId = mPendingVerificationToken++;
8764
8765                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8766
8767                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8768                            installerPackageName);
8769
8770                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8771                            installFlags);
8772
8773                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8774                            pkgLite.packageName);
8775
8776                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8777                            pkgLite.versionCode);
8778
8779                    if (verificationParams != null) {
8780                        if (verificationParams.getVerificationURI() != null) {
8781                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8782                                 verificationParams.getVerificationURI());
8783                        }
8784                        if (verificationParams.getOriginatingURI() != null) {
8785                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8786                                  verificationParams.getOriginatingURI());
8787                        }
8788                        if (verificationParams.getReferrer() != null) {
8789                            verification.putExtra(Intent.EXTRA_REFERRER,
8790                                  verificationParams.getReferrer());
8791                        }
8792                        if (verificationParams.getOriginatingUid() >= 0) {
8793                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8794                                  verificationParams.getOriginatingUid());
8795                        }
8796                        if (verificationParams.getInstallerUid() >= 0) {
8797                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8798                                  verificationParams.getInstallerUid());
8799                        }
8800                    }
8801
8802                    final PackageVerificationState verificationState = new PackageVerificationState(
8803                            requiredUid, args);
8804
8805                    mPendingVerification.append(verificationId, verificationState);
8806
8807                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8808                            receivers, verificationState);
8809
8810                    /*
8811                     * If any sufficient verifiers were listed in the package
8812                     * manifest, attempt to ask them.
8813                     */
8814                    if (sufficientVerifiers != null) {
8815                        final int N = sufficientVerifiers.size();
8816                        if (N == 0) {
8817                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8818                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8819                        } else {
8820                            for (int i = 0; i < N; i++) {
8821                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8822
8823                                final Intent sufficientIntent = new Intent(verification);
8824                                sufficientIntent.setComponent(verifierComponent);
8825
8826                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8827                            }
8828                        }
8829                    }
8830
8831                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8832                            mRequiredVerifierPackage, receivers);
8833                    if (ret == PackageManager.INSTALL_SUCCEEDED
8834                            && mRequiredVerifierPackage != null) {
8835                        /*
8836                         * Send the intent to the required verification agent,
8837                         * but only start the verification timeout after the
8838                         * target BroadcastReceivers have run.
8839                         */
8840                        verification.setComponent(requiredVerifierComponent);
8841                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8842                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8843                                new BroadcastReceiver() {
8844                                    @Override
8845                                    public void onReceive(Context context, Intent intent) {
8846                                        final Message msg = mHandler
8847                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8848                                        msg.arg1 = verificationId;
8849                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8850                                    }
8851                                }, null, 0, null, null);
8852
8853                        /*
8854                         * We don't want the copy to proceed until verification
8855                         * succeeds, so null out this field.
8856                         */
8857                        mArgs = null;
8858                    }
8859                } else {
8860                    /*
8861                     * No package verification is enabled, so immediately start
8862                     * the remote call to initiate copy using temporary file.
8863                     */
8864                    ret = args.copyApk(mContainerService, true);
8865                }
8866            }
8867
8868            mRet = ret;
8869        }
8870
8871        @Override
8872        void handleReturnCode() {
8873            // If mArgs is null, then MCS couldn't be reached. When it
8874            // reconnects, it will try again to install. At that point, this
8875            // will succeed.
8876            if (mArgs != null) {
8877                processPendingInstall(mArgs, mRet);
8878            }
8879        }
8880
8881        @Override
8882        void handleServiceError() {
8883            mArgs = createInstallArgs(this);
8884            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8885        }
8886
8887        public boolean isForwardLocked() {
8888            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8889        }
8890    }
8891
8892    /**
8893     * Used during creation of InstallArgs
8894     *
8895     * @param installFlags package installation flags
8896     * @return true if should be installed on external storage
8897     */
8898    private static boolean installOnSd(int installFlags) {
8899        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8900            return false;
8901        }
8902        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8903            return true;
8904        }
8905        return false;
8906    }
8907
8908    /**
8909     * Used during creation of InstallArgs
8910     *
8911     * @param installFlags package installation flags
8912     * @return true if should be installed as forward locked
8913     */
8914    private static boolean installForwardLocked(int installFlags) {
8915        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8916    }
8917
8918    private InstallArgs createInstallArgs(InstallParams params) {
8919        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8920            return new AsecInstallArgs(params);
8921        } else {
8922            return new FileInstallArgs(params);
8923        }
8924    }
8925
8926    /**
8927     * Create args that describe an existing installed package. Typically used
8928     * when cleaning up old installs, or used as a move source.
8929     */
8930    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8931            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8932        final boolean isInAsec;
8933        if (installOnSd(installFlags)) {
8934            /* Apps on SD card are always in ASEC containers. */
8935            isInAsec = true;
8936        } else if (installForwardLocked(installFlags)
8937                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8938            /*
8939             * Forward-locked apps are only in ASEC containers if they're the
8940             * new style
8941             */
8942            isInAsec = true;
8943        } else {
8944            isInAsec = false;
8945        }
8946
8947        if (isInAsec) {
8948            return new AsecInstallArgs(codePath, instructionSets,
8949                    installOnSd(installFlags), installForwardLocked(installFlags));
8950        } else {
8951            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8952                    instructionSets);
8953        }
8954    }
8955
8956    static abstract class InstallArgs {
8957        /** @see InstallParams#origin */
8958        final OriginInfo origin;
8959
8960        final IPackageInstallObserver2 observer;
8961        // Always refers to PackageManager flags only
8962        final int installFlags;
8963        final String installerPackageName;
8964        final ManifestDigest manifestDigest;
8965        final UserHandle user;
8966        final String abiOverride;
8967
8968        // The list of instruction sets supported by this app. This is currently
8969        // only used during the rmdex() phase to clean up resources. We can get rid of this
8970        // if we move dex files under the common app path.
8971        /* nullable */ String[] instructionSets;
8972
8973        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8974                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8975                String[] instructionSets, String abiOverride) {
8976            this.origin = origin;
8977            this.installFlags = installFlags;
8978            this.observer = observer;
8979            this.installerPackageName = installerPackageName;
8980            this.manifestDigest = manifestDigest;
8981            this.user = user;
8982            this.instructionSets = instructionSets;
8983            this.abiOverride = abiOverride;
8984        }
8985
8986        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8987        abstract int doPreInstall(int status);
8988
8989        /**
8990         * Rename package into final resting place. All paths on the given
8991         * scanned package should be updated to reflect the rename.
8992         */
8993        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8994        abstract int doPostInstall(int status, int uid);
8995
8996        /** @see PackageSettingBase#codePathString */
8997        abstract String getCodePath();
8998        /** @see PackageSettingBase#resourcePathString */
8999        abstract String getResourcePath();
9000        abstract String getLegacyNativeLibraryPath();
9001
9002        // Need installer lock especially for dex file removal.
9003        abstract void cleanUpResourcesLI();
9004        abstract boolean doPostDeleteLI(boolean delete);
9005        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9006
9007        /**
9008         * Called before the source arguments are copied. This is used mostly
9009         * for MoveParams when it needs to read the source file to put it in the
9010         * destination.
9011         */
9012        int doPreCopy() {
9013            return PackageManager.INSTALL_SUCCEEDED;
9014        }
9015
9016        /**
9017         * Called after the source arguments are copied. This is used mostly for
9018         * MoveParams when it needs to read the source file to put it in the
9019         * destination.
9020         *
9021         * @return
9022         */
9023        int doPostCopy(int uid) {
9024            return PackageManager.INSTALL_SUCCEEDED;
9025        }
9026
9027        protected boolean isFwdLocked() {
9028            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9029        }
9030
9031        protected boolean isExternal() {
9032            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9033        }
9034
9035        UserHandle getUser() {
9036            return user;
9037        }
9038    }
9039
9040    /**
9041     * Logic to handle installation of non-ASEC applications, including copying
9042     * and renaming logic.
9043     */
9044    class FileInstallArgs extends InstallArgs {
9045        private File codeFile;
9046        private File resourceFile;
9047        private File legacyNativeLibraryPath;
9048
9049        // Example topology:
9050        // /data/app/com.example/base.apk
9051        // /data/app/com.example/split_foo.apk
9052        // /data/app/com.example/lib/arm/libfoo.so
9053        // /data/app/com.example/lib/arm64/libfoo.so
9054        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9055
9056        /** New install */
9057        FileInstallArgs(InstallParams params) {
9058            super(params.origin, params.observer, params.installFlags,
9059                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9060                    null /* instruction sets */, params.packageAbiOverride);
9061            if (isFwdLocked()) {
9062                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9063            }
9064        }
9065
9066        /** Existing install */
9067        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9068                String[] instructionSets) {
9069            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9070            this.codeFile = (codePath != null) ? new File(codePath) : null;
9071            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9072            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9073                    new File(legacyNativeLibraryPath) : null;
9074        }
9075
9076        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9077            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9078                    isFwdLocked(), abiOverride);
9079
9080            final StorageManager storage = StorageManager.from(mContext);
9081            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9082        }
9083
9084        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9085            if (origin.staged) {
9086                Slog.d(TAG, origin.file + " already staged; skipping copy");
9087                codeFile = origin.file;
9088                resourceFile = origin.file;
9089                return PackageManager.INSTALL_SUCCEEDED;
9090            }
9091
9092            try {
9093                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9094                codeFile = tempDir;
9095                resourceFile = tempDir;
9096            } catch (IOException e) {
9097                Slog.w(TAG, "Failed to create copy file: " + e);
9098                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9099            }
9100
9101            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9102                @Override
9103                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9104                    if (!FileUtils.isValidExtFilename(name)) {
9105                        throw new IllegalArgumentException("Invalid filename: " + name);
9106                    }
9107                    try {
9108                        final File file = new File(codeFile, name);
9109                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9110                                O_RDWR | O_CREAT, 0644);
9111                        Os.chmod(file.getAbsolutePath(), 0644);
9112                        return new ParcelFileDescriptor(fd);
9113                    } catch (ErrnoException e) {
9114                        throw new RemoteException("Failed to open: " + e.getMessage());
9115                    }
9116                }
9117            };
9118
9119            int ret = PackageManager.INSTALL_SUCCEEDED;
9120            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9121            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9122                Slog.e(TAG, "Failed to copy package");
9123                return ret;
9124            }
9125
9126            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9127            NativeLibraryHelper.Handle handle = null;
9128            try {
9129                handle = NativeLibraryHelper.Handle.create(codeFile);
9130                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9131                        abiOverride);
9132            } catch (IOException e) {
9133                Slog.e(TAG, "Copying native libraries failed", e);
9134                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9135            } finally {
9136                IoUtils.closeQuietly(handle);
9137            }
9138
9139            return ret;
9140        }
9141
9142        int doPreInstall(int status) {
9143            if (status != PackageManager.INSTALL_SUCCEEDED) {
9144                cleanUp();
9145            }
9146            return status;
9147        }
9148
9149        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9150            if (status != PackageManager.INSTALL_SUCCEEDED) {
9151                cleanUp();
9152                return false;
9153            } else {
9154                final File beforeCodeFile = codeFile;
9155                final File afterCodeFile = getNextCodePath(pkg.packageName);
9156
9157                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9158                try {
9159                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9160                } catch (ErrnoException e) {
9161                    Slog.d(TAG, "Failed to rename", e);
9162                    return false;
9163                }
9164
9165                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9166                    Slog.d(TAG, "Failed to restorecon");
9167                    return false;
9168                }
9169
9170                // Reflect the rename internally
9171                codeFile = afterCodeFile;
9172                resourceFile = afterCodeFile;
9173
9174                // Reflect the rename in scanned details
9175                pkg.codePath = afterCodeFile.getAbsolutePath();
9176                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9177                        pkg.baseCodePath);
9178                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9179                        pkg.splitCodePaths);
9180
9181                // Reflect the rename in app info
9182                pkg.applicationInfo.setCodePath(pkg.codePath);
9183                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9184                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9185                pkg.applicationInfo.setResourcePath(pkg.codePath);
9186                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9187                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9188
9189                return true;
9190            }
9191        }
9192
9193        int doPostInstall(int status, int uid) {
9194            if (status != PackageManager.INSTALL_SUCCEEDED) {
9195                cleanUp();
9196            }
9197            return status;
9198        }
9199
9200        @Override
9201        String getCodePath() {
9202            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9203        }
9204
9205        @Override
9206        String getResourcePath() {
9207            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9208        }
9209
9210        @Override
9211        String getLegacyNativeLibraryPath() {
9212            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9213        }
9214
9215        private boolean cleanUp() {
9216            if (codeFile == null || !codeFile.exists()) {
9217                return false;
9218            }
9219
9220            if (codeFile.isDirectory()) {
9221                FileUtils.deleteContents(codeFile);
9222            }
9223            codeFile.delete();
9224
9225            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9226                resourceFile.delete();
9227            }
9228
9229            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9230                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9231                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9232                }
9233                legacyNativeLibraryPath.delete();
9234            }
9235
9236            return true;
9237        }
9238
9239        void cleanUpResourcesLI() {
9240            // Try enumerating all code paths before deleting
9241            List<String> allCodePaths = Collections.EMPTY_LIST;
9242            if (codeFile != null && codeFile.exists()) {
9243                try {
9244                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9245                    allCodePaths = pkg.getAllCodePaths();
9246                } catch (PackageParserException e) {
9247                    // Ignored; we tried our best
9248                }
9249            }
9250
9251            cleanUp();
9252
9253            if (!allCodePaths.isEmpty()) {
9254                if (instructionSets == null) {
9255                    throw new IllegalStateException("instructionSet == null");
9256                }
9257                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9258                for (String codePath : allCodePaths) {
9259                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9260                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9261                        if (retCode < 0) {
9262                            Slog.w(TAG, "Couldn't remove dex file for package: "
9263                                    + " at location " + codePath + ", retcode=" + retCode);
9264                            // we don't consider this to be a failure of the core package deletion
9265                        }
9266                    }
9267                }
9268            }
9269        }
9270
9271        boolean doPostDeleteLI(boolean delete) {
9272            // XXX err, shouldn't we respect the delete flag?
9273            cleanUpResourcesLI();
9274            return true;
9275        }
9276    }
9277
9278    private boolean isAsecExternal(String cid) {
9279        final String asecPath = PackageHelper.getSdFilesystem(cid);
9280        return !asecPath.startsWith(mAsecInternalPath);
9281    }
9282
9283    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9284            PackageManagerException {
9285        if (copyRet < 0) {
9286            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9287                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9288                throw new PackageManagerException(copyRet, message);
9289            }
9290        }
9291    }
9292
9293    /**
9294     * Extract the MountService "container ID" from the full code path of an
9295     * .apk.
9296     */
9297    static String cidFromCodePath(String fullCodePath) {
9298        int eidx = fullCodePath.lastIndexOf("/");
9299        String subStr1 = fullCodePath.substring(0, eidx);
9300        int sidx = subStr1.lastIndexOf("/");
9301        return subStr1.substring(sidx+1, eidx);
9302    }
9303
9304    /**
9305     * Logic to handle installation of ASEC applications, including copying and
9306     * renaming logic.
9307     */
9308    class AsecInstallArgs extends InstallArgs {
9309        static final String RES_FILE_NAME = "pkg.apk";
9310        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9311
9312        String cid;
9313        String packagePath;
9314        String resourcePath;
9315        String legacyNativeLibraryDir;
9316
9317        /** New install */
9318        AsecInstallArgs(InstallParams params) {
9319            super(params.origin, params.observer, params.installFlags,
9320                    params.installerPackageName, params.getManifestDigest(),
9321                    params.getUser(), null /* instruction sets */,
9322                    params.packageAbiOverride);
9323        }
9324
9325        /** Existing install */
9326        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9327                        boolean isExternal, boolean isForwardLocked) {
9328            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9329                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9330                    instructionSets, null);
9331            // Hackily pretend we're still looking at a full code path
9332            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9333                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9334            }
9335
9336            // Extract cid from fullCodePath
9337            int eidx = fullCodePath.lastIndexOf("/");
9338            String subStr1 = fullCodePath.substring(0, eidx);
9339            int sidx = subStr1.lastIndexOf("/");
9340            cid = subStr1.substring(sidx+1, eidx);
9341            setMountPath(subStr1);
9342        }
9343
9344        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9345            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9346                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9347                    instructionSets, null);
9348            this.cid = cid;
9349            setMountPath(PackageHelper.getSdDir(cid));
9350        }
9351
9352        void createCopyFile() {
9353            cid = mInstallerService.allocateExternalStageCidLegacy();
9354        }
9355
9356        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9357            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9358                    abiOverride);
9359
9360            final File target;
9361            if (isExternal()) {
9362                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9363            } else {
9364                target = Environment.getDataDirectory();
9365            }
9366
9367            final StorageManager storage = StorageManager.from(mContext);
9368            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9369        }
9370
9371        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9372            if (origin.staged) {
9373                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9374                cid = origin.cid;
9375                setMountPath(PackageHelper.getSdDir(cid));
9376                return PackageManager.INSTALL_SUCCEEDED;
9377            }
9378
9379            if (temp) {
9380                createCopyFile();
9381            } else {
9382                /*
9383                 * Pre-emptively destroy the container since it's destroyed if
9384                 * copying fails due to it existing anyway.
9385                 */
9386                PackageHelper.destroySdDir(cid);
9387            }
9388
9389            final String newMountPath = imcs.copyPackageToContainer(
9390                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9391                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9392
9393            if (newMountPath != null) {
9394                setMountPath(newMountPath);
9395                return PackageManager.INSTALL_SUCCEEDED;
9396            } else {
9397                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9398            }
9399        }
9400
9401        @Override
9402        String getCodePath() {
9403            return packagePath;
9404        }
9405
9406        @Override
9407        String getResourcePath() {
9408            return resourcePath;
9409        }
9410
9411        @Override
9412        String getLegacyNativeLibraryPath() {
9413            return legacyNativeLibraryDir;
9414        }
9415
9416        int doPreInstall(int status) {
9417            if (status != PackageManager.INSTALL_SUCCEEDED) {
9418                // Destroy container
9419                PackageHelper.destroySdDir(cid);
9420            } else {
9421                boolean mounted = PackageHelper.isContainerMounted(cid);
9422                if (!mounted) {
9423                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9424                            Process.SYSTEM_UID);
9425                    if (newMountPath != null) {
9426                        setMountPath(newMountPath);
9427                    } else {
9428                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9429                    }
9430                }
9431            }
9432            return status;
9433        }
9434
9435        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9436            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9437            String newMountPath = null;
9438            if (PackageHelper.isContainerMounted(cid)) {
9439                // Unmount the container
9440                if (!PackageHelper.unMountSdDir(cid)) {
9441                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9442                    return false;
9443                }
9444            }
9445            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9446                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9447                        " which might be stale. Will try to clean up.");
9448                // Clean up the stale container and proceed to recreate.
9449                if (!PackageHelper.destroySdDir(newCacheId)) {
9450                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9451                    return false;
9452                }
9453                // Successfully cleaned up stale container. Try to rename again.
9454                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9455                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9456                            + " inspite of cleaning it up.");
9457                    return false;
9458                }
9459            }
9460            if (!PackageHelper.isContainerMounted(newCacheId)) {
9461                Slog.w(TAG, "Mounting container " + newCacheId);
9462                newMountPath = PackageHelper.mountSdDir(newCacheId,
9463                        getEncryptKey(), Process.SYSTEM_UID);
9464            } else {
9465                newMountPath = PackageHelper.getSdDir(newCacheId);
9466            }
9467            if (newMountPath == null) {
9468                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9469                return false;
9470            }
9471            Log.i(TAG, "Succesfully renamed " + cid +
9472                    " to " + newCacheId +
9473                    " at new path: " + newMountPath);
9474            cid = newCacheId;
9475
9476            final File beforeCodeFile = new File(packagePath);
9477            setMountPath(newMountPath);
9478            final File afterCodeFile = new File(packagePath);
9479
9480            // Reflect the rename in scanned details
9481            pkg.codePath = afterCodeFile.getAbsolutePath();
9482            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9483                    pkg.baseCodePath);
9484            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9485                    pkg.splitCodePaths);
9486
9487            // Reflect the rename in app info
9488            pkg.applicationInfo.setCodePath(pkg.codePath);
9489            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9490            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9491            pkg.applicationInfo.setResourcePath(pkg.codePath);
9492            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9493            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9494
9495            return true;
9496        }
9497
9498        private void setMountPath(String mountPath) {
9499            final File mountFile = new File(mountPath);
9500
9501            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9502            if (monolithicFile.exists()) {
9503                packagePath = monolithicFile.getAbsolutePath();
9504                if (isFwdLocked()) {
9505                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9506                } else {
9507                    resourcePath = packagePath;
9508                }
9509            } else {
9510                packagePath = mountFile.getAbsolutePath();
9511                resourcePath = packagePath;
9512            }
9513
9514            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9515        }
9516
9517        int doPostInstall(int status, int uid) {
9518            if (status != PackageManager.INSTALL_SUCCEEDED) {
9519                cleanUp();
9520            } else {
9521                final int groupOwner;
9522                final String protectedFile;
9523                if (isFwdLocked()) {
9524                    groupOwner = UserHandle.getSharedAppGid(uid);
9525                    protectedFile = RES_FILE_NAME;
9526                } else {
9527                    groupOwner = -1;
9528                    protectedFile = null;
9529                }
9530
9531                if (uid < Process.FIRST_APPLICATION_UID
9532                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9533                    Slog.e(TAG, "Failed to finalize " + cid);
9534                    PackageHelper.destroySdDir(cid);
9535                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9536                }
9537
9538                boolean mounted = PackageHelper.isContainerMounted(cid);
9539                if (!mounted) {
9540                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9541                }
9542            }
9543            return status;
9544        }
9545
9546        private void cleanUp() {
9547            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9548
9549            // Destroy secure container
9550            PackageHelper.destroySdDir(cid);
9551        }
9552
9553        private List<String> getAllCodePaths() {
9554            final File codeFile = new File(getCodePath());
9555            if (codeFile != null && codeFile.exists()) {
9556                try {
9557                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9558                    return pkg.getAllCodePaths();
9559                } catch (PackageParserException e) {
9560                    // Ignored; we tried our best
9561                }
9562            }
9563            return Collections.EMPTY_LIST;
9564        }
9565
9566        void cleanUpResourcesLI() {
9567            // Enumerate all code paths before deleting
9568            cleanUpResourcesLI(getAllCodePaths());
9569        }
9570
9571        private void cleanUpResourcesLI(List<String> allCodePaths) {
9572            cleanUp();
9573
9574            if (!allCodePaths.isEmpty()) {
9575                if (instructionSets == null) {
9576                    throw new IllegalStateException("instructionSet == null");
9577                }
9578                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9579                for (String codePath : allCodePaths) {
9580                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9581                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9582                        if (retCode < 0) {
9583                            Slog.w(TAG, "Couldn't remove dex file for package: "
9584                                    + " at location " + codePath + ", retcode=" + retCode);
9585                            // we don't consider this to be a failure of the core package deletion
9586                        }
9587                    }
9588                }
9589            }
9590        }
9591
9592        boolean matchContainer(String app) {
9593            if (cid.startsWith(app)) {
9594                return true;
9595            }
9596            return false;
9597        }
9598
9599        String getPackageName() {
9600            return getAsecPackageName(cid);
9601        }
9602
9603        boolean doPostDeleteLI(boolean delete) {
9604            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9605            final List<String> allCodePaths = getAllCodePaths();
9606            boolean mounted = PackageHelper.isContainerMounted(cid);
9607            if (mounted) {
9608                // Unmount first
9609                if (PackageHelper.unMountSdDir(cid)) {
9610                    mounted = false;
9611                }
9612            }
9613            if (!mounted && delete) {
9614                cleanUpResourcesLI(allCodePaths);
9615            }
9616            return !mounted;
9617        }
9618
9619        @Override
9620        int doPreCopy() {
9621            if (isFwdLocked()) {
9622                if (!PackageHelper.fixSdPermissions(cid,
9623                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9624                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9625                }
9626            }
9627
9628            return PackageManager.INSTALL_SUCCEEDED;
9629        }
9630
9631        @Override
9632        int doPostCopy(int uid) {
9633            if (isFwdLocked()) {
9634                if (uid < Process.FIRST_APPLICATION_UID
9635                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9636                                RES_FILE_NAME)) {
9637                    Slog.e(TAG, "Failed to finalize " + cid);
9638                    PackageHelper.destroySdDir(cid);
9639                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9640                }
9641            }
9642
9643            return PackageManager.INSTALL_SUCCEEDED;
9644        }
9645    }
9646
9647    static String getAsecPackageName(String packageCid) {
9648        int idx = packageCid.lastIndexOf("-");
9649        if (idx == -1) {
9650            return packageCid;
9651        }
9652        return packageCid.substring(0, idx);
9653    }
9654
9655    // Utility method used to create code paths based on package name and available index.
9656    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9657        String idxStr = "";
9658        int idx = 1;
9659        // Fall back to default value of idx=1 if prefix is not
9660        // part of oldCodePath
9661        if (oldCodePath != null) {
9662            String subStr = oldCodePath;
9663            // Drop the suffix right away
9664            if (suffix != null && subStr.endsWith(suffix)) {
9665                subStr = subStr.substring(0, subStr.length() - suffix.length());
9666            }
9667            // If oldCodePath already contains prefix find out the
9668            // ending index to either increment or decrement.
9669            int sidx = subStr.lastIndexOf(prefix);
9670            if (sidx != -1) {
9671                subStr = subStr.substring(sidx + prefix.length());
9672                if (subStr != null) {
9673                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9674                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9675                    }
9676                    try {
9677                        idx = Integer.parseInt(subStr);
9678                        if (idx <= 1) {
9679                            idx++;
9680                        } else {
9681                            idx--;
9682                        }
9683                    } catch(NumberFormatException e) {
9684                    }
9685                }
9686            }
9687        }
9688        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9689        return prefix + idxStr;
9690    }
9691
9692    private File getNextCodePath(String packageName) {
9693        int suffix = 1;
9694        File result;
9695        do {
9696            result = new File(mAppInstallDir, packageName + "-" + suffix);
9697            suffix++;
9698        } while (result.exists());
9699        return result;
9700    }
9701
9702    // Utility method used to ignore ADD/REMOVE events
9703    // by directory observer.
9704    private static boolean ignoreCodePath(String fullPathStr) {
9705        String apkName = deriveCodePathName(fullPathStr);
9706        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9707        if (idx != -1 && ((idx+1) < apkName.length())) {
9708            // Make sure the package ends with a numeral
9709            String version = apkName.substring(idx+1);
9710            try {
9711                Integer.parseInt(version);
9712                return true;
9713            } catch (NumberFormatException e) {}
9714        }
9715        return false;
9716    }
9717
9718    // Utility method that returns the relative package path with respect
9719    // to the installation directory. Like say for /data/data/com.test-1.apk
9720    // string com.test-1 is returned.
9721    static String deriveCodePathName(String codePath) {
9722        if (codePath == null) {
9723            return null;
9724        }
9725        final File codeFile = new File(codePath);
9726        final String name = codeFile.getName();
9727        if (codeFile.isDirectory()) {
9728            return name;
9729        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9730            final int lastDot = name.lastIndexOf('.');
9731            return name.substring(0, lastDot);
9732        } else {
9733            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9734            return null;
9735        }
9736    }
9737
9738    class PackageInstalledInfo {
9739        String name;
9740        int uid;
9741        // The set of users that originally had this package installed.
9742        int[] origUsers;
9743        // The set of users that now have this package installed.
9744        int[] newUsers;
9745        PackageParser.Package pkg;
9746        int returnCode;
9747        String returnMsg;
9748        PackageRemovedInfo removedInfo;
9749
9750        public void setError(int code, String msg) {
9751            returnCode = code;
9752            returnMsg = msg;
9753            Slog.w(TAG, msg);
9754        }
9755
9756        public void setError(String msg, PackageParserException e) {
9757            returnCode = e.error;
9758            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9759            Slog.w(TAG, msg, e);
9760        }
9761
9762        public void setError(String msg, PackageManagerException e) {
9763            returnCode = e.error;
9764            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9765            Slog.w(TAG, msg, e);
9766        }
9767
9768        // In some error cases we want to convey more info back to the observer
9769        String origPackage;
9770        String origPermission;
9771    }
9772
9773    /*
9774     * Install a non-existing package.
9775     */
9776    private void installNewPackageLI(PackageParser.Package pkg,
9777            int parseFlags, int scanFlags, UserHandle user,
9778            String installerPackageName, PackageInstalledInfo res) {
9779        // Remember this for later, in case we need to rollback this install
9780        String pkgName = pkg.packageName;
9781
9782        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9783        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9784        synchronized(mPackages) {
9785            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9786                // A package with the same name is already installed, though
9787                // it has been renamed to an older name.  The package we
9788                // are trying to install should be installed as an update to
9789                // the existing one, but that has not been requested, so bail.
9790                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9791                        + " without first uninstalling package running as "
9792                        + mSettings.mRenamedPackages.get(pkgName));
9793                return;
9794            }
9795            if (mPackages.containsKey(pkgName)) {
9796                // Don't allow installation over an existing package with the same name.
9797                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9798                        + " without first uninstalling.");
9799                return;
9800            }
9801        }
9802
9803        try {
9804            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9805                    System.currentTimeMillis(), user);
9806
9807            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9808            // delete the partially installed application. the data directory will have to be
9809            // restored if it was already existing
9810            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9811                // remove package from internal structures.  Note that we want deletePackageX to
9812                // delete the package data and cache directories that it created in
9813                // scanPackageLocked, unless those directories existed before we even tried to
9814                // install.
9815                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9816                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9817                                res.removedInfo, true);
9818            }
9819
9820        } catch (PackageManagerException e) {
9821            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9822        }
9823    }
9824
9825    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9826        // Upgrade keysets are being used.  Determine if new package has a superset of the
9827        // required keys.
9828        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9829        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9830        for (int i = 0; i < upgradeKeySets.length; i++) {
9831            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9832            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9833                return true;
9834            }
9835        }
9836        return false;
9837    }
9838
9839    private void replacePackageLI(PackageParser.Package pkg,
9840            int parseFlags, int scanFlags, UserHandle user,
9841            String installerPackageName, PackageInstalledInfo res) {
9842        PackageParser.Package oldPackage;
9843        String pkgName = pkg.packageName;
9844        int[] allUsers;
9845        boolean[] perUserInstalled;
9846
9847        // First find the old package info and check signatures
9848        synchronized(mPackages) {
9849            oldPackage = mPackages.get(pkgName);
9850            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9851            PackageSetting ps = mSettings.mPackages.get(pkgName);
9852            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9853                // default to original signature matching
9854                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9855                    != PackageManager.SIGNATURE_MATCH) {
9856                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9857                            "New package has a different signature: " + pkgName);
9858                    return;
9859                }
9860            } else {
9861                if(!checkUpgradeKeySetLP(ps, pkg)) {
9862                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9863                            "New package not signed by keys specified by upgrade-keysets: "
9864                            + pkgName);
9865                    return;
9866                }
9867            }
9868
9869            // In case of rollback, remember per-user/profile install state
9870            allUsers = sUserManager.getUserIds();
9871            perUserInstalled = new boolean[allUsers.length];
9872            for (int i = 0; i < allUsers.length; i++) {
9873                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9874            }
9875        }
9876
9877        boolean sysPkg = (isSystemApp(oldPackage));
9878        if (sysPkg) {
9879            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9880                    user, allUsers, perUserInstalled, installerPackageName, res);
9881        } else {
9882            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9883                    user, allUsers, perUserInstalled, installerPackageName, res);
9884        }
9885    }
9886
9887    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9888            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9889            int[] allUsers, boolean[] perUserInstalled,
9890            String installerPackageName, PackageInstalledInfo res) {
9891        String pkgName = deletedPackage.packageName;
9892        boolean deletedPkg = true;
9893        boolean updatedSettings = false;
9894
9895        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9896                + deletedPackage);
9897        long origUpdateTime;
9898        if (pkg.mExtras != null) {
9899            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9900        } else {
9901            origUpdateTime = 0;
9902        }
9903
9904        // First delete the existing package while retaining the data directory
9905        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9906                res.removedInfo, true)) {
9907            // If the existing package wasn't successfully deleted
9908            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9909            deletedPkg = false;
9910        } else {
9911            // Successfully deleted the old package; proceed with replace.
9912
9913            // If deleted package lived in a container, give users a chance to
9914            // relinquish resources before killing.
9915            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9916                if (DEBUG_INSTALL) {
9917                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9918                }
9919                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9920                final ArrayList<String> pkgList = new ArrayList<String>(1);
9921                pkgList.add(deletedPackage.applicationInfo.packageName);
9922                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9923            }
9924
9925            deleteCodeCacheDirsLI(pkgName);
9926            try {
9927                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9928                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9929                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9930                updatedSettings = true;
9931            } catch (PackageManagerException e) {
9932                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9933            }
9934        }
9935
9936        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9937            // remove package from internal structures.  Note that we want deletePackageX to
9938            // delete the package data and cache directories that it created in
9939            // scanPackageLocked, unless those directories existed before we even tried to
9940            // install.
9941            if(updatedSettings) {
9942                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9943                deletePackageLI(
9944                        pkgName, null, true, allUsers, perUserInstalled,
9945                        PackageManager.DELETE_KEEP_DATA,
9946                                res.removedInfo, true);
9947            }
9948            // Since we failed to install the new package we need to restore the old
9949            // package that we deleted.
9950            if (deletedPkg) {
9951                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9952                File restoreFile = new File(deletedPackage.codePath);
9953                // Parse old package
9954                boolean oldOnSd = isExternal(deletedPackage);
9955                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9956                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9957                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9958                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9959                try {
9960                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9961                } catch (PackageManagerException e) {
9962                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9963                            + e.getMessage());
9964                    return;
9965                }
9966                // Restore of old package succeeded. Update permissions.
9967                // writer
9968                synchronized (mPackages) {
9969                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9970                            UPDATE_PERMISSIONS_ALL);
9971                    // can downgrade to reader
9972                    mSettings.writeLPr();
9973                }
9974                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9975            }
9976        }
9977    }
9978
9979    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9980            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9981            int[] allUsers, boolean[] perUserInstalled,
9982            String installerPackageName, PackageInstalledInfo res) {
9983        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9984                + ", old=" + deletedPackage);
9985        boolean updatedSettings = false;
9986        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9987        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9988            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9989        }
9990        String packageName = deletedPackage.packageName;
9991        if (packageName == null) {
9992            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9993                    "Attempt to delete null packageName.");
9994            return;
9995        }
9996        PackageParser.Package oldPkg;
9997        PackageSetting oldPkgSetting;
9998        // reader
9999        synchronized (mPackages) {
10000            oldPkg = mPackages.get(packageName);
10001            oldPkgSetting = mSettings.mPackages.get(packageName);
10002            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10003                    (oldPkgSetting == null)) {
10004                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10005                        "Couldn't find package:" + packageName + " information");
10006                return;
10007            }
10008        }
10009
10010        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10011
10012        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10013        res.removedInfo.removedPackage = packageName;
10014        // Remove existing system package
10015        removePackageLI(oldPkgSetting, true);
10016        // writer
10017        synchronized (mPackages) {
10018            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10019                // We didn't need to disable the .apk as a current system package,
10020                // which means we are replacing another update that is already
10021                // installed.  We need to make sure to delete the older one's .apk.
10022                res.removedInfo.args = createInstallArgsForExisting(0,
10023                        deletedPackage.applicationInfo.getCodePath(),
10024                        deletedPackage.applicationInfo.getResourcePath(),
10025                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10026                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10027            } else {
10028                res.removedInfo.args = null;
10029            }
10030        }
10031
10032        // Successfully disabled the old package. Now proceed with re-installation
10033        deleteCodeCacheDirsLI(packageName);
10034
10035        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10036        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10037
10038        PackageParser.Package newPackage = null;
10039        try {
10040            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10041            if (newPackage.mExtras != null) {
10042                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10043                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10044                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10045
10046                // is the update attempting to change shared user? that isn't going to work...
10047                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10048                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10049                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10050                            + " to " + newPkgSetting.sharedUser);
10051                    updatedSettings = true;
10052                }
10053            }
10054
10055            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10056                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10057                updatedSettings = true;
10058            }
10059
10060        } catch (PackageManagerException e) {
10061            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10062        }
10063
10064        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10065            // Re installation failed. Restore old information
10066            // Remove new pkg information
10067            if (newPackage != null) {
10068                removeInstalledPackageLI(newPackage, true);
10069            }
10070            // Add back the old system package
10071            try {
10072                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10073            } catch (PackageManagerException e) {
10074                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10075            }
10076            // Restore the old system information in Settings
10077            synchronized(mPackages) {
10078                if (updatedSettings) {
10079                    mSettings.enableSystemPackageLPw(packageName);
10080                    mSettings.setInstallerPackageName(packageName,
10081                            oldPkgSetting.installerPackageName);
10082                }
10083                mSettings.writeLPr();
10084            }
10085        }
10086    }
10087
10088    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10089            int[] allUsers, boolean[] perUserInstalled,
10090            PackageInstalledInfo res) {
10091        String pkgName = newPackage.packageName;
10092        synchronized (mPackages) {
10093            //write settings. the installStatus will be incomplete at this stage.
10094            //note that the new package setting would have already been
10095            //added to mPackages. It hasn't been persisted yet.
10096            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10097            mSettings.writeLPr();
10098        }
10099
10100        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10101
10102        synchronized (mPackages) {
10103            updatePermissionsLPw(newPackage.packageName, newPackage,
10104                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10105                            ? UPDATE_PERMISSIONS_ALL : 0));
10106            // For system-bundled packages, we assume that installing an upgraded version
10107            // of the package implies that the user actually wants to run that new code,
10108            // so we enable the package.
10109            if (isSystemApp(newPackage)) {
10110                // NB: implicit assumption that system package upgrades apply to all users
10111                if (DEBUG_INSTALL) {
10112                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10113                }
10114                PackageSetting ps = mSettings.mPackages.get(pkgName);
10115                if (ps != null) {
10116                    if (res.origUsers != null) {
10117                        for (int userHandle : res.origUsers) {
10118                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10119                                    userHandle, installerPackageName);
10120                        }
10121                    }
10122                    // Also convey the prior install/uninstall state
10123                    if (allUsers != null && perUserInstalled != null) {
10124                        for (int i = 0; i < allUsers.length; i++) {
10125                            if (DEBUG_INSTALL) {
10126                                Slog.d(TAG, "    user " + allUsers[i]
10127                                        + " => " + perUserInstalled[i]);
10128                            }
10129                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10130                        }
10131                        // these install state changes will be persisted in the
10132                        // upcoming call to mSettings.writeLPr().
10133                    }
10134                }
10135            }
10136            res.name = pkgName;
10137            res.uid = newPackage.applicationInfo.uid;
10138            res.pkg = newPackage;
10139            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10140            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10141            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10142            //to update install status
10143            mSettings.writeLPr();
10144        }
10145    }
10146
10147    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10148        final int installFlags = args.installFlags;
10149        String installerPackageName = args.installerPackageName;
10150        File tmpPackageFile = new File(args.getCodePath());
10151        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10152        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10153        boolean replace = false;
10154        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10155        // Result object to be returned
10156        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10157
10158        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10159        // Retrieve PackageSettings and parse package
10160        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10161                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10162                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10163        PackageParser pp = new PackageParser();
10164        pp.setSeparateProcesses(mSeparateProcesses);
10165        pp.setDisplayMetrics(mMetrics);
10166
10167        final PackageParser.Package pkg;
10168        try {
10169            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10170        } catch (PackageParserException e) {
10171            res.setError("Failed parse during installPackageLI", e);
10172            return;
10173        }
10174
10175        // Mark that we have an install time CPU ABI override.
10176        pkg.cpuAbiOverride = args.abiOverride;
10177
10178        String pkgName = res.name = pkg.packageName;
10179        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10180            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10181                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10182                return;
10183            }
10184        }
10185
10186        try {
10187            pp.collectCertificates(pkg, parseFlags);
10188            pp.collectManifestDigest(pkg);
10189        } catch (PackageParserException e) {
10190            res.setError("Failed collect during installPackageLI", e);
10191            return;
10192        }
10193
10194        /* If the installer passed in a manifest digest, compare it now. */
10195        if (args.manifestDigest != null) {
10196            if (DEBUG_INSTALL) {
10197                final String parsedManifest = pkg.manifestDigest == null ? "null"
10198                        : pkg.manifestDigest.toString();
10199                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10200                        + parsedManifest);
10201            }
10202
10203            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10204                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10205                return;
10206            }
10207        } else if (DEBUG_INSTALL) {
10208            final String parsedManifest = pkg.manifestDigest == null
10209                    ? "null" : pkg.manifestDigest.toString();
10210            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10211        }
10212
10213        // Get rid of all references to package scan path via parser.
10214        pp = null;
10215        String oldCodePath = null;
10216        boolean systemApp = false;
10217        synchronized (mPackages) {
10218            // Check whether the newly-scanned package wants to define an already-defined perm
10219            int N = pkg.permissions.size();
10220            for (int i = N-1; i >= 0; i--) {
10221                PackageParser.Permission perm = pkg.permissions.get(i);
10222                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10223                if (bp != null) {
10224                    // If the defining package is signed with our cert, it's okay.  This
10225                    // also includes the "updating the same package" case, of course.
10226                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10227                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10228                        // If the owning package is the system itself, we log but allow
10229                        // install to proceed; we fail the install on all other permission
10230                        // redefinitions.
10231                        if (!bp.sourcePackage.equals("android")) {
10232                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10233                                    + pkg.packageName + " attempting to redeclare permission "
10234                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10235                            res.origPermission = perm.info.name;
10236                            res.origPackage = bp.sourcePackage;
10237                            return;
10238                        } else {
10239                            Slog.w(TAG, "Package " + pkg.packageName
10240                                    + " attempting to redeclare system permission "
10241                                    + perm.info.name + "; ignoring new declaration");
10242                            pkg.permissions.remove(i);
10243                        }
10244                    }
10245                }
10246            }
10247
10248            // Check if installing already existing package
10249            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10250                String oldName = mSettings.mRenamedPackages.get(pkgName);
10251                if (pkg.mOriginalPackages != null
10252                        && pkg.mOriginalPackages.contains(oldName)
10253                        && mPackages.containsKey(oldName)) {
10254                    // This package is derived from an original package,
10255                    // and this device has been updating from that original
10256                    // name.  We must continue using the original name, so
10257                    // rename the new package here.
10258                    pkg.setPackageName(oldName);
10259                    pkgName = pkg.packageName;
10260                    replace = true;
10261                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10262                            + oldName + " pkgName=" + pkgName);
10263                } else if (mPackages.containsKey(pkgName)) {
10264                    // This package, under its official name, already exists
10265                    // on the device; we should replace it.
10266                    replace = true;
10267                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10268                }
10269            }
10270            PackageSetting ps = mSettings.mPackages.get(pkgName);
10271            if (ps != null) {
10272                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10273                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10274                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10275                    systemApp = (ps.pkg.applicationInfo.flags &
10276                            ApplicationInfo.FLAG_SYSTEM) != 0;
10277                }
10278                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10279            }
10280        }
10281
10282        if (systemApp && onSd) {
10283            // Disable updates to system apps on sdcard
10284            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10285                    "Cannot install updates to system apps on sdcard");
10286            return;
10287        }
10288
10289        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10290            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10291            return;
10292        }
10293
10294        if (replace) {
10295            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10296                    installerPackageName, res);
10297        } else {
10298            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10299                    args.user, installerPackageName, res);
10300        }
10301        synchronized (mPackages) {
10302            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10303            if (ps != null) {
10304                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10305            }
10306        }
10307    }
10308
10309    private static boolean isForwardLocked(PackageParser.Package pkg) {
10310        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10311    }
10312
10313    private static boolean isForwardLocked(ApplicationInfo info) {
10314        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10315    }
10316
10317    private boolean isForwardLocked(PackageSetting ps) {
10318        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10319    }
10320
10321    private static boolean isMultiArch(PackageSetting ps) {
10322        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10323    }
10324
10325    private static boolean isMultiArch(ApplicationInfo info) {
10326        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10327    }
10328
10329    private static boolean isExternal(PackageParser.Package pkg) {
10330        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10331    }
10332
10333    private static boolean isExternal(PackageSetting ps) {
10334        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10335    }
10336
10337    private static boolean isExternal(ApplicationInfo info) {
10338        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10339    }
10340
10341    private static boolean isSystemApp(PackageParser.Package pkg) {
10342        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10343    }
10344
10345    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10346        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10347    }
10348
10349    private static boolean isSystemApp(ApplicationInfo info) {
10350        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10351    }
10352
10353    private static boolean isSystemApp(PackageSetting ps) {
10354        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10355    }
10356
10357    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10358        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10359    }
10360
10361    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10362        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10363    }
10364
10365    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10366        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10367    }
10368
10369    private int packageFlagsToInstallFlags(PackageSetting ps) {
10370        int installFlags = 0;
10371        if (isExternal(ps)) {
10372            installFlags |= PackageManager.INSTALL_EXTERNAL;
10373        }
10374        if (isForwardLocked(ps)) {
10375            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10376        }
10377        return installFlags;
10378    }
10379
10380    private void deleteTempPackageFiles() {
10381        final FilenameFilter filter = new FilenameFilter() {
10382            public boolean accept(File dir, String name) {
10383                return name.startsWith("vmdl") && name.endsWith(".tmp");
10384            }
10385        };
10386        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10387            file.delete();
10388        }
10389    }
10390
10391    @Override
10392    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10393            int flags) {
10394        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10395                flags);
10396    }
10397
10398    @Override
10399    public void deletePackage(final String packageName,
10400            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10401        mContext.enforceCallingOrSelfPermission(
10402                android.Manifest.permission.DELETE_PACKAGES, null);
10403        final int uid = Binder.getCallingUid();
10404        if (UserHandle.getUserId(uid) != userId) {
10405            mContext.enforceCallingPermission(
10406                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10407                    "deletePackage for user " + userId);
10408        }
10409        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10410            try {
10411                observer.onPackageDeleted(packageName,
10412                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10413            } catch (RemoteException re) {
10414            }
10415            return;
10416        }
10417
10418        boolean uninstallBlocked = false;
10419        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10420            int[] users = sUserManager.getUserIds();
10421            for (int i = 0; i < users.length; ++i) {
10422                if (getBlockUninstallForUser(packageName, users[i])) {
10423                    uninstallBlocked = true;
10424                    break;
10425                }
10426            }
10427        } else {
10428            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10429        }
10430        if (uninstallBlocked) {
10431            try {
10432                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10433                        null);
10434            } catch (RemoteException re) {
10435            }
10436            return;
10437        }
10438
10439        if (DEBUG_REMOVE) {
10440            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10441        }
10442        // Queue up an async operation since the package deletion may take a little while.
10443        mHandler.post(new Runnable() {
10444            public void run() {
10445                mHandler.removeCallbacks(this);
10446                final int returnCode = deletePackageX(packageName, userId, flags);
10447                if (observer != null) {
10448                    try {
10449                        observer.onPackageDeleted(packageName, returnCode, null);
10450                    } catch (RemoteException e) {
10451                        Log.i(TAG, "Observer no longer exists.");
10452                    } //end catch
10453                } //end if
10454            } //end run
10455        });
10456    }
10457
10458    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10459        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10460                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10461        try {
10462            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10463                    || dpm.isDeviceOwner(packageName))) {
10464                return true;
10465            }
10466        } catch (RemoteException e) {
10467        }
10468        return false;
10469    }
10470
10471    /**
10472     *  This method is an internal method that could be get invoked either
10473     *  to delete an installed package or to clean up a failed installation.
10474     *  After deleting an installed package, a broadcast is sent to notify any
10475     *  listeners that the package has been installed. For cleaning up a failed
10476     *  installation, the broadcast is not necessary since the package's
10477     *  installation wouldn't have sent the initial broadcast either
10478     *  The key steps in deleting a package are
10479     *  deleting the package information in internal structures like mPackages,
10480     *  deleting the packages base directories through installd
10481     *  updating mSettings to reflect current status
10482     *  persisting settings for later use
10483     *  sending a broadcast if necessary
10484     */
10485    private int deletePackageX(String packageName, int userId, int flags) {
10486        final PackageRemovedInfo info = new PackageRemovedInfo();
10487        final boolean res;
10488
10489        if (isPackageDeviceAdmin(packageName, userId)) {
10490            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10491            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10492        }
10493
10494        boolean removedForAllUsers = false;
10495        boolean systemUpdate = false;
10496
10497        // for the uninstall-updates case and restricted profiles, remember the per-
10498        // userhandle installed state
10499        int[] allUsers;
10500        boolean[] perUserInstalled;
10501        synchronized (mPackages) {
10502            PackageSetting ps = mSettings.mPackages.get(packageName);
10503            allUsers = sUserManager.getUserIds();
10504            perUserInstalled = new boolean[allUsers.length];
10505            for (int i = 0; i < allUsers.length; i++) {
10506                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10507            }
10508        }
10509
10510        synchronized (mInstallLock) {
10511            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10512            res = deletePackageLI(packageName,
10513                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10514                            ? UserHandle.ALL : new UserHandle(userId),
10515                    true, allUsers, perUserInstalled,
10516                    flags | REMOVE_CHATTY, info, true);
10517            systemUpdate = info.isRemovedPackageSystemUpdate;
10518            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10519                removedForAllUsers = true;
10520            }
10521            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10522                    + " removedForAllUsers=" + removedForAllUsers);
10523        }
10524
10525        if (res) {
10526            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10527
10528            // If the removed package was a system update, the old system package
10529            // was re-enabled; we need to broadcast this information
10530            if (systemUpdate) {
10531                Bundle extras = new Bundle(1);
10532                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10533                        ? info.removedAppId : info.uid);
10534                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10535
10536                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10537                        extras, null, null, null);
10538                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10539                        extras, null, null, null);
10540                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10541                        null, packageName, null, null);
10542            }
10543        }
10544        // Force a gc here.
10545        Runtime.getRuntime().gc();
10546        // Delete the resources here after sending the broadcast to let
10547        // other processes clean up before deleting resources.
10548        if (info.args != null) {
10549            synchronized (mInstallLock) {
10550                info.args.doPostDeleteLI(true);
10551            }
10552        }
10553
10554        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10555    }
10556
10557    static class PackageRemovedInfo {
10558        String removedPackage;
10559        int uid = -1;
10560        int removedAppId = -1;
10561        int[] removedUsers = null;
10562        boolean isRemovedPackageSystemUpdate = false;
10563        // Clean up resources deleted packages.
10564        InstallArgs args = null;
10565
10566        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10567            Bundle extras = new Bundle(1);
10568            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10569            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10570            if (replacing) {
10571                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10572            }
10573            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10574            if (removedPackage != null) {
10575                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10576                        extras, null, null, removedUsers);
10577                if (fullRemove && !replacing) {
10578                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10579                            extras, null, null, removedUsers);
10580                }
10581            }
10582            if (removedAppId >= 0) {
10583                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10584                        removedUsers);
10585            }
10586        }
10587    }
10588
10589    /*
10590     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10591     * flag is not set, the data directory is removed as well.
10592     * make sure this flag is set for partially installed apps. If not its meaningless to
10593     * delete a partially installed application.
10594     */
10595    private void removePackageDataLI(PackageSetting ps,
10596            int[] allUserHandles, boolean[] perUserInstalled,
10597            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10598        String packageName = ps.name;
10599        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10600        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10601        // Retrieve object to delete permissions for shared user later on
10602        final PackageSetting deletedPs;
10603        // reader
10604        synchronized (mPackages) {
10605            deletedPs = mSettings.mPackages.get(packageName);
10606            if (outInfo != null) {
10607                outInfo.removedPackage = packageName;
10608                outInfo.removedUsers = deletedPs != null
10609                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10610                        : null;
10611            }
10612        }
10613        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10614            removeDataDirsLI(packageName);
10615            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10616        }
10617        // writer
10618        synchronized (mPackages) {
10619            if (deletedPs != null) {
10620                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10621                    if (outInfo != null) {
10622                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10623                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10624                    }
10625                    if (deletedPs != null) {
10626                        updatePermissionsLPw(deletedPs.name, null, 0);
10627                        if (deletedPs.sharedUser != null) {
10628                            // remove permissions associated with package
10629                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10630                        }
10631                    }
10632                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10633                }
10634                // make sure to preserve per-user disabled state if this removal was just
10635                // a downgrade of a system app to the factory package
10636                if (allUserHandles != null && perUserInstalled != null) {
10637                    if (DEBUG_REMOVE) {
10638                        Slog.d(TAG, "Propagating install state across downgrade");
10639                    }
10640                    for (int i = 0; i < allUserHandles.length; i++) {
10641                        if (DEBUG_REMOVE) {
10642                            Slog.d(TAG, "    user " + allUserHandles[i]
10643                                    + " => " + perUserInstalled[i]);
10644                        }
10645                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10646                    }
10647                }
10648            }
10649            // can downgrade to reader
10650            if (writeSettings) {
10651                // Save settings now
10652                mSettings.writeLPr();
10653            }
10654        }
10655        if (outInfo != null) {
10656            // A user ID was deleted here. Go through all users and remove it
10657            // from KeyStore.
10658            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10659        }
10660    }
10661
10662    static boolean locationIsPrivileged(File path) {
10663        try {
10664            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10665                    .getCanonicalPath();
10666            return path.getCanonicalPath().startsWith(privilegedAppDir);
10667        } catch (IOException e) {
10668            Slog.e(TAG, "Unable to access code path " + path);
10669        }
10670        return false;
10671    }
10672
10673    /*
10674     * Tries to delete system package.
10675     */
10676    private boolean deleteSystemPackageLI(PackageSetting newPs,
10677            int[] allUserHandles, boolean[] perUserInstalled,
10678            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10679        final boolean applyUserRestrictions
10680                = (allUserHandles != null) && (perUserInstalled != null);
10681        PackageSetting disabledPs = null;
10682        // Confirm if the system package has been updated
10683        // An updated system app can be deleted. This will also have to restore
10684        // the system pkg from system partition
10685        // reader
10686        synchronized (mPackages) {
10687            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10688        }
10689        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10690                + " disabledPs=" + disabledPs);
10691        if (disabledPs == null) {
10692            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10693            return false;
10694        } else if (DEBUG_REMOVE) {
10695            Slog.d(TAG, "Deleting system pkg from data partition");
10696        }
10697        if (DEBUG_REMOVE) {
10698            if (applyUserRestrictions) {
10699                Slog.d(TAG, "Remembering install states:");
10700                for (int i = 0; i < allUserHandles.length; i++) {
10701                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10702                }
10703            }
10704        }
10705        // Delete the updated package
10706        outInfo.isRemovedPackageSystemUpdate = true;
10707        if (disabledPs.versionCode < newPs.versionCode) {
10708            // Delete data for downgrades
10709            flags &= ~PackageManager.DELETE_KEEP_DATA;
10710        } else {
10711            // Preserve data by setting flag
10712            flags |= PackageManager.DELETE_KEEP_DATA;
10713        }
10714        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10715                allUserHandles, perUserInstalled, outInfo, writeSettings);
10716        if (!ret) {
10717            return false;
10718        }
10719        // writer
10720        synchronized (mPackages) {
10721            // Reinstate the old system package
10722            mSettings.enableSystemPackageLPw(newPs.name);
10723            // Remove any native libraries from the upgraded package.
10724            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10725        }
10726        // Install the system package
10727        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10728        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10729        if (locationIsPrivileged(disabledPs.codePath)) {
10730            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10731        }
10732
10733        final PackageParser.Package newPkg;
10734        try {
10735            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10736        } catch (PackageManagerException e) {
10737            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10738            return false;
10739        }
10740
10741        // writer
10742        synchronized (mPackages) {
10743            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10744            updatePermissionsLPw(newPkg.packageName, newPkg,
10745                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10746            if (applyUserRestrictions) {
10747                if (DEBUG_REMOVE) {
10748                    Slog.d(TAG, "Propagating install state across reinstall");
10749                }
10750                for (int i = 0; i < allUserHandles.length; i++) {
10751                    if (DEBUG_REMOVE) {
10752                        Slog.d(TAG, "    user " + allUserHandles[i]
10753                                + " => " + perUserInstalled[i]);
10754                    }
10755                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10756                }
10757                // Regardless of writeSettings we need to ensure that this restriction
10758                // state propagation is persisted
10759                mSettings.writeAllUsersPackageRestrictionsLPr();
10760            }
10761            // can downgrade to reader here
10762            if (writeSettings) {
10763                mSettings.writeLPr();
10764            }
10765        }
10766        return true;
10767    }
10768
10769    private boolean deleteInstalledPackageLI(PackageSetting ps,
10770            boolean deleteCodeAndResources, int flags,
10771            int[] allUserHandles, boolean[] perUserInstalled,
10772            PackageRemovedInfo outInfo, boolean writeSettings) {
10773        if (outInfo != null) {
10774            outInfo.uid = ps.appId;
10775        }
10776
10777        // Delete package data from internal structures and also remove data if flag is set
10778        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10779
10780        // Delete application code and resources
10781        if (deleteCodeAndResources && (outInfo != null)) {
10782            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10783                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10784                    getAppDexInstructionSets(ps));
10785            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10786        }
10787        return true;
10788    }
10789
10790    @Override
10791    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10792            int userId) {
10793        mContext.enforceCallingOrSelfPermission(
10794                android.Manifest.permission.DELETE_PACKAGES, null);
10795        synchronized (mPackages) {
10796            PackageSetting ps = mSettings.mPackages.get(packageName);
10797            if (ps == null) {
10798                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10799                return false;
10800            }
10801            if (!ps.getInstalled(userId)) {
10802                // Can't block uninstall for an app that is not installed or enabled.
10803                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10804                return false;
10805            }
10806            ps.setBlockUninstall(blockUninstall, userId);
10807            mSettings.writePackageRestrictionsLPr(userId);
10808        }
10809        return true;
10810    }
10811
10812    @Override
10813    public boolean getBlockUninstallForUser(String packageName, int userId) {
10814        synchronized (mPackages) {
10815            PackageSetting ps = mSettings.mPackages.get(packageName);
10816            if (ps == null) {
10817                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10818                return false;
10819            }
10820            return ps.getBlockUninstall(userId);
10821        }
10822    }
10823
10824    /*
10825     * This method handles package deletion in general
10826     */
10827    private boolean deletePackageLI(String packageName, UserHandle user,
10828            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10829            int flags, PackageRemovedInfo outInfo,
10830            boolean writeSettings) {
10831        if (packageName == null) {
10832            Slog.w(TAG, "Attempt to delete null packageName.");
10833            return false;
10834        }
10835        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10836        PackageSetting ps;
10837        boolean dataOnly = false;
10838        int removeUser = -1;
10839        int appId = -1;
10840        synchronized (mPackages) {
10841            ps = mSettings.mPackages.get(packageName);
10842            if (ps == null) {
10843                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10844                return false;
10845            }
10846            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10847                    && user.getIdentifier() != UserHandle.USER_ALL) {
10848                // The caller is asking that the package only be deleted for a single
10849                // user.  To do this, we just mark its uninstalled state and delete
10850                // its data.  If this is a system app, we only allow this to happen if
10851                // they have set the special DELETE_SYSTEM_APP which requests different
10852                // semantics than normal for uninstalling system apps.
10853                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10854                ps.setUserState(user.getIdentifier(),
10855                        COMPONENT_ENABLED_STATE_DEFAULT,
10856                        false, //installed
10857                        true,  //stopped
10858                        true,  //notLaunched
10859                        false, //hidden
10860                        null, null, null,
10861                        false // blockUninstall
10862                        );
10863                if (!isSystemApp(ps)) {
10864                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10865                        // Other user still have this package installed, so all
10866                        // we need to do is clear this user's data and save that
10867                        // it is uninstalled.
10868                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10869                        removeUser = user.getIdentifier();
10870                        appId = ps.appId;
10871                        mSettings.writePackageRestrictionsLPr(removeUser);
10872                    } else {
10873                        // We need to set it back to 'installed' so the uninstall
10874                        // broadcasts will be sent correctly.
10875                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10876                        ps.setInstalled(true, user.getIdentifier());
10877                    }
10878                } else {
10879                    // This is a system app, so we assume that the
10880                    // other users still have this package installed, so all
10881                    // we need to do is clear this user's data and save that
10882                    // it is uninstalled.
10883                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10884                    removeUser = user.getIdentifier();
10885                    appId = ps.appId;
10886                    mSettings.writePackageRestrictionsLPr(removeUser);
10887                }
10888            }
10889        }
10890
10891        if (removeUser >= 0) {
10892            // From above, we determined that we are deleting this only
10893            // for a single user.  Continue the work here.
10894            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10895            if (outInfo != null) {
10896                outInfo.removedPackage = packageName;
10897                outInfo.removedAppId = appId;
10898                outInfo.removedUsers = new int[] {removeUser};
10899            }
10900            mInstaller.clearUserData(packageName, removeUser);
10901            removeKeystoreDataIfNeeded(removeUser, appId);
10902            schedulePackageCleaning(packageName, removeUser, false);
10903            return true;
10904        }
10905
10906        if (dataOnly) {
10907            // Delete application data first
10908            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10909            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10910            return true;
10911        }
10912
10913        boolean ret = false;
10914        if (isSystemApp(ps)) {
10915            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10916            // When an updated system application is deleted we delete the existing resources as well and
10917            // fall back to existing code in system partition
10918            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10919                    flags, outInfo, writeSettings);
10920        } else {
10921            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10922            // Kill application pre-emptively especially for apps on sd.
10923            killApplication(packageName, ps.appId, "uninstall pkg");
10924            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10925                    allUserHandles, perUserInstalled,
10926                    outInfo, writeSettings);
10927        }
10928
10929        return ret;
10930    }
10931
10932    private final class ClearStorageConnection implements ServiceConnection {
10933        IMediaContainerService mContainerService;
10934
10935        @Override
10936        public void onServiceConnected(ComponentName name, IBinder service) {
10937            synchronized (this) {
10938                mContainerService = IMediaContainerService.Stub.asInterface(service);
10939                notifyAll();
10940            }
10941        }
10942
10943        @Override
10944        public void onServiceDisconnected(ComponentName name) {
10945        }
10946    }
10947
10948    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10949        final boolean mounted;
10950        if (Environment.isExternalStorageEmulated()) {
10951            mounted = true;
10952        } else {
10953            final String status = Environment.getExternalStorageState();
10954
10955            mounted = status.equals(Environment.MEDIA_MOUNTED)
10956                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10957        }
10958
10959        if (!mounted) {
10960            return;
10961        }
10962
10963        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10964        int[] users;
10965        if (userId == UserHandle.USER_ALL) {
10966            users = sUserManager.getUserIds();
10967        } else {
10968            users = new int[] { userId };
10969        }
10970        final ClearStorageConnection conn = new ClearStorageConnection();
10971        if (mContext.bindServiceAsUser(
10972                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10973            try {
10974                for (int curUser : users) {
10975                    long timeout = SystemClock.uptimeMillis() + 5000;
10976                    synchronized (conn) {
10977                        long now = SystemClock.uptimeMillis();
10978                        while (conn.mContainerService == null && now < timeout) {
10979                            try {
10980                                conn.wait(timeout - now);
10981                            } catch (InterruptedException e) {
10982                            }
10983                        }
10984                    }
10985                    if (conn.mContainerService == null) {
10986                        return;
10987                    }
10988
10989                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10990                    clearDirectory(conn.mContainerService,
10991                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10992                    if (allData) {
10993                        clearDirectory(conn.mContainerService,
10994                                userEnv.buildExternalStorageAppDataDirs(packageName));
10995                        clearDirectory(conn.mContainerService,
10996                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10997                    }
10998                }
10999            } finally {
11000                mContext.unbindService(conn);
11001            }
11002        }
11003    }
11004
11005    @Override
11006    public void clearApplicationUserData(final String packageName,
11007            final IPackageDataObserver observer, final int userId) {
11008        mContext.enforceCallingOrSelfPermission(
11009                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11010        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11011        // Queue up an async operation since the package deletion may take a little while.
11012        mHandler.post(new Runnable() {
11013            public void run() {
11014                mHandler.removeCallbacks(this);
11015                final boolean succeeded;
11016                synchronized (mInstallLock) {
11017                    succeeded = clearApplicationUserDataLI(packageName, userId);
11018                }
11019                clearExternalStorageDataSync(packageName, userId, true);
11020                if (succeeded) {
11021                    // invoke DeviceStorageMonitor's update method to clear any notifications
11022                    DeviceStorageMonitorInternal
11023                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11024                    if (dsm != null) {
11025                        dsm.checkMemory();
11026                    }
11027                }
11028                if(observer != null) {
11029                    try {
11030                        observer.onRemoveCompleted(packageName, succeeded);
11031                    } catch (RemoteException e) {
11032                        Log.i(TAG, "Observer no longer exists.");
11033                    }
11034                } //end if observer
11035            } //end run
11036        });
11037    }
11038
11039    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11040        if (packageName == null) {
11041            Slog.w(TAG, "Attempt to delete null packageName.");
11042            return false;
11043        }
11044        PackageParser.Package pkg;
11045        boolean dataOnly = false;
11046        final int appId;
11047        synchronized (mPackages) {
11048            pkg = mPackages.get(packageName);
11049            if (pkg == null) {
11050                dataOnly = true;
11051                PackageSetting ps = mSettings.mPackages.get(packageName);
11052                if ((ps == null) || (ps.pkg == null)) {
11053                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11054                    return false;
11055                }
11056                pkg = ps.pkg;
11057            }
11058            if (!dataOnly) {
11059                // need to check this only for fully installed applications
11060                if (pkg == null) {
11061                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11062                    return false;
11063                }
11064                final ApplicationInfo applicationInfo = pkg.applicationInfo;
11065                if (applicationInfo == null) {
11066                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11067                    return false;
11068                }
11069            }
11070            if (pkg != null && pkg.applicationInfo != null) {
11071                appId = pkg.applicationInfo.uid;
11072            } else {
11073                appId = -1;
11074            }
11075        }
11076        int retCode = mInstaller.clearUserData(packageName, userId);
11077        if (retCode < 0) {
11078            Slog.w(TAG, "Couldn't remove cache files for package: "
11079                    + packageName);
11080            return false;
11081        }
11082        removeKeystoreDataIfNeeded(userId, appId);
11083
11084        // Create a native library symlink only if we have native libraries
11085        // and if the native libraries are 32 bit libraries. We do not provide
11086        // this symlink for 64 bit libraries.
11087        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11088                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11089            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11090            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11091                Slog.w(TAG, "Failed linking native library dir");
11092                return false;
11093            }
11094        }
11095
11096        return true;
11097    }
11098
11099    /**
11100     * Remove entries from the keystore daemon. Will only remove it if the
11101     * {@code appId} is valid.
11102     */
11103    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11104        if (appId < 0) {
11105            return;
11106        }
11107
11108        final KeyStore keyStore = KeyStore.getInstance();
11109        if (keyStore != null) {
11110            if (userId == UserHandle.USER_ALL) {
11111                for (final int individual : sUserManager.getUserIds()) {
11112                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11113                }
11114            } else {
11115                keyStore.clearUid(UserHandle.getUid(userId, appId));
11116            }
11117        } else {
11118            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11119        }
11120    }
11121
11122    @Override
11123    public void deleteApplicationCacheFiles(final String packageName,
11124            final IPackageDataObserver observer) {
11125        mContext.enforceCallingOrSelfPermission(
11126                android.Manifest.permission.DELETE_CACHE_FILES, null);
11127        // Queue up an async operation since the package deletion may take a little while.
11128        final int userId = UserHandle.getCallingUserId();
11129        mHandler.post(new Runnable() {
11130            public void run() {
11131                mHandler.removeCallbacks(this);
11132                final boolean succeded;
11133                synchronized (mInstallLock) {
11134                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11135                }
11136                clearExternalStorageDataSync(packageName, userId, false);
11137                if(observer != null) {
11138                    try {
11139                        observer.onRemoveCompleted(packageName, succeded);
11140                    } catch (RemoteException e) {
11141                        Log.i(TAG, "Observer no longer exists.");
11142                    }
11143                } //end if observer
11144            } //end run
11145        });
11146    }
11147
11148    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11149        if (packageName == null) {
11150            Slog.w(TAG, "Attempt to delete null packageName.");
11151            return false;
11152        }
11153        PackageParser.Package p;
11154        synchronized (mPackages) {
11155            p = mPackages.get(packageName);
11156        }
11157        if (p == null) {
11158            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11159            return false;
11160        }
11161        final ApplicationInfo applicationInfo = p.applicationInfo;
11162        if (applicationInfo == null) {
11163            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11164            return false;
11165        }
11166        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11167        if (retCode < 0) {
11168            Slog.w(TAG, "Couldn't remove cache files for package: "
11169                       + packageName + " u" + userId);
11170            return false;
11171        }
11172        return true;
11173    }
11174
11175    @Override
11176    public void getPackageSizeInfo(final String packageName, int userHandle,
11177            final IPackageStatsObserver observer) {
11178        mContext.enforceCallingOrSelfPermission(
11179                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11180        if (packageName == null) {
11181            throw new IllegalArgumentException("Attempt to get size of null packageName");
11182        }
11183
11184        PackageStats stats = new PackageStats(packageName, userHandle);
11185
11186        /*
11187         * Queue up an async operation since the package measurement may take a
11188         * little while.
11189         */
11190        Message msg = mHandler.obtainMessage(INIT_COPY);
11191        msg.obj = new MeasureParams(stats, observer);
11192        mHandler.sendMessage(msg);
11193    }
11194
11195    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11196            PackageStats pStats) {
11197        if (packageName == null) {
11198            Slog.w(TAG, "Attempt to get size of null packageName.");
11199            return false;
11200        }
11201        PackageParser.Package p;
11202        boolean dataOnly = false;
11203        String libDirRoot = null;
11204        String asecPath = null;
11205        PackageSetting ps = null;
11206        synchronized (mPackages) {
11207            p = mPackages.get(packageName);
11208            ps = mSettings.mPackages.get(packageName);
11209            if(p == null) {
11210                dataOnly = true;
11211                if((ps == null) || (ps.pkg == null)) {
11212                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11213                    return false;
11214                }
11215                p = ps.pkg;
11216            }
11217            if (ps != null) {
11218                libDirRoot = ps.legacyNativeLibraryPathString;
11219            }
11220            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11221                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11222                if (secureContainerId != null) {
11223                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11224                }
11225            }
11226        }
11227        String publicSrcDir = null;
11228        if(!dataOnly) {
11229            final ApplicationInfo applicationInfo = p.applicationInfo;
11230            if (applicationInfo == null) {
11231                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11232                return false;
11233            }
11234            if (isForwardLocked(p)) {
11235                publicSrcDir = applicationInfo.getBaseResourcePath();
11236            }
11237        }
11238        // TODO: extend to measure size of split APKs
11239        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11240        // not just the first level.
11241        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11242        // just the primary.
11243        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11244        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11245                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11246        if (res < 0) {
11247            return false;
11248        }
11249
11250        // Fix-up for forward-locked applications in ASEC containers.
11251        if (!isExternal(p)) {
11252            pStats.codeSize += pStats.externalCodeSize;
11253            pStats.externalCodeSize = 0L;
11254        }
11255
11256        return true;
11257    }
11258
11259
11260    @Override
11261    public void addPackageToPreferred(String packageName) {
11262        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11263    }
11264
11265    @Override
11266    public void removePackageFromPreferred(String packageName) {
11267        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11268    }
11269
11270    @Override
11271    public List<PackageInfo> getPreferredPackages(int flags) {
11272        return new ArrayList<PackageInfo>();
11273    }
11274
11275    private int getUidTargetSdkVersionLockedLPr(int uid) {
11276        Object obj = mSettings.getUserIdLPr(uid);
11277        if (obj instanceof SharedUserSetting) {
11278            final SharedUserSetting sus = (SharedUserSetting) obj;
11279            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11280            final Iterator<PackageSetting> it = sus.packages.iterator();
11281            while (it.hasNext()) {
11282                final PackageSetting ps = it.next();
11283                if (ps.pkg != null) {
11284                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11285                    if (v < vers) vers = v;
11286                }
11287            }
11288            return vers;
11289        } else if (obj instanceof PackageSetting) {
11290            final PackageSetting ps = (PackageSetting) obj;
11291            if (ps.pkg != null) {
11292                return ps.pkg.applicationInfo.targetSdkVersion;
11293            }
11294        }
11295        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11296    }
11297
11298    @Override
11299    public void addPreferredActivity(IntentFilter filter, int match,
11300            ComponentName[] set, ComponentName activity, int userId) {
11301        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11302                "Adding preferred");
11303    }
11304
11305    private void addPreferredActivityInternal(IntentFilter filter, int match,
11306            ComponentName[] set, ComponentName activity, boolean always, int userId,
11307            String opname) {
11308        // writer
11309        int callingUid = Binder.getCallingUid();
11310        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11311        if (filter.countActions() == 0) {
11312            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11313            return;
11314        }
11315        synchronized (mPackages) {
11316            if (mContext.checkCallingOrSelfPermission(
11317                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11318                    != PackageManager.PERMISSION_GRANTED) {
11319                if (getUidTargetSdkVersionLockedLPr(callingUid)
11320                        < Build.VERSION_CODES.FROYO) {
11321                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11322                            + callingUid);
11323                    return;
11324                }
11325                mContext.enforceCallingOrSelfPermission(
11326                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11327            }
11328
11329            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11330            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11331                    + userId + ":");
11332            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11333            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11334            mSettings.writePackageRestrictionsLPr(userId);
11335        }
11336    }
11337
11338    @Override
11339    public void replacePreferredActivity(IntentFilter filter, int match,
11340            ComponentName[] set, ComponentName activity, int userId) {
11341        if (filter.countActions() != 1) {
11342            throw new IllegalArgumentException(
11343                    "replacePreferredActivity expects filter to have only 1 action.");
11344        }
11345        if (filter.countDataAuthorities() != 0
11346                || filter.countDataPaths() != 0
11347                || filter.countDataSchemes() > 1
11348                || filter.countDataTypes() != 0) {
11349            throw new IllegalArgumentException(
11350                    "replacePreferredActivity expects filter to have no data authorities, " +
11351                    "paths, or types; and at most one scheme.");
11352        }
11353
11354        final int callingUid = Binder.getCallingUid();
11355        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11356        synchronized (mPackages) {
11357            if (mContext.checkCallingOrSelfPermission(
11358                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11359                    != PackageManager.PERMISSION_GRANTED) {
11360                if (getUidTargetSdkVersionLockedLPr(callingUid)
11361                        < Build.VERSION_CODES.FROYO) {
11362                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11363                            + Binder.getCallingUid());
11364                    return;
11365                }
11366                mContext.enforceCallingOrSelfPermission(
11367                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11368            }
11369
11370            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11371            if (pir != null) {
11372                // Get all of the existing entries that exactly match this filter.
11373                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11374                if (existing != null && existing.size() == 1) {
11375                    PreferredActivity cur = existing.get(0);
11376                    if (DEBUG_PREFERRED) {
11377                        Slog.i(TAG, "Checking replace of preferred:");
11378                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11379                        if (!cur.mPref.mAlways) {
11380                            Slog.i(TAG, "  -- CUR; not mAlways!");
11381                        } else {
11382                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11383                            Slog.i(TAG, "  -- CUR: mSet="
11384                                    + Arrays.toString(cur.mPref.mSetComponents));
11385                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11386                            Slog.i(TAG, "  -- NEW: mMatch="
11387                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11388                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11389                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11390                        }
11391                    }
11392                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11393                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11394                            && cur.mPref.sameSet(set)) {
11395                        if (DEBUG_PREFERRED) {
11396                            Slog.i(TAG, "Replacing with same preferred activity "
11397                                    + cur.mPref.mShortComponent + " for user "
11398                                    + userId + ":");
11399                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11400                        } else {
11401                            Slog.i(TAG, "Replacing with same preferred activity "
11402                                    + cur.mPref.mShortComponent + " for user "
11403                                    + userId);
11404                        }
11405                        return;
11406                    }
11407                }
11408
11409                if (existing != null) {
11410                    if (DEBUG_PREFERRED) {
11411                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11412                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11413                    }
11414                    for (int i = 0; i < existing.size(); i++) {
11415                        PreferredActivity pa = existing.get(i);
11416                        if (DEBUG_PREFERRED) {
11417                            Slog.i(TAG, "Removing existing preferred activity "
11418                                    + pa.mPref.mComponent + ":");
11419                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11420                        }
11421                        pir.removeFilter(pa);
11422                    }
11423                }
11424            }
11425            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11426                    "Replacing preferred");
11427        }
11428    }
11429
11430    @Override
11431    public void clearPackagePreferredActivities(String packageName) {
11432        final int uid = Binder.getCallingUid();
11433        // writer
11434        synchronized (mPackages) {
11435            PackageParser.Package pkg = mPackages.get(packageName);
11436            if (pkg == null || pkg.applicationInfo.uid != uid) {
11437                if (mContext.checkCallingOrSelfPermission(
11438                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11439                        != PackageManager.PERMISSION_GRANTED) {
11440                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11441                            < Build.VERSION_CODES.FROYO) {
11442                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11443                                + Binder.getCallingUid());
11444                        return;
11445                    }
11446                    mContext.enforceCallingOrSelfPermission(
11447                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11448                }
11449            }
11450
11451            int user = UserHandle.getCallingUserId();
11452            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11453                mSettings.writePackageRestrictionsLPr(user);
11454                scheduleWriteSettingsLocked();
11455            }
11456        }
11457    }
11458
11459    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11460    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11461        ArrayList<PreferredActivity> removed = null;
11462        boolean changed = false;
11463        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11464            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11465            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11466            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11467                continue;
11468            }
11469            Iterator<PreferredActivity> it = pir.filterIterator();
11470            while (it.hasNext()) {
11471                PreferredActivity pa = it.next();
11472                // Mark entry for removal only if it matches the package name
11473                // and the entry is of type "always".
11474                if (packageName == null ||
11475                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11476                                && pa.mPref.mAlways)) {
11477                    if (removed == null) {
11478                        removed = new ArrayList<PreferredActivity>();
11479                    }
11480                    removed.add(pa);
11481                }
11482            }
11483            if (removed != null) {
11484                for (int j=0; j<removed.size(); j++) {
11485                    PreferredActivity pa = removed.get(j);
11486                    pir.removeFilter(pa);
11487                }
11488                changed = true;
11489            }
11490        }
11491        return changed;
11492    }
11493
11494    @Override
11495    public void resetPreferredActivities(int userId) {
11496        mContext.enforceCallingOrSelfPermission(
11497                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11498        // writer
11499        synchronized (mPackages) {
11500            int user = UserHandle.getCallingUserId();
11501            clearPackagePreferredActivitiesLPw(null, user);
11502            mSettings.readDefaultPreferredAppsLPw(this, user);
11503            mSettings.writePackageRestrictionsLPr(user);
11504            scheduleWriteSettingsLocked();
11505        }
11506    }
11507
11508    @Override
11509    public int getPreferredActivities(List<IntentFilter> outFilters,
11510            List<ComponentName> outActivities, String packageName) {
11511
11512        int num = 0;
11513        final int userId = UserHandle.getCallingUserId();
11514        // reader
11515        synchronized (mPackages) {
11516            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11517            if (pir != null) {
11518                final Iterator<PreferredActivity> it = pir.filterIterator();
11519                while (it.hasNext()) {
11520                    final PreferredActivity pa = it.next();
11521                    if (packageName == null
11522                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11523                                    && pa.mPref.mAlways)) {
11524                        if (outFilters != null) {
11525                            outFilters.add(new IntentFilter(pa));
11526                        }
11527                        if (outActivities != null) {
11528                            outActivities.add(pa.mPref.mComponent);
11529                        }
11530                    }
11531                }
11532            }
11533        }
11534
11535        return num;
11536    }
11537
11538    @Override
11539    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11540            int userId) {
11541        int callingUid = Binder.getCallingUid();
11542        if (callingUid != Process.SYSTEM_UID) {
11543            throw new SecurityException(
11544                    "addPersistentPreferredActivity can only be run by the system");
11545        }
11546        if (filter.countActions() == 0) {
11547            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11548            return;
11549        }
11550        synchronized (mPackages) {
11551            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11552                    " :");
11553            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11554            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11555                    new PersistentPreferredActivity(filter, activity));
11556            mSettings.writePackageRestrictionsLPr(userId);
11557        }
11558    }
11559
11560    @Override
11561    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11562        int callingUid = Binder.getCallingUid();
11563        if (callingUid != Process.SYSTEM_UID) {
11564            throw new SecurityException(
11565                    "clearPackagePersistentPreferredActivities can only be run by the system");
11566        }
11567        ArrayList<PersistentPreferredActivity> removed = null;
11568        boolean changed = false;
11569        synchronized (mPackages) {
11570            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11571                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11572                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11573                        .valueAt(i);
11574                if (userId != thisUserId) {
11575                    continue;
11576                }
11577                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11578                while (it.hasNext()) {
11579                    PersistentPreferredActivity ppa = it.next();
11580                    // Mark entry for removal only if it matches the package name.
11581                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11582                        if (removed == null) {
11583                            removed = new ArrayList<PersistentPreferredActivity>();
11584                        }
11585                        removed.add(ppa);
11586                    }
11587                }
11588                if (removed != null) {
11589                    for (int j=0; j<removed.size(); j++) {
11590                        PersistentPreferredActivity ppa = removed.get(j);
11591                        ppir.removeFilter(ppa);
11592                    }
11593                    changed = true;
11594                }
11595            }
11596
11597            if (changed) {
11598                mSettings.writePackageRestrictionsLPr(userId);
11599            }
11600        }
11601    }
11602
11603    @Override
11604    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11605            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11606        mContext.enforceCallingOrSelfPermission(
11607                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11608        int callingUid = Binder.getCallingUid();
11609        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11610        if (intentFilter.countActions() == 0) {
11611            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11612            return;
11613        }
11614        synchronized (mPackages) {
11615            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11616                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11617            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11618            mSettings.writePackageRestrictionsLPr(sourceUserId);
11619        }
11620    }
11621
11622    @Override
11623    public void addCrossProfileIntentsForPackage(String packageName,
11624            int sourceUserId, int targetUserId) {
11625        mContext.enforceCallingOrSelfPermission(
11626                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11627        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11628        mSettings.writePackageRestrictionsLPr(sourceUserId);
11629    }
11630
11631    @Override
11632    public void removeCrossProfileIntentsForPackage(String packageName,
11633            int sourceUserId, int targetUserId) {
11634        mContext.enforceCallingOrSelfPermission(
11635                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11636        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11637        mSettings.writePackageRestrictionsLPr(sourceUserId);
11638    }
11639
11640    @Override
11641    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11642            int ownerUserId) {
11643        mContext.enforceCallingOrSelfPermission(
11644                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11645        int callingUid = Binder.getCallingUid();
11646        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11647        int callingUserId = UserHandle.getUserId(callingUid);
11648        synchronized (mPackages) {
11649            CrossProfileIntentResolver resolver =
11650                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11651            HashSet<CrossProfileIntentFilter> set =
11652                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11653            for (CrossProfileIntentFilter filter : set) {
11654                if (filter.getOwnerPackage().equals(ownerPackage)
11655                        && filter.getOwnerUserId() == callingUserId) {
11656                    resolver.removeFilter(filter);
11657                }
11658            }
11659            mSettings.writePackageRestrictionsLPr(sourceUserId);
11660        }
11661    }
11662
11663    // Enforcing that callingUid is owning pkg on userId
11664    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11665        // The system owns everything.
11666        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11667            return;
11668        }
11669        int callingUserId = UserHandle.getUserId(callingUid);
11670        if (callingUserId != userId) {
11671            throw new SecurityException("calling uid " + callingUid
11672                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11673                    + callingUserId);
11674        }
11675        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11676        if (pi == null) {
11677            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11678                    + callingUserId);
11679        }
11680        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11681            throw new SecurityException("Calling uid " + callingUid
11682                    + " does not own package " + pkg);
11683        }
11684    }
11685
11686    @Override
11687    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11688        Intent intent = new Intent(Intent.ACTION_MAIN);
11689        intent.addCategory(Intent.CATEGORY_HOME);
11690
11691        final int callingUserId = UserHandle.getCallingUserId();
11692        List<ResolveInfo> list = queryIntentActivities(intent, null,
11693                PackageManager.GET_META_DATA, callingUserId);
11694        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11695                true, false, false, callingUserId);
11696
11697        allHomeCandidates.clear();
11698        if (list != null) {
11699            for (ResolveInfo ri : list) {
11700                allHomeCandidates.add(ri);
11701            }
11702        }
11703        return (preferred == null || preferred.activityInfo == null)
11704                ? null
11705                : new ComponentName(preferred.activityInfo.packageName,
11706                        preferred.activityInfo.name);
11707    }
11708
11709    /**
11710     * Check if calling UID is the current home app. This handles both the case
11711     * where the user has selected a specific home app, and where there is only
11712     * one home app.
11713     */
11714    public boolean checkCallerIsHomeApp() {
11715        final Intent intent = new Intent(Intent.ACTION_MAIN);
11716        intent.addCategory(Intent.CATEGORY_HOME);
11717
11718        final int callingUid = Binder.getCallingUid();
11719        final int callingUserId = UserHandle.getCallingUserId();
11720        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11721        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11722                false, false, callingUserId);
11723
11724        if (preferredHome != null) {
11725            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11726                return true;
11727            }
11728        } else {
11729            for (ResolveInfo info : allHomes) {
11730                if (callingUid == info.activityInfo.applicationInfo.uid) {
11731                    return true;
11732                }
11733            }
11734        }
11735
11736        return false;
11737    }
11738
11739    /**
11740     * Enforce that calling UID is the current home app. This handles both the
11741     * case where the user has selected a specific home app, and where there is
11742     * only one home app.
11743     */
11744    public void enforceCallerIsHomeApp() {
11745        if (!checkCallerIsHomeApp()) {
11746            throw new SecurityException("Caller is not currently selected home app");
11747        }
11748    }
11749
11750    @Override
11751    public void setApplicationEnabledSetting(String appPackageName,
11752            int newState, int flags, int userId, String callingPackage) {
11753        if (!sUserManager.exists(userId)) return;
11754        if (callingPackage == null) {
11755            callingPackage = Integer.toString(Binder.getCallingUid());
11756        }
11757        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11758    }
11759
11760    @Override
11761    public void setComponentEnabledSetting(ComponentName componentName,
11762            int newState, int flags, int userId) {
11763        if (!sUserManager.exists(userId)) return;
11764        setEnabledSetting(componentName.getPackageName(),
11765                componentName.getClassName(), newState, flags, userId, null);
11766    }
11767
11768    private void setEnabledSetting(final String packageName, String className, int newState,
11769            final int flags, int userId, String callingPackage) {
11770        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11771              || newState == COMPONENT_ENABLED_STATE_ENABLED
11772              || newState == COMPONENT_ENABLED_STATE_DISABLED
11773              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11774              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11775            throw new IllegalArgumentException("Invalid new component state: "
11776                    + newState);
11777        }
11778        PackageSetting pkgSetting;
11779        final int uid = Binder.getCallingUid();
11780        final int permission = mContext.checkCallingOrSelfPermission(
11781                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11782        enforceCrossUserPermission(uid, userId, false, "set enabled");
11783        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11784        boolean sendNow = false;
11785        boolean isApp = (className == null);
11786        String componentName = isApp ? packageName : className;
11787        int packageUid = -1;
11788        ArrayList<String> components;
11789
11790        // writer
11791        synchronized (mPackages) {
11792            pkgSetting = mSettings.mPackages.get(packageName);
11793            if (pkgSetting == null) {
11794                if (className == null) {
11795                    throw new IllegalArgumentException(
11796                            "Unknown package: " + packageName);
11797                }
11798                throw new IllegalArgumentException(
11799                        "Unknown component: " + packageName
11800                        + "/" + className);
11801            }
11802            // Allow root and verify that userId is not being specified by a different user
11803            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11804                throw new SecurityException(
11805                        "Permission Denial: attempt to change component state from pid="
11806                        + Binder.getCallingPid()
11807                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11808            }
11809            if (className == null) {
11810                // We're dealing with an application/package level state change
11811                if (pkgSetting.getEnabled(userId) == newState) {
11812                    // Nothing to do
11813                    return;
11814                }
11815                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11816                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11817                    // Don't care about who enables an app.
11818                    callingPackage = null;
11819                }
11820                pkgSetting.setEnabled(newState, userId, callingPackage);
11821                // pkgSetting.pkg.mSetEnabled = newState;
11822            } else {
11823                // We're dealing with a component level state change
11824                // First, verify that this is a valid class name.
11825                PackageParser.Package pkg = pkgSetting.pkg;
11826                if (pkg == null || !pkg.hasComponentClassName(className)) {
11827                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11828                        throw new IllegalArgumentException("Component class " + className
11829                                + " does not exist in " + packageName);
11830                    } else {
11831                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11832                                + className + " does not exist in " + packageName);
11833                    }
11834                }
11835                switch (newState) {
11836                case COMPONENT_ENABLED_STATE_ENABLED:
11837                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11838                        return;
11839                    }
11840                    break;
11841                case COMPONENT_ENABLED_STATE_DISABLED:
11842                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11843                        return;
11844                    }
11845                    break;
11846                case COMPONENT_ENABLED_STATE_DEFAULT:
11847                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11848                        return;
11849                    }
11850                    break;
11851                default:
11852                    Slog.e(TAG, "Invalid new component state: " + newState);
11853                    return;
11854                }
11855            }
11856            mSettings.writePackageRestrictionsLPr(userId);
11857            components = mPendingBroadcasts.get(userId, packageName);
11858            final boolean newPackage = components == null;
11859            if (newPackage) {
11860                components = new ArrayList<String>();
11861            }
11862            if (!components.contains(componentName)) {
11863                components.add(componentName);
11864            }
11865            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11866                sendNow = true;
11867                // Purge entry from pending broadcast list if another one exists already
11868                // since we are sending one right away.
11869                mPendingBroadcasts.remove(userId, packageName);
11870            } else {
11871                if (newPackage) {
11872                    mPendingBroadcasts.put(userId, packageName, components);
11873                }
11874                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11875                    // Schedule a message
11876                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11877                }
11878            }
11879        }
11880
11881        long callingId = Binder.clearCallingIdentity();
11882        try {
11883            if (sendNow) {
11884                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11885                sendPackageChangedBroadcast(packageName,
11886                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11887            }
11888        } finally {
11889            Binder.restoreCallingIdentity(callingId);
11890        }
11891    }
11892
11893    private void sendPackageChangedBroadcast(String packageName,
11894            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11895        if (DEBUG_INSTALL)
11896            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11897                    + componentNames);
11898        Bundle extras = new Bundle(4);
11899        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11900        String nameList[] = new String[componentNames.size()];
11901        componentNames.toArray(nameList);
11902        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11903        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11904        extras.putInt(Intent.EXTRA_UID, packageUid);
11905        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11906                new int[] {UserHandle.getUserId(packageUid)});
11907    }
11908
11909    @Override
11910    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11911        if (!sUserManager.exists(userId)) return;
11912        final int uid = Binder.getCallingUid();
11913        final int permission = mContext.checkCallingOrSelfPermission(
11914                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11915        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11916        enforceCrossUserPermission(uid, userId, true, "stop package");
11917        // writer
11918        synchronized (mPackages) {
11919            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11920                    uid, userId)) {
11921                scheduleWritePackageRestrictionsLocked(userId);
11922            }
11923        }
11924    }
11925
11926    @Override
11927    public String getInstallerPackageName(String packageName) {
11928        // reader
11929        synchronized (mPackages) {
11930            return mSettings.getInstallerPackageNameLPr(packageName);
11931        }
11932    }
11933
11934    @Override
11935    public int getApplicationEnabledSetting(String packageName, int userId) {
11936        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11937        int uid = Binder.getCallingUid();
11938        enforceCrossUserPermission(uid, userId, false, "get enabled");
11939        // reader
11940        synchronized (mPackages) {
11941            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11942        }
11943    }
11944
11945    @Override
11946    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11947        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11948        int uid = Binder.getCallingUid();
11949        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11950        // reader
11951        synchronized (mPackages) {
11952            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11953        }
11954    }
11955
11956    @Override
11957    public void enterSafeMode() {
11958        enforceSystemOrRoot("Only the system can request entering safe mode");
11959
11960        if (!mSystemReady) {
11961            mSafeMode = true;
11962        }
11963    }
11964
11965    @Override
11966    public void systemReady() {
11967        mSystemReady = true;
11968
11969        // Read the compatibilty setting when the system is ready.
11970        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11971                mContext.getContentResolver(),
11972                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11973        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11974        if (DEBUG_SETTINGS) {
11975            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11976        }
11977
11978        synchronized (mPackages) {
11979            // Verify that all of the preferred activity components actually
11980            // exist.  It is possible for applications to be updated and at
11981            // that point remove a previously declared activity component that
11982            // had been set as a preferred activity.  We try to clean this up
11983            // the next time we encounter that preferred activity, but it is
11984            // possible for the user flow to never be able to return to that
11985            // situation so here we do a sanity check to make sure we haven't
11986            // left any junk around.
11987            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11988            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11989                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11990                removed.clear();
11991                for (PreferredActivity pa : pir.filterSet()) {
11992                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11993                        removed.add(pa);
11994                    }
11995                }
11996                if (removed.size() > 0) {
11997                    for (int r=0; r<removed.size(); r++) {
11998                        PreferredActivity pa = removed.get(r);
11999                        Slog.w(TAG, "Removing dangling preferred activity: "
12000                                + pa.mPref.mComponent);
12001                        pir.removeFilter(pa);
12002                    }
12003                    mSettings.writePackageRestrictionsLPr(
12004                            mSettings.mPreferredActivities.keyAt(i));
12005                }
12006            }
12007        }
12008        sUserManager.systemReady();
12009    }
12010
12011    @Override
12012    public boolean isSafeMode() {
12013        return mSafeMode;
12014    }
12015
12016    @Override
12017    public boolean hasSystemUidErrors() {
12018        return mHasSystemUidErrors;
12019    }
12020
12021    static String arrayToString(int[] array) {
12022        StringBuffer buf = new StringBuffer(128);
12023        buf.append('[');
12024        if (array != null) {
12025            for (int i=0; i<array.length; i++) {
12026                if (i > 0) buf.append(", ");
12027                buf.append(array[i]);
12028            }
12029        }
12030        buf.append(']');
12031        return buf.toString();
12032    }
12033
12034    static class DumpState {
12035        public static final int DUMP_LIBS = 1 << 0;
12036        public static final int DUMP_FEATURES = 1 << 1;
12037        public static final int DUMP_RESOLVERS = 1 << 2;
12038        public static final int DUMP_PERMISSIONS = 1 << 3;
12039        public static final int DUMP_PACKAGES = 1 << 4;
12040        public static final int DUMP_SHARED_USERS = 1 << 5;
12041        public static final int DUMP_MESSAGES = 1 << 6;
12042        public static final int DUMP_PROVIDERS = 1 << 7;
12043        public static final int DUMP_VERIFIERS = 1 << 8;
12044        public static final int DUMP_PREFERRED = 1 << 9;
12045        public static final int DUMP_PREFERRED_XML = 1 << 10;
12046        public static final int DUMP_KEYSETS = 1 << 11;
12047        public static final int DUMP_VERSION = 1 << 12;
12048        public static final int DUMP_INSTALLS = 1 << 13;
12049
12050        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12051
12052        private int mTypes;
12053
12054        private int mOptions;
12055
12056        private boolean mTitlePrinted;
12057
12058        private SharedUserSetting mSharedUser;
12059
12060        public boolean isDumping(int type) {
12061            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12062                return true;
12063            }
12064
12065            return (mTypes & type) != 0;
12066        }
12067
12068        public void setDump(int type) {
12069            mTypes |= type;
12070        }
12071
12072        public boolean isOptionEnabled(int option) {
12073            return (mOptions & option) != 0;
12074        }
12075
12076        public void setOptionEnabled(int option) {
12077            mOptions |= option;
12078        }
12079
12080        public boolean onTitlePrinted() {
12081            final boolean printed = mTitlePrinted;
12082            mTitlePrinted = true;
12083            return printed;
12084        }
12085
12086        public boolean getTitlePrinted() {
12087            return mTitlePrinted;
12088        }
12089
12090        public void setTitlePrinted(boolean enabled) {
12091            mTitlePrinted = enabled;
12092        }
12093
12094        public SharedUserSetting getSharedUser() {
12095            return mSharedUser;
12096        }
12097
12098        public void setSharedUser(SharedUserSetting user) {
12099            mSharedUser = user;
12100        }
12101    }
12102
12103    @Override
12104    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12105        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12106                != PackageManager.PERMISSION_GRANTED) {
12107            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12108                    + Binder.getCallingPid()
12109                    + ", uid=" + Binder.getCallingUid()
12110                    + " without permission "
12111                    + android.Manifest.permission.DUMP);
12112            return;
12113        }
12114
12115        DumpState dumpState = new DumpState();
12116        boolean fullPreferred = false;
12117        boolean checkin = false;
12118
12119        String packageName = null;
12120
12121        int opti = 0;
12122        while (opti < args.length) {
12123            String opt = args[opti];
12124            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12125                break;
12126            }
12127            opti++;
12128            if ("-a".equals(opt)) {
12129                // Right now we only know how to print all.
12130            } else if ("-h".equals(opt)) {
12131                pw.println("Package manager dump options:");
12132                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12133                pw.println("    --checkin: dump for a checkin");
12134                pw.println("    -f: print details of intent filters");
12135                pw.println("    -h: print this help");
12136                pw.println("  cmd may be one of:");
12137                pw.println("    l[ibraries]: list known shared libraries");
12138                pw.println("    f[ibraries]: list device features");
12139                pw.println("    k[eysets]: print known keysets");
12140                pw.println("    r[esolvers]: dump intent resolvers");
12141                pw.println("    perm[issions]: dump permissions");
12142                pw.println("    pref[erred]: print preferred package settings");
12143                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12144                pw.println("    prov[iders]: dump content providers");
12145                pw.println("    p[ackages]: dump installed packages");
12146                pw.println("    s[hared-users]: dump shared user IDs");
12147                pw.println("    m[essages]: print collected runtime messages");
12148                pw.println("    v[erifiers]: print package verifier info");
12149                pw.println("    version: print database version info");
12150                pw.println("    write: write current settings now");
12151                pw.println("    <package.name>: info about given package");
12152                pw.println("    installs: details about install sessions");
12153                return;
12154            } else if ("--checkin".equals(opt)) {
12155                checkin = true;
12156            } else if ("-f".equals(opt)) {
12157                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12158            } else {
12159                pw.println("Unknown argument: " + opt + "; use -h for help");
12160            }
12161        }
12162
12163        // Is the caller requesting to dump a particular piece of data?
12164        if (opti < args.length) {
12165            String cmd = args[opti];
12166            opti++;
12167            // Is this a package name?
12168            if ("android".equals(cmd) || cmd.contains(".")) {
12169                packageName = cmd;
12170                // When dumping a single package, we always dump all of its
12171                // filter information since the amount of data will be reasonable.
12172                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12173            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12174                dumpState.setDump(DumpState.DUMP_LIBS);
12175            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12176                dumpState.setDump(DumpState.DUMP_FEATURES);
12177            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12178                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12179            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12180                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12181            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12182                dumpState.setDump(DumpState.DUMP_PREFERRED);
12183            } else if ("preferred-xml".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12185                if (opti < args.length && "--full".equals(args[opti])) {
12186                    fullPreferred = true;
12187                    opti++;
12188                }
12189            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12190                dumpState.setDump(DumpState.DUMP_PACKAGES);
12191            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12192                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12193            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12194                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12195            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12196                dumpState.setDump(DumpState.DUMP_MESSAGES);
12197            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12198                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12199            } else if ("version".equals(cmd)) {
12200                dumpState.setDump(DumpState.DUMP_VERSION);
12201            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12202                dumpState.setDump(DumpState.DUMP_KEYSETS);
12203            } else if ("write".equals(cmd)) {
12204                synchronized (mPackages) {
12205                    mSettings.writeLPr();
12206                    pw.println("Settings written.");
12207                    return;
12208                }
12209            } else if ("installs".equals(cmd)) {
12210                dumpState.setDump(DumpState.DUMP_INSTALLS);
12211            }
12212        }
12213
12214        if (checkin) {
12215            pw.println("vers,1");
12216        }
12217
12218        // reader
12219        synchronized (mPackages) {
12220            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12221                if (!checkin) {
12222                    if (dumpState.onTitlePrinted())
12223                        pw.println();
12224                    pw.println("Database versions:");
12225                    pw.print("  SDK Version:");
12226                    pw.print(" internal=");
12227                    pw.print(mSettings.mInternalSdkPlatform);
12228                    pw.print(" external=");
12229                    pw.println(mSettings.mExternalSdkPlatform);
12230                    pw.print("  DB Version:");
12231                    pw.print(" internal=");
12232                    pw.print(mSettings.mInternalDatabaseVersion);
12233                    pw.print(" external=");
12234                    pw.println(mSettings.mExternalDatabaseVersion);
12235                }
12236            }
12237
12238            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12239                if (!checkin) {
12240                    if (dumpState.onTitlePrinted())
12241                        pw.println();
12242                    pw.println("Verifiers:");
12243                    pw.print("  Required: ");
12244                    pw.print(mRequiredVerifierPackage);
12245                    pw.print(" (uid=");
12246                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12247                    pw.println(")");
12248                } else if (mRequiredVerifierPackage != null) {
12249                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12250                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12251                }
12252            }
12253
12254            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12255                boolean printedHeader = false;
12256                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12257                while (it.hasNext()) {
12258                    String name = it.next();
12259                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12260                    if (!checkin) {
12261                        if (!printedHeader) {
12262                            if (dumpState.onTitlePrinted())
12263                                pw.println();
12264                            pw.println("Libraries:");
12265                            printedHeader = true;
12266                        }
12267                        pw.print("  ");
12268                    } else {
12269                        pw.print("lib,");
12270                    }
12271                    pw.print(name);
12272                    if (!checkin) {
12273                        pw.print(" -> ");
12274                    }
12275                    if (ent.path != null) {
12276                        if (!checkin) {
12277                            pw.print("(jar) ");
12278                            pw.print(ent.path);
12279                        } else {
12280                            pw.print(",jar,");
12281                            pw.print(ent.path);
12282                        }
12283                    } else {
12284                        if (!checkin) {
12285                            pw.print("(apk) ");
12286                            pw.print(ent.apk);
12287                        } else {
12288                            pw.print(",apk,");
12289                            pw.print(ent.apk);
12290                        }
12291                    }
12292                    pw.println();
12293                }
12294            }
12295
12296            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12297                if (dumpState.onTitlePrinted())
12298                    pw.println();
12299                if (!checkin) {
12300                    pw.println("Features:");
12301                }
12302                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12303                while (it.hasNext()) {
12304                    String name = it.next();
12305                    if (!checkin) {
12306                        pw.print("  ");
12307                    } else {
12308                        pw.print("feat,");
12309                    }
12310                    pw.println(name);
12311                }
12312            }
12313
12314            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12315                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12316                        : "Activity Resolver Table:", "  ", packageName,
12317                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12318                    dumpState.setTitlePrinted(true);
12319                }
12320                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12321                        : "Receiver Resolver Table:", "  ", packageName,
12322                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12323                    dumpState.setTitlePrinted(true);
12324                }
12325                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12326                        : "Service Resolver Table:", "  ", packageName,
12327                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12328                    dumpState.setTitlePrinted(true);
12329                }
12330                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12331                        : "Provider Resolver Table:", "  ", packageName,
12332                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12333                    dumpState.setTitlePrinted(true);
12334                }
12335            }
12336
12337            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12338                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12339                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12340                    int user = mSettings.mPreferredActivities.keyAt(i);
12341                    if (pir.dump(pw,
12342                            dumpState.getTitlePrinted()
12343                                ? "\nPreferred Activities User " + user + ":"
12344                                : "Preferred Activities User " + user + ":", "  ",
12345                            packageName, true)) {
12346                        dumpState.setTitlePrinted(true);
12347                    }
12348                }
12349            }
12350
12351            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12352                pw.flush();
12353                FileOutputStream fout = new FileOutputStream(fd);
12354                BufferedOutputStream str = new BufferedOutputStream(fout);
12355                XmlSerializer serializer = new FastXmlSerializer();
12356                try {
12357                    serializer.setOutput(str, "utf-8");
12358                    serializer.startDocument(null, true);
12359                    serializer.setFeature(
12360                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12361                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12362                    serializer.endDocument();
12363                    serializer.flush();
12364                } catch (IllegalArgumentException e) {
12365                    pw.println("Failed writing: " + e);
12366                } catch (IllegalStateException e) {
12367                    pw.println("Failed writing: " + e);
12368                } catch (IOException e) {
12369                    pw.println("Failed writing: " + e);
12370                }
12371            }
12372
12373            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12374                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12375                if (packageName == null) {
12376                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12377                        if (iperm == 0) {
12378                            if (dumpState.onTitlePrinted())
12379                                pw.println();
12380                            pw.println("AppOp Permissions:");
12381                        }
12382                        pw.print("  AppOp Permission ");
12383                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12384                        pw.println(":");
12385                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12386                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12387                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12388                        }
12389                    }
12390                }
12391            }
12392
12393            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12394                boolean printedSomething = false;
12395                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12396                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12397                        continue;
12398                    }
12399                    if (!printedSomething) {
12400                        if (dumpState.onTitlePrinted())
12401                            pw.println();
12402                        pw.println("Registered ContentProviders:");
12403                        printedSomething = true;
12404                    }
12405                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12406                    pw.print("    "); pw.println(p.toString());
12407                }
12408                printedSomething = false;
12409                for (Map.Entry<String, PackageParser.Provider> entry :
12410                        mProvidersByAuthority.entrySet()) {
12411                    PackageParser.Provider p = entry.getValue();
12412                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12413                        continue;
12414                    }
12415                    if (!printedSomething) {
12416                        if (dumpState.onTitlePrinted())
12417                            pw.println();
12418                        pw.println("ContentProvider Authorities:");
12419                        printedSomething = true;
12420                    }
12421                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12422                    pw.print("    "); pw.println(p.toString());
12423                    if (p.info != null && p.info.applicationInfo != null) {
12424                        final String appInfo = p.info.applicationInfo.toString();
12425                        pw.print("      applicationInfo="); pw.println(appInfo);
12426                    }
12427                }
12428            }
12429
12430            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12431                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12432            }
12433
12434            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12435                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12436            }
12437
12438            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12439                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12440            }
12441
12442            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12443                if (dumpState.onTitlePrinted()) pw.println();
12444                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12445            }
12446
12447            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12448                if (dumpState.onTitlePrinted()) pw.println();
12449                mSettings.dumpReadMessagesLPr(pw, dumpState);
12450
12451                pw.println();
12452                pw.println("Package warning messages:");
12453                final File fname = getSettingsProblemFile();
12454                FileInputStream in = null;
12455                try {
12456                    in = new FileInputStream(fname);
12457                    final int avail = in.available();
12458                    final byte[] data = new byte[avail];
12459                    in.read(data);
12460                    pw.print(new String(data));
12461                } catch (FileNotFoundException e) {
12462                } catch (IOException e) {
12463                } finally {
12464                    if (in != null) {
12465                        try {
12466                            in.close();
12467                        } catch (IOException e) {
12468                        }
12469                    }
12470                }
12471            }
12472        }
12473    }
12474
12475    // ------- apps on sdcard specific code -------
12476    static final boolean DEBUG_SD_INSTALL = false;
12477
12478    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12479
12480    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12481
12482    private boolean mMediaMounted = false;
12483
12484    static String getEncryptKey() {
12485        try {
12486            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12487                    SD_ENCRYPTION_KEYSTORE_NAME);
12488            if (sdEncKey == null) {
12489                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12490                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12491                if (sdEncKey == null) {
12492                    Slog.e(TAG, "Failed to create encryption keys");
12493                    return null;
12494                }
12495            }
12496            return sdEncKey;
12497        } catch (NoSuchAlgorithmException nsae) {
12498            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12499            return null;
12500        } catch (IOException ioe) {
12501            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12502            return null;
12503        }
12504    }
12505
12506    /*
12507     * Update media status on PackageManager.
12508     */
12509    @Override
12510    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12511        int callingUid = Binder.getCallingUid();
12512        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12513            throw new SecurityException("Media status can only be updated by the system");
12514        }
12515        // reader; this apparently protects mMediaMounted, but should probably
12516        // be a different lock in that case.
12517        synchronized (mPackages) {
12518            Log.i(TAG, "Updating external media status from "
12519                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12520                    + (mediaStatus ? "mounted" : "unmounted"));
12521            if (DEBUG_SD_INSTALL)
12522                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12523                        + ", mMediaMounted=" + mMediaMounted);
12524            if (mediaStatus == mMediaMounted) {
12525                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12526                        : 0, -1);
12527                mHandler.sendMessage(msg);
12528                return;
12529            }
12530            mMediaMounted = mediaStatus;
12531        }
12532        // Queue up an async operation since the package installation may take a
12533        // little while.
12534        mHandler.post(new Runnable() {
12535            public void run() {
12536                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12537            }
12538        });
12539    }
12540
12541    /**
12542     * Called by MountService when the initial ASECs to scan are available.
12543     * Should block until all the ASEC containers are finished being scanned.
12544     */
12545    public void scanAvailableAsecs() {
12546        updateExternalMediaStatusInner(true, false, false);
12547        if (mShouldRestoreconData) {
12548            SELinuxMMAC.setRestoreconDone();
12549            mShouldRestoreconData = false;
12550        }
12551    }
12552
12553    /*
12554     * Collect information of applications on external media, map them against
12555     * existing containers and update information based on current mount status.
12556     * Please note that we always have to report status if reportStatus has been
12557     * set to true especially when unloading packages.
12558     */
12559    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12560            boolean externalStorage) {
12561        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12562        int[] uidArr = EmptyArray.INT;
12563
12564        final String[] list = PackageHelper.getSecureContainerList();
12565        if (ArrayUtils.isEmpty(list)) {
12566            Log.i(TAG, "No secure containers found");
12567        } else {
12568            // Process list of secure containers and categorize them
12569            // as active or stale based on their package internal state.
12570
12571            // reader
12572            synchronized (mPackages) {
12573                for (String cid : list) {
12574                    // Leave stages untouched for now; installer service owns them
12575                    if (PackageInstallerService.isStageName(cid)) continue;
12576
12577                    if (DEBUG_SD_INSTALL)
12578                        Log.i(TAG, "Processing container " + cid);
12579                    String pkgName = getAsecPackageName(cid);
12580                    if (pkgName == null) {
12581                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12582                        continue;
12583                    }
12584                    if (DEBUG_SD_INSTALL)
12585                        Log.i(TAG, "Looking for pkg : " + pkgName);
12586
12587                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12588                    if (ps == null) {
12589                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12590                        continue;
12591                    }
12592
12593                    /*
12594                     * Skip packages that are not external if we're unmounting
12595                     * external storage.
12596                     */
12597                    if (externalStorage && !isMounted && !isExternal(ps)) {
12598                        continue;
12599                    }
12600
12601                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12602                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12603                    // The package status is changed only if the code path
12604                    // matches between settings and the container id.
12605                    if (ps.codePathString != null
12606                            && ps.codePathString.startsWith(args.getCodePath())) {
12607                        if (DEBUG_SD_INSTALL) {
12608                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12609                                    + " at code path: " + ps.codePathString);
12610                        }
12611
12612                        // We do have a valid package installed on sdcard
12613                        processCids.put(args, ps.codePathString);
12614                        final int uid = ps.appId;
12615                        if (uid != -1) {
12616                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12617                        }
12618                    } else {
12619                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12620                                + ps.codePathString);
12621                    }
12622                }
12623            }
12624
12625            Arrays.sort(uidArr);
12626        }
12627
12628        // Process packages with valid entries.
12629        if (isMounted) {
12630            if (DEBUG_SD_INSTALL)
12631                Log.i(TAG, "Loading packages");
12632            loadMediaPackages(processCids, uidArr);
12633            startCleaningPackages();
12634            mInstallerService.onSecureContainersAvailable();
12635        } else {
12636            if (DEBUG_SD_INSTALL)
12637                Log.i(TAG, "Unloading packages");
12638            unloadMediaPackages(processCids, uidArr, reportStatus);
12639        }
12640    }
12641
12642    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12643            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12644        int size = pkgList.size();
12645        if (size > 0) {
12646            // Send broadcasts here
12647            Bundle extras = new Bundle();
12648            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12649                    .toArray(new String[size]));
12650            if (uidArr != null) {
12651                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12652            }
12653            if (replacing) {
12654                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12655            }
12656            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12657                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12658            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12659        }
12660    }
12661
12662   /*
12663     * Look at potentially valid container ids from processCids If package
12664     * information doesn't match the one on record or package scanning fails,
12665     * the cid is added to list of removeCids. We currently don't delete stale
12666     * containers.
12667     */
12668    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12669        ArrayList<String> pkgList = new ArrayList<String>();
12670        Set<AsecInstallArgs> keys = processCids.keySet();
12671
12672        for (AsecInstallArgs args : keys) {
12673            String codePath = processCids.get(args);
12674            if (DEBUG_SD_INSTALL)
12675                Log.i(TAG, "Loading container : " + args.cid);
12676            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12677            try {
12678                // Make sure there are no container errors first.
12679                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12680                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12681                            + " when installing from sdcard");
12682                    continue;
12683                }
12684                // Check code path here.
12685                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12686                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12687                            + " does not match one in settings " + codePath);
12688                    continue;
12689                }
12690                // Parse package
12691                int parseFlags = mDefParseFlags;
12692                if (args.isExternal()) {
12693                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12694                }
12695                if (args.isFwdLocked()) {
12696                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12697                }
12698
12699                synchronized (mInstallLock) {
12700                    PackageParser.Package pkg = null;
12701                    try {
12702                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12703                    } catch (PackageManagerException e) {
12704                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12705                    }
12706                    // Scan the package
12707                    if (pkg != null) {
12708                        /*
12709                         * TODO why is the lock being held? doPostInstall is
12710                         * called in other places without the lock. This needs
12711                         * to be straightened out.
12712                         */
12713                        // writer
12714                        synchronized (mPackages) {
12715                            retCode = PackageManager.INSTALL_SUCCEEDED;
12716                            pkgList.add(pkg.packageName);
12717                            // Post process args
12718                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12719                                    pkg.applicationInfo.uid);
12720                        }
12721                    } else {
12722                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12723                    }
12724                }
12725
12726            } finally {
12727                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12728                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12729                }
12730            }
12731        }
12732        // writer
12733        synchronized (mPackages) {
12734            // If the platform SDK has changed since the last time we booted,
12735            // we need to re-grant app permission to catch any new ones that
12736            // appear. This is really a hack, and means that apps can in some
12737            // cases get permissions that the user didn't initially explicitly
12738            // allow... it would be nice to have some better way to handle
12739            // this situation.
12740            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12741            if (regrantPermissions)
12742                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12743                        + mSdkVersion + "; regranting permissions for external storage");
12744            mSettings.mExternalSdkPlatform = mSdkVersion;
12745
12746            // Make sure group IDs have been assigned, and any permission
12747            // changes in other apps are accounted for
12748            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12749                    | (regrantPermissions
12750                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12751                            : 0));
12752
12753            mSettings.updateExternalDatabaseVersion();
12754
12755            // can downgrade to reader
12756            // Persist settings
12757            mSettings.writeLPr();
12758        }
12759        // Send a broadcast to let everyone know we are done processing
12760        if (pkgList.size() > 0) {
12761            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12762        }
12763    }
12764
12765   /*
12766     * Utility method to unload a list of specified containers
12767     */
12768    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12769        // Just unmount all valid containers.
12770        for (AsecInstallArgs arg : cidArgs) {
12771            synchronized (mInstallLock) {
12772                arg.doPostDeleteLI(false);
12773           }
12774       }
12775   }
12776
12777    /*
12778     * Unload packages mounted on external media. This involves deleting package
12779     * data from internal structures, sending broadcasts about diabled packages,
12780     * gc'ing to free up references, unmounting all secure containers
12781     * corresponding to packages on external media, and posting a
12782     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12783     * that we always have to post this message if status has been requested no
12784     * matter what.
12785     */
12786    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12787            final boolean reportStatus) {
12788        if (DEBUG_SD_INSTALL)
12789            Log.i(TAG, "unloading media packages");
12790        ArrayList<String> pkgList = new ArrayList<String>();
12791        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12792        final Set<AsecInstallArgs> keys = processCids.keySet();
12793        for (AsecInstallArgs args : keys) {
12794            String pkgName = args.getPackageName();
12795            if (DEBUG_SD_INSTALL)
12796                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12797            // Delete package internally
12798            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12799            synchronized (mInstallLock) {
12800                boolean res = deletePackageLI(pkgName, null, false, null, null,
12801                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12802                if (res) {
12803                    pkgList.add(pkgName);
12804                } else {
12805                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12806                    failedList.add(args);
12807                }
12808            }
12809        }
12810
12811        // reader
12812        synchronized (mPackages) {
12813            // We didn't update the settings after removing each package;
12814            // write them now for all packages.
12815            mSettings.writeLPr();
12816        }
12817
12818        // We have to absolutely send UPDATED_MEDIA_STATUS only
12819        // after confirming that all the receivers processed the ordered
12820        // broadcast when packages get disabled, force a gc to clean things up.
12821        // and unload all the containers.
12822        if (pkgList.size() > 0) {
12823            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12824                    new IIntentReceiver.Stub() {
12825                public void performReceive(Intent intent, int resultCode, String data,
12826                        Bundle extras, boolean ordered, boolean sticky,
12827                        int sendingUser) throws RemoteException {
12828                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12829                            reportStatus ? 1 : 0, 1, keys);
12830                    mHandler.sendMessage(msg);
12831                }
12832            });
12833        } else {
12834            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12835                    keys);
12836            mHandler.sendMessage(msg);
12837        }
12838    }
12839
12840    /** Binder call */
12841    @Override
12842    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12843            final int flags) {
12844        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12845        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12846        int returnCode = PackageManager.MOVE_SUCCEEDED;
12847        int currInstallFlags = 0;
12848        int newInstallFlags = 0;
12849
12850        File codeFile = null;
12851        String installerPackageName = null;
12852        String packageAbiOverride = null;
12853
12854        // reader
12855        synchronized (mPackages) {
12856            final PackageParser.Package pkg = mPackages.get(packageName);
12857            final PackageSetting ps = mSettings.mPackages.get(packageName);
12858            if (pkg == null || ps == null) {
12859                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12860            } else {
12861                // Disable moving fwd locked apps and system packages
12862                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12863                    Slog.w(TAG, "Cannot move system application");
12864                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12865                } else if (pkg.mOperationPending) {
12866                    Slog.w(TAG, "Attempt to move package which has pending operations");
12867                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12868                } else {
12869                    // Find install location first
12870                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12871                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12872                        Slog.w(TAG, "Ambigous flags specified for move location.");
12873                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12874                    } else {
12875                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12876                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12877                        currInstallFlags = isExternal(pkg)
12878                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12879
12880                        if (newInstallFlags == currInstallFlags) {
12881                            Slog.w(TAG, "No move required. Trying to move to same location");
12882                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12883                        } else {
12884                            if (isForwardLocked(pkg)) {
12885                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12886                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12887                            }
12888                        }
12889                    }
12890                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12891                        pkg.mOperationPending = true;
12892                    }
12893                }
12894
12895                codeFile = new File(pkg.codePath);
12896                installerPackageName = ps.installerPackageName;
12897                packageAbiOverride = ps.cpuAbiOverrideString;
12898            }
12899        }
12900
12901        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12902            try {
12903                observer.packageMoved(packageName, returnCode);
12904            } catch (RemoteException ignored) {
12905            }
12906            return;
12907        }
12908
12909        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12910            @Override
12911            public void onUserActionRequired(Intent intent) throws RemoteException {
12912                throw new IllegalStateException();
12913            }
12914
12915            @Override
12916            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12917                    Bundle extras) throws RemoteException {
12918                Slog.d(TAG, "Install result for move: "
12919                        + PackageManager.installStatusToString(returnCode, msg));
12920
12921                // We usually have a new package now after the install, but if
12922                // we failed we need to clear the pending flag on the original
12923                // package object.
12924                synchronized (mPackages) {
12925                    final PackageParser.Package pkg = mPackages.get(packageName);
12926                    if (pkg != null) {
12927                        pkg.mOperationPending = false;
12928                    }
12929                }
12930
12931                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12932                switch (status) {
12933                    case PackageInstaller.STATUS_SUCCESS:
12934                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12935                        break;
12936                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12937                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12938                        break;
12939                    default:
12940                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12941                        break;
12942                }
12943            }
12944        };
12945
12946        // Treat a move like reinstalling an existing app, which ensures that we
12947        // process everythign uniformly, like unpacking native libraries.
12948        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12949
12950        final Message msg = mHandler.obtainMessage(INIT_COPY);
12951        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12952        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12953                installerPackageName, null, user, packageAbiOverride);
12954        mHandler.sendMessage(msg);
12955    }
12956
12957    @Override
12958    public boolean setInstallLocation(int loc) {
12959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12960                null);
12961        if (getInstallLocation() == loc) {
12962            return true;
12963        }
12964        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12965                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12966            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12967                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12968            return true;
12969        }
12970        return false;
12971   }
12972
12973    @Override
12974    public int getInstallLocation() {
12975        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12976                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12977                PackageHelper.APP_INSTALL_AUTO);
12978    }
12979
12980    /** Called by UserManagerService */
12981    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12982        mDirtyUsers.remove(userHandle);
12983        mSettings.removeUserLPw(userHandle);
12984        mPendingBroadcasts.remove(userHandle);
12985        if (mInstaller != null) {
12986            // Technically, we shouldn't be doing this with the package lock
12987            // held.  However, this is very rare, and there is already so much
12988            // other disk I/O going on, that we'll let it slide for now.
12989            mInstaller.removeUserDataDirs(userHandle);
12990        }
12991        mUserNeedsBadging.delete(userHandle);
12992        removeUnusedPackagesLILPw(userManager, userHandle);
12993    }
12994
12995    /**
12996     * We're removing userHandle and would like to remove any downloaded packages
12997     * that are no longer in use by any other user.
12998     * @param userHandle the user being removed
12999     */
13000    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13001        final boolean DEBUG_CLEAN_APKS = false;
13002        int [] users = userManager.getUserIdsLPr();
13003        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13004        while (psit.hasNext()) {
13005            PackageSetting ps = psit.next();
13006            final String packageName = ps.pkg.packageName;
13007            // Skip over if system app
13008            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13009                continue;
13010            }
13011            if (DEBUG_CLEAN_APKS) {
13012                Slog.i(TAG, "Checking package " + packageName);
13013            }
13014            boolean keep = false;
13015            for (int i = 0; i < users.length; i++) {
13016                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13017                    keep = true;
13018                    if (DEBUG_CLEAN_APKS) {
13019                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13020                                + users[i]);
13021                    }
13022                    break;
13023                }
13024            }
13025            if (!keep) {
13026                if (DEBUG_CLEAN_APKS) {
13027                    Slog.i(TAG, "  Removing package " + packageName);
13028                }
13029                mHandler.post(new Runnable() {
13030                    public void run() {
13031                        deletePackageX(packageName, userHandle, 0);
13032                    } //end run
13033                });
13034            }
13035        }
13036    }
13037
13038    /** Called by UserManagerService */
13039    void createNewUserLILPw(int userHandle, File path) {
13040        if (mInstaller != null) {
13041            mInstaller.createUserConfig(userHandle);
13042            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13043        }
13044    }
13045
13046    @Override
13047    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13048        mContext.enforceCallingOrSelfPermission(
13049                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13050                "Only package verification agents can read the verifier device identity");
13051
13052        synchronized (mPackages) {
13053            return mSettings.getVerifierDeviceIdentityLPw();
13054        }
13055    }
13056
13057    @Override
13058    public void setPermissionEnforced(String permission, boolean enforced) {
13059        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13060        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13061            synchronized (mPackages) {
13062                if (mSettings.mReadExternalStorageEnforced == null
13063                        || mSettings.mReadExternalStorageEnforced != enforced) {
13064                    mSettings.mReadExternalStorageEnforced = enforced;
13065                    mSettings.writeLPr();
13066                }
13067            }
13068            // kill any non-foreground processes so we restart them and
13069            // grant/revoke the GID.
13070            final IActivityManager am = ActivityManagerNative.getDefault();
13071            if (am != null) {
13072                final long token = Binder.clearCallingIdentity();
13073                try {
13074                    am.killProcessesBelowForeground("setPermissionEnforcement");
13075                } catch (RemoteException e) {
13076                } finally {
13077                    Binder.restoreCallingIdentity(token);
13078                }
13079            }
13080        } else {
13081            throw new IllegalArgumentException("No selective enforcement for " + permission);
13082        }
13083    }
13084
13085    @Override
13086    @Deprecated
13087    public boolean isPermissionEnforced(String permission) {
13088        return true;
13089    }
13090
13091    @Override
13092    public boolean isStorageLow() {
13093        final long token = Binder.clearCallingIdentity();
13094        try {
13095            final DeviceStorageMonitorInternal
13096                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13097            if (dsm != null) {
13098                return dsm.isMemoryLow();
13099            } else {
13100                return false;
13101            }
13102        } finally {
13103            Binder.restoreCallingIdentity(token);
13104        }
13105    }
13106
13107    @Override
13108    public IPackageInstaller getPackageInstaller() {
13109        return mInstallerService;
13110    }
13111
13112    private boolean userNeedsBadging(int userId) {
13113        int index = mUserNeedsBadging.indexOfKey(userId);
13114        if (index < 0) {
13115            final UserInfo userInfo;
13116            final long token = Binder.clearCallingIdentity();
13117            try {
13118                userInfo = sUserManager.getUserInfo(userId);
13119            } finally {
13120                Binder.restoreCallingIdentity(token);
13121            }
13122            final boolean b;
13123            if (userInfo != null && userInfo.isManagedProfile()) {
13124                b = true;
13125            } else {
13126                b = false;
13127            }
13128            mUserNeedsBadging.put(userId, b);
13129            return b;
13130        }
13131        return mUserNeedsBadging.valueAt(index);
13132    }
13133
13134    @Override
13135    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13136        if (packageName == null || alias == null) {
13137            return null;
13138        }
13139        synchronized(mPackages) {
13140            final PackageParser.Package pkg = mPackages.get(packageName);
13141            if (pkg == null) {
13142                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13143                throw new IllegalArgumentException("Unknown package: " + packageName);
13144            }
13145            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13146                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13147                throw new SecurityException("May not access KeySets defined by"
13148                        + " aliases in other applications.");
13149            }
13150            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13151            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13152        }
13153    }
13154
13155    @Override
13156    public KeySetHandle getSigningKeySet(String packageName) {
13157        if (packageName == null) {
13158            return null;
13159        }
13160        synchronized(mPackages) {
13161            final PackageParser.Package pkg = mPackages.get(packageName);
13162            if (pkg == null) {
13163                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13164                throw new IllegalArgumentException("Unknown package: " + packageName);
13165            }
13166            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13167                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13168                throw new SecurityException("May not access signing KeySet of other apps.");
13169            }
13170            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13171            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13172        }
13173    }
13174
13175    @Override
13176    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13177        if (packageName == null || ks == null) {
13178            return false;
13179        }
13180        synchronized(mPackages) {
13181            final PackageParser.Package pkg = mPackages.get(packageName);
13182            if (pkg == null) {
13183                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13184                throw new IllegalArgumentException("Unknown package: " + packageName);
13185            }
13186            if (ks instanceof KeySetHandle) {
13187                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13188                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13189            }
13190            return false;
13191        }
13192    }
13193
13194    @Override
13195    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13196        if (packageName == null || ks == null) {
13197            return false;
13198        }
13199        synchronized(mPackages) {
13200            final PackageParser.Package pkg = mPackages.get(packageName);
13201            if (pkg == null) {
13202                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13203                throw new IllegalArgumentException("Unknown package: " + packageName);
13204            }
13205            if (ks instanceof KeySetHandle) {
13206                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13207                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13208            }
13209            return false;
13210        }
13211    }
13212}
13213