PackageManagerService.java revision e545035e0ece992941047d7676a53d090c81448d
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        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7702                null);
7703
7704        final File originFile = new File(originPath);
7705        final int uid = Binder.getCallingUid();
7706        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7707            try {
7708                if (observer != null) {
7709                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7710                }
7711            } catch (RemoteException re) {
7712            }
7713            return;
7714        }
7715
7716        UserHandle user;
7717        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7718            user = UserHandle.ALL;
7719        } else {
7720            user = new UserHandle(UserHandle.getUserId(uid));
7721        }
7722
7723        final int filteredInstallFlags;
7724        if (uid == Process.SHELL_UID || uid == 0) {
7725            if (DEBUG_INSTALL) {
7726                Slog.v(TAG, "Install from ADB");
7727            }
7728            filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB;
7729        } else {
7730            filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB;
7731        }
7732
7733        verificationParams.setInstallerUid(uid);
7734
7735        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7736
7737        final Message msg = mHandler.obtainMessage(INIT_COPY);
7738        msg.obj = new InstallParams(origin, observer, filteredInstallFlags,
7739                installerPackageName, verificationParams, user, packageAbiOverride);
7740        mHandler.sendMessage(msg);
7741    }
7742
7743    void installStage(String packageName, File stagedDir, String stagedCid,
7744            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7745            String installerPackageName, int installerUid, UserHandle user) {
7746        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7747                params.referrerUri, installerUid, null);
7748
7749        final OriginInfo origin;
7750        if (stagedDir != null) {
7751            origin = OriginInfo.fromStagedFile(stagedDir);
7752        } else {
7753            origin = OriginInfo.fromStagedContainer(stagedCid);
7754        }
7755
7756        final Message msg = mHandler.obtainMessage(INIT_COPY);
7757        msg.obj = new InstallParams(origin, observer, params.installFlags,
7758                installerPackageName, verifParams, user, params.abiOverride);
7759        mHandler.sendMessage(msg);
7760    }
7761
7762    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7763        Bundle extras = new Bundle(1);
7764        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7765
7766        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7767                packageName, extras, null, null, new int[] {userId});
7768        try {
7769            IActivityManager am = ActivityManagerNative.getDefault();
7770            final boolean isSystem =
7771                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7772            if (isSystem && am.isUserRunning(userId, false)) {
7773                // The just-installed/enabled app is bundled on the system, so presumed
7774                // to be able to run automatically without needing an explicit launch.
7775                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7776                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7777                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7778                        .setPackage(packageName);
7779                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7780                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7781            }
7782        } catch (RemoteException e) {
7783            // shouldn't happen
7784            Slog.w(TAG, "Unable to bootstrap installed package", e);
7785        }
7786    }
7787
7788    @Override
7789    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7790            int userId) {
7791        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7792        PackageSetting pkgSetting;
7793        final int uid = Binder.getCallingUid();
7794        if (UserHandle.getUserId(uid) != userId) {
7795            mContext.enforceCallingOrSelfPermission(
7796                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7797                    "setApplicationHiddenSetting for user " + userId);
7798        }
7799
7800        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7801            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7802            return false;
7803        }
7804
7805        long callingId = Binder.clearCallingIdentity();
7806        try {
7807            boolean sendAdded = false;
7808            boolean sendRemoved = false;
7809            // writer
7810            synchronized (mPackages) {
7811                pkgSetting = mSettings.mPackages.get(packageName);
7812                if (pkgSetting == null) {
7813                    return false;
7814                }
7815                if (pkgSetting.getHidden(userId) != hidden) {
7816                    pkgSetting.setHidden(hidden, userId);
7817                    mSettings.writePackageRestrictionsLPr(userId);
7818                    if (hidden) {
7819                        sendRemoved = true;
7820                    } else {
7821                        sendAdded = true;
7822                    }
7823                }
7824            }
7825            if (sendAdded) {
7826                sendPackageAddedForUser(packageName, pkgSetting, userId);
7827                return true;
7828            }
7829            if (sendRemoved) {
7830                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7831                        "hiding pkg");
7832                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7833            }
7834        } finally {
7835            Binder.restoreCallingIdentity(callingId);
7836        }
7837        return false;
7838    }
7839
7840    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7841            int userId) {
7842        final PackageRemovedInfo info = new PackageRemovedInfo();
7843        info.removedPackage = packageName;
7844        info.removedUsers = new int[] {userId};
7845        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7846        info.sendBroadcast(false, false, false);
7847    }
7848
7849    /**
7850     * Returns true if application is not found or there was an error. Otherwise it returns
7851     * the hidden state of the package for the given user.
7852     */
7853    @Override
7854    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7855        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7856        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7857                "getApplicationHidden for user " + userId);
7858        PackageSetting pkgSetting;
7859        long callingId = Binder.clearCallingIdentity();
7860        try {
7861            // writer
7862            synchronized (mPackages) {
7863                pkgSetting = mSettings.mPackages.get(packageName);
7864                if (pkgSetting == null) {
7865                    return true;
7866                }
7867                return pkgSetting.getHidden(userId);
7868            }
7869        } finally {
7870            Binder.restoreCallingIdentity(callingId);
7871        }
7872    }
7873
7874    /**
7875     * @hide
7876     */
7877    @Override
7878    public int installExistingPackageAsUser(String packageName, int userId) {
7879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7880                null);
7881        PackageSetting pkgSetting;
7882        final int uid = Binder.getCallingUid();
7883        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7884        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7885            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7886        }
7887
7888        long callingId = Binder.clearCallingIdentity();
7889        try {
7890            boolean sendAdded = false;
7891            Bundle extras = new Bundle(1);
7892
7893            // writer
7894            synchronized (mPackages) {
7895                pkgSetting = mSettings.mPackages.get(packageName);
7896                if (pkgSetting == null) {
7897                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7898                }
7899                if (!pkgSetting.getInstalled(userId)) {
7900                    pkgSetting.setInstalled(true, userId);
7901                    pkgSetting.setHidden(false, userId);
7902                    mSettings.writePackageRestrictionsLPr(userId);
7903                    sendAdded = true;
7904                }
7905            }
7906
7907            if (sendAdded) {
7908                sendPackageAddedForUser(packageName, pkgSetting, userId);
7909            }
7910        } finally {
7911            Binder.restoreCallingIdentity(callingId);
7912        }
7913
7914        return PackageManager.INSTALL_SUCCEEDED;
7915    }
7916
7917    boolean isUserRestricted(int userId, String restrictionKey) {
7918        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7919        if (restrictions.getBoolean(restrictionKey, false)) {
7920            Log.w(TAG, "User is restricted: " + restrictionKey);
7921            return true;
7922        }
7923        return false;
7924    }
7925
7926    @Override
7927    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7928        mContext.enforceCallingOrSelfPermission(
7929                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7930                "Only package verification agents can verify applications");
7931
7932        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7933        final PackageVerificationResponse response = new PackageVerificationResponse(
7934                verificationCode, Binder.getCallingUid());
7935        msg.arg1 = id;
7936        msg.obj = response;
7937        mHandler.sendMessage(msg);
7938    }
7939
7940    @Override
7941    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7942            long millisecondsToDelay) {
7943        mContext.enforceCallingOrSelfPermission(
7944                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7945                "Only package verification agents can extend verification timeouts");
7946
7947        final PackageVerificationState state = mPendingVerification.get(id);
7948        final PackageVerificationResponse response = new PackageVerificationResponse(
7949                verificationCodeAtTimeout, Binder.getCallingUid());
7950
7951        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7952            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7953        }
7954        if (millisecondsToDelay < 0) {
7955            millisecondsToDelay = 0;
7956        }
7957        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7958                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7959            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7960        }
7961
7962        if ((state != null) && !state.timeoutExtended()) {
7963            state.extendTimeout();
7964
7965            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7966            msg.arg1 = id;
7967            msg.obj = response;
7968            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7969        }
7970    }
7971
7972    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7973            int verificationCode, UserHandle user) {
7974        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7975        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7976        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7977        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7978        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7979
7980        mContext.sendBroadcastAsUser(intent, user,
7981                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7982    }
7983
7984    private ComponentName matchComponentForVerifier(String packageName,
7985            List<ResolveInfo> receivers) {
7986        ActivityInfo targetReceiver = null;
7987
7988        final int NR = receivers.size();
7989        for (int i = 0; i < NR; i++) {
7990            final ResolveInfo info = receivers.get(i);
7991            if (info.activityInfo == null) {
7992                continue;
7993            }
7994
7995            if (packageName.equals(info.activityInfo.packageName)) {
7996                targetReceiver = info.activityInfo;
7997                break;
7998            }
7999        }
8000
8001        if (targetReceiver == null) {
8002            return null;
8003        }
8004
8005        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8006    }
8007
8008    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8009            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8010        if (pkgInfo.verifiers.length == 0) {
8011            return null;
8012        }
8013
8014        final int N = pkgInfo.verifiers.length;
8015        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8016        for (int i = 0; i < N; i++) {
8017            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8018
8019            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8020                    receivers);
8021            if (comp == null) {
8022                continue;
8023            }
8024
8025            final int verifierUid = getUidForVerifier(verifierInfo);
8026            if (verifierUid == -1) {
8027                continue;
8028            }
8029
8030            if (DEBUG_VERIFY) {
8031                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8032                        + " with the correct signature");
8033            }
8034            sufficientVerifiers.add(comp);
8035            verificationState.addSufficientVerifier(verifierUid);
8036        }
8037
8038        return sufficientVerifiers;
8039    }
8040
8041    private int getUidForVerifier(VerifierInfo verifierInfo) {
8042        synchronized (mPackages) {
8043            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8044            if (pkg == null) {
8045                return -1;
8046            } else if (pkg.mSignatures.length != 1) {
8047                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8048                        + " has more than one signature; ignoring");
8049                return -1;
8050            }
8051
8052            /*
8053             * If the public key of the package's signature does not match
8054             * our expected public key, then this is a different package and
8055             * we should skip.
8056             */
8057
8058            final byte[] expectedPublicKey;
8059            try {
8060                final Signature verifierSig = pkg.mSignatures[0];
8061                final PublicKey publicKey = verifierSig.getPublicKey();
8062                expectedPublicKey = publicKey.getEncoded();
8063            } catch (CertificateException e) {
8064                return -1;
8065            }
8066
8067            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8068
8069            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8070                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8071                        + " does not have the expected public key; ignoring");
8072                return -1;
8073            }
8074
8075            return pkg.applicationInfo.uid;
8076        }
8077    }
8078
8079    @Override
8080    public void finishPackageInstall(int token) {
8081        enforceSystemOrRoot("Only the system is allowed to finish installs");
8082
8083        if (DEBUG_INSTALL) {
8084            Slog.v(TAG, "BM finishing package install for " + token);
8085        }
8086
8087        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8088        mHandler.sendMessage(msg);
8089    }
8090
8091    /**
8092     * Get the verification agent timeout.
8093     *
8094     * @return verification timeout in milliseconds
8095     */
8096    private long getVerificationTimeout() {
8097        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8098                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8099                DEFAULT_VERIFICATION_TIMEOUT);
8100    }
8101
8102    /**
8103     * Get the default verification agent response code.
8104     *
8105     * @return default verification response code
8106     */
8107    private int getDefaultVerificationResponse() {
8108        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8109                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8110                DEFAULT_VERIFICATION_RESPONSE);
8111    }
8112
8113    /**
8114     * Check whether or not package verification has been enabled.
8115     *
8116     * @return true if verification should be performed
8117     */
8118    private boolean isVerificationEnabled(int userId, int installFlags) {
8119        if (!DEFAULT_VERIFY_ENABLE) {
8120            return false;
8121        }
8122
8123        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8124
8125        // Check if installing from ADB
8126        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8127            // Do not run verification in a test harness environment
8128            if (ActivityManager.isRunningInTestHarness()) {
8129                return false;
8130            }
8131            if (ensureVerifyAppsEnabled) {
8132                return true;
8133            }
8134            // Check if the developer does not want package verification for ADB installs
8135            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8136                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8137                return false;
8138            }
8139        }
8140
8141        if (ensureVerifyAppsEnabled) {
8142            return true;
8143        }
8144
8145        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8146                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8147    }
8148
8149    /**
8150     * Get the "allow unknown sources" setting.
8151     *
8152     * @return the current "allow unknown sources" setting
8153     */
8154    private int getUnknownSourcesSettings() {
8155        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8156                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8157                -1);
8158    }
8159
8160    @Override
8161    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8162        final int uid = Binder.getCallingUid();
8163        // writer
8164        synchronized (mPackages) {
8165            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8166            if (targetPackageSetting == null) {
8167                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8168            }
8169
8170            PackageSetting installerPackageSetting;
8171            if (installerPackageName != null) {
8172                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8173                if (installerPackageSetting == null) {
8174                    throw new IllegalArgumentException("Unknown installer package: "
8175                            + installerPackageName);
8176                }
8177            } else {
8178                installerPackageSetting = null;
8179            }
8180
8181            Signature[] callerSignature;
8182            Object obj = mSettings.getUserIdLPr(uid);
8183            if (obj != null) {
8184                if (obj instanceof SharedUserSetting) {
8185                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8186                } else if (obj instanceof PackageSetting) {
8187                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8188                } else {
8189                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8190                }
8191            } else {
8192                throw new SecurityException("Unknown calling uid " + uid);
8193            }
8194
8195            // Verify: can't set installerPackageName to a package that is
8196            // not signed with the same cert as the caller.
8197            if (installerPackageSetting != null) {
8198                if (compareSignatures(callerSignature,
8199                        installerPackageSetting.signatures.mSignatures)
8200                        != PackageManager.SIGNATURE_MATCH) {
8201                    throw new SecurityException(
8202                            "Caller does not have same cert as new installer package "
8203                            + installerPackageName);
8204                }
8205            }
8206
8207            // Verify: if target already has an installer package, it must
8208            // be signed with the same cert as the caller.
8209            if (targetPackageSetting.installerPackageName != null) {
8210                PackageSetting setting = mSettings.mPackages.get(
8211                        targetPackageSetting.installerPackageName);
8212                // If the currently set package isn't valid, then it's always
8213                // okay to change it.
8214                if (setting != null) {
8215                    if (compareSignatures(callerSignature,
8216                            setting.signatures.mSignatures)
8217                            != PackageManager.SIGNATURE_MATCH) {
8218                        throw new SecurityException(
8219                                "Caller does not have same cert as old installer package "
8220                                + targetPackageSetting.installerPackageName);
8221                    }
8222                }
8223            }
8224
8225            // Okay!
8226            targetPackageSetting.installerPackageName = installerPackageName;
8227            scheduleWriteSettingsLocked();
8228        }
8229    }
8230
8231    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8232        // Queue up an async operation since the package installation may take a little while.
8233        mHandler.post(new Runnable() {
8234            public void run() {
8235                mHandler.removeCallbacks(this);
8236                 // Result object to be returned
8237                PackageInstalledInfo res = new PackageInstalledInfo();
8238                res.returnCode = currentStatus;
8239                res.uid = -1;
8240                res.pkg = null;
8241                res.removedInfo = new PackageRemovedInfo();
8242                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8243                    args.doPreInstall(res.returnCode);
8244                    synchronized (mInstallLock) {
8245                        installPackageLI(args, res);
8246                    }
8247                    args.doPostInstall(res.returnCode, res.uid);
8248                }
8249
8250                // A restore should be performed at this point if (a) the install
8251                // succeeded, (b) the operation is not an update, and (c) the new
8252                // package has not opted out of backup participation.
8253                final boolean update = res.removedInfo.removedPackage != null;
8254                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8255                boolean doRestore = !update
8256                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8257
8258                // Set up the post-install work request bookkeeping.  This will be used
8259                // and cleaned up by the post-install event handling regardless of whether
8260                // there's a restore pass performed.  Token values are >= 1.
8261                int token;
8262                if (mNextInstallToken < 0) mNextInstallToken = 1;
8263                token = mNextInstallToken++;
8264
8265                PostInstallData data = new PostInstallData(args, res);
8266                mRunningInstalls.put(token, data);
8267                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8268
8269                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8270                    // Pass responsibility to the Backup Manager.  It will perform a
8271                    // restore if appropriate, then pass responsibility back to the
8272                    // Package Manager to run the post-install observer callbacks
8273                    // and broadcasts.
8274                    IBackupManager bm = IBackupManager.Stub.asInterface(
8275                            ServiceManager.getService(Context.BACKUP_SERVICE));
8276                    if (bm != null) {
8277                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8278                                + " to BM for possible restore");
8279                        try {
8280                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8281                        } catch (RemoteException e) {
8282                            // can't happen; the backup manager is local
8283                        } catch (Exception e) {
8284                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8285                            doRestore = false;
8286                        }
8287                    } else {
8288                        Slog.e(TAG, "Backup Manager not found!");
8289                        doRestore = false;
8290                    }
8291                }
8292
8293                if (!doRestore) {
8294                    // No restore possible, or the Backup Manager was mysteriously not
8295                    // available -- just fire the post-install work request directly.
8296                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8297                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8298                    mHandler.sendMessage(msg);
8299                }
8300            }
8301        });
8302    }
8303
8304    private abstract class HandlerParams {
8305        private static final int MAX_RETRIES = 4;
8306
8307        /**
8308         * Number of times startCopy() has been attempted and had a non-fatal
8309         * error.
8310         */
8311        private int mRetries = 0;
8312
8313        /** User handle for the user requesting the information or installation. */
8314        private final UserHandle mUser;
8315
8316        HandlerParams(UserHandle user) {
8317            mUser = user;
8318        }
8319
8320        UserHandle getUser() {
8321            return mUser;
8322        }
8323
8324        final boolean startCopy() {
8325            boolean res;
8326            try {
8327                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8328
8329                if (++mRetries > MAX_RETRIES) {
8330                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8331                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8332                    handleServiceError();
8333                    return false;
8334                } else {
8335                    handleStartCopy();
8336                    res = true;
8337                }
8338            } catch (RemoteException e) {
8339                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8340                mHandler.sendEmptyMessage(MCS_RECONNECT);
8341                res = false;
8342            }
8343            handleReturnCode();
8344            return res;
8345        }
8346
8347        final void serviceError() {
8348            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8349            handleServiceError();
8350            handleReturnCode();
8351        }
8352
8353        abstract void handleStartCopy() throws RemoteException;
8354        abstract void handleServiceError();
8355        abstract void handleReturnCode();
8356    }
8357
8358    class MeasureParams extends HandlerParams {
8359        private final PackageStats mStats;
8360        private boolean mSuccess;
8361
8362        private final IPackageStatsObserver mObserver;
8363
8364        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8365            super(new UserHandle(stats.userHandle));
8366            mObserver = observer;
8367            mStats = stats;
8368        }
8369
8370        @Override
8371        public String toString() {
8372            return "MeasureParams{"
8373                + Integer.toHexString(System.identityHashCode(this))
8374                + " " + mStats.packageName + "}";
8375        }
8376
8377        @Override
8378        void handleStartCopy() throws RemoteException {
8379            synchronized (mInstallLock) {
8380                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8381            }
8382
8383            if (mSuccess) {
8384                final boolean mounted;
8385                if (Environment.isExternalStorageEmulated()) {
8386                    mounted = true;
8387                } else {
8388                    final String status = Environment.getExternalStorageState();
8389                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8390                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8391                }
8392
8393                if (mounted) {
8394                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8395
8396                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8397                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8398
8399                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8400                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8401
8402                    // Always subtract cache size, since it's a subdirectory
8403                    mStats.externalDataSize -= mStats.externalCacheSize;
8404
8405                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8406                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8407
8408                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8409                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8410                }
8411            }
8412        }
8413
8414        @Override
8415        void handleReturnCode() {
8416            if (mObserver != null) {
8417                try {
8418                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8419                } catch (RemoteException e) {
8420                    Slog.i(TAG, "Observer no longer exists.");
8421                }
8422            }
8423        }
8424
8425        @Override
8426        void handleServiceError() {
8427            Slog.e(TAG, "Could not measure application " + mStats.packageName
8428                            + " external storage");
8429        }
8430    }
8431
8432    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8433            throws RemoteException {
8434        long result = 0;
8435        for (File path : paths) {
8436            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8437        }
8438        return result;
8439    }
8440
8441    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8442        for (File path : paths) {
8443            try {
8444                mcs.clearDirectory(path.getAbsolutePath());
8445            } catch (RemoteException e) {
8446            }
8447        }
8448    }
8449
8450    static class OriginInfo {
8451        /**
8452         * Location where install is coming from, before it has been
8453         * copied/renamed into place. This could be a single monolithic APK
8454         * file, or a cluster directory. This location may be untrusted.
8455         */
8456        final File file;
8457        final String cid;
8458
8459        /**
8460         * Flag indicating that {@link #file} or {@link #cid} has already been
8461         * staged, meaning downstream users don't need to defensively copy the
8462         * contents.
8463         */
8464        final boolean staged;
8465
8466        /**
8467         * Flag indicating that {@link #file} or {@link #cid} is an already
8468         * installed app that is being moved.
8469         */
8470        final boolean existing;
8471
8472        final String resolvedPath;
8473        final File resolvedFile;
8474
8475        static OriginInfo fromNothing() {
8476            return new OriginInfo(null, null, false, false);
8477        }
8478
8479        static OriginInfo fromUntrustedFile(File file) {
8480            return new OriginInfo(file, null, false, false);
8481        }
8482
8483        static OriginInfo fromExistingFile(File file) {
8484            return new OriginInfo(file, null, false, true);
8485        }
8486
8487        static OriginInfo fromStagedFile(File file) {
8488            return new OriginInfo(file, null, true, false);
8489        }
8490
8491        static OriginInfo fromStagedContainer(String cid) {
8492            return new OriginInfo(null, cid, true, false);
8493        }
8494
8495        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8496            this.file = file;
8497            this.cid = cid;
8498            this.staged = staged;
8499            this.existing = existing;
8500
8501            if (cid != null) {
8502                resolvedPath = PackageHelper.getSdDir(cid);
8503                resolvedFile = new File(resolvedPath);
8504            } else if (file != null) {
8505                resolvedPath = file.getAbsolutePath();
8506                resolvedFile = file;
8507            } else {
8508                resolvedPath = null;
8509                resolvedFile = null;
8510            }
8511        }
8512    }
8513
8514    class InstallParams extends HandlerParams {
8515        final OriginInfo origin;
8516        final IPackageInstallObserver2 observer;
8517        int installFlags;
8518        final String installerPackageName;
8519        final VerificationParams verificationParams;
8520        private InstallArgs mArgs;
8521        private int mRet;
8522        final String packageAbiOverride;
8523
8524        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8525                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8526                String packageAbiOverride) {
8527            super(user);
8528            this.origin = origin;
8529            this.observer = observer;
8530            this.installFlags = installFlags;
8531            this.installerPackageName = installerPackageName;
8532            this.verificationParams = verificationParams;
8533            this.packageAbiOverride = packageAbiOverride;
8534        }
8535
8536        @Override
8537        public String toString() {
8538            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8539                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8540        }
8541
8542        public ManifestDigest getManifestDigest() {
8543            if (verificationParams == null) {
8544                return null;
8545            }
8546            return verificationParams.getManifestDigest();
8547        }
8548
8549        private int installLocationPolicy(PackageInfoLite pkgLite) {
8550            String packageName = pkgLite.packageName;
8551            int installLocation = pkgLite.installLocation;
8552            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8553            // reader
8554            synchronized (mPackages) {
8555                PackageParser.Package pkg = mPackages.get(packageName);
8556                if (pkg != null) {
8557                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8558                        // Check for downgrading.
8559                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8560                            if (pkgLite.versionCode < pkg.mVersionCode) {
8561                                Slog.w(TAG, "Can't install update of " + packageName
8562                                        + " update version " + pkgLite.versionCode
8563                                        + " is older than installed version "
8564                                        + pkg.mVersionCode);
8565                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8566                            }
8567                        }
8568                        // Check for updated system application.
8569                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8570                            if (onSd) {
8571                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8572                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8573                            }
8574                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8575                        } else {
8576                            if (onSd) {
8577                                // Install flag overrides everything.
8578                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8579                            }
8580                            // If current upgrade specifies particular preference
8581                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8582                                // Application explicitly specified internal.
8583                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8584                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8585                                // App explictly prefers external. Let policy decide
8586                            } else {
8587                                // Prefer previous location
8588                                if (isExternal(pkg)) {
8589                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8590                                }
8591                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8592                            }
8593                        }
8594                    } else {
8595                        // Invalid install. Return error code
8596                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8597                    }
8598                }
8599            }
8600            // All the special cases have been taken care of.
8601            // Return result based on recommended install location.
8602            if (onSd) {
8603                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8604            }
8605            return pkgLite.recommendedInstallLocation;
8606        }
8607
8608        /*
8609         * Invoke remote method to get package information and install
8610         * location values. Override install location based on default
8611         * policy if needed and then create install arguments based
8612         * on the install location.
8613         */
8614        public void handleStartCopy() throws RemoteException {
8615            int ret = PackageManager.INSTALL_SUCCEEDED;
8616
8617            // If we're already staged, we've firmly committed to an install location
8618            if (origin.staged) {
8619                if (origin.file != null) {
8620                    installFlags |= PackageManager.INSTALL_INTERNAL;
8621                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8622                } else if (origin.cid != null) {
8623                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8624                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8625                } else {
8626                    throw new IllegalStateException("Invalid stage location");
8627                }
8628            }
8629
8630            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8631            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8632
8633            PackageInfoLite pkgLite = null;
8634
8635            if (onInt && onSd) {
8636                // Check if both bits are set.
8637                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8638                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8639            } else {
8640                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8641                        packageAbiOverride);
8642
8643                /*
8644                 * If we have too little free space, try to free cache
8645                 * before giving up.
8646                 */
8647                if (!origin.staged && pkgLite.recommendedInstallLocation
8648                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8649                    // TODO: focus freeing disk space on the target device
8650                    final StorageManager storage = StorageManager.from(mContext);
8651                    final long lowThreshold = storage.getStorageLowBytes(
8652                            Environment.getDataDirectory());
8653
8654                    final long sizeBytes = mContainerService.calculateInstalledSize(
8655                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8656
8657                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8658                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8659                                installFlags, packageAbiOverride);
8660                    }
8661
8662                    /*
8663                     * The cache free must have deleted the file we
8664                     * downloaded to install.
8665                     *
8666                     * TODO: fix the "freeCache" call to not delete
8667                     *       the file we care about.
8668                     */
8669                    if (pkgLite.recommendedInstallLocation
8670                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8671                        pkgLite.recommendedInstallLocation
8672                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8673                    }
8674                }
8675            }
8676
8677            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8678                int loc = pkgLite.recommendedInstallLocation;
8679                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8680                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8681                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8682                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8683                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8684                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8685                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8686                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8687                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8688                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8689                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8690                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8691                } else {
8692                    // Override with defaults if needed.
8693                    loc = installLocationPolicy(pkgLite);
8694                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8695                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8696                    } else if (!onSd && !onInt) {
8697                        // Override install location with flags
8698                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8699                            // Set the flag to install on external media.
8700                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8701                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8702                        } else {
8703                            // Make sure the flag for installing on external
8704                            // media is unset
8705                            installFlags |= PackageManager.INSTALL_INTERNAL;
8706                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8707                        }
8708                    }
8709                }
8710            }
8711
8712            final InstallArgs args = createInstallArgs(this);
8713            mArgs = args;
8714
8715            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8716                 /*
8717                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8718                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8719                 */
8720                int userIdentifier = getUser().getIdentifier();
8721                if (userIdentifier == UserHandle.USER_ALL
8722                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8723                    userIdentifier = UserHandle.USER_OWNER;
8724                }
8725
8726                /*
8727                 * Determine if we have any installed package verifiers. If we
8728                 * do, then we'll defer to them to verify the packages.
8729                 */
8730                final int requiredUid = mRequiredVerifierPackage == null ? -1
8731                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8732                if (!origin.existing && requiredUid != -1
8733                        && isVerificationEnabled(userIdentifier, installFlags)) {
8734                    final Intent verification = new Intent(
8735                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8736                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8737                            PACKAGE_MIME_TYPE);
8738                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8739
8740                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8741                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8742                            0 /* TODO: Which userId? */);
8743
8744                    if (DEBUG_VERIFY) {
8745                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8746                                + verification.toString() + " with " + pkgLite.verifiers.length
8747                                + " optional verifiers");
8748                    }
8749
8750                    final int verificationId = mPendingVerificationToken++;
8751
8752                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8753
8754                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8755                            installerPackageName);
8756
8757                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8758                            installFlags);
8759
8760                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8761                            pkgLite.packageName);
8762
8763                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8764                            pkgLite.versionCode);
8765
8766                    if (verificationParams != null) {
8767                        if (verificationParams.getVerificationURI() != null) {
8768                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8769                                 verificationParams.getVerificationURI());
8770                        }
8771                        if (verificationParams.getOriginatingURI() != null) {
8772                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8773                                  verificationParams.getOriginatingURI());
8774                        }
8775                        if (verificationParams.getReferrer() != null) {
8776                            verification.putExtra(Intent.EXTRA_REFERRER,
8777                                  verificationParams.getReferrer());
8778                        }
8779                        if (verificationParams.getOriginatingUid() >= 0) {
8780                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8781                                  verificationParams.getOriginatingUid());
8782                        }
8783                        if (verificationParams.getInstallerUid() >= 0) {
8784                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8785                                  verificationParams.getInstallerUid());
8786                        }
8787                    }
8788
8789                    final PackageVerificationState verificationState = new PackageVerificationState(
8790                            requiredUid, args);
8791
8792                    mPendingVerification.append(verificationId, verificationState);
8793
8794                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8795                            receivers, verificationState);
8796
8797                    /*
8798                     * If any sufficient verifiers were listed in the package
8799                     * manifest, attempt to ask them.
8800                     */
8801                    if (sufficientVerifiers != null) {
8802                        final int N = sufficientVerifiers.size();
8803                        if (N == 0) {
8804                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8805                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8806                        } else {
8807                            for (int i = 0; i < N; i++) {
8808                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8809
8810                                final Intent sufficientIntent = new Intent(verification);
8811                                sufficientIntent.setComponent(verifierComponent);
8812
8813                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8814                            }
8815                        }
8816                    }
8817
8818                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8819                            mRequiredVerifierPackage, receivers);
8820                    if (ret == PackageManager.INSTALL_SUCCEEDED
8821                            && mRequiredVerifierPackage != null) {
8822                        /*
8823                         * Send the intent to the required verification agent,
8824                         * but only start the verification timeout after the
8825                         * target BroadcastReceivers have run.
8826                         */
8827                        verification.setComponent(requiredVerifierComponent);
8828                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8829                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8830                                new BroadcastReceiver() {
8831                                    @Override
8832                                    public void onReceive(Context context, Intent intent) {
8833                                        final Message msg = mHandler
8834                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8835                                        msg.arg1 = verificationId;
8836                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8837                                    }
8838                                }, null, 0, null, null);
8839
8840                        /*
8841                         * We don't want the copy to proceed until verification
8842                         * succeeds, so null out this field.
8843                         */
8844                        mArgs = null;
8845                    }
8846                } else {
8847                    /*
8848                     * No package verification is enabled, so immediately start
8849                     * the remote call to initiate copy using temporary file.
8850                     */
8851                    ret = args.copyApk(mContainerService, true);
8852                }
8853            }
8854
8855            mRet = ret;
8856        }
8857
8858        @Override
8859        void handleReturnCode() {
8860            // If mArgs is null, then MCS couldn't be reached. When it
8861            // reconnects, it will try again to install. At that point, this
8862            // will succeed.
8863            if (mArgs != null) {
8864                processPendingInstall(mArgs, mRet);
8865            }
8866        }
8867
8868        @Override
8869        void handleServiceError() {
8870            mArgs = createInstallArgs(this);
8871            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8872        }
8873
8874        public boolean isForwardLocked() {
8875            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8876        }
8877    }
8878
8879    /**
8880     * Used during creation of InstallArgs
8881     *
8882     * @param installFlags package installation flags
8883     * @return true if should be installed on external storage
8884     */
8885    private static boolean installOnSd(int installFlags) {
8886        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8887            return false;
8888        }
8889        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8890            return true;
8891        }
8892        return false;
8893    }
8894
8895    /**
8896     * Used during creation of InstallArgs
8897     *
8898     * @param installFlags package installation flags
8899     * @return true if should be installed as forward locked
8900     */
8901    private static boolean installForwardLocked(int installFlags) {
8902        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8903    }
8904
8905    private InstallArgs createInstallArgs(InstallParams params) {
8906        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8907            return new AsecInstallArgs(params);
8908        } else {
8909            return new FileInstallArgs(params);
8910        }
8911    }
8912
8913    /**
8914     * Create args that describe an existing installed package. Typically used
8915     * when cleaning up old installs, or used as a move source.
8916     */
8917    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8918            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8919        final boolean isInAsec;
8920        if (installOnSd(installFlags)) {
8921            /* Apps on SD card are always in ASEC containers. */
8922            isInAsec = true;
8923        } else if (installForwardLocked(installFlags)
8924                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8925            /*
8926             * Forward-locked apps are only in ASEC containers if they're the
8927             * new style
8928             */
8929            isInAsec = true;
8930        } else {
8931            isInAsec = false;
8932        }
8933
8934        if (isInAsec) {
8935            return new AsecInstallArgs(codePath, instructionSets,
8936                    installOnSd(installFlags), installForwardLocked(installFlags));
8937        } else {
8938            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8939                    instructionSets);
8940        }
8941    }
8942
8943    static abstract class InstallArgs {
8944        /** @see InstallParams#origin */
8945        final OriginInfo origin;
8946
8947        final IPackageInstallObserver2 observer;
8948        // Always refers to PackageManager flags only
8949        final int installFlags;
8950        final String installerPackageName;
8951        final ManifestDigest manifestDigest;
8952        final UserHandle user;
8953        final String abiOverride;
8954
8955        // The list of instruction sets supported by this app. This is currently
8956        // only used during the rmdex() phase to clean up resources. We can get rid of this
8957        // if we move dex files under the common app path.
8958        /* nullable */ String[] instructionSets;
8959
8960        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8961                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8962                String[] instructionSets, String abiOverride) {
8963            this.origin = origin;
8964            this.installFlags = installFlags;
8965            this.observer = observer;
8966            this.installerPackageName = installerPackageName;
8967            this.manifestDigest = manifestDigest;
8968            this.user = user;
8969            this.instructionSets = instructionSets;
8970            this.abiOverride = abiOverride;
8971        }
8972
8973        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8974        abstract int doPreInstall(int status);
8975
8976        /**
8977         * Rename package into final resting place. All paths on the given
8978         * scanned package should be updated to reflect the rename.
8979         */
8980        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8981        abstract int doPostInstall(int status, int uid);
8982
8983        /** @see PackageSettingBase#codePathString */
8984        abstract String getCodePath();
8985        /** @see PackageSettingBase#resourcePathString */
8986        abstract String getResourcePath();
8987        abstract String getLegacyNativeLibraryPath();
8988
8989        // Need installer lock especially for dex file removal.
8990        abstract void cleanUpResourcesLI();
8991        abstract boolean doPostDeleteLI(boolean delete);
8992        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8993
8994        /**
8995         * Called before the source arguments are copied. This is used mostly
8996         * for MoveParams when it needs to read the source file to put it in the
8997         * destination.
8998         */
8999        int doPreCopy() {
9000            return PackageManager.INSTALL_SUCCEEDED;
9001        }
9002
9003        /**
9004         * Called after the source arguments are copied. This is used mostly for
9005         * MoveParams when it needs to read the source file to put it in the
9006         * destination.
9007         *
9008         * @return
9009         */
9010        int doPostCopy(int uid) {
9011            return PackageManager.INSTALL_SUCCEEDED;
9012        }
9013
9014        protected boolean isFwdLocked() {
9015            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9016        }
9017
9018        protected boolean isExternal() {
9019            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9020        }
9021
9022        UserHandle getUser() {
9023            return user;
9024        }
9025    }
9026
9027    /**
9028     * Logic to handle installation of non-ASEC applications, including copying
9029     * and renaming logic.
9030     */
9031    class FileInstallArgs extends InstallArgs {
9032        private File codeFile;
9033        private File resourceFile;
9034        private File legacyNativeLibraryPath;
9035
9036        // Example topology:
9037        // /data/app/com.example/base.apk
9038        // /data/app/com.example/split_foo.apk
9039        // /data/app/com.example/lib/arm/libfoo.so
9040        // /data/app/com.example/lib/arm64/libfoo.so
9041        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9042
9043        /** New install */
9044        FileInstallArgs(InstallParams params) {
9045            super(params.origin, params.observer, params.installFlags,
9046                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9047                    null /* instruction sets */, params.packageAbiOverride);
9048            if (isFwdLocked()) {
9049                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9050            }
9051        }
9052
9053        /** Existing install */
9054        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9055                String[] instructionSets) {
9056            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9057            this.codeFile = (codePath != null) ? new File(codePath) : null;
9058            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9059            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9060                    new File(legacyNativeLibraryPath) : null;
9061        }
9062
9063        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9064            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9065                    isFwdLocked(), abiOverride);
9066
9067            final StorageManager storage = StorageManager.from(mContext);
9068            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9069        }
9070
9071        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9072            if (origin.staged) {
9073                Slog.d(TAG, origin.file + " already staged; skipping copy");
9074                codeFile = origin.file;
9075                resourceFile = origin.file;
9076                return PackageManager.INSTALL_SUCCEEDED;
9077            }
9078
9079            try {
9080                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9081                codeFile = tempDir;
9082                resourceFile = tempDir;
9083            } catch (IOException e) {
9084                Slog.w(TAG, "Failed to create copy file: " + e);
9085                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9086            }
9087
9088            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9089                @Override
9090                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9091                    if (!FileUtils.isValidExtFilename(name)) {
9092                        throw new IllegalArgumentException("Invalid filename: " + name);
9093                    }
9094                    try {
9095                        final File file = new File(codeFile, name);
9096                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9097                                O_RDWR | O_CREAT, 0644);
9098                        Os.chmod(file.getAbsolutePath(), 0644);
9099                        return new ParcelFileDescriptor(fd);
9100                    } catch (ErrnoException e) {
9101                        throw new RemoteException("Failed to open: " + e.getMessage());
9102                    }
9103                }
9104            };
9105
9106            int ret = PackageManager.INSTALL_SUCCEEDED;
9107            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9108            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9109                Slog.e(TAG, "Failed to copy package");
9110                return ret;
9111            }
9112
9113            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9114            NativeLibraryHelper.Handle handle = null;
9115            try {
9116                handle = NativeLibraryHelper.Handle.create(codeFile);
9117                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9118                        abiOverride);
9119            } catch (IOException e) {
9120                Slog.e(TAG, "Copying native libraries failed", e);
9121                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9122            } finally {
9123                IoUtils.closeQuietly(handle);
9124            }
9125
9126            return ret;
9127        }
9128
9129        int doPreInstall(int status) {
9130            if (status != PackageManager.INSTALL_SUCCEEDED) {
9131                cleanUp();
9132            }
9133            return status;
9134        }
9135
9136        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9137            if (status != PackageManager.INSTALL_SUCCEEDED) {
9138                cleanUp();
9139                return false;
9140            } else {
9141                final File beforeCodeFile = codeFile;
9142                final File afterCodeFile = getNextCodePath(pkg.packageName);
9143
9144                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9145                try {
9146                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9147                } catch (ErrnoException e) {
9148                    Slog.d(TAG, "Failed to rename", e);
9149                    return false;
9150                }
9151
9152                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9153                    Slog.d(TAG, "Failed to restorecon");
9154                    return false;
9155                }
9156
9157                // Reflect the rename internally
9158                codeFile = afterCodeFile;
9159                resourceFile = afterCodeFile;
9160
9161                // Reflect the rename in scanned details
9162                pkg.codePath = afterCodeFile.getAbsolutePath();
9163                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9164                        pkg.baseCodePath);
9165                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9166                        pkg.splitCodePaths);
9167
9168                // Reflect the rename in app info
9169                pkg.applicationInfo.setCodePath(pkg.codePath);
9170                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9171                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9172                pkg.applicationInfo.setResourcePath(pkg.codePath);
9173                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9174                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9175
9176                return true;
9177            }
9178        }
9179
9180        int doPostInstall(int status, int uid) {
9181            if (status != PackageManager.INSTALL_SUCCEEDED) {
9182                cleanUp();
9183            }
9184            return status;
9185        }
9186
9187        @Override
9188        String getCodePath() {
9189            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9190        }
9191
9192        @Override
9193        String getResourcePath() {
9194            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9195        }
9196
9197        @Override
9198        String getLegacyNativeLibraryPath() {
9199            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9200        }
9201
9202        private boolean cleanUp() {
9203            if (codeFile == null || !codeFile.exists()) {
9204                return false;
9205            }
9206
9207            if (codeFile.isDirectory()) {
9208                FileUtils.deleteContents(codeFile);
9209            }
9210            codeFile.delete();
9211
9212            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9213                resourceFile.delete();
9214            }
9215
9216            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9217                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9218                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9219                }
9220                legacyNativeLibraryPath.delete();
9221            }
9222
9223            return true;
9224        }
9225
9226        void cleanUpResourcesLI() {
9227            // Try enumerating all code paths before deleting
9228            List<String> allCodePaths = Collections.EMPTY_LIST;
9229            if (codeFile != null && codeFile.exists()) {
9230                try {
9231                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9232                    allCodePaths = pkg.getAllCodePaths();
9233                } catch (PackageParserException e) {
9234                    // Ignored; we tried our best
9235                }
9236            }
9237
9238            cleanUp();
9239
9240            if (!allCodePaths.isEmpty()) {
9241                if (instructionSets == null) {
9242                    throw new IllegalStateException("instructionSet == null");
9243                }
9244                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9245                for (String codePath : allCodePaths) {
9246                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9247                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9248                        if (retCode < 0) {
9249                            Slog.w(TAG, "Couldn't remove dex file for package: "
9250                                    + " at location " + codePath + ", retcode=" + retCode);
9251                            // we don't consider this to be a failure of the core package deletion
9252                        }
9253                    }
9254                }
9255            }
9256        }
9257
9258        boolean doPostDeleteLI(boolean delete) {
9259            // XXX err, shouldn't we respect the delete flag?
9260            cleanUpResourcesLI();
9261            return true;
9262        }
9263    }
9264
9265    private boolean isAsecExternal(String cid) {
9266        final String asecPath = PackageHelper.getSdFilesystem(cid);
9267        return !asecPath.startsWith(mAsecInternalPath);
9268    }
9269
9270    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9271            PackageManagerException {
9272        if (copyRet < 0) {
9273            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9274                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9275                throw new PackageManagerException(copyRet, message);
9276            }
9277        }
9278    }
9279
9280    /**
9281     * Extract the MountService "container ID" from the full code path of an
9282     * .apk.
9283     */
9284    static String cidFromCodePath(String fullCodePath) {
9285        int eidx = fullCodePath.lastIndexOf("/");
9286        String subStr1 = fullCodePath.substring(0, eidx);
9287        int sidx = subStr1.lastIndexOf("/");
9288        return subStr1.substring(sidx+1, eidx);
9289    }
9290
9291    /**
9292     * Logic to handle installation of ASEC applications, including copying and
9293     * renaming logic.
9294     */
9295    class AsecInstallArgs extends InstallArgs {
9296        static final String RES_FILE_NAME = "pkg.apk";
9297        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9298
9299        String cid;
9300        String packagePath;
9301        String resourcePath;
9302        String legacyNativeLibraryDir;
9303
9304        /** New install */
9305        AsecInstallArgs(InstallParams params) {
9306            super(params.origin, params.observer, params.installFlags,
9307                    params.installerPackageName, params.getManifestDigest(),
9308                    params.getUser(), null /* instruction sets */,
9309                    params.packageAbiOverride);
9310        }
9311
9312        /** Existing install */
9313        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9314                        boolean isExternal, boolean isForwardLocked) {
9315            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9316                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9317                    instructionSets, null);
9318            // Hackily pretend we're still looking at a full code path
9319            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9320                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9321            }
9322
9323            // Extract cid from fullCodePath
9324            int eidx = fullCodePath.lastIndexOf("/");
9325            String subStr1 = fullCodePath.substring(0, eidx);
9326            int sidx = subStr1.lastIndexOf("/");
9327            cid = subStr1.substring(sidx+1, eidx);
9328            setMountPath(subStr1);
9329        }
9330
9331        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9332            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9333                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9334                    instructionSets, null);
9335            this.cid = cid;
9336            setMountPath(PackageHelper.getSdDir(cid));
9337        }
9338
9339        void createCopyFile() {
9340            cid = mInstallerService.allocateExternalStageCidLegacy();
9341        }
9342
9343        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9344            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9345                    abiOverride);
9346
9347            final File target;
9348            if (isExternal()) {
9349                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9350            } else {
9351                target = Environment.getDataDirectory();
9352            }
9353
9354            final StorageManager storage = StorageManager.from(mContext);
9355            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9356        }
9357
9358        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9359            if (origin.staged) {
9360                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9361                cid = origin.cid;
9362                setMountPath(PackageHelper.getSdDir(cid));
9363                return PackageManager.INSTALL_SUCCEEDED;
9364            }
9365
9366            if (temp) {
9367                createCopyFile();
9368            } else {
9369                /*
9370                 * Pre-emptively destroy the container since it's destroyed if
9371                 * copying fails due to it existing anyway.
9372                 */
9373                PackageHelper.destroySdDir(cid);
9374            }
9375
9376            final String newMountPath = imcs.copyPackageToContainer(
9377                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9378                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9379
9380            if (newMountPath != null) {
9381                setMountPath(newMountPath);
9382                return PackageManager.INSTALL_SUCCEEDED;
9383            } else {
9384                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9385            }
9386        }
9387
9388        @Override
9389        String getCodePath() {
9390            return packagePath;
9391        }
9392
9393        @Override
9394        String getResourcePath() {
9395            return resourcePath;
9396        }
9397
9398        @Override
9399        String getLegacyNativeLibraryPath() {
9400            return legacyNativeLibraryDir;
9401        }
9402
9403        int doPreInstall(int status) {
9404            if (status != PackageManager.INSTALL_SUCCEEDED) {
9405                // Destroy container
9406                PackageHelper.destroySdDir(cid);
9407            } else {
9408                boolean mounted = PackageHelper.isContainerMounted(cid);
9409                if (!mounted) {
9410                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9411                            Process.SYSTEM_UID);
9412                    if (newMountPath != null) {
9413                        setMountPath(newMountPath);
9414                    } else {
9415                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9416                    }
9417                }
9418            }
9419            return status;
9420        }
9421
9422        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9423            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9424            String newMountPath = null;
9425            if (PackageHelper.isContainerMounted(cid)) {
9426                // Unmount the container
9427                if (!PackageHelper.unMountSdDir(cid)) {
9428                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9429                    return false;
9430                }
9431            }
9432            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9433                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9434                        " which might be stale. Will try to clean up.");
9435                // Clean up the stale container and proceed to recreate.
9436                if (!PackageHelper.destroySdDir(newCacheId)) {
9437                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9438                    return false;
9439                }
9440                // Successfully cleaned up stale container. Try to rename again.
9441                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9442                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9443                            + " inspite of cleaning it up.");
9444                    return false;
9445                }
9446            }
9447            if (!PackageHelper.isContainerMounted(newCacheId)) {
9448                Slog.w(TAG, "Mounting container " + newCacheId);
9449                newMountPath = PackageHelper.mountSdDir(newCacheId,
9450                        getEncryptKey(), Process.SYSTEM_UID);
9451            } else {
9452                newMountPath = PackageHelper.getSdDir(newCacheId);
9453            }
9454            if (newMountPath == null) {
9455                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9456                return false;
9457            }
9458            Log.i(TAG, "Succesfully renamed " + cid +
9459                    " to " + newCacheId +
9460                    " at new path: " + newMountPath);
9461            cid = newCacheId;
9462
9463            final File beforeCodeFile = new File(packagePath);
9464            setMountPath(newMountPath);
9465            final File afterCodeFile = new File(packagePath);
9466
9467            // Reflect the rename in scanned details
9468            pkg.codePath = afterCodeFile.getAbsolutePath();
9469            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9470                    pkg.baseCodePath);
9471            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9472                    pkg.splitCodePaths);
9473
9474            // Reflect the rename in app info
9475            pkg.applicationInfo.setCodePath(pkg.codePath);
9476            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9477            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9478            pkg.applicationInfo.setResourcePath(pkg.codePath);
9479            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9480            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9481
9482            return true;
9483        }
9484
9485        private void setMountPath(String mountPath) {
9486            final File mountFile = new File(mountPath);
9487
9488            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9489            if (monolithicFile.exists()) {
9490                packagePath = monolithicFile.getAbsolutePath();
9491                if (isFwdLocked()) {
9492                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9493                } else {
9494                    resourcePath = packagePath;
9495                }
9496            } else {
9497                packagePath = mountFile.getAbsolutePath();
9498                resourcePath = packagePath;
9499            }
9500
9501            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9502        }
9503
9504        int doPostInstall(int status, int uid) {
9505            if (status != PackageManager.INSTALL_SUCCEEDED) {
9506                cleanUp();
9507            } else {
9508                final int groupOwner;
9509                final String protectedFile;
9510                if (isFwdLocked()) {
9511                    groupOwner = UserHandle.getSharedAppGid(uid);
9512                    protectedFile = RES_FILE_NAME;
9513                } else {
9514                    groupOwner = -1;
9515                    protectedFile = null;
9516                }
9517
9518                if (uid < Process.FIRST_APPLICATION_UID
9519                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9520                    Slog.e(TAG, "Failed to finalize " + cid);
9521                    PackageHelper.destroySdDir(cid);
9522                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9523                }
9524
9525                boolean mounted = PackageHelper.isContainerMounted(cid);
9526                if (!mounted) {
9527                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9528                }
9529            }
9530            return status;
9531        }
9532
9533        private void cleanUp() {
9534            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9535
9536            // Destroy secure container
9537            PackageHelper.destroySdDir(cid);
9538        }
9539
9540        private List<String> getAllCodePaths() {
9541            final File codeFile = new File(getCodePath());
9542            if (codeFile != null && codeFile.exists()) {
9543                try {
9544                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9545                    return pkg.getAllCodePaths();
9546                } catch (PackageParserException e) {
9547                    // Ignored; we tried our best
9548                }
9549            }
9550            return Collections.EMPTY_LIST;
9551        }
9552
9553        void cleanUpResourcesLI() {
9554            // Enumerate all code paths before deleting
9555            cleanUpResourcesLI(getAllCodePaths());
9556        }
9557
9558        private void cleanUpResourcesLI(List<String> allCodePaths) {
9559            cleanUp();
9560
9561            if (!allCodePaths.isEmpty()) {
9562                if (instructionSets == null) {
9563                    throw new IllegalStateException("instructionSet == null");
9564                }
9565                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9566                for (String codePath : allCodePaths) {
9567                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9568                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9569                        if (retCode < 0) {
9570                            Slog.w(TAG, "Couldn't remove dex file for package: "
9571                                    + " at location " + codePath + ", retcode=" + retCode);
9572                            // we don't consider this to be a failure of the core package deletion
9573                        }
9574                    }
9575                }
9576            }
9577        }
9578
9579        boolean matchContainer(String app) {
9580            if (cid.startsWith(app)) {
9581                return true;
9582            }
9583            return false;
9584        }
9585
9586        String getPackageName() {
9587            return getAsecPackageName(cid);
9588        }
9589
9590        boolean doPostDeleteLI(boolean delete) {
9591            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9592            final List<String> allCodePaths = getAllCodePaths();
9593            boolean mounted = PackageHelper.isContainerMounted(cid);
9594            if (mounted) {
9595                // Unmount first
9596                if (PackageHelper.unMountSdDir(cid)) {
9597                    mounted = false;
9598                }
9599            }
9600            if (!mounted && delete) {
9601                cleanUpResourcesLI(allCodePaths);
9602            }
9603            return !mounted;
9604        }
9605
9606        @Override
9607        int doPreCopy() {
9608            if (isFwdLocked()) {
9609                if (!PackageHelper.fixSdPermissions(cid,
9610                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9611                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9612                }
9613            }
9614
9615            return PackageManager.INSTALL_SUCCEEDED;
9616        }
9617
9618        @Override
9619        int doPostCopy(int uid) {
9620            if (isFwdLocked()) {
9621                if (uid < Process.FIRST_APPLICATION_UID
9622                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9623                                RES_FILE_NAME)) {
9624                    Slog.e(TAG, "Failed to finalize " + cid);
9625                    PackageHelper.destroySdDir(cid);
9626                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9627                }
9628            }
9629
9630            return PackageManager.INSTALL_SUCCEEDED;
9631        }
9632    }
9633
9634    static String getAsecPackageName(String packageCid) {
9635        int idx = packageCid.lastIndexOf("-");
9636        if (idx == -1) {
9637            return packageCid;
9638        }
9639        return packageCid.substring(0, idx);
9640    }
9641
9642    // Utility method used to create code paths based on package name and available index.
9643    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9644        String idxStr = "";
9645        int idx = 1;
9646        // Fall back to default value of idx=1 if prefix is not
9647        // part of oldCodePath
9648        if (oldCodePath != null) {
9649            String subStr = oldCodePath;
9650            // Drop the suffix right away
9651            if (suffix != null && subStr.endsWith(suffix)) {
9652                subStr = subStr.substring(0, subStr.length() - suffix.length());
9653            }
9654            // If oldCodePath already contains prefix find out the
9655            // ending index to either increment or decrement.
9656            int sidx = subStr.lastIndexOf(prefix);
9657            if (sidx != -1) {
9658                subStr = subStr.substring(sidx + prefix.length());
9659                if (subStr != null) {
9660                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9661                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9662                    }
9663                    try {
9664                        idx = Integer.parseInt(subStr);
9665                        if (idx <= 1) {
9666                            idx++;
9667                        } else {
9668                            idx--;
9669                        }
9670                    } catch(NumberFormatException e) {
9671                    }
9672                }
9673            }
9674        }
9675        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9676        return prefix + idxStr;
9677    }
9678
9679    private File getNextCodePath(String packageName) {
9680        int suffix = 1;
9681        File result;
9682        do {
9683            result = new File(mAppInstallDir, packageName + "-" + suffix);
9684            suffix++;
9685        } while (result.exists());
9686        return result;
9687    }
9688
9689    // Utility method used to ignore ADD/REMOVE events
9690    // by directory observer.
9691    private static boolean ignoreCodePath(String fullPathStr) {
9692        String apkName = deriveCodePathName(fullPathStr);
9693        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9694        if (idx != -1 && ((idx+1) < apkName.length())) {
9695            // Make sure the package ends with a numeral
9696            String version = apkName.substring(idx+1);
9697            try {
9698                Integer.parseInt(version);
9699                return true;
9700            } catch (NumberFormatException e) {}
9701        }
9702        return false;
9703    }
9704
9705    // Utility method that returns the relative package path with respect
9706    // to the installation directory. Like say for /data/data/com.test-1.apk
9707    // string com.test-1 is returned.
9708    static String deriveCodePathName(String codePath) {
9709        if (codePath == null) {
9710            return null;
9711        }
9712        final File codeFile = new File(codePath);
9713        final String name = codeFile.getName();
9714        if (codeFile.isDirectory()) {
9715            return name;
9716        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9717            final int lastDot = name.lastIndexOf('.');
9718            return name.substring(0, lastDot);
9719        } else {
9720            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9721            return null;
9722        }
9723    }
9724
9725    class PackageInstalledInfo {
9726        String name;
9727        int uid;
9728        // The set of users that originally had this package installed.
9729        int[] origUsers;
9730        // The set of users that now have this package installed.
9731        int[] newUsers;
9732        PackageParser.Package pkg;
9733        int returnCode;
9734        String returnMsg;
9735        PackageRemovedInfo removedInfo;
9736
9737        public void setError(int code, String msg) {
9738            returnCode = code;
9739            returnMsg = msg;
9740            Slog.w(TAG, msg);
9741        }
9742
9743        public void setError(String msg, PackageParserException e) {
9744            returnCode = e.error;
9745            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9746            Slog.w(TAG, msg, e);
9747        }
9748
9749        public void setError(String msg, PackageManagerException e) {
9750            returnCode = e.error;
9751            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9752            Slog.w(TAG, msg, e);
9753        }
9754
9755        // In some error cases we want to convey more info back to the observer
9756        String origPackage;
9757        String origPermission;
9758    }
9759
9760    /*
9761     * Install a non-existing package.
9762     */
9763    private void installNewPackageLI(PackageParser.Package pkg,
9764            int parseFlags, int scanFlags, UserHandle user,
9765            String installerPackageName, PackageInstalledInfo res) {
9766        // Remember this for later, in case we need to rollback this install
9767        String pkgName = pkg.packageName;
9768
9769        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9770        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9771        synchronized(mPackages) {
9772            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9773                // A package with the same name is already installed, though
9774                // it has been renamed to an older name.  The package we
9775                // are trying to install should be installed as an update to
9776                // the existing one, but that has not been requested, so bail.
9777                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9778                        + " without first uninstalling package running as "
9779                        + mSettings.mRenamedPackages.get(pkgName));
9780                return;
9781            }
9782            if (mPackages.containsKey(pkgName)) {
9783                // Don't allow installation over an existing package with the same name.
9784                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9785                        + " without first uninstalling.");
9786                return;
9787            }
9788        }
9789
9790        try {
9791            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9792                    System.currentTimeMillis(), user);
9793
9794            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9795            // delete the partially installed application. the data directory will have to be
9796            // restored if it was already existing
9797            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9798                // remove package from internal structures.  Note that we want deletePackageX to
9799                // delete the package data and cache directories that it created in
9800                // scanPackageLocked, unless those directories existed before we even tried to
9801                // install.
9802                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9803                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9804                                res.removedInfo, true);
9805            }
9806
9807        } catch (PackageManagerException e) {
9808            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9809        }
9810    }
9811
9812    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9813        // Upgrade keysets are being used.  Determine if new package has a superset of the
9814        // required keys.
9815        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9816        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9817        for (int i = 0; i < upgradeKeySets.length; i++) {
9818            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9819            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9820                return true;
9821            }
9822        }
9823        return false;
9824    }
9825
9826    private void replacePackageLI(PackageParser.Package pkg,
9827            int parseFlags, int scanFlags, UserHandle user,
9828            String installerPackageName, PackageInstalledInfo res) {
9829        PackageParser.Package oldPackage;
9830        String pkgName = pkg.packageName;
9831        int[] allUsers;
9832        boolean[] perUserInstalled;
9833
9834        // First find the old package info and check signatures
9835        synchronized(mPackages) {
9836            oldPackage = mPackages.get(pkgName);
9837            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9838            PackageSetting ps = mSettings.mPackages.get(pkgName);
9839            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9840                // default to original signature matching
9841                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9842                    != PackageManager.SIGNATURE_MATCH) {
9843                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9844                            "New package has a different signature: " + pkgName);
9845                    return;
9846                }
9847            } else {
9848                if(!checkUpgradeKeySetLP(ps, pkg)) {
9849                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9850                            "New package not signed by keys specified by upgrade-keysets: "
9851                            + pkgName);
9852                    return;
9853                }
9854            }
9855
9856            // In case of rollback, remember per-user/profile install state
9857            allUsers = sUserManager.getUserIds();
9858            perUserInstalled = new boolean[allUsers.length];
9859            for (int i = 0; i < allUsers.length; i++) {
9860                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9861            }
9862        }
9863
9864        boolean sysPkg = (isSystemApp(oldPackage));
9865        if (sysPkg) {
9866            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9867                    user, allUsers, perUserInstalled, installerPackageName, res);
9868        } else {
9869            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9870                    user, allUsers, perUserInstalled, installerPackageName, res);
9871        }
9872    }
9873
9874    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9875            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9876            int[] allUsers, boolean[] perUserInstalled,
9877            String installerPackageName, PackageInstalledInfo res) {
9878        String pkgName = deletedPackage.packageName;
9879        boolean deletedPkg = true;
9880        boolean updatedSettings = false;
9881
9882        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9883                + deletedPackage);
9884        long origUpdateTime;
9885        if (pkg.mExtras != null) {
9886            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9887        } else {
9888            origUpdateTime = 0;
9889        }
9890
9891        // First delete the existing package while retaining the data directory
9892        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9893                res.removedInfo, true)) {
9894            // If the existing package wasn't successfully deleted
9895            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9896            deletedPkg = false;
9897        } else {
9898            // Successfully deleted the old package; proceed with replace.
9899
9900            // If deleted package lived in a container, give users a chance to
9901            // relinquish resources before killing.
9902            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9903                if (DEBUG_INSTALL) {
9904                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9905                }
9906                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9907                final ArrayList<String> pkgList = new ArrayList<String>(1);
9908                pkgList.add(deletedPackage.applicationInfo.packageName);
9909                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9910            }
9911
9912            deleteCodeCacheDirsLI(pkgName);
9913            try {
9914                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9915                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9916                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9917                updatedSettings = true;
9918            } catch (PackageManagerException e) {
9919                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9920            }
9921        }
9922
9923        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9924            // remove package from internal structures.  Note that we want deletePackageX to
9925            // delete the package data and cache directories that it created in
9926            // scanPackageLocked, unless those directories existed before we even tried to
9927            // install.
9928            if(updatedSettings) {
9929                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9930                deletePackageLI(
9931                        pkgName, null, true, allUsers, perUserInstalled,
9932                        PackageManager.DELETE_KEEP_DATA,
9933                                res.removedInfo, true);
9934            }
9935            // Since we failed to install the new package we need to restore the old
9936            // package that we deleted.
9937            if (deletedPkg) {
9938                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9939                File restoreFile = new File(deletedPackage.codePath);
9940                // Parse old package
9941                boolean oldOnSd = isExternal(deletedPackage);
9942                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9943                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9944                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9945                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9946                try {
9947                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9948                } catch (PackageManagerException e) {
9949                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9950                            + e.getMessage());
9951                    return;
9952                }
9953                // Restore of old package succeeded. Update permissions.
9954                // writer
9955                synchronized (mPackages) {
9956                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9957                            UPDATE_PERMISSIONS_ALL);
9958                    // can downgrade to reader
9959                    mSettings.writeLPr();
9960                }
9961                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9962            }
9963        }
9964    }
9965
9966    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9967            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9968            int[] allUsers, boolean[] perUserInstalled,
9969            String installerPackageName, PackageInstalledInfo res) {
9970        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9971                + ", old=" + deletedPackage);
9972        boolean updatedSettings = false;
9973        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9974        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9975            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9976        }
9977        String packageName = deletedPackage.packageName;
9978        if (packageName == null) {
9979            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9980                    "Attempt to delete null packageName.");
9981            return;
9982        }
9983        PackageParser.Package oldPkg;
9984        PackageSetting oldPkgSetting;
9985        // reader
9986        synchronized (mPackages) {
9987            oldPkg = mPackages.get(packageName);
9988            oldPkgSetting = mSettings.mPackages.get(packageName);
9989            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9990                    (oldPkgSetting == null)) {
9991                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9992                        "Couldn't find package:" + packageName + " information");
9993                return;
9994            }
9995        }
9996
9997        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9998
9999        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10000        res.removedInfo.removedPackage = packageName;
10001        // Remove existing system package
10002        removePackageLI(oldPkgSetting, true);
10003        // writer
10004        synchronized (mPackages) {
10005            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10006                // We didn't need to disable the .apk as a current system package,
10007                // which means we are replacing another update that is already
10008                // installed.  We need to make sure to delete the older one's .apk.
10009                res.removedInfo.args = createInstallArgsForExisting(0,
10010                        deletedPackage.applicationInfo.getCodePath(),
10011                        deletedPackage.applicationInfo.getResourcePath(),
10012                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10013                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10014            } else {
10015                res.removedInfo.args = null;
10016            }
10017        }
10018
10019        // Successfully disabled the old package. Now proceed with re-installation
10020        deleteCodeCacheDirsLI(packageName);
10021
10022        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10023        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10024
10025        PackageParser.Package newPackage = null;
10026        try {
10027            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10028            if (newPackage.mExtras != null) {
10029                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10030                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10031                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10032
10033                // is the update attempting to change shared user? that isn't going to work...
10034                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10035                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10036                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10037                            + " to " + newPkgSetting.sharedUser);
10038                    updatedSettings = true;
10039                }
10040            }
10041
10042            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10043                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10044                updatedSettings = true;
10045            }
10046
10047        } catch (PackageManagerException e) {
10048            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10049        }
10050
10051        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10052            // Re installation failed. Restore old information
10053            // Remove new pkg information
10054            if (newPackage != null) {
10055                removeInstalledPackageLI(newPackage, true);
10056            }
10057            // Add back the old system package
10058            try {
10059                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10060            } catch (PackageManagerException e) {
10061                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10062            }
10063            // Restore the old system information in Settings
10064            synchronized(mPackages) {
10065                if (updatedSettings) {
10066                    mSettings.enableSystemPackageLPw(packageName);
10067                    mSettings.setInstallerPackageName(packageName,
10068                            oldPkgSetting.installerPackageName);
10069                }
10070                mSettings.writeLPr();
10071            }
10072        }
10073    }
10074
10075    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10076            int[] allUsers, boolean[] perUserInstalled,
10077            PackageInstalledInfo res) {
10078        String pkgName = newPackage.packageName;
10079        synchronized (mPackages) {
10080            //write settings. the installStatus will be incomplete at this stage.
10081            //note that the new package setting would have already been
10082            //added to mPackages. It hasn't been persisted yet.
10083            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10084            mSettings.writeLPr();
10085        }
10086
10087        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10088
10089        synchronized (mPackages) {
10090            updatePermissionsLPw(newPackage.packageName, newPackage,
10091                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10092                            ? UPDATE_PERMISSIONS_ALL : 0));
10093            // For system-bundled packages, we assume that installing an upgraded version
10094            // of the package implies that the user actually wants to run that new code,
10095            // so we enable the package.
10096            if (isSystemApp(newPackage)) {
10097                // NB: implicit assumption that system package upgrades apply to all users
10098                if (DEBUG_INSTALL) {
10099                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10100                }
10101                PackageSetting ps = mSettings.mPackages.get(pkgName);
10102                if (ps != null) {
10103                    if (res.origUsers != null) {
10104                        for (int userHandle : res.origUsers) {
10105                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10106                                    userHandle, installerPackageName);
10107                        }
10108                    }
10109                    // Also convey the prior install/uninstall state
10110                    if (allUsers != null && perUserInstalled != null) {
10111                        for (int i = 0; i < allUsers.length; i++) {
10112                            if (DEBUG_INSTALL) {
10113                                Slog.d(TAG, "    user " + allUsers[i]
10114                                        + " => " + perUserInstalled[i]);
10115                            }
10116                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10117                        }
10118                        // these install state changes will be persisted in the
10119                        // upcoming call to mSettings.writeLPr().
10120                    }
10121                }
10122            }
10123            res.name = pkgName;
10124            res.uid = newPackage.applicationInfo.uid;
10125            res.pkg = newPackage;
10126            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10127            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10128            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10129            //to update install status
10130            mSettings.writeLPr();
10131        }
10132    }
10133
10134    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10135        final int installFlags = args.installFlags;
10136        String installerPackageName = args.installerPackageName;
10137        File tmpPackageFile = new File(args.getCodePath());
10138        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10139        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10140        boolean replace = false;
10141        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10142        // Result object to be returned
10143        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10144
10145        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10146        // Retrieve PackageSettings and parse package
10147        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10148                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10149                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10150        PackageParser pp = new PackageParser();
10151        pp.setSeparateProcesses(mSeparateProcesses);
10152        pp.setDisplayMetrics(mMetrics);
10153
10154        final PackageParser.Package pkg;
10155        try {
10156            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10157        } catch (PackageParserException e) {
10158            res.setError("Failed parse during installPackageLI", e);
10159            return;
10160        }
10161
10162        // Mark that we have an install time CPU ABI override.
10163        pkg.cpuAbiOverride = args.abiOverride;
10164
10165        String pkgName = res.name = pkg.packageName;
10166        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10167            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10168                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10169                return;
10170            }
10171        }
10172
10173        try {
10174            pp.collectCertificates(pkg, parseFlags);
10175            pp.collectManifestDigest(pkg);
10176        } catch (PackageParserException e) {
10177            res.setError("Failed collect during installPackageLI", e);
10178            return;
10179        }
10180
10181        /* If the installer passed in a manifest digest, compare it now. */
10182        if (args.manifestDigest != null) {
10183            if (DEBUG_INSTALL) {
10184                final String parsedManifest = pkg.manifestDigest == null ? "null"
10185                        : pkg.manifestDigest.toString();
10186                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10187                        + parsedManifest);
10188            }
10189
10190            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10191                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10192                return;
10193            }
10194        } else if (DEBUG_INSTALL) {
10195            final String parsedManifest = pkg.manifestDigest == null
10196                    ? "null" : pkg.manifestDigest.toString();
10197            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10198        }
10199
10200        // Get rid of all references to package scan path via parser.
10201        pp = null;
10202        String oldCodePath = null;
10203        boolean systemApp = false;
10204        synchronized (mPackages) {
10205            // Check whether the newly-scanned package wants to define an already-defined perm
10206            int N = pkg.permissions.size();
10207            for (int i = N-1; i >= 0; i--) {
10208                PackageParser.Permission perm = pkg.permissions.get(i);
10209                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10210                if (bp != null) {
10211                    // If the defining package is signed with our cert, it's okay.  This
10212                    // also includes the "updating the same package" case, of course.
10213                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10214                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10215                        // If the owning package is the system itself, we log but allow
10216                        // install to proceed; we fail the install on all other permission
10217                        // redefinitions.
10218                        if (!bp.sourcePackage.equals("android")) {
10219                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10220                                    + pkg.packageName + " attempting to redeclare permission "
10221                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10222                            res.origPermission = perm.info.name;
10223                            res.origPackage = bp.sourcePackage;
10224                            return;
10225                        } else {
10226                            Slog.w(TAG, "Package " + pkg.packageName
10227                                    + " attempting to redeclare system permission "
10228                                    + perm.info.name + "; ignoring new declaration");
10229                            pkg.permissions.remove(i);
10230                        }
10231                    }
10232                }
10233            }
10234
10235            // Check if installing already existing package
10236            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10237                String oldName = mSettings.mRenamedPackages.get(pkgName);
10238                if (pkg.mOriginalPackages != null
10239                        && pkg.mOriginalPackages.contains(oldName)
10240                        && mPackages.containsKey(oldName)) {
10241                    // This package is derived from an original package,
10242                    // and this device has been updating from that original
10243                    // name.  We must continue using the original name, so
10244                    // rename the new package here.
10245                    pkg.setPackageName(oldName);
10246                    pkgName = pkg.packageName;
10247                    replace = true;
10248                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10249                            + oldName + " pkgName=" + pkgName);
10250                } else if (mPackages.containsKey(pkgName)) {
10251                    // This package, under its official name, already exists
10252                    // on the device; we should replace it.
10253                    replace = true;
10254                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10255                }
10256            }
10257            PackageSetting ps = mSettings.mPackages.get(pkgName);
10258            if (ps != null) {
10259                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10260                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10261                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10262                    systemApp = (ps.pkg.applicationInfo.flags &
10263                            ApplicationInfo.FLAG_SYSTEM) != 0;
10264                }
10265                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10266            }
10267        }
10268
10269        if (systemApp && onSd) {
10270            // Disable updates to system apps on sdcard
10271            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10272                    "Cannot install updates to system apps on sdcard");
10273            return;
10274        }
10275
10276        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10277            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10278            return;
10279        }
10280
10281        if (replace) {
10282            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10283                    installerPackageName, res);
10284        } else {
10285            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10286                    args.user, installerPackageName, res);
10287        }
10288        synchronized (mPackages) {
10289            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10290            if (ps != null) {
10291                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10292            }
10293        }
10294    }
10295
10296    private static boolean isForwardLocked(PackageParser.Package pkg) {
10297        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10298    }
10299
10300    private static boolean isForwardLocked(ApplicationInfo info) {
10301        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10302    }
10303
10304    private boolean isForwardLocked(PackageSetting ps) {
10305        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10306    }
10307
10308    private static boolean isMultiArch(PackageSetting ps) {
10309        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10310    }
10311
10312    private static boolean isMultiArch(ApplicationInfo info) {
10313        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10314    }
10315
10316    private static boolean isExternal(PackageParser.Package pkg) {
10317        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10318    }
10319
10320    private static boolean isExternal(PackageSetting ps) {
10321        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10322    }
10323
10324    private static boolean isExternal(ApplicationInfo info) {
10325        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10326    }
10327
10328    private static boolean isSystemApp(PackageParser.Package pkg) {
10329        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10330    }
10331
10332    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10333        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10334    }
10335
10336    private static boolean isSystemApp(ApplicationInfo info) {
10337        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10338    }
10339
10340    private static boolean isSystemApp(PackageSetting ps) {
10341        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10342    }
10343
10344    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10345        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10346    }
10347
10348    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10349        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10350    }
10351
10352    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10353        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10354    }
10355
10356    private int packageFlagsToInstallFlags(PackageSetting ps) {
10357        int installFlags = 0;
10358        if (isExternal(ps)) {
10359            installFlags |= PackageManager.INSTALL_EXTERNAL;
10360        }
10361        if (isForwardLocked(ps)) {
10362            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10363        }
10364        return installFlags;
10365    }
10366
10367    private void deleteTempPackageFiles() {
10368        final FilenameFilter filter = new FilenameFilter() {
10369            public boolean accept(File dir, String name) {
10370                return name.startsWith("vmdl") && name.endsWith(".tmp");
10371            }
10372        };
10373        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10374            file.delete();
10375        }
10376    }
10377
10378    @Override
10379    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10380            int flags) {
10381        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10382                flags);
10383    }
10384
10385    @Override
10386    public void deletePackage(final String packageName,
10387            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10388        mContext.enforceCallingOrSelfPermission(
10389                android.Manifest.permission.DELETE_PACKAGES, null);
10390        final int uid = Binder.getCallingUid();
10391        if (UserHandle.getUserId(uid) != userId) {
10392            mContext.enforceCallingPermission(
10393                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10394                    "deletePackage for user " + userId);
10395        }
10396        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10397            try {
10398                observer.onPackageDeleted(packageName,
10399                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10400            } catch (RemoteException re) {
10401            }
10402            return;
10403        }
10404
10405        boolean uninstallBlocked = false;
10406        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10407            int[] users = sUserManager.getUserIds();
10408            for (int i = 0; i < users.length; ++i) {
10409                if (getBlockUninstallForUser(packageName, users[i])) {
10410                    uninstallBlocked = true;
10411                    break;
10412                }
10413            }
10414        } else {
10415            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10416        }
10417        if (uninstallBlocked) {
10418            try {
10419                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10420                        null);
10421            } catch (RemoteException re) {
10422            }
10423            return;
10424        }
10425
10426        if (DEBUG_REMOVE) {
10427            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10428        }
10429        // Queue up an async operation since the package deletion may take a little while.
10430        mHandler.post(new Runnable() {
10431            public void run() {
10432                mHandler.removeCallbacks(this);
10433                final int returnCode = deletePackageX(packageName, userId, flags);
10434                if (observer != null) {
10435                    try {
10436                        observer.onPackageDeleted(packageName, returnCode, null);
10437                    } catch (RemoteException e) {
10438                        Log.i(TAG, "Observer no longer exists.");
10439                    } //end catch
10440                } //end if
10441            } //end run
10442        });
10443    }
10444
10445    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10446        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10447                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10448        try {
10449            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10450                    || dpm.isDeviceOwner(packageName))) {
10451                return true;
10452            }
10453        } catch (RemoteException e) {
10454        }
10455        return false;
10456    }
10457
10458    /**
10459     *  This method is an internal method that could be get invoked either
10460     *  to delete an installed package or to clean up a failed installation.
10461     *  After deleting an installed package, a broadcast is sent to notify any
10462     *  listeners that the package has been installed. For cleaning up a failed
10463     *  installation, the broadcast is not necessary since the package's
10464     *  installation wouldn't have sent the initial broadcast either
10465     *  The key steps in deleting a package are
10466     *  deleting the package information in internal structures like mPackages,
10467     *  deleting the packages base directories through installd
10468     *  updating mSettings to reflect current status
10469     *  persisting settings for later use
10470     *  sending a broadcast if necessary
10471     */
10472    private int deletePackageX(String packageName, int userId, int flags) {
10473        final PackageRemovedInfo info = new PackageRemovedInfo();
10474        final boolean res;
10475
10476        if (isPackageDeviceAdmin(packageName, userId)) {
10477            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10478            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10479        }
10480
10481        boolean removedForAllUsers = false;
10482        boolean systemUpdate = false;
10483
10484        // for the uninstall-updates case and restricted profiles, remember the per-
10485        // userhandle installed state
10486        int[] allUsers;
10487        boolean[] perUserInstalled;
10488        synchronized (mPackages) {
10489            PackageSetting ps = mSettings.mPackages.get(packageName);
10490            allUsers = sUserManager.getUserIds();
10491            perUserInstalled = new boolean[allUsers.length];
10492            for (int i = 0; i < allUsers.length; i++) {
10493                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10494            }
10495        }
10496
10497        synchronized (mInstallLock) {
10498            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10499            res = deletePackageLI(packageName,
10500                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10501                            ? UserHandle.ALL : new UserHandle(userId),
10502                    true, allUsers, perUserInstalled,
10503                    flags | REMOVE_CHATTY, info, true);
10504            systemUpdate = info.isRemovedPackageSystemUpdate;
10505            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10506                removedForAllUsers = true;
10507            }
10508            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10509                    + " removedForAllUsers=" + removedForAllUsers);
10510        }
10511
10512        if (res) {
10513            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10514
10515            // If the removed package was a system update, the old system package
10516            // was re-enabled; we need to broadcast this information
10517            if (systemUpdate) {
10518                Bundle extras = new Bundle(1);
10519                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10520                        ? info.removedAppId : info.uid);
10521                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10522
10523                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10524                        extras, null, null, null);
10525                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10526                        extras, null, null, null);
10527                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10528                        null, packageName, null, null);
10529            }
10530        }
10531        // Force a gc here.
10532        Runtime.getRuntime().gc();
10533        // Delete the resources here after sending the broadcast to let
10534        // other processes clean up before deleting resources.
10535        if (info.args != null) {
10536            synchronized (mInstallLock) {
10537                info.args.doPostDeleteLI(true);
10538            }
10539        }
10540
10541        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10542    }
10543
10544    static class PackageRemovedInfo {
10545        String removedPackage;
10546        int uid = -1;
10547        int removedAppId = -1;
10548        int[] removedUsers = null;
10549        boolean isRemovedPackageSystemUpdate = false;
10550        // Clean up resources deleted packages.
10551        InstallArgs args = null;
10552
10553        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10554            Bundle extras = new Bundle(1);
10555            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10556            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10557            if (replacing) {
10558                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10559            }
10560            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10561            if (removedPackage != null) {
10562                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10563                        extras, null, null, removedUsers);
10564                if (fullRemove && !replacing) {
10565                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10566                            extras, null, null, removedUsers);
10567                }
10568            }
10569            if (removedAppId >= 0) {
10570                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10571                        removedUsers);
10572            }
10573        }
10574    }
10575
10576    /*
10577     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10578     * flag is not set, the data directory is removed as well.
10579     * make sure this flag is set for partially installed apps. If not its meaningless to
10580     * delete a partially installed application.
10581     */
10582    private void removePackageDataLI(PackageSetting ps,
10583            int[] allUserHandles, boolean[] perUserInstalled,
10584            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10585        String packageName = ps.name;
10586        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10587        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10588        // Retrieve object to delete permissions for shared user later on
10589        final PackageSetting deletedPs;
10590        // reader
10591        synchronized (mPackages) {
10592            deletedPs = mSettings.mPackages.get(packageName);
10593            if (outInfo != null) {
10594                outInfo.removedPackage = packageName;
10595                outInfo.removedUsers = deletedPs != null
10596                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10597                        : null;
10598            }
10599        }
10600        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10601            removeDataDirsLI(packageName);
10602            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10603        }
10604        // writer
10605        synchronized (mPackages) {
10606            if (deletedPs != null) {
10607                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10608                    if (outInfo != null) {
10609                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10610                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10611                    }
10612                    if (deletedPs != null) {
10613                        updatePermissionsLPw(deletedPs.name, null, 0);
10614                        if (deletedPs.sharedUser != null) {
10615                            // remove permissions associated with package
10616                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10617                        }
10618                    }
10619                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10620                }
10621                // make sure to preserve per-user disabled state if this removal was just
10622                // a downgrade of a system app to the factory package
10623                if (allUserHandles != null && perUserInstalled != null) {
10624                    if (DEBUG_REMOVE) {
10625                        Slog.d(TAG, "Propagating install state across downgrade");
10626                    }
10627                    for (int i = 0; i < allUserHandles.length; i++) {
10628                        if (DEBUG_REMOVE) {
10629                            Slog.d(TAG, "    user " + allUserHandles[i]
10630                                    + " => " + perUserInstalled[i]);
10631                        }
10632                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10633                    }
10634                }
10635            }
10636            // can downgrade to reader
10637            if (writeSettings) {
10638                // Save settings now
10639                mSettings.writeLPr();
10640            }
10641        }
10642        if (outInfo != null) {
10643            // A user ID was deleted here. Go through all users and remove it
10644            // from KeyStore.
10645            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10646        }
10647    }
10648
10649    static boolean locationIsPrivileged(File path) {
10650        try {
10651            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10652                    .getCanonicalPath();
10653            return path.getCanonicalPath().startsWith(privilegedAppDir);
10654        } catch (IOException e) {
10655            Slog.e(TAG, "Unable to access code path " + path);
10656        }
10657        return false;
10658    }
10659
10660    /*
10661     * Tries to delete system package.
10662     */
10663    private boolean deleteSystemPackageLI(PackageSetting newPs,
10664            int[] allUserHandles, boolean[] perUserInstalled,
10665            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10666        final boolean applyUserRestrictions
10667                = (allUserHandles != null) && (perUserInstalled != null);
10668        PackageSetting disabledPs = null;
10669        // Confirm if the system package has been updated
10670        // An updated system app can be deleted. This will also have to restore
10671        // the system pkg from system partition
10672        // reader
10673        synchronized (mPackages) {
10674            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10675        }
10676        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10677                + " disabledPs=" + disabledPs);
10678        if (disabledPs == null) {
10679            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10680            return false;
10681        } else if (DEBUG_REMOVE) {
10682            Slog.d(TAG, "Deleting system pkg from data partition");
10683        }
10684        if (DEBUG_REMOVE) {
10685            if (applyUserRestrictions) {
10686                Slog.d(TAG, "Remembering install states:");
10687                for (int i = 0; i < allUserHandles.length; i++) {
10688                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10689                }
10690            }
10691        }
10692        // Delete the updated package
10693        outInfo.isRemovedPackageSystemUpdate = true;
10694        if (disabledPs.versionCode < newPs.versionCode) {
10695            // Delete data for downgrades
10696            flags &= ~PackageManager.DELETE_KEEP_DATA;
10697        } else {
10698            // Preserve data by setting flag
10699            flags |= PackageManager.DELETE_KEEP_DATA;
10700        }
10701        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10702                allUserHandles, perUserInstalled, outInfo, writeSettings);
10703        if (!ret) {
10704            return false;
10705        }
10706        // writer
10707        synchronized (mPackages) {
10708            // Reinstate the old system package
10709            mSettings.enableSystemPackageLPw(newPs.name);
10710            // Remove any native libraries from the upgraded package.
10711            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10712        }
10713        // Install the system package
10714        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10715        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10716        if (locationIsPrivileged(disabledPs.codePath)) {
10717            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10718        }
10719
10720        final PackageParser.Package newPkg;
10721        try {
10722            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10723        } catch (PackageManagerException e) {
10724            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10725            return false;
10726        }
10727
10728        // writer
10729        synchronized (mPackages) {
10730            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10731            updatePermissionsLPw(newPkg.packageName, newPkg,
10732                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10733            if (applyUserRestrictions) {
10734                if (DEBUG_REMOVE) {
10735                    Slog.d(TAG, "Propagating install state across reinstall");
10736                }
10737                for (int i = 0; i < allUserHandles.length; i++) {
10738                    if (DEBUG_REMOVE) {
10739                        Slog.d(TAG, "    user " + allUserHandles[i]
10740                                + " => " + perUserInstalled[i]);
10741                    }
10742                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10743                }
10744                // Regardless of writeSettings we need to ensure that this restriction
10745                // state propagation is persisted
10746                mSettings.writeAllUsersPackageRestrictionsLPr();
10747            }
10748            // can downgrade to reader here
10749            if (writeSettings) {
10750                mSettings.writeLPr();
10751            }
10752        }
10753        return true;
10754    }
10755
10756    private boolean deleteInstalledPackageLI(PackageSetting ps,
10757            boolean deleteCodeAndResources, int flags,
10758            int[] allUserHandles, boolean[] perUserInstalled,
10759            PackageRemovedInfo outInfo, boolean writeSettings) {
10760        if (outInfo != null) {
10761            outInfo.uid = ps.appId;
10762        }
10763
10764        // Delete package data from internal structures and also remove data if flag is set
10765        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10766
10767        // Delete application code and resources
10768        if (deleteCodeAndResources && (outInfo != null)) {
10769            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10770                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10771                    getAppDexInstructionSets(ps));
10772            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10773        }
10774        return true;
10775    }
10776
10777    @Override
10778    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10779            int userId) {
10780        mContext.enforceCallingOrSelfPermission(
10781                android.Manifest.permission.DELETE_PACKAGES, null);
10782        synchronized (mPackages) {
10783            PackageSetting ps = mSettings.mPackages.get(packageName);
10784            if (ps == null) {
10785                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10786                return false;
10787            }
10788            if (!ps.getInstalled(userId)) {
10789                // Can't block uninstall for an app that is not installed or enabled.
10790                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10791                return false;
10792            }
10793            ps.setBlockUninstall(blockUninstall, userId);
10794            mSettings.writePackageRestrictionsLPr(userId);
10795        }
10796        return true;
10797    }
10798
10799    @Override
10800    public boolean getBlockUninstallForUser(String packageName, int userId) {
10801        synchronized (mPackages) {
10802            PackageSetting ps = mSettings.mPackages.get(packageName);
10803            if (ps == null) {
10804                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10805                return false;
10806            }
10807            return ps.getBlockUninstall(userId);
10808        }
10809    }
10810
10811    /*
10812     * This method handles package deletion in general
10813     */
10814    private boolean deletePackageLI(String packageName, UserHandle user,
10815            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10816            int flags, PackageRemovedInfo outInfo,
10817            boolean writeSettings) {
10818        if (packageName == null) {
10819            Slog.w(TAG, "Attempt to delete null packageName.");
10820            return false;
10821        }
10822        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10823        PackageSetting ps;
10824        boolean dataOnly = false;
10825        int removeUser = -1;
10826        int appId = -1;
10827        synchronized (mPackages) {
10828            ps = mSettings.mPackages.get(packageName);
10829            if (ps == null) {
10830                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10831                return false;
10832            }
10833            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10834                    && user.getIdentifier() != UserHandle.USER_ALL) {
10835                // The caller is asking that the package only be deleted for a single
10836                // user.  To do this, we just mark its uninstalled state and delete
10837                // its data.  If this is a system app, we only allow this to happen if
10838                // they have set the special DELETE_SYSTEM_APP which requests different
10839                // semantics than normal for uninstalling system apps.
10840                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10841                ps.setUserState(user.getIdentifier(),
10842                        COMPONENT_ENABLED_STATE_DEFAULT,
10843                        false, //installed
10844                        true,  //stopped
10845                        true,  //notLaunched
10846                        false, //hidden
10847                        null, null, null,
10848                        false // blockUninstall
10849                        );
10850                if (!isSystemApp(ps)) {
10851                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10852                        // Other user still have this package installed, so all
10853                        // we need to do is clear this user's data and save that
10854                        // it is uninstalled.
10855                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10856                        removeUser = user.getIdentifier();
10857                        appId = ps.appId;
10858                        mSettings.writePackageRestrictionsLPr(removeUser);
10859                    } else {
10860                        // We need to set it back to 'installed' so the uninstall
10861                        // broadcasts will be sent correctly.
10862                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10863                        ps.setInstalled(true, user.getIdentifier());
10864                    }
10865                } else {
10866                    // This is a system app, so we assume that the
10867                    // other users still have this package installed, so all
10868                    // we need to do is clear this user's data and save that
10869                    // it is uninstalled.
10870                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10871                    removeUser = user.getIdentifier();
10872                    appId = ps.appId;
10873                    mSettings.writePackageRestrictionsLPr(removeUser);
10874                }
10875            }
10876        }
10877
10878        if (removeUser >= 0) {
10879            // From above, we determined that we are deleting this only
10880            // for a single user.  Continue the work here.
10881            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10882            if (outInfo != null) {
10883                outInfo.removedPackage = packageName;
10884                outInfo.removedAppId = appId;
10885                outInfo.removedUsers = new int[] {removeUser};
10886            }
10887            mInstaller.clearUserData(packageName, removeUser);
10888            removeKeystoreDataIfNeeded(removeUser, appId);
10889            schedulePackageCleaning(packageName, removeUser, false);
10890            return true;
10891        }
10892
10893        if (dataOnly) {
10894            // Delete application data first
10895            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10896            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10897            return true;
10898        }
10899
10900        boolean ret = false;
10901        if (isSystemApp(ps)) {
10902            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10903            // When an updated system application is deleted we delete the existing resources as well and
10904            // fall back to existing code in system partition
10905            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10906                    flags, outInfo, writeSettings);
10907        } else {
10908            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10909            // Kill application pre-emptively especially for apps on sd.
10910            killApplication(packageName, ps.appId, "uninstall pkg");
10911            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10912                    allUserHandles, perUserInstalled,
10913                    outInfo, writeSettings);
10914        }
10915
10916        return ret;
10917    }
10918
10919    private final class ClearStorageConnection implements ServiceConnection {
10920        IMediaContainerService mContainerService;
10921
10922        @Override
10923        public void onServiceConnected(ComponentName name, IBinder service) {
10924            synchronized (this) {
10925                mContainerService = IMediaContainerService.Stub.asInterface(service);
10926                notifyAll();
10927            }
10928        }
10929
10930        @Override
10931        public void onServiceDisconnected(ComponentName name) {
10932        }
10933    }
10934
10935    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10936        final boolean mounted;
10937        if (Environment.isExternalStorageEmulated()) {
10938            mounted = true;
10939        } else {
10940            final String status = Environment.getExternalStorageState();
10941
10942            mounted = status.equals(Environment.MEDIA_MOUNTED)
10943                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10944        }
10945
10946        if (!mounted) {
10947            return;
10948        }
10949
10950        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10951        int[] users;
10952        if (userId == UserHandle.USER_ALL) {
10953            users = sUserManager.getUserIds();
10954        } else {
10955            users = new int[] { userId };
10956        }
10957        final ClearStorageConnection conn = new ClearStorageConnection();
10958        if (mContext.bindServiceAsUser(
10959                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10960            try {
10961                for (int curUser : users) {
10962                    long timeout = SystemClock.uptimeMillis() + 5000;
10963                    synchronized (conn) {
10964                        long now = SystemClock.uptimeMillis();
10965                        while (conn.mContainerService == null && now < timeout) {
10966                            try {
10967                                conn.wait(timeout - now);
10968                            } catch (InterruptedException e) {
10969                            }
10970                        }
10971                    }
10972                    if (conn.mContainerService == null) {
10973                        return;
10974                    }
10975
10976                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10977                    clearDirectory(conn.mContainerService,
10978                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10979                    if (allData) {
10980                        clearDirectory(conn.mContainerService,
10981                                userEnv.buildExternalStorageAppDataDirs(packageName));
10982                        clearDirectory(conn.mContainerService,
10983                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10984                    }
10985                }
10986            } finally {
10987                mContext.unbindService(conn);
10988            }
10989        }
10990    }
10991
10992    @Override
10993    public void clearApplicationUserData(final String packageName,
10994            final IPackageDataObserver observer, final int userId) {
10995        mContext.enforceCallingOrSelfPermission(
10996                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10997        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10998        // Queue up an async operation since the package deletion may take a little while.
10999        mHandler.post(new Runnable() {
11000            public void run() {
11001                mHandler.removeCallbacks(this);
11002                final boolean succeeded;
11003                synchronized (mInstallLock) {
11004                    succeeded = clearApplicationUserDataLI(packageName, userId);
11005                }
11006                clearExternalStorageDataSync(packageName, userId, true);
11007                if (succeeded) {
11008                    // invoke DeviceStorageMonitor's update method to clear any notifications
11009                    DeviceStorageMonitorInternal
11010                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11011                    if (dsm != null) {
11012                        dsm.checkMemory();
11013                    }
11014                }
11015                if(observer != null) {
11016                    try {
11017                        observer.onRemoveCompleted(packageName, succeeded);
11018                    } catch (RemoteException e) {
11019                        Log.i(TAG, "Observer no longer exists.");
11020                    }
11021                } //end if observer
11022            } //end run
11023        });
11024    }
11025
11026    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11027        if (packageName == null) {
11028            Slog.w(TAG, "Attempt to delete null packageName.");
11029            return false;
11030        }
11031        PackageParser.Package pkg;
11032        boolean dataOnly = false;
11033        final int appId;
11034        synchronized (mPackages) {
11035            pkg = mPackages.get(packageName);
11036            if (pkg == null) {
11037                dataOnly = true;
11038                PackageSetting ps = mSettings.mPackages.get(packageName);
11039                if ((ps == null) || (ps.pkg == null)) {
11040                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11041                    return false;
11042                }
11043                pkg = ps.pkg;
11044            }
11045            if (!dataOnly) {
11046                // need to check this only for fully installed applications
11047                if (pkg == null) {
11048                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11049                    return false;
11050                }
11051                final ApplicationInfo applicationInfo = pkg.applicationInfo;
11052                if (applicationInfo == null) {
11053                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11054                    return false;
11055                }
11056            }
11057            if (pkg != null && pkg.applicationInfo != null) {
11058                appId = pkg.applicationInfo.uid;
11059            } else {
11060                appId = -1;
11061            }
11062        }
11063        int retCode = mInstaller.clearUserData(packageName, userId);
11064        if (retCode < 0) {
11065            Slog.w(TAG, "Couldn't remove cache files for package: "
11066                    + packageName);
11067            return false;
11068        }
11069        removeKeystoreDataIfNeeded(userId, appId);
11070
11071        // Create a native library symlink only if we have native libraries
11072        // and if the native libraries are 32 bit libraries. We do not provide
11073        // this symlink for 64 bit libraries.
11074        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11075                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11076            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11077            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11078                Slog.w(TAG, "Failed linking native library dir");
11079                return false;
11080            }
11081        }
11082
11083        return true;
11084    }
11085
11086    /**
11087     * Remove entries from the keystore daemon. Will only remove it if the
11088     * {@code appId} is valid.
11089     */
11090    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11091        if (appId < 0) {
11092            return;
11093        }
11094
11095        final KeyStore keyStore = KeyStore.getInstance();
11096        if (keyStore != null) {
11097            if (userId == UserHandle.USER_ALL) {
11098                for (final int individual : sUserManager.getUserIds()) {
11099                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11100                }
11101            } else {
11102                keyStore.clearUid(UserHandle.getUid(userId, appId));
11103            }
11104        } else {
11105            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11106        }
11107    }
11108
11109    @Override
11110    public void deleteApplicationCacheFiles(final String packageName,
11111            final IPackageDataObserver observer) {
11112        mContext.enforceCallingOrSelfPermission(
11113                android.Manifest.permission.DELETE_CACHE_FILES, null);
11114        // Queue up an async operation since the package deletion may take a little while.
11115        final int userId = UserHandle.getCallingUserId();
11116        mHandler.post(new Runnable() {
11117            public void run() {
11118                mHandler.removeCallbacks(this);
11119                final boolean succeded;
11120                synchronized (mInstallLock) {
11121                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11122                }
11123                clearExternalStorageDataSync(packageName, userId, false);
11124                if(observer != null) {
11125                    try {
11126                        observer.onRemoveCompleted(packageName, succeded);
11127                    } catch (RemoteException e) {
11128                        Log.i(TAG, "Observer no longer exists.");
11129                    }
11130                } //end if observer
11131            } //end run
11132        });
11133    }
11134
11135    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11136        if (packageName == null) {
11137            Slog.w(TAG, "Attempt to delete null packageName.");
11138            return false;
11139        }
11140        PackageParser.Package p;
11141        synchronized (mPackages) {
11142            p = mPackages.get(packageName);
11143        }
11144        if (p == null) {
11145            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11146            return false;
11147        }
11148        final ApplicationInfo applicationInfo = p.applicationInfo;
11149        if (applicationInfo == null) {
11150            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11151            return false;
11152        }
11153        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11154        if (retCode < 0) {
11155            Slog.w(TAG, "Couldn't remove cache files for package: "
11156                       + packageName + " u" + userId);
11157            return false;
11158        }
11159        return true;
11160    }
11161
11162    @Override
11163    public void getPackageSizeInfo(final String packageName, int userHandle,
11164            final IPackageStatsObserver observer) {
11165        mContext.enforceCallingOrSelfPermission(
11166                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11167        if (packageName == null) {
11168            throw new IllegalArgumentException("Attempt to get size of null packageName");
11169        }
11170
11171        PackageStats stats = new PackageStats(packageName, userHandle);
11172
11173        /*
11174         * Queue up an async operation since the package measurement may take a
11175         * little while.
11176         */
11177        Message msg = mHandler.obtainMessage(INIT_COPY);
11178        msg.obj = new MeasureParams(stats, observer);
11179        mHandler.sendMessage(msg);
11180    }
11181
11182    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11183            PackageStats pStats) {
11184        if (packageName == null) {
11185            Slog.w(TAG, "Attempt to get size of null packageName.");
11186            return false;
11187        }
11188        PackageParser.Package p;
11189        boolean dataOnly = false;
11190        String libDirRoot = null;
11191        String asecPath = null;
11192        PackageSetting ps = null;
11193        synchronized (mPackages) {
11194            p = mPackages.get(packageName);
11195            ps = mSettings.mPackages.get(packageName);
11196            if(p == null) {
11197                dataOnly = true;
11198                if((ps == null) || (ps.pkg == null)) {
11199                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11200                    return false;
11201                }
11202                p = ps.pkg;
11203            }
11204            if (ps != null) {
11205                libDirRoot = ps.legacyNativeLibraryPathString;
11206            }
11207            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11208                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11209                if (secureContainerId != null) {
11210                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11211                }
11212            }
11213        }
11214        String publicSrcDir = null;
11215        if(!dataOnly) {
11216            final ApplicationInfo applicationInfo = p.applicationInfo;
11217            if (applicationInfo == null) {
11218                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11219                return false;
11220            }
11221            if (isForwardLocked(p)) {
11222                publicSrcDir = applicationInfo.getBaseResourcePath();
11223            }
11224        }
11225        // TODO: extend to measure size of split APKs
11226        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11227        // not just the first level.
11228        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11229        // just the primary.
11230        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11231        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11232                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11233        if (res < 0) {
11234            return false;
11235        }
11236
11237        // Fix-up for forward-locked applications in ASEC containers.
11238        if (!isExternal(p)) {
11239            pStats.codeSize += pStats.externalCodeSize;
11240            pStats.externalCodeSize = 0L;
11241        }
11242
11243        return true;
11244    }
11245
11246
11247    @Override
11248    public void addPackageToPreferred(String packageName) {
11249        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11250    }
11251
11252    @Override
11253    public void removePackageFromPreferred(String packageName) {
11254        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11255    }
11256
11257    @Override
11258    public List<PackageInfo> getPreferredPackages(int flags) {
11259        return new ArrayList<PackageInfo>();
11260    }
11261
11262    private int getUidTargetSdkVersionLockedLPr(int uid) {
11263        Object obj = mSettings.getUserIdLPr(uid);
11264        if (obj instanceof SharedUserSetting) {
11265            final SharedUserSetting sus = (SharedUserSetting) obj;
11266            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11267            final Iterator<PackageSetting> it = sus.packages.iterator();
11268            while (it.hasNext()) {
11269                final PackageSetting ps = it.next();
11270                if (ps.pkg != null) {
11271                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11272                    if (v < vers) vers = v;
11273                }
11274            }
11275            return vers;
11276        } else if (obj instanceof PackageSetting) {
11277            final PackageSetting ps = (PackageSetting) obj;
11278            if (ps.pkg != null) {
11279                return ps.pkg.applicationInfo.targetSdkVersion;
11280            }
11281        }
11282        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11283    }
11284
11285    @Override
11286    public void addPreferredActivity(IntentFilter filter, int match,
11287            ComponentName[] set, ComponentName activity, int userId) {
11288        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11289                "Adding preferred");
11290    }
11291
11292    private void addPreferredActivityInternal(IntentFilter filter, int match,
11293            ComponentName[] set, ComponentName activity, boolean always, int userId,
11294            String opname) {
11295        // writer
11296        int callingUid = Binder.getCallingUid();
11297        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11298        if (filter.countActions() == 0) {
11299            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11300            return;
11301        }
11302        synchronized (mPackages) {
11303            if (mContext.checkCallingOrSelfPermission(
11304                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11305                    != PackageManager.PERMISSION_GRANTED) {
11306                if (getUidTargetSdkVersionLockedLPr(callingUid)
11307                        < Build.VERSION_CODES.FROYO) {
11308                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11309                            + callingUid);
11310                    return;
11311                }
11312                mContext.enforceCallingOrSelfPermission(
11313                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11314            }
11315
11316            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11317            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11318                    + userId + ":");
11319            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11320            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11321            mSettings.writePackageRestrictionsLPr(userId);
11322        }
11323    }
11324
11325    @Override
11326    public void replacePreferredActivity(IntentFilter filter, int match,
11327            ComponentName[] set, ComponentName activity, int userId) {
11328        if (filter.countActions() != 1) {
11329            throw new IllegalArgumentException(
11330                    "replacePreferredActivity expects filter to have only 1 action.");
11331        }
11332        if (filter.countDataAuthorities() != 0
11333                || filter.countDataPaths() != 0
11334                || filter.countDataSchemes() > 1
11335                || filter.countDataTypes() != 0) {
11336            throw new IllegalArgumentException(
11337                    "replacePreferredActivity expects filter to have no data authorities, " +
11338                    "paths, or types; and at most one scheme.");
11339        }
11340
11341        final int callingUid = Binder.getCallingUid();
11342        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11343        synchronized (mPackages) {
11344            if (mContext.checkCallingOrSelfPermission(
11345                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11346                    != PackageManager.PERMISSION_GRANTED) {
11347                if (getUidTargetSdkVersionLockedLPr(callingUid)
11348                        < Build.VERSION_CODES.FROYO) {
11349                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11350                            + Binder.getCallingUid());
11351                    return;
11352                }
11353                mContext.enforceCallingOrSelfPermission(
11354                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11355            }
11356
11357            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11358            if (pir != null) {
11359                // Get all of the existing entries that exactly match this filter.
11360                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11361                if (existing != null && existing.size() == 1) {
11362                    PreferredActivity cur = existing.get(0);
11363                    if (DEBUG_PREFERRED) {
11364                        Slog.i(TAG, "Checking replace of preferred:");
11365                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11366                        if (!cur.mPref.mAlways) {
11367                            Slog.i(TAG, "  -- CUR; not mAlways!");
11368                        } else {
11369                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11370                            Slog.i(TAG, "  -- CUR: mSet="
11371                                    + Arrays.toString(cur.mPref.mSetComponents));
11372                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11373                            Slog.i(TAG, "  -- NEW: mMatch="
11374                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11375                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11376                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11377                        }
11378                    }
11379                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11380                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11381                            && cur.mPref.sameSet(set)) {
11382                        if (DEBUG_PREFERRED) {
11383                            Slog.i(TAG, "Replacing with same preferred activity "
11384                                    + cur.mPref.mShortComponent + " for user "
11385                                    + userId + ":");
11386                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11387                        } else {
11388                            Slog.i(TAG, "Replacing with same preferred activity "
11389                                    + cur.mPref.mShortComponent + " for user "
11390                                    + userId);
11391                        }
11392                        return;
11393                    }
11394                }
11395
11396                if (existing != null) {
11397                    if (DEBUG_PREFERRED) {
11398                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11399                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11400                    }
11401                    for (int i = 0; i < existing.size(); i++) {
11402                        PreferredActivity pa = existing.get(i);
11403                        if (DEBUG_PREFERRED) {
11404                            Slog.i(TAG, "Removing existing preferred activity "
11405                                    + pa.mPref.mComponent + ":");
11406                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11407                        }
11408                        pir.removeFilter(pa);
11409                    }
11410                }
11411            }
11412            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11413                    "Replacing preferred");
11414        }
11415    }
11416
11417    @Override
11418    public void clearPackagePreferredActivities(String packageName) {
11419        final int uid = Binder.getCallingUid();
11420        // writer
11421        synchronized (mPackages) {
11422            PackageParser.Package pkg = mPackages.get(packageName);
11423            if (pkg == null || pkg.applicationInfo.uid != uid) {
11424                if (mContext.checkCallingOrSelfPermission(
11425                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11426                        != PackageManager.PERMISSION_GRANTED) {
11427                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11428                            < Build.VERSION_CODES.FROYO) {
11429                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11430                                + Binder.getCallingUid());
11431                        return;
11432                    }
11433                    mContext.enforceCallingOrSelfPermission(
11434                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11435                }
11436            }
11437
11438            int user = UserHandle.getCallingUserId();
11439            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11440                mSettings.writePackageRestrictionsLPr(user);
11441                scheduleWriteSettingsLocked();
11442            }
11443        }
11444    }
11445
11446    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11447    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11448        ArrayList<PreferredActivity> removed = null;
11449        boolean changed = false;
11450        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11451            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11452            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11453            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11454                continue;
11455            }
11456            Iterator<PreferredActivity> it = pir.filterIterator();
11457            while (it.hasNext()) {
11458                PreferredActivity pa = it.next();
11459                // Mark entry for removal only if it matches the package name
11460                // and the entry is of type "always".
11461                if (packageName == null ||
11462                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11463                                && pa.mPref.mAlways)) {
11464                    if (removed == null) {
11465                        removed = new ArrayList<PreferredActivity>();
11466                    }
11467                    removed.add(pa);
11468                }
11469            }
11470            if (removed != null) {
11471                for (int j=0; j<removed.size(); j++) {
11472                    PreferredActivity pa = removed.get(j);
11473                    pir.removeFilter(pa);
11474                }
11475                changed = true;
11476            }
11477        }
11478        return changed;
11479    }
11480
11481    @Override
11482    public void resetPreferredActivities(int userId) {
11483        mContext.enforceCallingOrSelfPermission(
11484                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11485        // writer
11486        synchronized (mPackages) {
11487            int user = UserHandle.getCallingUserId();
11488            clearPackagePreferredActivitiesLPw(null, user);
11489            mSettings.readDefaultPreferredAppsLPw(this, user);
11490            mSettings.writePackageRestrictionsLPr(user);
11491            scheduleWriteSettingsLocked();
11492        }
11493    }
11494
11495    @Override
11496    public int getPreferredActivities(List<IntentFilter> outFilters,
11497            List<ComponentName> outActivities, String packageName) {
11498
11499        int num = 0;
11500        final int userId = UserHandle.getCallingUserId();
11501        // reader
11502        synchronized (mPackages) {
11503            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11504            if (pir != null) {
11505                final Iterator<PreferredActivity> it = pir.filterIterator();
11506                while (it.hasNext()) {
11507                    final PreferredActivity pa = it.next();
11508                    if (packageName == null
11509                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11510                                    && pa.mPref.mAlways)) {
11511                        if (outFilters != null) {
11512                            outFilters.add(new IntentFilter(pa));
11513                        }
11514                        if (outActivities != null) {
11515                            outActivities.add(pa.mPref.mComponent);
11516                        }
11517                    }
11518                }
11519            }
11520        }
11521
11522        return num;
11523    }
11524
11525    @Override
11526    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11527            int userId) {
11528        int callingUid = Binder.getCallingUid();
11529        if (callingUid != Process.SYSTEM_UID) {
11530            throw new SecurityException(
11531                    "addPersistentPreferredActivity can only be run by the system");
11532        }
11533        if (filter.countActions() == 0) {
11534            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11535            return;
11536        }
11537        synchronized (mPackages) {
11538            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11539                    " :");
11540            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11541            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11542                    new PersistentPreferredActivity(filter, activity));
11543            mSettings.writePackageRestrictionsLPr(userId);
11544        }
11545    }
11546
11547    @Override
11548    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11549        int callingUid = Binder.getCallingUid();
11550        if (callingUid != Process.SYSTEM_UID) {
11551            throw new SecurityException(
11552                    "clearPackagePersistentPreferredActivities can only be run by the system");
11553        }
11554        ArrayList<PersistentPreferredActivity> removed = null;
11555        boolean changed = false;
11556        synchronized (mPackages) {
11557            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11558                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11559                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11560                        .valueAt(i);
11561                if (userId != thisUserId) {
11562                    continue;
11563                }
11564                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11565                while (it.hasNext()) {
11566                    PersistentPreferredActivity ppa = it.next();
11567                    // Mark entry for removal only if it matches the package name.
11568                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11569                        if (removed == null) {
11570                            removed = new ArrayList<PersistentPreferredActivity>();
11571                        }
11572                        removed.add(ppa);
11573                    }
11574                }
11575                if (removed != null) {
11576                    for (int j=0; j<removed.size(); j++) {
11577                        PersistentPreferredActivity ppa = removed.get(j);
11578                        ppir.removeFilter(ppa);
11579                    }
11580                    changed = true;
11581                }
11582            }
11583
11584            if (changed) {
11585                mSettings.writePackageRestrictionsLPr(userId);
11586            }
11587        }
11588    }
11589
11590    @Override
11591    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11592            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11593        mContext.enforceCallingOrSelfPermission(
11594                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11595        int callingUid = Binder.getCallingUid();
11596        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11597        if (intentFilter.countActions() == 0) {
11598            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11599            return;
11600        }
11601        synchronized (mPackages) {
11602            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11603                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11604            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11605            mSettings.writePackageRestrictionsLPr(sourceUserId);
11606        }
11607    }
11608
11609    @Override
11610    public void addCrossProfileIntentsForPackage(String packageName,
11611            int sourceUserId, int targetUserId) {
11612        mContext.enforceCallingOrSelfPermission(
11613                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11614        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11615        mSettings.writePackageRestrictionsLPr(sourceUserId);
11616    }
11617
11618    @Override
11619    public void removeCrossProfileIntentsForPackage(String packageName,
11620            int sourceUserId, int targetUserId) {
11621        mContext.enforceCallingOrSelfPermission(
11622                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11623        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11624        mSettings.writePackageRestrictionsLPr(sourceUserId);
11625    }
11626
11627    @Override
11628    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11629            int ownerUserId) {
11630        mContext.enforceCallingOrSelfPermission(
11631                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11632        int callingUid = Binder.getCallingUid();
11633        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11634        int callingUserId = UserHandle.getUserId(callingUid);
11635        synchronized (mPackages) {
11636            CrossProfileIntentResolver resolver =
11637                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11638            HashSet<CrossProfileIntentFilter> set =
11639                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11640            for (CrossProfileIntentFilter filter : set) {
11641                if (filter.getOwnerPackage().equals(ownerPackage)
11642                        && filter.getOwnerUserId() == callingUserId) {
11643                    resolver.removeFilter(filter);
11644                }
11645            }
11646            mSettings.writePackageRestrictionsLPr(sourceUserId);
11647        }
11648    }
11649
11650    // Enforcing that callingUid is owning pkg on userId
11651    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11652        // The system owns everything.
11653        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11654            return;
11655        }
11656        int callingUserId = UserHandle.getUserId(callingUid);
11657        if (callingUserId != userId) {
11658            throw new SecurityException("calling uid " + callingUid
11659                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11660                    + callingUserId);
11661        }
11662        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11663        if (pi == null) {
11664            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11665                    + callingUserId);
11666        }
11667        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11668            throw new SecurityException("Calling uid " + callingUid
11669                    + " does not own package " + pkg);
11670        }
11671    }
11672
11673    @Override
11674    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11675        Intent intent = new Intent(Intent.ACTION_MAIN);
11676        intent.addCategory(Intent.CATEGORY_HOME);
11677
11678        final int callingUserId = UserHandle.getCallingUserId();
11679        List<ResolveInfo> list = queryIntentActivities(intent, null,
11680                PackageManager.GET_META_DATA, callingUserId);
11681        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11682                true, false, false, callingUserId);
11683
11684        allHomeCandidates.clear();
11685        if (list != null) {
11686            for (ResolveInfo ri : list) {
11687                allHomeCandidates.add(ri);
11688            }
11689        }
11690        return (preferred == null || preferred.activityInfo == null)
11691                ? null
11692                : new ComponentName(preferred.activityInfo.packageName,
11693                        preferred.activityInfo.name);
11694    }
11695
11696    /**
11697     * Check if calling UID is the current home app. This handles both the case
11698     * where the user has selected a specific home app, and where there is only
11699     * one home app.
11700     */
11701    public boolean checkCallerIsHomeApp() {
11702        final Intent intent = new Intent(Intent.ACTION_MAIN);
11703        intent.addCategory(Intent.CATEGORY_HOME);
11704
11705        final int callingUid = Binder.getCallingUid();
11706        final int callingUserId = UserHandle.getCallingUserId();
11707        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11708        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11709                false, false, callingUserId);
11710
11711        if (preferredHome != null) {
11712            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11713                return true;
11714            }
11715        } else {
11716            for (ResolveInfo info : allHomes) {
11717                if (callingUid == info.activityInfo.applicationInfo.uid) {
11718                    return true;
11719                }
11720            }
11721        }
11722
11723        return false;
11724    }
11725
11726    /**
11727     * Enforce that calling UID is the current home app. This handles both the
11728     * case where the user has selected a specific home app, and where there is
11729     * only one home app.
11730     */
11731    public void enforceCallerIsHomeApp() {
11732        if (!checkCallerIsHomeApp()) {
11733            throw new SecurityException("Caller is not currently selected home app");
11734        }
11735    }
11736
11737    @Override
11738    public void setApplicationEnabledSetting(String appPackageName,
11739            int newState, int flags, int userId, String callingPackage) {
11740        if (!sUserManager.exists(userId)) return;
11741        if (callingPackage == null) {
11742            callingPackage = Integer.toString(Binder.getCallingUid());
11743        }
11744        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11745    }
11746
11747    @Override
11748    public void setComponentEnabledSetting(ComponentName componentName,
11749            int newState, int flags, int userId) {
11750        if (!sUserManager.exists(userId)) return;
11751        setEnabledSetting(componentName.getPackageName(),
11752                componentName.getClassName(), newState, flags, userId, null);
11753    }
11754
11755    private void setEnabledSetting(final String packageName, String className, int newState,
11756            final int flags, int userId, String callingPackage) {
11757        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11758              || newState == COMPONENT_ENABLED_STATE_ENABLED
11759              || newState == COMPONENT_ENABLED_STATE_DISABLED
11760              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11761              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11762            throw new IllegalArgumentException("Invalid new component state: "
11763                    + newState);
11764        }
11765        PackageSetting pkgSetting;
11766        final int uid = Binder.getCallingUid();
11767        final int permission = mContext.checkCallingOrSelfPermission(
11768                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11769        enforceCrossUserPermission(uid, userId, false, "set enabled");
11770        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11771        boolean sendNow = false;
11772        boolean isApp = (className == null);
11773        String componentName = isApp ? packageName : className;
11774        int packageUid = -1;
11775        ArrayList<String> components;
11776
11777        // writer
11778        synchronized (mPackages) {
11779            pkgSetting = mSettings.mPackages.get(packageName);
11780            if (pkgSetting == null) {
11781                if (className == null) {
11782                    throw new IllegalArgumentException(
11783                            "Unknown package: " + packageName);
11784                }
11785                throw new IllegalArgumentException(
11786                        "Unknown component: " + packageName
11787                        + "/" + className);
11788            }
11789            // Allow root and verify that userId is not being specified by a different user
11790            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11791                throw new SecurityException(
11792                        "Permission Denial: attempt to change component state from pid="
11793                        + Binder.getCallingPid()
11794                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11795            }
11796            if (className == null) {
11797                // We're dealing with an application/package level state change
11798                if (pkgSetting.getEnabled(userId) == newState) {
11799                    // Nothing to do
11800                    return;
11801                }
11802                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11803                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11804                    // Don't care about who enables an app.
11805                    callingPackage = null;
11806                }
11807                pkgSetting.setEnabled(newState, userId, callingPackage);
11808                // pkgSetting.pkg.mSetEnabled = newState;
11809            } else {
11810                // We're dealing with a component level state change
11811                // First, verify that this is a valid class name.
11812                PackageParser.Package pkg = pkgSetting.pkg;
11813                if (pkg == null || !pkg.hasComponentClassName(className)) {
11814                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11815                        throw new IllegalArgumentException("Component class " + className
11816                                + " does not exist in " + packageName);
11817                    } else {
11818                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11819                                + className + " does not exist in " + packageName);
11820                    }
11821                }
11822                switch (newState) {
11823                case COMPONENT_ENABLED_STATE_ENABLED:
11824                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11825                        return;
11826                    }
11827                    break;
11828                case COMPONENT_ENABLED_STATE_DISABLED:
11829                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11830                        return;
11831                    }
11832                    break;
11833                case COMPONENT_ENABLED_STATE_DEFAULT:
11834                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11835                        return;
11836                    }
11837                    break;
11838                default:
11839                    Slog.e(TAG, "Invalid new component state: " + newState);
11840                    return;
11841                }
11842            }
11843            mSettings.writePackageRestrictionsLPr(userId);
11844            components = mPendingBroadcasts.get(userId, packageName);
11845            final boolean newPackage = components == null;
11846            if (newPackage) {
11847                components = new ArrayList<String>();
11848            }
11849            if (!components.contains(componentName)) {
11850                components.add(componentName);
11851            }
11852            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11853                sendNow = true;
11854                // Purge entry from pending broadcast list if another one exists already
11855                // since we are sending one right away.
11856                mPendingBroadcasts.remove(userId, packageName);
11857            } else {
11858                if (newPackage) {
11859                    mPendingBroadcasts.put(userId, packageName, components);
11860                }
11861                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11862                    // Schedule a message
11863                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11864                }
11865            }
11866        }
11867
11868        long callingId = Binder.clearCallingIdentity();
11869        try {
11870            if (sendNow) {
11871                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11872                sendPackageChangedBroadcast(packageName,
11873                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11874            }
11875        } finally {
11876            Binder.restoreCallingIdentity(callingId);
11877        }
11878    }
11879
11880    private void sendPackageChangedBroadcast(String packageName,
11881            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11882        if (DEBUG_INSTALL)
11883            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11884                    + componentNames);
11885        Bundle extras = new Bundle(4);
11886        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11887        String nameList[] = new String[componentNames.size()];
11888        componentNames.toArray(nameList);
11889        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11890        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11891        extras.putInt(Intent.EXTRA_UID, packageUid);
11892        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11893                new int[] {UserHandle.getUserId(packageUid)});
11894    }
11895
11896    @Override
11897    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11898        if (!sUserManager.exists(userId)) return;
11899        final int uid = Binder.getCallingUid();
11900        final int permission = mContext.checkCallingOrSelfPermission(
11901                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11902        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11903        enforceCrossUserPermission(uid, userId, true, "stop package");
11904        // writer
11905        synchronized (mPackages) {
11906            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11907                    uid, userId)) {
11908                scheduleWritePackageRestrictionsLocked(userId);
11909            }
11910        }
11911    }
11912
11913    @Override
11914    public String getInstallerPackageName(String packageName) {
11915        // reader
11916        synchronized (mPackages) {
11917            return mSettings.getInstallerPackageNameLPr(packageName);
11918        }
11919    }
11920
11921    @Override
11922    public int getApplicationEnabledSetting(String packageName, int userId) {
11923        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11924        int uid = Binder.getCallingUid();
11925        enforceCrossUserPermission(uid, userId, false, "get enabled");
11926        // reader
11927        synchronized (mPackages) {
11928            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11929        }
11930    }
11931
11932    @Override
11933    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11934        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11935        int uid = Binder.getCallingUid();
11936        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11937        // reader
11938        synchronized (mPackages) {
11939            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11940        }
11941    }
11942
11943    @Override
11944    public void enterSafeMode() {
11945        enforceSystemOrRoot("Only the system can request entering safe mode");
11946
11947        if (!mSystemReady) {
11948            mSafeMode = true;
11949        }
11950    }
11951
11952    @Override
11953    public void systemReady() {
11954        mSystemReady = true;
11955
11956        // Read the compatibilty setting when the system is ready.
11957        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11958                mContext.getContentResolver(),
11959                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11960        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11961        if (DEBUG_SETTINGS) {
11962            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11963        }
11964
11965        synchronized (mPackages) {
11966            // Verify that all of the preferred activity components actually
11967            // exist.  It is possible for applications to be updated and at
11968            // that point remove a previously declared activity component that
11969            // had been set as a preferred activity.  We try to clean this up
11970            // the next time we encounter that preferred activity, but it is
11971            // possible for the user flow to never be able to return to that
11972            // situation so here we do a sanity check to make sure we haven't
11973            // left any junk around.
11974            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11975            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11976                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11977                removed.clear();
11978                for (PreferredActivity pa : pir.filterSet()) {
11979                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11980                        removed.add(pa);
11981                    }
11982                }
11983                if (removed.size() > 0) {
11984                    for (int r=0; r<removed.size(); r++) {
11985                        PreferredActivity pa = removed.get(r);
11986                        Slog.w(TAG, "Removing dangling preferred activity: "
11987                                + pa.mPref.mComponent);
11988                        pir.removeFilter(pa);
11989                    }
11990                    mSettings.writePackageRestrictionsLPr(
11991                            mSettings.mPreferredActivities.keyAt(i));
11992                }
11993            }
11994        }
11995        sUserManager.systemReady();
11996    }
11997
11998    @Override
11999    public boolean isSafeMode() {
12000        return mSafeMode;
12001    }
12002
12003    @Override
12004    public boolean hasSystemUidErrors() {
12005        return mHasSystemUidErrors;
12006    }
12007
12008    static String arrayToString(int[] array) {
12009        StringBuffer buf = new StringBuffer(128);
12010        buf.append('[');
12011        if (array != null) {
12012            for (int i=0; i<array.length; i++) {
12013                if (i > 0) buf.append(", ");
12014                buf.append(array[i]);
12015            }
12016        }
12017        buf.append(']');
12018        return buf.toString();
12019    }
12020
12021    static class DumpState {
12022        public static final int DUMP_LIBS = 1 << 0;
12023        public static final int DUMP_FEATURES = 1 << 1;
12024        public static final int DUMP_RESOLVERS = 1 << 2;
12025        public static final int DUMP_PERMISSIONS = 1 << 3;
12026        public static final int DUMP_PACKAGES = 1 << 4;
12027        public static final int DUMP_SHARED_USERS = 1 << 5;
12028        public static final int DUMP_MESSAGES = 1 << 6;
12029        public static final int DUMP_PROVIDERS = 1 << 7;
12030        public static final int DUMP_VERIFIERS = 1 << 8;
12031        public static final int DUMP_PREFERRED = 1 << 9;
12032        public static final int DUMP_PREFERRED_XML = 1 << 10;
12033        public static final int DUMP_KEYSETS = 1 << 11;
12034        public static final int DUMP_VERSION = 1 << 12;
12035        public static final int DUMP_INSTALLS = 1 << 13;
12036
12037        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12038
12039        private int mTypes;
12040
12041        private int mOptions;
12042
12043        private boolean mTitlePrinted;
12044
12045        private SharedUserSetting mSharedUser;
12046
12047        public boolean isDumping(int type) {
12048            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12049                return true;
12050            }
12051
12052            return (mTypes & type) != 0;
12053        }
12054
12055        public void setDump(int type) {
12056            mTypes |= type;
12057        }
12058
12059        public boolean isOptionEnabled(int option) {
12060            return (mOptions & option) != 0;
12061        }
12062
12063        public void setOptionEnabled(int option) {
12064            mOptions |= option;
12065        }
12066
12067        public boolean onTitlePrinted() {
12068            final boolean printed = mTitlePrinted;
12069            mTitlePrinted = true;
12070            return printed;
12071        }
12072
12073        public boolean getTitlePrinted() {
12074            return mTitlePrinted;
12075        }
12076
12077        public void setTitlePrinted(boolean enabled) {
12078            mTitlePrinted = enabled;
12079        }
12080
12081        public SharedUserSetting getSharedUser() {
12082            return mSharedUser;
12083        }
12084
12085        public void setSharedUser(SharedUserSetting user) {
12086            mSharedUser = user;
12087        }
12088    }
12089
12090    @Override
12091    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12092        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12093                != PackageManager.PERMISSION_GRANTED) {
12094            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12095                    + Binder.getCallingPid()
12096                    + ", uid=" + Binder.getCallingUid()
12097                    + " without permission "
12098                    + android.Manifest.permission.DUMP);
12099            return;
12100        }
12101
12102        DumpState dumpState = new DumpState();
12103        boolean fullPreferred = false;
12104        boolean checkin = false;
12105
12106        String packageName = null;
12107
12108        int opti = 0;
12109        while (opti < args.length) {
12110            String opt = args[opti];
12111            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12112                break;
12113            }
12114            opti++;
12115            if ("-a".equals(opt)) {
12116                // Right now we only know how to print all.
12117            } else if ("-h".equals(opt)) {
12118                pw.println("Package manager dump options:");
12119                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12120                pw.println("    --checkin: dump for a checkin");
12121                pw.println("    -f: print details of intent filters");
12122                pw.println("    -h: print this help");
12123                pw.println("  cmd may be one of:");
12124                pw.println("    l[ibraries]: list known shared libraries");
12125                pw.println("    f[ibraries]: list device features");
12126                pw.println("    k[eysets]: print known keysets");
12127                pw.println("    r[esolvers]: dump intent resolvers");
12128                pw.println("    perm[issions]: dump permissions");
12129                pw.println("    pref[erred]: print preferred package settings");
12130                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12131                pw.println("    prov[iders]: dump content providers");
12132                pw.println("    p[ackages]: dump installed packages");
12133                pw.println("    s[hared-users]: dump shared user IDs");
12134                pw.println("    m[essages]: print collected runtime messages");
12135                pw.println("    v[erifiers]: print package verifier info");
12136                pw.println("    version: print database version info");
12137                pw.println("    write: write current settings now");
12138                pw.println("    <package.name>: info about given package");
12139                pw.println("    installs: details about install sessions");
12140                return;
12141            } else if ("--checkin".equals(opt)) {
12142                checkin = true;
12143            } else if ("-f".equals(opt)) {
12144                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12145            } else {
12146                pw.println("Unknown argument: " + opt + "; use -h for help");
12147            }
12148        }
12149
12150        // Is the caller requesting to dump a particular piece of data?
12151        if (opti < args.length) {
12152            String cmd = args[opti];
12153            opti++;
12154            // Is this a package name?
12155            if ("android".equals(cmd) || cmd.contains(".")) {
12156                packageName = cmd;
12157                // When dumping a single package, we always dump all of its
12158                // filter information since the amount of data will be reasonable.
12159                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12160            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12161                dumpState.setDump(DumpState.DUMP_LIBS);
12162            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12163                dumpState.setDump(DumpState.DUMP_FEATURES);
12164            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12165                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12166            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12167                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12168            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12169                dumpState.setDump(DumpState.DUMP_PREFERRED);
12170            } else if ("preferred-xml".equals(cmd)) {
12171                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12172                if (opti < args.length && "--full".equals(args[opti])) {
12173                    fullPreferred = true;
12174                    opti++;
12175                }
12176            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12177                dumpState.setDump(DumpState.DUMP_PACKAGES);
12178            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12179                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12180            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12181                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12182            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12183                dumpState.setDump(DumpState.DUMP_MESSAGES);
12184            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12185                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12186            } else if ("version".equals(cmd)) {
12187                dumpState.setDump(DumpState.DUMP_VERSION);
12188            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12189                dumpState.setDump(DumpState.DUMP_KEYSETS);
12190            } else if ("write".equals(cmd)) {
12191                synchronized (mPackages) {
12192                    mSettings.writeLPr();
12193                    pw.println("Settings written.");
12194                    return;
12195                }
12196            } else if ("installs".equals(cmd)) {
12197                dumpState.setDump(DumpState.DUMP_INSTALLS);
12198            }
12199        }
12200
12201        if (checkin) {
12202            pw.println("vers,1");
12203        }
12204
12205        // reader
12206        synchronized (mPackages) {
12207            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12208                if (!checkin) {
12209                    if (dumpState.onTitlePrinted())
12210                        pw.println();
12211                    pw.println("Database versions:");
12212                    pw.print("  SDK Version:");
12213                    pw.print(" internal=");
12214                    pw.print(mSettings.mInternalSdkPlatform);
12215                    pw.print(" external=");
12216                    pw.println(mSettings.mExternalSdkPlatform);
12217                    pw.print("  DB Version:");
12218                    pw.print(" internal=");
12219                    pw.print(mSettings.mInternalDatabaseVersion);
12220                    pw.print(" external=");
12221                    pw.println(mSettings.mExternalDatabaseVersion);
12222                }
12223            }
12224
12225            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12226                if (!checkin) {
12227                    if (dumpState.onTitlePrinted())
12228                        pw.println();
12229                    pw.println("Verifiers:");
12230                    pw.print("  Required: ");
12231                    pw.print(mRequiredVerifierPackage);
12232                    pw.print(" (uid=");
12233                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12234                    pw.println(")");
12235                } else if (mRequiredVerifierPackage != null) {
12236                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12237                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12238                }
12239            }
12240
12241            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12242                boolean printedHeader = false;
12243                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12244                while (it.hasNext()) {
12245                    String name = it.next();
12246                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12247                    if (!checkin) {
12248                        if (!printedHeader) {
12249                            if (dumpState.onTitlePrinted())
12250                                pw.println();
12251                            pw.println("Libraries:");
12252                            printedHeader = true;
12253                        }
12254                        pw.print("  ");
12255                    } else {
12256                        pw.print("lib,");
12257                    }
12258                    pw.print(name);
12259                    if (!checkin) {
12260                        pw.print(" -> ");
12261                    }
12262                    if (ent.path != null) {
12263                        if (!checkin) {
12264                            pw.print("(jar) ");
12265                            pw.print(ent.path);
12266                        } else {
12267                            pw.print(",jar,");
12268                            pw.print(ent.path);
12269                        }
12270                    } else {
12271                        if (!checkin) {
12272                            pw.print("(apk) ");
12273                            pw.print(ent.apk);
12274                        } else {
12275                            pw.print(",apk,");
12276                            pw.print(ent.apk);
12277                        }
12278                    }
12279                    pw.println();
12280                }
12281            }
12282
12283            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12284                if (dumpState.onTitlePrinted())
12285                    pw.println();
12286                if (!checkin) {
12287                    pw.println("Features:");
12288                }
12289                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12290                while (it.hasNext()) {
12291                    String name = it.next();
12292                    if (!checkin) {
12293                        pw.print("  ");
12294                    } else {
12295                        pw.print("feat,");
12296                    }
12297                    pw.println(name);
12298                }
12299            }
12300
12301            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12302                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12303                        : "Activity Resolver Table:", "  ", packageName,
12304                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12305                    dumpState.setTitlePrinted(true);
12306                }
12307                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12308                        : "Receiver Resolver Table:", "  ", packageName,
12309                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12310                    dumpState.setTitlePrinted(true);
12311                }
12312                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12313                        : "Service Resolver Table:", "  ", packageName,
12314                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12315                    dumpState.setTitlePrinted(true);
12316                }
12317                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12318                        : "Provider Resolver Table:", "  ", packageName,
12319                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12320                    dumpState.setTitlePrinted(true);
12321                }
12322            }
12323
12324            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12325                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12326                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12327                    int user = mSettings.mPreferredActivities.keyAt(i);
12328                    if (pir.dump(pw,
12329                            dumpState.getTitlePrinted()
12330                                ? "\nPreferred Activities User " + user + ":"
12331                                : "Preferred Activities User " + user + ":", "  ",
12332                            packageName, true)) {
12333                        dumpState.setTitlePrinted(true);
12334                    }
12335                }
12336            }
12337
12338            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12339                pw.flush();
12340                FileOutputStream fout = new FileOutputStream(fd);
12341                BufferedOutputStream str = new BufferedOutputStream(fout);
12342                XmlSerializer serializer = new FastXmlSerializer();
12343                try {
12344                    serializer.setOutput(str, "utf-8");
12345                    serializer.startDocument(null, true);
12346                    serializer.setFeature(
12347                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12348                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12349                    serializer.endDocument();
12350                    serializer.flush();
12351                } catch (IllegalArgumentException e) {
12352                    pw.println("Failed writing: " + e);
12353                } catch (IllegalStateException e) {
12354                    pw.println("Failed writing: " + e);
12355                } catch (IOException e) {
12356                    pw.println("Failed writing: " + e);
12357                }
12358            }
12359
12360            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12361                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12362                if (packageName == null) {
12363                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12364                        if (iperm == 0) {
12365                            if (dumpState.onTitlePrinted())
12366                                pw.println();
12367                            pw.println("AppOp Permissions:");
12368                        }
12369                        pw.print("  AppOp Permission ");
12370                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12371                        pw.println(":");
12372                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12373                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12374                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12375                        }
12376                    }
12377                }
12378            }
12379
12380            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12381                boolean printedSomething = false;
12382                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12383                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12384                        continue;
12385                    }
12386                    if (!printedSomething) {
12387                        if (dumpState.onTitlePrinted())
12388                            pw.println();
12389                        pw.println("Registered ContentProviders:");
12390                        printedSomething = true;
12391                    }
12392                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12393                    pw.print("    "); pw.println(p.toString());
12394                }
12395                printedSomething = false;
12396                for (Map.Entry<String, PackageParser.Provider> entry :
12397                        mProvidersByAuthority.entrySet()) {
12398                    PackageParser.Provider p = entry.getValue();
12399                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12400                        continue;
12401                    }
12402                    if (!printedSomething) {
12403                        if (dumpState.onTitlePrinted())
12404                            pw.println();
12405                        pw.println("ContentProvider Authorities:");
12406                        printedSomething = true;
12407                    }
12408                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12409                    pw.print("    "); pw.println(p.toString());
12410                    if (p.info != null && p.info.applicationInfo != null) {
12411                        final String appInfo = p.info.applicationInfo.toString();
12412                        pw.print("      applicationInfo="); pw.println(appInfo);
12413                    }
12414                }
12415            }
12416
12417            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12418                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12419            }
12420
12421            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12422                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12423            }
12424
12425            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12426                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12427            }
12428
12429            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12430                if (dumpState.onTitlePrinted()) pw.println();
12431                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12432            }
12433
12434            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12435                if (dumpState.onTitlePrinted()) pw.println();
12436                mSettings.dumpReadMessagesLPr(pw, dumpState);
12437
12438                pw.println();
12439                pw.println("Package warning messages:");
12440                final File fname = getSettingsProblemFile();
12441                FileInputStream in = null;
12442                try {
12443                    in = new FileInputStream(fname);
12444                    final int avail = in.available();
12445                    final byte[] data = new byte[avail];
12446                    in.read(data);
12447                    pw.print(new String(data));
12448                } catch (FileNotFoundException e) {
12449                } catch (IOException e) {
12450                } finally {
12451                    if (in != null) {
12452                        try {
12453                            in.close();
12454                        } catch (IOException e) {
12455                        }
12456                    }
12457                }
12458            }
12459        }
12460    }
12461
12462    // ------- apps on sdcard specific code -------
12463    static final boolean DEBUG_SD_INSTALL = false;
12464
12465    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12466
12467    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12468
12469    private boolean mMediaMounted = false;
12470
12471    static String getEncryptKey() {
12472        try {
12473            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12474                    SD_ENCRYPTION_KEYSTORE_NAME);
12475            if (sdEncKey == null) {
12476                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12477                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12478                if (sdEncKey == null) {
12479                    Slog.e(TAG, "Failed to create encryption keys");
12480                    return null;
12481                }
12482            }
12483            return sdEncKey;
12484        } catch (NoSuchAlgorithmException nsae) {
12485            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12486            return null;
12487        } catch (IOException ioe) {
12488            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12489            return null;
12490        }
12491    }
12492
12493    /*
12494     * Update media status on PackageManager.
12495     */
12496    @Override
12497    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12498        int callingUid = Binder.getCallingUid();
12499        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12500            throw new SecurityException("Media status can only be updated by the system");
12501        }
12502        // reader; this apparently protects mMediaMounted, but should probably
12503        // be a different lock in that case.
12504        synchronized (mPackages) {
12505            Log.i(TAG, "Updating external media status from "
12506                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12507                    + (mediaStatus ? "mounted" : "unmounted"));
12508            if (DEBUG_SD_INSTALL)
12509                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12510                        + ", mMediaMounted=" + mMediaMounted);
12511            if (mediaStatus == mMediaMounted) {
12512                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12513                        : 0, -1);
12514                mHandler.sendMessage(msg);
12515                return;
12516            }
12517            mMediaMounted = mediaStatus;
12518        }
12519        // Queue up an async operation since the package installation may take a
12520        // little while.
12521        mHandler.post(new Runnable() {
12522            public void run() {
12523                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12524            }
12525        });
12526    }
12527
12528    /**
12529     * Called by MountService when the initial ASECs to scan are available.
12530     * Should block until all the ASEC containers are finished being scanned.
12531     */
12532    public void scanAvailableAsecs() {
12533        updateExternalMediaStatusInner(true, false, false);
12534        if (mShouldRestoreconData) {
12535            SELinuxMMAC.setRestoreconDone();
12536            mShouldRestoreconData = false;
12537        }
12538    }
12539
12540    /*
12541     * Collect information of applications on external media, map them against
12542     * existing containers and update information based on current mount status.
12543     * Please note that we always have to report status if reportStatus has been
12544     * set to true especially when unloading packages.
12545     */
12546    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12547            boolean externalStorage) {
12548        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12549        int[] uidArr = EmptyArray.INT;
12550
12551        final String[] list = PackageHelper.getSecureContainerList();
12552        if (ArrayUtils.isEmpty(list)) {
12553            Log.i(TAG, "No secure containers found");
12554        } else {
12555            // Process list of secure containers and categorize them
12556            // as active or stale based on their package internal state.
12557
12558            // reader
12559            synchronized (mPackages) {
12560                for (String cid : list) {
12561                    // Leave stages untouched for now; installer service owns them
12562                    if (PackageInstallerService.isStageName(cid)) continue;
12563
12564                    if (DEBUG_SD_INSTALL)
12565                        Log.i(TAG, "Processing container " + cid);
12566                    String pkgName = getAsecPackageName(cid);
12567                    if (pkgName == null) {
12568                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12569                        continue;
12570                    }
12571                    if (DEBUG_SD_INSTALL)
12572                        Log.i(TAG, "Looking for pkg : " + pkgName);
12573
12574                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12575                    if (ps == null) {
12576                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12577                        continue;
12578                    }
12579
12580                    /*
12581                     * Skip packages that are not external if we're unmounting
12582                     * external storage.
12583                     */
12584                    if (externalStorage && !isMounted && !isExternal(ps)) {
12585                        continue;
12586                    }
12587
12588                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12589                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12590                    // The package status is changed only if the code path
12591                    // matches between settings and the container id.
12592                    if (ps.codePathString != null
12593                            && ps.codePathString.startsWith(args.getCodePath())) {
12594                        if (DEBUG_SD_INSTALL) {
12595                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12596                                    + " at code path: " + ps.codePathString);
12597                        }
12598
12599                        // We do have a valid package installed on sdcard
12600                        processCids.put(args, ps.codePathString);
12601                        final int uid = ps.appId;
12602                        if (uid != -1) {
12603                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12604                        }
12605                    } else {
12606                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12607                                + ps.codePathString);
12608                    }
12609                }
12610            }
12611
12612            Arrays.sort(uidArr);
12613        }
12614
12615        // Process packages with valid entries.
12616        if (isMounted) {
12617            if (DEBUG_SD_INSTALL)
12618                Log.i(TAG, "Loading packages");
12619            loadMediaPackages(processCids, uidArr);
12620            startCleaningPackages();
12621            mInstallerService.onSecureContainersAvailable();
12622        } else {
12623            if (DEBUG_SD_INSTALL)
12624                Log.i(TAG, "Unloading packages");
12625            unloadMediaPackages(processCids, uidArr, reportStatus);
12626        }
12627    }
12628
12629    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12630            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12631        int size = pkgList.size();
12632        if (size > 0) {
12633            // Send broadcasts here
12634            Bundle extras = new Bundle();
12635            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12636                    .toArray(new String[size]));
12637            if (uidArr != null) {
12638                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12639            }
12640            if (replacing) {
12641                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12642            }
12643            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12644                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12645            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12646        }
12647    }
12648
12649   /*
12650     * Look at potentially valid container ids from processCids If package
12651     * information doesn't match the one on record or package scanning fails,
12652     * the cid is added to list of removeCids. We currently don't delete stale
12653     * containers.
12654     */
12655    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12656        ArrayList<String> pkgList = new ArrayList<String>();
12657        Set<AsecInstallArgs> keys = processCids.keySet();
12658
12659        for (AsecInstallArgs args : keys) {
12660            String codePath = processCids.get(args);
12661            if (DEBUG_SD_INSTALL)
12662                Log.i(TAG, "Loading container : " + args.cid);
12663            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12664            try {
12665                // Make sure there are no container errors first.
12666                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12667                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12668                            + " when installing from sdcard");
12669                    continue;
12670                }
12671                // Check code path here.
12672                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12673                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12674                            + " does not match one in settings " + codePath);
12675                    continue;
12676                }
12677                // Parse package
12678                int parseFlags = mDefParseFlags;
12679                if (args.isExternal()) {
12680                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12681                }
12682                if (args.isFwdLocked()) {
12683                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12684                }
12685
12686                synchronized (mInstallLock) {
12687                    PackageParser.Package pkg = null;
12688                    try {
12689                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12690                    } catch (PackageManagerException e) {
12691                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12692                    }
12693                    // Scan the package
12694                    if (pkg != null) {
12695                        /*
12696                         * TODO why is the lock being held? doPostInstall is
12697                         * called in other places without the lock. This needs
12698                         * to be straightened out.
12699                         */
12700                        // writer
12701                        synchronized (mPackages) {
12702                            retCode = PackageManager.INSTALL_SUCCEEDED;
12703                            pkgList.add(pkg.packageName);
12704                            // Post process args
12705                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12706                                    pkg.applicationInfo.uid);
12707                        }
12708                    } else {
12709                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12710                    }
12711                }
12712
12713            } finally {
12714                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12715                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12716                }
12717            }
12718        }
12719        // writer
12720        synchronized (mPackages) {
12721            // If the platform SDK has changed since the last time we booted,
12722            // we need to re-grant app permission to catch any new ones that
12723            // appear. This is really a hack, and means that apps can in some
12724            // cases get permissions that the user didn't initially explicitly
12725            // allow... it would be nice to have some better way to handle
12726            // this situation.
12727            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12728            if (regrantPermissions)
12729                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12730                        + mSdkVersion + "; regranting permissions for external storage");
12731            mSettings.mExternalSdkPlatform = mSdkVersion;
12732
12733            // Make sure group IDs have been assigned, and any permission
12734            // changes in other apps are accounted for
12735            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12736                    | (regrantPermissions
12737                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12738                            : 0));
12739
12740            mSettings.updateExternalDatabaseVersion();
12741
12742            // can downgrade to reader
12743            // Persist settings
12744            mSettings.writeLPr();
12745        }
12746        // Send a broadcast to let everyone know we are done processing
12747        if (pkgList.size() > 0) {
12748            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12749        }
12750    }
12751
12752   /*
12753     * Utility method to unload a list of specified containers
12754     */
12755    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12756        // Just unmount all valid containers.
12757        for (AsecInstallArgs arg : cidArgs) {
12758            synchronized (mInstallLock) {
12759                arg.doPostDeleteLI(false);
12760           }
12761       }
12762   }
12763
12764    /*
12765     * Unload packages mounted on external media. This involves deleting package
12766     * data from internal structures, sending broadcasts about diabled packages,
12767     * gc'ing to free up references, unmounting all secure containers
12768     * corresponding to packages on external media, and posting a
12769     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12770     * that we always have to post this message if status has been requested no
12771     * matter what.
12772     */
12773    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12774            final boolean reportStatus) {
12775        if (DEBUG_SD_INSTALL)
12776            Log.i(TAG, "unloading media packages");
12777        ArrayList<String> pkgList = new ArrayList<String>();
12778        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12779        final Set<AsecInstallArgs> keys = processCids.keySet();
12780        for (AsecInstallArgs args : keys) {
12781            String pkgName = args.getPackageName();
12782            if (DEBUG_SD_INSTALL)
12783                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12784            // Delete package internally
12785            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12786            synchronized (mInstallLock) {
12787                boolean res = deletePackageLI(pkgName, null, false, null, null,
12788                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12789                if (res) {
12790                    pkgList.add(pkgName);
12791                } else {
12792                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12793                    failedList.add(args);
12794                }
12795            }
12796        }
12797
12798        // reader
12799        synchronized (mPackages) {
12800            // We didn't update the settings after removing each package;
12801            // write them now for all packages.
12802            mSettings.writeLPr();
12803        }
12804
12805        // We have to absolutely send UPDATED_MEDIA_STATUS only
12806        // after confirming that all the receivers processed the ordered
12807        // broadcast when packages get disabled, force a gc to clean things up.
12808        // and unload all the containers.
12809        if (pkgList.size() > 0) {
12810            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12811                    new IIntentReceiver.Stub() {
12812                public void performReceive(Intent intent, int resultCode, String data,
12813                        Bundle extras, boolean ordered, boolean sticky,
12814                        int sendingUser) throws RemoteException {
12815                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12816                            reportStatus ? 1 : 0, 1, keys);
12817                    mHandler.sendMessage(msg);
12818                }
12819            });
12820        } else {
12821            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12822                    keys);
12823            mHandler.sendMessage(msg);
12824        }
12825    }
12826
12827    /** Binder call */
12828    @Override
12829    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12830            final int flags) {
12831        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12832        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12833        int returnCode = PackageManager.MOVE_SUCCEEDED;
12834        int currInstallFlags = 0;
12835        int newInstallFlags = 0;
12836
12837        File codeFile = null;
12838        String installerPackageName = null;
12839        String packageAbiOverride = null;
12840
12841        // reader
12842        synchronized (mPackages) {
12843            final PackageParser.Package pkg = mPackages.get(packageName);
12844            final PackageSetting ps = mSettings.mPackages.get(packageName);
12845            if (pkg == null || ps == null) {
12846                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12847            } else {
12848                // Disable moving fwd locked apps and system packages
12849                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12850                    Slog.w(TAG, "Cannot move system application");
12851                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12852                } else if (pkg.mOperationPending) {
12853                    Slog.w(TAG, "Attempt to move package which has pending operations");
12854                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12855                } else {
12856                    // Find install location first
12857                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12858                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12859                        Slog.w(TAG, "Ambigous flags specified for move location.");
12860                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12861                    } else {
12862                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12863                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12864                        currInstallFlags = isExternal(pkg)
12865                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12866
12867                        if (newInstallFlags == currInstallFlags) {
12868                            Slog.w(TAG, "No move required. Trying to move to same location");
12869                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12870                        } else {
12871                            if (isForwardLocked(pkg)) {
12872                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12873                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12874                            }
12875                        }
12876                    }
12877                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12878                        pkg.mOperationPending = true;
12879                    }
12880                }
12881
12882                codeFile = new File(pkg.codePath);
12883                installerPackageName = ps.installerPackageName;
12884                packageAbiOverride = ps.cpuAbiOverrideString;
12885            }
12886        }
12887
12888        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12889            try {
12890                observer.packageMoved(packageName, returnCode);
12891            } catch (RemoteException ignored) {
12892            }
12893            return;
12894        }
12895
12896        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12897            @Override
12898            public void onUserActionRequired(Intent intent) throws RemoteException {
12899                throw new IllegalStateException();
12900            }
12901
12902            @Override
12903            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12904                    Bundle extras) throws RemoteException {
12905                Slog.d(TAG, "Install result for move: "
12906                        + PackageManager.installStatusToString(returnCode, msg));
12907
12908                // We usually have a new package now after the install, but if
12909                // we failed we need to clear the pending flag on the original
12910                // package object.
12911                synchronized (mPackages) {
12912                    final PackageParser.Package pkg = mPackages.get(packageName);
12913                    if (pkg != null) {
12914                        pkg.mOperationPending = false;
12915                    }
12916                }
12917
12918                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12919                switch (status) {
12920                    case PackageInstaller.STATUS_SUCCESS:
12921                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12922                        break;
12923                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12924                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12925                        break;
12926                    default:
12927                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12928                        break;
12929                }
12930            }
12931        };
12932
12933        // Treat a move like reinstalling an existing app, which ensures that we
12934        // process everythign uniformly, like unpacking native libraries.
12935        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12936
12937        final Message msg = mHandler.obtainMessage(INIT_COPY);
12938        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12939        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12940                installerPackageName, null, user, packageAbiOverride);
12941        mHandler.sendMessage(msg);
12942    }
12943
12944    @Override
12945    public boolean setInstallLocation(int loc) {
12946        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12947                null);
12948        if (getInstallLocation() == loc) {
12949            return true;
12950        }
12951        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12952                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12953            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12954                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12955            return true;
12956        }
12957        return false;
12958   }
12959
12960    @Override
12961    public int getInstallLocation() {
12962        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12963                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12964                PackageHelper.APP_INSTALL_AUTO);
12965    }
12966
12967    /** Called by UserManagerService */
12968    void cleanUpUserLILPw(int userHandle) {
12969        mDirtyUsers.remove(userHandle);
12970        mSettings.removeUserLPw(userHandle);
12971        mPendingBroadcasts.remove(userHandle);
12972        if (mInstaller != null) {
12973            // Technically, we shouldn't be doing this with the package lock
12974            // held.  However, this is very rare, and there is already so much
12975            // other disk I/O going on, that we'll let it slide for now.
12976            mInstaller.removeUserDataDirs(userHandle);
12977        }
12978        mUserNeedsBadging.delete(userHandle);
12979    }
12980
12981    /** Called by UserManagerService */
12982    void createNewUserLILPw(int userHandle, File path) {
12983        if (mInstaller != null) {
12984            mInstaller.createUserConfig(userHandle);
12985            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12986        }
12987    }
12988
12989    @Override
12990    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12991        mContext.enforceCallingOrSelfPermission(
12992                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12993                "Only package verification agents can read the verifier device identity");
12994
12995        synchronized (mPackages) {
12996            return mSettings.getVerifierDeviceIdentityLPw();
12997        }
12998    }
12999
13000    @Override
13001    public void setPermissionEnforced(String permission, boolean enforced) {
13002        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13003        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13004            synchronized (mPackages) {
13005                if (mSettings.mReadExternalStorageEnforced == null
13006                        || mSettings.mReadExternalStorageEnforced != enforced) {
13007                    mSettings.mReadExternalStorageEnforced = enforced;
13008                    mSettings.writeLPr();
13009                }
13010            }
13011            // kill any non-foreground processes so we restart them and
13012            // grant/revoke the GID.
13013            final IActivityManager am = ActivityManagerNative.getDefault();
13014            if (am != null) {
13015                final long token = Binder.clearCallingIdentity();
13016                try {
13017                    am.killProcessesBelowForeground("setPermissionEnforcement");
13018                } catch (RemoteException e) {
13019                } finally {
13020                    Binder.restoreCallingIdentity(token);
13021                }
13022            }
13023        } else {
13024            throw new IllegalArgumentException("No selective enforcement for " + permission);
13025        }
13026    }
13027
13028    @Override
13029    @Deprecated
13030    public boolean isPermissionEnforced(String permission) {
13031        return true;
13032    }
13033
13034    @Override
13035    public boolean isStorageLow() {
13036        final long token = Binder.clearCallingIdentity();
13037        try {
13038            final DeviceStorageMonitorInternal
13039                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13040            if (dsm != null) {
13041                return dsm.isMemoryLow();
13042            } else {
13043                return false;
13044            }
13045        } finally {
13046            Binder.restoreCallingIdentity(token);
13047        }
13048    }
13049
13050    @Override
13051    public IPackageInstaller getPackageInstaller() {
13052        return mInstallerService;
13053    }
13054
13055    private boolean userNeedsBadging(int userId) {
13056        int index = mUserNeedsBadging.indexOfKey(userId);
13057        if (index < 0) {
13058            final UserInfo userInfo;
13059            final long token = Binder.clearCallingIdentity();
13060            try {
13061                userInfo = sUserManager.getUserInfo(userId);
13062            } finally {
13063                Binder.restoreCallingIdentity(token);
13064            }
13065            final boolean b;
13066            if (userInfo != null && userInfo.isManagedProfile()) {
13067                b = true;
13068            } else {
13069                b = false;
13070            }
13071            mUserNeedsBadging.put(userId, b);
13072            return b;
13073        }
13074        return mUserNeedsBadging.valueAt(index);
13075    }
13076
13077    @Override
13078    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13079        if (packageName == null || alias == null) {
13080            return null;
13081        }
13082        synchronized(mPackages) {
13083            final PackageParser.Package pkg = mPackages.get(packageName);
13084            if (pkg == null) {
13085                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13086                throw new IllegalArgumentException("Unknown package: " + packageName);
13087            }
13088            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13089                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13090                throw new SecurityException("May not access KeySets defined by"
13091                        + " aliases in other applications.");
13092            }
13093            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13094            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13095        }
13096    }
13097
13098    @Override
13099    public KeySetHandle getSigningKeySet(String packageName) {
13100        if (packageName == null) {
13101            return null;
13102        }
13103        synchronized(mPackages) {
13104            final PackageParser.Package pkg = mPackages.get(packageName);
13105            if (pkg == null) {
13106                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13107                throw new IllegalArgumentException("Unknown package: " + packageName);
13108            }
13109            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13110                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13111                throw new SecurityException("May not access signing KeySet of other apps.");
13112            }
13113            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13114            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13115        }
13116    }
13117
13118    @Override
13119    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13120        if (packageName == null || ks == null) {
13121            return false;
13122        }
13123        synchronized(mPackages) {
13124            final PackageParser.Package pkg = mPackages.get(packageName);
13125            if (pkg == null) {
13126                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13127                throw new IllegalArgumentException("Unknown package: " + packageName);
13128            }
13129            if (ks instanceof KeySetHandle) {
13130                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13131                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13132            }
13133            return false;
13134        }
13135    }
13136
13137    @Override
13138    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13139        if (packageName == null || ks == null) {
13140            return false;
13141        }
13142        synchronized(mPackages) {
13143            final PackageParser.Package pkg = mPackages.get(packageName);
13144            if (pkg == null) {
13145                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13146                throw new IllegalArgumentException("Unknown package: " + packageName);
13147            }
13148            if (ks instanceof KeySetHandle) {
13149                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13150                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13151            }
13152            return false;
13153        }
13154    }
13155}
13156