PackageManagerService.java revision 6c0b9da65e36543bb50833d1b54ca532d0bd3aab
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 android.system.OsConstants.S_IRGRP;
52import static android.system.OsConstants.S_IROTH;
53import static android.system.OsConstants.S_IRWXU;
54import static android.system.OsConstants.S_IXGRP;
55import static android.system.OsConstants.S_IXOTH;
56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
58import static com.android.internal.util.ArrayUtils.appendInt;
59import static com.android.internal.util.ArrayUtils.removeInt;
60
61import android.util.ArrayMap;
62
63import com.android.internal.R;
64import com.android.internal.app.IMediaContainerService;
65import com.android.internal.app.ResolverActivity;
66import com.android.internal.content.NativeLibraryHelper;
67import com.android.internal.content.PackageHelper;
68import com.android.internal.os.IParcelFileDescriptorFactory;
69import com.android.internal.util.ArrayUtils;
70import com.android.internal.util.FastPrintWriter;
71import com.android.internal.util.FastXmlSerializer;
72import com.android.internal.util.IndentingPrintWriter;
73import com.android.internal.util.Preconditions;
74import com.android.server.EventLogTags;
75import com.android.server.IntentResolver;
76import com.android.server.LocalServices;
77import com.android.server.ServiceThread;
78import com.android.server.SystemConfig;
79import com.android.server.Watchdog;
80import com.android.server.pm.Settings.DatabaseVersion;
81import com.android.server.storage.DeviceStorageMonitorInternal;
82
83import org.xmlpull.v1.XmlSerializer;
84
85import android.app.ActivityManager;
86import android.app.ActivityManagerNative;
87import android.app.IActivityManager;
88import android.app.admin.IDevicePolicyManager;
89import android.app.backup.IBackupManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageDeleteObserver2;
105import android.content.pm.IPackageInstallObserver2;
106import android.content.pm.IPackageInstaller;
107import android.content.pm.IPackageManager;
108import android.content.pm.IPackageMoveObserver;
109import android.content.pm.IPackageStatsObserver;
110import android.content.pm.InstallSessionParams;
111import android.content.pm.InstrumentationInfo;
112import android.content.pm.ManifestDigest;
113import android.content.pm.PackageCleanItem;
114import android.content.pm.PackageInfo;
115import android.content.pm.PackageInfoLite;
116import android.content.pm.PackageManager;
117import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageParser;
122import android.content.pm.PackageStats;
123import android.content.pm.PackageUserState;
124import android.content.pm.ParceledListSlice;
125import android.content.pm.PermissionGroupInfo;
126import android.content.pm.PermissionInfo;
127import android.content.pm.ProviderInfo;
128import android.content.pm.ResolveInfo;
129import android.content.pm.ServiceInfo;
130import android.content.pm.Signature;
131import android.content.pm.UserInfo;
132import android.content.pm.VerificationParams;
133import android.content.pm.VerifierDeviceIdentity;
134import android.content.pm.VerifierInfo;
135import android.content.res.Resources;
136import android.hardware.display.DisplayManager;
137import android.net.Uri;
138import android.os.Binder;
139import android.os.Build;
140import android.os.Bundle;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.util.ArraySet;
165import android.util.AtomicFile;
166import android.util.DisplayMetrics;
167import android.util.EventLog;
168import android.util.ExceptionUtils;
169import android.util.Log;
170import android.util.LogPrinter;
171import android.util.PrintStreamPrinter;
172import android.util.Slog;
173import android.util.SparseArray;
174import android.util.SparseBooleanArray;
175import android.view.Display;
176
177import java.io.BufferedInputStream;
178import java.io.BufferedOutputStream;
179import java.io.File;
180import java.io.FileDescriptor;
181import java.io.FileInputStream;
182import java.io.FileNotFoundException;
183import java.io.FileOutputStream;
184import java.io.FilenameFilter;
185import java.io.IOException;
186import java.io.InputStream;
187import java.io.PrintWriter;
188import java.nio.charset.StandardCharsets;
189import java.security.NoSuchAlgorithmException;
190import java.security.PublicKey;
191import java.security.cert.CertificateEncodingException;
192import java.security.cert.CertificateException;
193import java.text.SimpleDateFormat;
194import java.util.ArrayList;
195import java.util.Arrays;
196import java.util.Collection;
197import java.util.Collections;
198import java.util.Comparator;
199import java.util.Date;
200import java.util.HashMap;
201import java.util.HashSet;
202import java.util.Iterator;
203import java.util.List;
204import java.util.Map;
205import java.util.Set;
206import java.util.concurrent.atomic.AtomicBoolean;
207import java.util.concurrent.atomic.AtomicLong;
208
209import dalvik.system.DexFile;
210import dalvik.system.StaleDexCacheError;
211import dalvik.system.VMRuntime;
212
213import libcore.io.IoUtils;
214
215/**
216 * Keep track of all those .apks everywhere.
217 *
218 * This is very central to the platform's security; please run the unit
219 * tests whenever making modifications here:
220 *
221mmm frameworks/base/tests/AndroidTests
222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
224 *
225 * {@hide}
226 */
227public class PackageManagerService extends IPackageManager.Stub {
228    static final String TAG = "PackageManager";
229    static final boolean DEBUG_SETTINGS = false;
230    static final boolean DEBUG_PREFERRED = false;
231    static final boolean DEBUG_UPGRADE = false;
232    private static final boolean DEBUG_INSTALL = false;
233    private static final boolean DEBUG_REMOVE = false;
234    private static final boolean DEBUG_BROADCASTS = false;
235    private static final boolean DEBUG_SHOW_INFO = false;
236    private static final boolean DEBUG_PACKAGE_INFO = false;
237    private static final boolean DEBUG_INTENT_MATCHING = false;
238    private static final boolean DEBUG_PACKAGE_SCANNING = false;
239    private static final boolean DEBUG_VERIFY = false;
240    private static final boolean DEBUG_DEXOPT = false;
241    private static final boolean DEBUG_ABI_SELECTION = false;
242
243    private static final int RADIO_UID = Process.PHONE_UID;
244    private static final int LOG_UID = Process.LOG_UID;
245    private static final int NFC_UID = Process.NFC_UID;
246    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
247    private static final int SHELL_UID = Process.SHELL_UID;
248
249    // Cap the size of permission trees that 3rd party apps can define
250    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
251
252    // Suffix used during package installation when copying/moving
253    // package apks to install directory.
254    private static final String INSTALL_PACKAGE_SUFFIX = "-";
255
256    static final int SCAN_MONITOR = 1<<0;
257    static final int SCAN_NO_DEX = 1<<1;
258    static final int SCAN_FORCE_DEX = 1<<2;
259    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
260    static final int SCAN_NEW_INSTALL = 1<<4;
261    static final int SCAN_NO_PATHS = 1<<5;
262    static final int SCAN_UPDATE_TIME = 1<<6;
263    static final int SCAN_DEFER_DEX = 1<<7;
264    static final int SCAN_BOOTING = 1<<8;
265    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
266    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
267
268    static final int REMOVE_CHATTY = 1<<16;
269
270    /**
271     * Timeout (in milliseconds) after which the watchdog should declare that
272     * our handler thread is wedged.  The usual default for such things is one
273     * minute but we sometimes do very lengthy I/O operations on this thread,
274     * such as installing multi-gigabyte applications, so ours needs to be longer.
275     */
276    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
277
278    /**
279     * Whether verification is enabled by default.
280     */
281    private static final boolean DEFAULT_VERIFY_ENABLE = true;
282
283    /**
284     * The default maximum time to wait for the verification agent to return in
285     * milliseconds.
286     */
287    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
288
289    /**
290     * The default response for package verification timeout.
291     *
292     * This can be either PackageManager.VERIFICATION_ALLOW or
293     * PackageManager.VERIFICATION_REJECT.
294     */
295    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
296
297    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
298
299    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
300            DEFAULT_CONTAINER_PACKAGE,
301            "com.android.defcontainer.DefaultContainerService");
302
303    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
304
305    private static final String LIB_DIR_NAME = "lib";
306    private static final String LIB64_DIR_NAME = "lib64";
307
308    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
309
310    static final String mTempContainerPrefix = "smdl2tmp";
311
312    private static String sPreferredInstructionSet;
313
314    final ServiceThread mHandlerThread;
315
316    private static final String IDMAP_PREFIX = "/data/resource-cache/";
317    private static final String IDMAP_SUFFIX = "@idmap";
318
319    final PackageHandler mHandler;
320
321    final int mSdkVersion = Build.VERSION.SDK_INT;
322
323    final Context mContext;
324    final boolean mFactoryTest;
325    final boolean mOnlyCore;
326    final DisplayMetrics mMetrics;
327    final int mDefParseFlags;
328    final String[] mSeparateProcesses;
329
330    // This is where all application persistent data goes.
331    final File mAppDataDir;
332
333    // This is where all application persistent data goes for secondary users.
334    final File mUserAppDataDir;
335
336    /** The location for ASEC container files on internal storage. */
337    final String mAsecInternalPath;
338
339    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
340    // LOCK HELD.  Can be called with mInstallLock held.
341    final Installer mInstaller;
342
343    /** Directory where installed third-party apps stored */
344    final File mAppInstallDir;
345
346    /**
347     * Directory to which applications installed internally have their
348     * 32 bit native libraries copied.
349     */
350    private File mAppLib32InstallDir;
351
352    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
353    // apps.
354    final File mDrmAppPrivateInstallDir;
355
356    // ----------------------------------------------------------------
357
358    // Lock for state used when installing and doing other long running
359    // operations.  Methods that must be called with this lock held have
360    // the suffix "LI".
361    final Object mInstallLock = new Object();
362
363    // These are the directories in the 3rd party applications installed dir
364    // that we have currently loaded packages from.  Keys are the application's
365    // installed zip file (absolute codePath), and values are Package.
366    final HashMap<String, PackageParser.Package> mAppDirs =
367            new HashMap<String, PackageParser.Package>();
368
369    // ----------------------------------------------------------------
370
371    // Keys are String (package name), values are Package.  This also serves
372    // as the lock for the global state.  Methods that must be called with
373    // this lock held have the prefix "LP".
374    final HashMap<String, PackageParser.Package> mPackages =
375            new HashMap<String, PackageParser.Package>();
376
377    // Tracks available target package names -> overlay package paths.
378    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
379        new HashMap<String, HashMap<String, PackageParser.Package>>();
380
381    final Settings mSettings;
382    boolean mRestoredSettings;
383
384    // System configuration read by SystemConfig.
385    final int[] mGlobalGids;
386    final SparseArray<HashSet<String>> mSystemPermissions;
387    final HashMap<String, FeatureInfo> mAvailableFeatures;
388
389    // If mac_permissions.xml was found for seinfo labeling.
390    boolean mFoundPolicyFile;
391
392    // If a recursive restorecon of /data/data/<pkg> is needed.
393    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
394
395    public static final class SharedLibraryEntry {
396        public final String path;
397        public final String apk;
398
399        SharedLibraryEntry(String _path, String _apk) {
400            path = _path;
401            apk = _apk;
402        }
403    }
404
405    // Currently known shared libraries.
406    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
407            new HashMap<String, SharedLibraryEntry>();
408
409    // All available activities, for your resolving pleasure.
410    final ActivityIntentResolver mActivities =
411            new ActivityIntentResolver();
412
413    // All available receivers, for your resolving pleasure.
414    final ActivityIntentResolver mReceivers =
415            new ActivityIntentResolver();
416
417    // All available services, for your resolving pleasure.
418    final ServiceIntentResolver mServices = new ServiceIntentResolver();
419
420    // All available providers, for your resolving pleasure.
421    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
422
423    // Mapping from provider base names (first directory in content URI codePath)
424    // to the provider information.
425    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
426            new HashMap<String, PackageParser.Provider>();
427
428    // Mapping from instrumentation class names to info about them.
429    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
430            new HashMap<ComponentName, PackageParser.Instrumentation>();
431
432    // Mapping from permission names to info about them.
433    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
434            new HashMap<String, PackageParser.PermissionGroup>();
435
436    // Packages whose data we have transfered into another package, thus
437    // should no longer exist.
438    final HashSet<String> mTransferedPackages = new HashSet<String>();
439
440    // Broadcast actions that are only available to the system.
441    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
442
443    /** List of packages waiting for verification. */
444    final SparseArray<PackageVerificationState> mPendingVerification
445            = new SparseArray<PackageVerificationState>();
446
447    /** Set of packages associated with each app op permission. */
448    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
449
450    final PackageInstallerService mInstallerService;
451
452    HashSet<PackageParser.Package> mDeferredDexOpt = null;
453
454    // Cache of users who need badging.
455    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
456
457    /** Token for keys in mPendingVerification. */
458    private int mPendingVerificationToken = 0;
459
460    boolean mSystemReady;
461    boolean mSafeMode;
462    boolean mHasSystemUidErrors;
463
464    ApplicationInfo mAndroidApplication;
465    final ActivityInfo mResolveActivity = new ActivityInfo();
466    final ResolveInfo mResolveInfo = new ResolveInfo();
467    ComponentName mResolveComponentName;
468    PackageParser.Package mPlatformPackage;
469    ComponentName mCustomResolverComponentName;
470
471    boolean mResolverReplaced = false;
472
473    // Set of pending broadcasts for aggregating enable/disable of components.
474    static class PendingPackageBroadcasts {
475        // for each user id, a map of <package name -> components within that package>
476        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
477
478        public PendingPackageBroadcasts() {
479            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
480        }
481
482        public ArrayList<String> get(int userId, String packageName) {
483            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
484            return packages.get(packageName);
485        }
486
487        public void put(int userId, String packageName, ArrayList<String> components) {
488            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
489            packages.put(packageName, components);
490        }
491
492        public void remove(int userId, String packageName) {
493            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
494            if (packages != null) {
495                packages.remove(packageName);
496            }
497        }
498
499        public void remove(int userId) {
500            mUidMap.remove(userId);
501        }
502
503        public int userIdCount() {
504            return mUidMap.size();
505        }
506
507        public int userIdAt(int n) {
508            return mUidMap.keyAt(n);
509        }
510
511        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
512            return mUidMap.get(userId);
513        }
514
515        public int size() {
516            // total number of pending broadcast entries across all userIds
517            int num = 0;
518            for (int i = 0; i< mUidMap.size(); i++) {
519                num += mUidMap.valueAt(i).size();
520            }
521            return num;
522        }
523
524        public void clear() {
525            mUidMap.clear();
526        }
527
528        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
529            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
530            if (map == null) {
531                map = new HashMap<String, ArrayList<String>>();
532                mUidMap.put(userId, map);
533            }
534            return map;
535        }
536    }
537    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
538
539    // Service Connection to remote media container service to copy
540    // package uri's from external media onto secure containers
541    // or internal storage.
542    private IMediaContainerService mContainerService = null;
543
544    static final int SEND_PENDING_BROADCAST = 1;
545    static final int MCS_BOUND = 3;
546    static final int END_COPY = 4;
547    static final int INIT_COPY = 5;
548    static final int MCS_UNBIND = 6;
549    static final int START_CLEANING_PACKAGE = 7;
550    static final int FIND_INSTALL_LOC = 8;
551    static final int POST_INSTALL = 9;
552    static final int MCS_RECONNECT = 10;
553    static final int MCS_GIVE_UP = 11;
554    static final int UPDATED_MEDIA_STATUS = 12;
555    static final int WRITE_SETTINGS = 13;
556    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
557    static final int PACKAGE_VERIFIED = 15;
558    static final int CHECK_PENDING_VERIFICATION = 16;
559
560    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
561
562    // Delay time in millisecs
563    static final int BROADCAST_DELAY = 10 * 1000;
564
565    static UserManagerService sUserManager;
566
567    // Stores a list of users whose package restrictions file needs to be updated
568    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
569
570    final private DefaultContainerConnection mDefContainerConn =
571            new DefaultContainerConnection();
572    class DefaultContainerConnection implements ServiceConnection {
573        public void onServiceConnected(ComponentName name, IBinder service) {
574            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
575            IMediaContainerService imcs =
576                IMediaContainerService.Stub.asInterface(service);
577            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
578        }
579
580        public void onServiceDisconnected(ComponentName name) {
581            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
582        }
583    };
584
585    // Recordkeeping of restore-after-install operations that are currently in flight
586    // between the Package Manager and the Backup Manager
587    class PostInstallData {
588        public InstallArgs args;
589        public PackageInstalledInfo res;
590
591        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
592            args = _a;
593            res = _r;
594        }
595    };
596    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
597    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
598
599    private final String mRequiredVerifierPackage;
600
601    private final PackageUsage mPackageUsage = new PackageUsage();
602
603    private class PackageUsage {
604        private static final int WRITE_INTERVAL
605            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
606
607        private final Object mFileLock = new Object();
608        private final AtomicLong mLastWritten = new AtomicLong(0);
609        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
610
611        private boolean mIsHistoricalPackageUsageAvailable = true;
612
613        boolean isHistoricalPackageUsageAvailable() {
614            return mIsHistoricalPackageUsageAvailable;
615        }
616
617        void write(boolean force) {
618            if (force) {
619                writeInternal();
620                return;
621            }
622            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
623                && !DEBUG_DEXOPT) {
624                return;
625            }
626            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
627                new Thread("PackageUsage_DiskWriter") {
628                    @Override
629                    public void run() {
630                        try {
631                            writeInternal();
632                        } finally {
633                            mBackgroundWriteRunning.set(false);
634                        }
635                    }
636                }.start();
637            }
638        }
639
640        private void writeInternal() {
641            synchronized (mPackages) {
642                synchronized (mFileLock) {
643                    AtomicFile file = getFile();
644                    FileOutputStream f = null;
645                    try {
646                        f = file.startWrite();
647                        BufferedOutputStream out = new BufferedOutputStream(f);
648                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
649                        StringBuilder sb = new StringBuilder();
650                        for (PackageParser.Package pkg : mPackages.values()) {
651                            if (pkg.mLastPackageUsageTimeInMills == 0) {
652                                continue;
653                            }
654                            sb.setLength(0);
655                            sb.append(pkg.packageName);
656                            sb.append(' ');
657                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
658                            sb.append('\n');
659                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
660                        }
661                        out.flush();
662                        file.finishWrite(f);
663                    } catch (IOException e) {
664                        if (f != null) {
665                            file.failWrite(f);
666                        }
667                        Log.e(TAG, "Failed to write package usage times", e);
668                    }
669                }
670            }
671            mLastWritten.set(SystemClock.elapsedRealtime());
672        }
673
674        void readLP() {
675            synchronized (mFileLock) {
676                AtomicFile file = getFile();
677                BufferedInputStream in = null;
678                try {
679                    in = new BufferedInputStream(file.openRead());
680                    StringBuffer sb = new StringBuffer();
681                    while (true) {
682                        String packageName = readToken(in, sb, ' ');
683                        if (packageName == null) {
684                            break;
685                        }
686                        String timeInMillisString = readToken(in, sb, '\n');
687                        if (timeInMillisString == null) {
688                            throw new IOException("Failed to find last usage time for package "
689                                                  + packageName);
690                        }
691                        PackageParser.Package pkg = mPackages.get(packageName);
692                        if (pkg == null) {
693                            continue;
694                        }
695                        long timeInMillis;
696                        try {
697                            timeInMillis = Long.parseLong(timeInMillisString.toString());
698                        } catch (NumberFormatException e) {
699                            throw new IOException("Failed to parse " + timeInMillisString
700                                                  + " as a long.", e);
701                        }
702                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
703                    }
704                } catch (FileNotFoundException expected) {
705                    mIsHistoricalPackageUsageAvailable = false;
706                } catch (IOException e) {
707                    Log.w(TAG, "Failed to read package usage times", e);
708                } finally {
709                    IoUtils.closeQuietly(in);
710                }
711            }
712            mLastWritten.set(SystemClock.elapsedRealtime());
713        }
714
715        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
716                throws IOException {
717            sb.setLength(0);
718            while (true) {
719                int ch = in.read();
720                if (ch == -1) {
721                    if (sb.length() == 0) {
722                        return null;
723                    }
724                    throw new IOException("Unexpected EOF");
725                }
726                if (ch == endOfToken) {
727                    return sb.toString();
728                }
729                sb.append((char)ch);
730            }
731        }
732
733        private AtomicFile getFile() {
734            File dataDir = Environment.getDataDirectory();
735            File systemDir = new File(dataDir, "system");
736            File fname = new File(systemDir, "package-usage.list");
737            return new AtomicFile(fname);
738        }
739    }
740
741    class PackageHandler extends Handler {
742        private boolean mBound = false;
743        final ArrayList<HandlerParams> mPendingInstalls =
744            new ArrayList<HandlerParams>();
745
746        private boolean connectToService() {
747            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
748                    " DefaultContainerService");
749            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
750            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
751            if (mContext.bindServiceAsUser(service, mDefContainerConn,
752                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
753                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754                mBound = true;
755                return true;
756            }
757            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
758            return false;
759        }
760
761        private void disconnectService() {
762            mContainerService = null;
763            mBound = false;
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            mContext.unbindService(mDefContainerConn);
766            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767        }
768
769        PackageHandler(Looper looper) {
770            super(looper);
771        }
772
773        public void handleMessage(Message msg) {
774            try {
775                doHandleMessage(msg);
776            } finally {
777                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
778            }
779        }
780
781        void doHandleMessage(Message msg) {
782            switch (msg.what) {
783                case INIT_COPY: {
784                    HandlerParams params = (HandlerParams) msg.obj;
785                    int idx = mPendingInstalls.size();
786                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
787                    // If a bind was already initiated we dont really
788                    // need to do anything. The pending install
789                    // will be processed later on.
790                    if (!mBound) {
791                        // If this is the only one pending we might
792                        // have to bind to the service again.
793                        if (!connectToService()) {
794                            Slog.e(TAG, "Failed to bind to media container service");
795                            params.serviceError();
796                            return;
797                        } else {
798                            // Once we bind to the service, the first
799                            // pending request will be processed.
800                            mPendingInstalls.add(idx, params);
801                        }
802                    } else {
803                        mPendingInstalls.add(idx, params);
804                        // Already bound to the service. Just make
805                        // sure we trigger off processing the first request.
806                        if (idx == 0) {
807                            mHandler.sendEmptyMessage(MCS_BOUND);
808                        }
809                    }
810                    break;
811                }
812                case MCS_BOUND: {
813                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
814                    if (msg.obj != null) {
815                        mContainerService = (IMediaContainerService) msg.obj;
816                    }
817                    if (mContainerService == null) {
818                        // Something seriously wrong. Bail out
819                        Slog.e(TAG, "Cannot bind to media container service");
820                        for (HandlerParams params : mPendingInstalls) {
821                            // Indicate service bind error
822                            params.serviceError();
823                        }
824                        mPendingInstalls.clear();
825                    } else if (mPendingInstalls.size() > 0) {
826                        HandlerParams params = mPendingInstalls.get(0);
827                        if (params != null) {
828                            if (params.startCopy()) {
829                                // We are done...  look for more work or to
830                                // go idle.
831                                if (DEBUG_SD_INSTALL) Log.i(TAG,
832                                        "Checking for more work or unbind...");
833                                // Delete pending install
834                                if (mPendingInstalls.size() > 0) {
835                                    mPendingInstalls.remove(0);
836                                }
837                                if (mPendingInstalls.size() == 0) {
838                                    if (mBound) {
839                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
840                                                "Posting delayed MCS_UNBIND");
841                                        removeMessages(MCS_UNBIND);
842                                        Message ubmsg = obtainMessage(MCS_UNBIND);
843                                        // Unbind after a little delay, to avoid
844                                        // continual thrashing.
845                                        sendMessageDelayed(ubmsg, 10000);
846                                    }
847                                } else {
848                                    // There are more pending requests in queue.
849                                    // Just post MCS_BOUND message to trigger processing
850                                    // of next pending install.
851                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
852                                            "Posting MCS_BOUND for next work");
853                                    mHandler.sendEmptyMessage(MCS_BOUND);
854                                }
855                            }
856                        }
857                    } else {
858                        // Should never happen ideally.
859                        Slog.w(TAG, "Empty queue");
860                    }
861                    break;
862                }
863                case MCS_RECONNECT: {
864                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
865                    if (mPendingInstalls.size() > 0) {
866                        if (mBound) {
867                            disconnectService();
868                        }
869                        if (!connectToService()) {
870                            Slog.e(TAG, "Failed to bind to media container service");
871                            for (HandlerParams params : mPendingInstalls) {
872                                // Indicate service bind error
873                                params.serviceError();
874                            }
875                            mPendingInstalls.clear();
876                        }
877                    }
878                    break;
879                }
880                case MCS_UNBIND: {
881                    // If there is no actual work left, then time to unbind.
882                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
883
884                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
885                        if (mBound) {
886                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
887
888                            disconnectService();
889                        }
890                    } else if (mPendingInstalls.size() > 0) {
891                        // There are more pending requests in queue.
892                        // Just post MCS_BOUND message to trigger processing
893                        // of next pending install.
894                        mHandler.sendEmptyMessage(MCS_BOUND);
895                    }
896
897                    break;
898                }
899                case MCS_GIVE_UP: {
900                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
901                    mPendingInstalls.remove(0);
902                    break;
903                }
904                case SEND_PENDING_BROADCAST: {
905                    String packages[];
906                    ArrayList<String> components[];
907                    int size = 0;
908                    int uids[];
909                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
910                    synchronized (mPackages) {
911                        if (mPendingBroadcasts == null) {
912                            return;
913                        }
914                        size = mPendingBroadcasts.size();
915                        if (size <= 0) {
916                            // Nothing to be done. Just return
917                            return;
918                        }
919                        packages = new String[size];
920                        components = new ArrayList[size];
921                        uids = new int[size];
922                        int i = 0;  // filling out the above arrays
923
924                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
925                            int packageUserId = mPendingBroadcasts.userIdAt(n);
926                            Iterator<Map.Entry<String, ArrayList<String>>> it
927                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
928                                            .entrySet().iterator();
929                            while (it.hasNext() && i < size) {
930                                Map.Entry<String, ArrayList<String>> ent = it.next();
931                                packages[i] = ent.getKey();
932                                components[i] = ent.getValue();
933                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
934                                uids[i] = (ps != null)
935                                        ? UserHandle.getUid(packageUserId, ps.appId)
936                                        : -1;
937                                i++;
938                            }
939                        }
940                        size = i;
941                        mPendingBroadcasts.clear();
942                    }
943                    // Send broadcasts
944                    for (int i = 0; i < size; i++) {
945                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
946                    }
947                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
948                    break;
949                }
950                case START_CLEANING_PACKAGE: {
951                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
952                    final String packageName = (String)msg.obj;
953                    final int userId = msg.arg1;
954                    final boolean andCode = msg.arg2 != 0;
955                    synchronized (mPackages) {
956                        if (userId == UserHandle.USER_ALL) {
957                            int[] users = sUserManager.getUserIds();
958                            for (int user : users) {
959                                mSettings.addPackageToCleanLPw(
960                                        new PackageCleanItem(user, packageName, andCode));
961                            }
962                        } else {
963                            mSettings.addPackageToCleanLPw(
964                                    new PackageCleanItem(userId, packageName, andCode));
965                        }
966                    }
967                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
968                    startCleaningPackages();
969                } break;
970                case POST_INSTALL: {
971                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
972                    PostInstallData data = mRunningInstalls.get(msg.arg1);
973                    mRunningInstalls.delete(msg.arg1);
974                    boolean deleteOld = false;
975
976                    if (data != null) {
977                        InstallArgs args = data.args;
978                        PackageInstalledInfo res = data.res;
979
980                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
981                            res.removedInfo.sendBroadcast(false, true, false);
982                            Bundle extras = new Bundle(1);
983                            extras.putInt(Intent.EXTRA_UID, res.uid);
984                            // Determine the set of users who are adding this
985                            // package for the first time vs. those who are seeing
986                            // an update.
987                            int[] firstUsers;
988                            int[] updateUsers = new int[0];
989                            if (res.origUsers == null || res.origUsers.length == 0) {
990                                firstUsers = res.newUsers;
991                            } else {
992                                firstUsers = new int[0];
993                                for (int i=0; i<res.newUsers.length; i++) {
994                                    int user = res.newUsers[i];
995                                    boolean isNew = true;
996                                    for (int j=0; j<res.origUsers.length; j++) {
997                                        if (res.origUsers[j] == user) {
998                                            isNew = false;
999                                            break;
1000                                        }
1001                                    }
1002                                    if (isNew) {
1003                                        int[] newFirst = new int[firstUsers.length+1];
1004                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1005                                                firstUsers.length);
1006                                        newFirst[firstUsers.length] = user;
1007                                        firstUsers = newFirst;
1008                                    } else {
1009                                        int[] newUpdate = new int[updateUsers.length+1];
1010                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1011                                                updateUsers.length);
1012                                        newUpdate[updateUsers.length] = user;
1013                                        updateUsers = newUpdate;
1014                                    }
1015                                }
1016                            }
1017                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1018                                    res.pkg.applicationInfo.packageName,
1019                                    extras, null, null, firstUsers);
1020                            final boolean update = res.removedInfo.removedPackage != null;
1021                            if (update) {
1022                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1023                            }
1024                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1025                                    res.pkg.applicationInfo.packageName,
1026                                    extras, null, null, updateUsers);
1027                            if (update) {
1028                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1029                                        res.pkg.applicationInfo.packageName,
1030                                        extras, null, null, updateUsers);
1031                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1032                                        null, null,
1033                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1034
1035                                // treat asec-hosted packages like removable media on upgrade
1036                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1037                                    if (DEBUG_INSTALL) {
1038                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1039                                                + " is ASEC-hosted -> AVAILABLE");
1040                                    }
1041                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1042                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1043                                    pkgList.add(res.pkg.applicationInfo.packageName);
1044                                    sendResourcesChangedBroadcast(true, true,
1045                                            pkgList,uidArray, null);
1046                                }
1047                            }
1048                            if (res.removedInfo.args != null) {
1049                                // Remove the replaced package's older resources safely now
1050                                deleteOld = true;
1051                            }
1052
1053                            // Log current value of "unknown sources" setting
1054                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1055                                getUnknownSourcesSettings());
1056                        }
1057                        // Force a gc to clear up things
1058                        Runtime.getRuntime().gc();
1059                        // We delete after a gc for applications  on sdcard.
1060                        if (deleteOld) {
1061                            synchronized (mInstallLock) {
1062                                res.removedInfo.args.doPostDeleteLI(true);
1063                            }
1064                        }
1065                        if (args.observer != null) {
1066                            try {
1067                                Bundle extras = extrasForInstallResult(res);
1068                                args.observer.onPackageInstalled(res.name, res.returnCode,
1069                                        res.returnMsg, extras);
1070                            } catch (RemoteException e) {
1071                                Slog.i(TAG, "Observer no longer exists.");
1072                            }
1073                        }
1074                    } else {
1075                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1076                    }
1077                } break;
1078                case UPDATED_MEDIA_STATUS: {
1079                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1080                    boolean reportStatus = msg.arg1 == 1;
1081                    boolean doGc = msg.arg2 == 1;
1082                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1083                    if (doGc) {
1084                        // Force a gc to clear up stale containers.
1085                        Runtime.getRuntime().gc();
1086                    }
1087                    if (msg.obj != null) {
1088                        @SuppressWarnings("unchecked")
1089                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1090                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1091                        // Unload containers
1092                        unloadAllContainers(args);
1093                    }
1094                    if (reportStatus) {
1095                        try {
1096                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1097                            PackageHelper.getMountService().finishMediaUpdate();
1098                        } catch (RemoteException e) {
1099                            Log.e(TAG, "MountService not running?");
1100                        }
1101                    }
1102                } break;
1103                case WRITE_SETTINGS: {
1104                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1105                    synchronized (mPackages) {
1106                        removeMessages(WRITE_SETTINGS);
1107                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1108                        mSettings.writeLPr();
1109                        mDirtyUsers.clear();
1110                    }
1111                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                } break;
1113                case WRITE_PACKAGE_RESTRICTIONS: {
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1115                    synchronized (mPackages) {
1116                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1117                        for (int userId : mDirtyUsers) {
1118                            mSettings.writePackageRestrictionsLPr(userId);
1119                        }
1120                        mDirtyUsers.clear();
1121                    }
1122                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1123                } break;
1124                case CHECK_PENDING_VERIFICATION: {
1125                    final int verificationId = msg.arg1;
1126                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1127
1128                    if ((state != null) && !state.timeoutExtended()) {
1129                        final InstallArgs args = state.getInstallArgs();
1130                        final Uri originUri = Uri.fromFile(args.originFile);
1131
1132                        Slog.i(TAG, "Verification timed out for " + originUri);
1133                        mPendingVerification.remove(verificationId);
1134
1135                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1136
1137                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1138                            Slog.i(TAG, "Continuing with installation of " + originUri);
1139                            state.setVerifierResponse(Binder.getCallingUid(),
1140                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1141                            broadcastPackageVerified(verificationId, originUri,
1142                                    PackageManager.VERIFICATION_ALLOW,
1143                                    state.getInstallArgs().getUser());
1144                            try {
1145                                ret = args.copyApk(mContainerService, true);
1146                            } catch (RemoteException e) {
1147                                Slog.e(TAG, "Could not contact the ContainerService");
1148                            }
1149                        } else {
1150                            broadcastPackageVerified(verificationId, originUri,
1151                                    PackageManager.VERIFICATION_REJECT,
1152                                    state.getInstallArgs().getUser());
1153                        }
1154
1155                        processPendingInstall(args, ret);
1156                        mHandler.sendEmptyMessage(MCS_UNBIND);
1157                    }
1158                    break;
1159                }
1160                case PACKAGE_VERIFIED: {
1161                    final int verificationId = msg.arg1;
1162
1163                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1164                    if (state == null) {
1165                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1166                        break;
1167                    }
1168
1169                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1170
1171                    state.setVerifierResponse(response.callerUid, response.code);
1172
1173                    if (state.isVerificationComplete()) {
1174                        mPendingVerification.remove(verificationId);
1175
1176                        final InstallArgs args = state.getInstallArgs();
1177                        final Uri originUri = Uri.fromFile(args.originFile);
1178
1179                        int ret;
1180                        if (state.isInstallAllowed()) {
1181                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1182                            broadcastPackageVerified(verificationId, originUri,
1183                                    response.code, state.getInstallArgs().getUser());
1184                            try {
1185                                ret = args.copyApk(mContainerService, true);
1186                            } catch (RemoteException e) {
1187                                Slog.e(TAG, "Could not contact the ContainerService");
1188                            }
1189                        } else {
1190                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1191                        }
1192
1193                        processPendingInstall(args, ret);
1194
1195                        mHandler.sendEmptyMessage(MCS_UNBIND);
1196                    }
1197
1198                    break;
1199                }
1200            }
1201        }
1202    }
1203
1204    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1205        Bundle extras = null;
1206        switch (res.returnCode) {
1207            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1208                extras = new Bundle();
1209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1210                        res.origPermission);
1211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1212                        res.origPackage);
1213                break;
1214            }
1215        }
1216        return extras;
1217    }
1218
1219    void scheduleWriteSettingsLocked() {
1220        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1221            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1222        }
1223    }
1224
1225    void scheduleWritePackageRestrictionsLocked(int userId) {
1226        if (!sUserManager.exists(userId)) return;
1227        mDirtyUsers.add(userId);
1228        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1229            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1230        }
1231    }
1232
1233    public static final PackageManagerService main(Context context, Installer installer,
1234            boolean factoryTest, boolean onlyCore) {
1235        PackageManagerService m = new PackageManagerService(context, installer,
1236                factoryTest, onlyCore);
1237        ServiceManager.addService("package", m);
1238        return m;
1239    }
1240
1241    static String[] splitString(String str, char sep) {
1242        int count = 1;
1243        int i = 0;
1244        while ((i=str.indexOf(sep, i)) >= 0) {
1245            count++;
1246            i++;
1247        }
1248
1249        String[] res = new String[count];
1250        i=0;
1251        count = 0;
1252        int lastI=0;
1253        while ((i=str.indexOf(sep, i)) >= 0) {
1254            res[count] = str.substring(lastI, i);
1255            count++;
1256            i++;
1257            lastI = i;
1258        }
1259        res[count] = str.substring(lastI, str.length());
1260        return res;
1261    }
1262
1263    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1264        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1265                Context.DISPLAY_SERVICE);
1266        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1267    }
1268
1269    public PackageManagerService(Context context, Installer installer,
1270            boolean factoryTest, boolean onlyCore) {
1271        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1272                SystemClock.uptimeMillis());
1273
1274        if (mSdkVersion <= 0) {
1275            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1276        }
1277
1278        mContext = context;
1279        mFactoryTest = factoryTest;
1280        mOnlyCore = onlyCore;
1281        mMetrics = new DisplayMetrics();
1282        mSettings = new Settings(context);
1283        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295
1296        String separateProcesses = SystemProperties.get("debug.separate_processes");
1297        if (separateProcesses != null && separateProcesses.length() > 0) {
1298            if ("*".equals(separateProcesses)) {
1299                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1300                mSeparateProcesses = null;
1301                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1302            } else {
1303                mDefParseFlags = 0;
1304                mSeparateProcesses = separateProcesses.split(",");
1305                Slog.w(TAG, "Running with debug.separate_processes: "
1306                        + separateProcesses);
1307            }
1308        } else {
1309            mDefParseFlags = 0;
1310            mSeparateProcesses = null;
1311        }
1312
1313        mInstaller = installer;
1314
1315        getDefaultDisplayMetrics(context, mMetrics);
1316
1317        SystemConfig systemConfig = SystemConfig.getInstance();
1318        mGlobalGids = systemConfig.getGlobalGids();
1319        mSystemPermissions = systemConfig.getSystemPermissions();
1320        mAvailableFeatures = systemConfig.getAvailableFeatures();
1321
1322        synchronized (mInstallLock) {
1323        // writer
1324        synchronized (mPackages) {
1325            mHandlerThread = new ServiceThread(TAG,
1326                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1327            mHandlerThread.start();
1328            mHandler = new PackageHandler(mHandlerThread.getLooper());
1329            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1330
1331            File dataDir = Environment.getDataDirectory();
1332            mAppDataDir = new File(dataDir, "data");
1333            mAppInstallDir = new File(dataDir, "app");
1334            mAppLib32InstallDir = new File(dataDir, "app-lib");
1335            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1336            mUserAppDataDir = new File(dataDir, "user");
1337            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1338
1339            sUserManager = new UserManagerService(context, this,
1340                    mInstallLock, mPackages);
1341
1342            // Propagate permission configuration in to package manager.
1343            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1344                    = systemConfig.getPermissions();
1345            for (int i=0; i<permConfig.size(); i++) {
1346                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1347                BasePermission bp = mSettings.mPermissions.get(perm.name);
1348                if (bp == null) {
1349                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1350                    mSettings.mPermissions.put(perm.name, bp);
1351                }
1352                if (perm.gids != null) {
1353                    bp.gids = appendInts(bp.gids, perm.gids);
1354                }
1355            }
1356
1357            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1358            for (int i=0; i<libConfig.size(); i++) {
1359                mSharedLibraries.put(libConfig.keyAt(i),
1360                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1361            }
1362
1363            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1364
1365            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1366                    mSdkVersion, mOnlyCore);
1367
1368            String customResolverActivity = Resources.getSystem().getString(
1369                    R.string.config_customResolverActivity);
1370            if (TextUtils.isEmpty(customResolverActivity)) {
1371                customResolverActivity = null;
1372            } else {
1373                mCustomResolverComponentName = ComponentName.unflattenFromString(
1374                        customResolverActivity);
1375            }
1376
1377            long startTime = SystemClock.uptimeMillis();
1378
1379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1380                    startTime);
1381
1382            // Set flag to monitor and not change apk file paths when
1383            // scanning install directories.
1384            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1385
1386            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1387
1388            /**
1389             * Add everything in the in the boot class path to the
1390             * list of process files because dexopt will have been run
1391             * if necessary during zygote startup.
1392             */
1393            String bootClassPath = System.getProperty("java.boot.class.path");
1394            if (bootClassPath != null) {
1395                String[] paths = splitString(bootClassPath, ':');
1396                for (int i=0; i<paths.length; i++) {
1397                    alreadyDexOpted.add(paths[i]);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            boolean didDexOptLibraryOrTool = false;
1404
1405            final List<String> instructionSets = getAllInstructionSets();
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 instructionSet : instructionSets) {
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                                                                                 instructionSet,
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, instructionSet);
1432                                } else {
1433                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, instructionSet);
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 instructionSet : instructionSets) {
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                                                                                 instructionSet,
1483                                                                                 false);
1484                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1485                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1486                                didDexOptLibraryOrTool = true;
1487                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1488                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, instructionSet);
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            if (didDexOptLibraryOrTool) {
1501                // If we dexopted a library or tool, then something on the system has
1502                // changed. Consider this significant, and wipe away all other
1503                // existing dexopt files to ensure we don't leave any dangling around.
1504                //
1505                // TODO: This should be revisited because it isn't as good an indicator
1506                // as it used to be. It used to include the boot classpath but at some point
1507                // DexFile.isDexOptNeeded started returning false for the boot
1508                // class path files in all cases. It is very possible in a
1509                // small maintenance release update that the library and tool
1510                // jars may be unchanged but APK could be removed resulting in
1511                // unused dalvik-cache files.
1512                for (String instructionSet : instructionSets) {
1513                    mInstaller.pruneDexCache(instructionSet);
1514                }
1515
1516                // Additionally, delete all dex files from the root directory
1517                // since there shouldn't be any there anyway, unless we're upgrading
1518                // from an older OS version or a build that contained the "old" style
1519                // flat scheme.
1520                mInstaller.pruneDexCache(".");
1521            }
1522
1523            // Collect vendor overlay packages.
1524            // (Do this before scanning any apps.)
1525            // For security and version matching reason, only consider
1526            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1527            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1528            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1529                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1530
1531            // Find base frameworks (resource packages without code).
1532            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1533                    | PackageParser.PARSE_IS_SYSTEM_DIR
1534                    | PackageParser.PARSE_IS_PRIVILEGED,
1535                    scanMode | SCAN_NO_DEX, 0);
1536
1537            // Collected privileged system packages.
1538            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1539            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1540                    | PackageParser.PARSE_IS_SYSTEM_DIR
1541                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1542
1543            // Collect ordinary system packages.
1544            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1545            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1547
1548            // Collect all vendor packages.
1549            File vendorAppDir = new File("/vendor/app");
1550            try {
1551                vendorAppDir = vendorAppDir.getCanonicalFile();
1552            } catch (IOException e) {
1553                // failed to look up canonical path, continue with original one
1554            }
1555            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1556                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1557
1558            // Collect all OEM packages.
1559            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1560            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1561                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1562
1563            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1564            mInstaller.moveFiles();
1565
1566            // Prune any system packages that no longer exist.
1567            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1568            if (!mOnlyCore) {
1569                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1570                while (psit.hasNext()) {
1571                    PackageSetting ps = psit.next();
1572
1573                    /*
1574                     * If this is not a system app, it can't be a
1575                     * disable system app.
1576                     */
1577                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1578                        continue;
1579                    }
1580
1581                    /*
1582                     * If the package is scanned, it's not erased.
1583                     */
1584                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1585                    if (scannedPkg != null) {
1586                        /*
1587                         * If the system app is both scanned and in the
1588                         * disabled packages list, then it must have been
1589                         * added via OTA. Remove it from the currently
1590                         * scanned package so the previously user-installed
1591                         * application can be scanned.
1592                         */
1593                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1594                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1595                                    + "; removing system app");
1596                            removePackageLI(ps, true);
1597                        }
1598
1599                        continue;
1600                    }
1601
1602                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1603                        psit.remove();
1604                        String msg = "System package " + ps.name
1605                                + " no longer exists; wiping its data";
1606                        reportSettingsProblem(Log.WARN, msg);
1607                        removeDataDirsLI(ps.name);
1608                    } else {
1609                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1610                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1611                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1612                        }
1613                    }
1614                }
1615            }
1616
1617            //look for any incomplete package installations
1618            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1619            //clean up list
1620            for(int i = 0; i < deletePkgsList.size(); i++) {
1621                //clean up here
1622                cleanupInstallFailedPackage(deletePkgsList.get(i));
1623            }
1624            //delete tmp files
1625            deleteTempPackageFiles();
1626
1627            // Remove any shared userIDs that have no associated packages
1628            mSettings.pruneSharedUsersLPw();
1629
1630            if (!mOnlyCore) {
1631                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1632                        SystemClock.uptimeMillis());
1633                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1634
1635                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1636                        scanMode, 0);
1637
1638                /**
1639                 * Remove disable package settings for any updated system
1640                 * apps that were removed via an OTA. If they're not a
1641                 * previously-updated app, remove them completely.
1642                 * Otherwise, just revoke their system-level permissions.
1643                 */
1644                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1645                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1646                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1647
1648                    String msg;
1649                    if (deletedPkg == null) {
1650                        msg = "Updated system package " + deletedAppName
1651                                + " no longer exists; wiping its data";
1652                        removeDataDirsLI(deletedAppName);
1653                    } else {
1654                        msg = "Updated system app + " + deletedAppName
1655                                + " no longer present; removing system privileges for "
1656                                + deletedAppName;
1657
1658                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1659
1660                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1661                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1662                    }
1663                    reportSettingsProblem(Log.WARN, msg);
1664                }
1665            }
1666
1667            // Now that we know all of the shared libraries, update all clients to have
1668            // the correct library paths.
1669            updateAllSharedLibrariesLPw();
1670
1671            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1672                // NOTE: We ignore potential failures here during a system scan (like
1673                // the rest of the commands above) because there's precious little we
1674                // can do about it. A settings error is reported, though.
1675                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1676                        false /* force dexopt */, false /* defer dexopt */);
1677            }
1678
1679            // Now that we know all the packages we are keeping,
1680            // read and update their last usage times.
1681            mPackageUsage.readLP();
1682
1683            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1684                    SystemClock.uptimeMillis());
1685            Slog.i(TAG, "Time to scan packages: "
1686                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1687                    + " seconds");
1688
1689            // If the platform SDK has changed since the last time we booted,
1690            // we need to re-grant app permission to catch any new ones that
1691            // appear.  This is really a hack, and means that apps can in some
1692            // cases get permissions that the user didn't initially explicitly
1693            // allow...  it would be nice to have some better way to handle
1694            // this situation.
1695            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1696                    != mSdkVersion;
1697            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1698                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1699                    + "; regranting permissions for internal storage");
1700            mSettings.mInternalSdkPlatform = mSdkVersion;
1701
1702            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1703                    | (regrantPermissions
1704                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1705                            : 0));
1706
1707            // If this is the first boot, and it is a normal boot, then
1708            // we need to initialize the default preferred apps.
1709            if (!mRestoredSettings && !onlyCore) {
1710                mSettings.readDefaultPreferredAppsLPw(this, 0);
1711            }
1712
1713            // If this is first boot after an OTA, and a normal boot, then
1714            // we need to clear code cache directories.
1715            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1716                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1717                for (String pkgName : mSettings.mPackages.keySet()) {
1718                    deleteCodeCacheDirsLI(pkgName);
1719                }
1720                mSettings.mFingerprint = Build.FINGERPRINT;
1721            }
1722
1723            // All the changes are done during package scanning.
1724            mSettings.updateInternalDatabaseVersion();
1725
1726            // can downgrade to reader
1727            mSettings.writeLPr();
1728
1729            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1730                    SystemClock.uptimeMillis());
1731
1732
1733            mRequiredVerifierPackage = getRequiredVerifierLPr();
1734        } // synchronized (mPackages)
1735        } // synchronized (mInstallLock)
1736
1737        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1738
1739        // Now after opening every single application zip, make sure they
1740        // are all flushed.  Not really needed, but keeps things nice and
1741        // tidy.
1742        Runtime.getRuntime().gc();
1743    }
1744
1745    @Override
1746    public boolean isFirstBoot() {
1747        return !mRestoredSettings;
1748    }
1749
1750    @Override
1751    public boolean isOnlyCoreApps() {
1752        return mOnlyCore;
1753    }
1754
1755    private String getRequiredVerifierLPr() {
1756        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1757        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1758                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1759
1760        String requiredVerifier = null;
1761
1762        final int N = receivers.size();
1763        for (int i = 0; i < N; i++) {
1764            final ResolveInfo info = receivers.get(i);
1765
1766            if (info.activityInfo == null) {
1767                continue;
1768            }
1769
1770            final String packageName = info.activityInfo.packageName;
1771
1772            final PackageSetting ps = mSettings.mPackages.get(packageName);
1773            if (ps == null) {
1774                continue;
1775            }
1776
1777            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1778            if (!gp.grantedPermissions
1779                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1780                continue;
1781            }
1782
1783            if (requiredVerifier != null) {
1784                throw new RuntimeException("There can be only one required verifier");
1785            }
1786
1787            requiredVerifier = packageName;
1788        }
1789
1790        return requiredVerifier;
1791    }
1792
1793    @Override
1794    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1795            throws RemoteException {
1796        try {
1797            return super.onTransact(code, data, reply, flags);
1798        } catch (RuntimeException e) {
1799            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1800                Slog.wtf(TAG, "Package Manager Crash", e);
1801            }
1802            throw e;
1803        }
1804    }
1805
1806    void cleanupInstallFailedPackage(PackageSetting ps) {
1807        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1808        removeDataDirsLI(ps.name);
1809
1810        // TODO: try cleaning up codePath directory contents first, since it
1811        // might be a cluster
1812
1813        if (ps.codePath != null) {
1814            if (!ps.codePath.delete()) {
1815                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1816            }
1817        }
1818        if (ps.resourcePath != null) {
1819            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1820                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1821            }
1822        }
1823        mSettings.removePackageLPw(ps.name);
1824    }
1825
1826    static int[] appendInts(int[] cur, int[] add) {
1827        if (add == null) return cur;
1828        if (cur == null) return add;
1829        final int N = add.length;
1830        for (int i=0; i<N; i++) {
1831            cur = appendInt(cur, add[i]);
1832        }
1833        return cur;
1834    }
1835
1836    static int[] removeInts(int[] cur, int[] rem) {
1837        if (rem == null) return cur;
1838        if (cur == null) return cur;
1839        final int N = rem.length;
1840        for (int i=0; i<N; i++) {
1841            cur = removeInt(cur, rem[i]);
1842        }
1843        return cur;
1844    }
1845
1846    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1847        if (!sUserManager.exists(userId)) return null;
1848        final PackageSetting ps = (PackageSetting) p.mExtras;
1849        if (ps == null) {
1850            return null;
1851        }
1852        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1853        final PackageUserState state = ps.readUserState(userId);
1854        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1855                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1856                state, userId);
1857    }
1858
1859    @Override
1860    public boolean isPackageAvailable(String packageName, int userId) {
1861        if (!sUserManager.exists(userId)) return false;
1862        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1863        synchronized (mPackages) {
1864            PackageParser.Package p = mPackages.get(packageName);
1865            if (p != null) {
1866                final PackageSetting ps = (PackageSetting) p.mExtras;
1867                if (ps != null) {
1868                    final PackageUserState state = ps.readUserState(userId);
1869                    if (state != null) {
1870                        return PackageParser.isAvailable(state);
1871                    }
1872                }
1873            }
1874        }
1875        return false;
1876    }
1877
1878    @Override
1879    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1880        if (!sUserManager.exists(userId)) return null;
1881        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1882        // reader
1883        synchronized (mPackages) {
1884            PackageParser.Package p = mPackages.get(packageName);
1885            if (DEBUG_PACKAGE_INFO)
1886                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1887            if (p != null) {
1888                return generatePackageInfo(p, flags, userId);
1889            }
1890            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1891                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1892            }
1893        }
1894        return null;
1895    }
1896
1897    @Override
1898    public String[] currentToCanonicalPackageNames(String[] names) {
1899        String[] out = new String[names.length];
1900        // reader
1901        synchronized (mPackages) {
1902            for (int i=names.length-1; i>=0; i--) {
1903                PackageSetting ps = mSettings.mPackages.get(names[i]);
1904                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1905            }
1906        }
1907        return out;
1908    }
1909
1910    @Override
1911    public String[] canonicalToCurrentPackageNames(String[] names) {
1912        String[] out = new String[names.length];
1913        // reader
1914        synchronized (mPackages) {
1915            for (int i=names.length-1; i>=0; i--) {
1916                String cur = mSettings.mRenamedPackages.get(names[i]);
1917                out[i] = cur != null ? cur : names[i];
1918            }
1919        }
1920        return out;
1921    }
1922
1923    @Override
1924    public int getPackageUid(String packageName, int userId) {
1925        if (!sUserManager.exists(userId)) return -1;
1926        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1927        // reader
1928        synchronized (mPackages) {
1929            PackageParser.Package p = mPackages.get(packageName);
1930            if(p != null) {
1931                return UserHandle.getUid(userId, p.applicationInfo.uid);
1932            }
1933            PackageSetting ps = mSettings.mPackages.get(packageName);
1934            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1935                return -1;
1936            }
1937            p = ps.pkg;
1938            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1939        }
1940    }
1941
1942    @Override
1943    public int[] getPackageGids(String packageName) {
1944        // reader
1945        synchronized (mPackages) {
1946            PackageParser.Package p = mPackages.get(packageName);
1947            if (DEBUG_PACKAGE_INFO)
1948                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1949            if (p != null) {
1950                final PackageSetting ps = (PackageSetting)p.mExtras;
1951                return ps.getGids();
1952            }
1953        }
1954        // stupid thing to indicate an error.
1955        return new int[0];
1956    }
1957
1958    static final PermissionInfo generatePermissionInfo(
1959            BasePermission bp, int flags) {
1960        if (bp.perm != null) {
1961            return PackageParser.generatePermissionInfo(bp.perm, flags);
1962        }
1963        PermissionInfo pi = new PermissionInfo();
1964        pi.name = bp.name;
1965        pi.packageName = bp.sourcePackage;
1966        pi.nonLocalizedLabel = bp.name;
1967        pi.protectionLevel = bp.protectionLevel;
1968        return pi;
1969    }
1970
1971    @Override
1972    public PermissionInfo getPermissionInfo(String name, int flags) {
1973        // reader
1974        synchronized (mPackages) {
1975            final BasePermission p = mSettings.mPermissions.get(name);
1976            if (p != null) {
1977                return generatePermissionInfo(p, flags);
1978            }
1979            return null;
1980        }
1981    }
1982
1983    @Override
1984    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1985        // reader
1986        synchronized (mPackages) {
1987            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1988            for (BasePermission p : mSettings.mPermissions.values()) {
1989                if (group == null) {
1990                    if (p.perm == null || p.perm.info.group == null) {
1991                        out.add(generatePermissionInfo(p, flags));
1992                    }
1993                } else {
1994                    if (p.perm != null && group.equals(p.perm.info.group)) {
1995                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1996                    }
1997                }
1998            }
1999
2000            if (out.size() > 0) {
2001                return out;
2002            }
2003            return mPermissionGroups.containsKey(group) ? out : null;
2004        }
2005    }
2006
2007    @Override
2008    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2009        // reader
2010        synchronized (mPackages) {
2011            return PackageParser.generatePermissionGroupInfo(
2012                    mPermissionGroups.get(name), flags);
2013        }
2014    }
2015
2016    @Override
2017    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2018        // reader
2019        synchronized (mPackages) {
2020            final int N = mPermissionGroups.size();
2021            ArrayList<PermissionGroupInfo> out
2022                    = new ArrayList<PermissionGroupInfo>(N);
2023            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2024                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2025            }
2026            return out;
2027        }
2028    }
2029
2030    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2031            int userId) {
2032        if (!sUserManager.exists(userId)) return null;
2033        PackageSetting ps = mSettings.mPackages.get(packageName);
2034        if (ps != null) {
2035            if (ps.pkg == null) {
2036                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2037                        flags, userId);
2038                if (pInfo != null) {
2039                    return pInfo.applicationInfo;
2040                }
2041                return null;
2042            }
2043            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2044                    ps.readUserState(userId), userId);
2045        }
2046        return null;
2047    }
2048
2049    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2050            int userId) {
2051        if (!sUserManager.exists(userId)) return null;
2052        PackageSetting ps = mSettings.mPackages.get(packageName);
2053        if (ps != null) {
2054            PackageParser.Package pkg = ps.pkg;
2055            if (pkg == null) {
2056                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2057                    return null;
2058                }
2059                // Only data remains, so we aren't worried about code paths
2060                pkg = new PackageParser.Package(packageName);
2061                pkg.applicationInfo.packageName = packageName;
2062                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2063                pkg.applicationInfo.dataDir =
2064                        getDataPathForPackage(packageName, 0).getPath();
2065                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2066                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2067            }
2068            return generatePackageInfo(pkg, flags, userId);
2069        }
2070        return null;
2071    }
2072
2073    @Override
2074    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2075        if (!sUserManager.exists(userId)) return null;
2076        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2077        // writer
2078        synchronized (mPackages) {
2079            PackageParser.Package p = mPackages.get(packageName);
2080            if (DEBUG_PACKAGE_INFO) Log.v(
2081                    TAG, "getApplicationInfo " + packageName
2082                    + ": " + p);
2083            if (p != null) {
2084                PackageSetting ps = mSettings.mPackages.get(packageName);
2085                if (ps == null) return null;
2086                // Note: isEnabledLP() does not apply here - always return info
2087                return PackageParser.generateApplicationInfo(
2088                        p, flags, ps.readUserState(userId), userId);
2089            }
2090            if ("android".equals(packageName)||"system".equals(packageName)) {
2091                return mAndroidApplication;
2092            }
2093            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2094                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2095            }
2096        }
2097        return null;
2098    }
2099
2100
2101    @Override
2102    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2103        mContext.enforceCallingOrSelfPermission(
2104                android.Manifest.permission.CLEAR_APP_CACHE, null);
2105        // Queue up an async operation since clearing cache may take a little while.
2106        mHandler.post(new Runnable() {
2107            public void run() {
2108                mHandler.removeCallbacks(this);
2109                int retCode = -1;
2110                synchronized (mInstallLock) {
2111                    retCode = mInstaller.freeCache(freeStorageSize);
2112                    if (retCode < 0) {
2113                        Slog.w(TAG, "Couldn't clear application caches");
2114                    }
2115                }
2116                if (observer != null) {
2117                    try {
2118                        observer.onRemoveCompleted(null, (retCode >= 0));
2119                    } catch (RemoteException e) {
2120                        Slog.w(TAG, "RemoveException when invoking call back");
2121                    }
2122                }
2123            }
2124        });
2125    }
2126
2127    @Override
2128    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2129        mContext.enforceCallingOrSelfPermission(
2130                android.Manifest.permission.CLEAR_APP_CACHE, null);
2131        // Queue up an async operation since clearing cache may take a little while.
2132        mHandler.post(new Runnable() {
2133            public void run() {
2134                mHandler.removeCallbacks(this);
2135                int retCode = -1;
2136                synchronized (mInstallLock) {
2137                    retCode = mInstaller.freeCache(freeStorageSize);
2138                    if (retCode < 0) {
2139                        Slog.w(TAG, "Couldn't clear application caches");
2140                    }
2141                }
2142                if(pi != null) {
2143                    try {
2144                        // Callback via pending intent
2145                        int code = (retCode >= 0) ? 1 : 0;
2146                        pi.sendIntent(null, code, null,
2147                                null, null);
2148                    } catch (SendIntentException e1) {
2149                        Slog.i(TAG, "Failed to send pending intent");
2150                    }
2151                }
2152            }
2153        });
2154    }
2155
2156    void freeStorage(long freeStorageSize) throws IOException {
2157        synchronized (mInstallLock) {
2158            if (mInstaller.freeCache(freeStorageSize) < 0) {
2159                throw new IOException("Failed to free enough space");
2160            }
2161        }
2162    }
2163
2164    @Override
2165    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2166        if (!sUserManager.exists(userId)) return null;
2167        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2168        synchronized (mPackages) {
2169            PackageParser.Activity a = mActivities.mActivities.get(component);
2170
2171            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2172            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2173                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2174                if (ps == null) return null;
2175                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2176                        userId);
2177            }
2178            if (mResolveComponentName.equals(component)) {
2179                return mResolveActivity;
2180            }
2181        }
2182        return null;
2183    }
2184
2185    @Override
2186    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2187            String resolvedType) {
2188        synchronized (mPackages) {
2189            PackageParser.Activity a = mActivities.mActivities.get(component);
2190            if (a == null) {
2191                return false;
2192            }
2193            for (int i=0; i<a.intents.size(); i++) {
2194                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2195                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2196                    return true;
2197                }
2198            }
2199            return false;
2200        }
2201    }
2202
2203    @Override
2204    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2205        if (!sUserManager.exists(userId)) return null;
2206        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2207        synchronized (mPackages) {
2208            PackageParser.Activity a = mReceivers.mActivities.get(component);
2209            if (DEBUG_PACKAGE_INFO) Log.v(
2210                TAG, "getReceiverInfo " + component + ": " + a);
2211            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2212                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2213                if (ps == null) return null;
2214                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2215                        userId);
2216            }
2217        }
2218        return null;
2219    }
2220
2221    @Override
2222    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2223        if (!sUserManager.exists(userId)) return null;
2224        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2225        synchronized (mPackages) {
2226            PackageParser.Service s = mServices.mServices.get(component);
2227            if (DEBUG_PACKAGE_INFO) Log.v(
2228                TAG, "getServiceInfo " + component + ": " + s);
2229            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2230                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2231                if (ps == null) return null;
2232                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2233                        userId);
2234            }
2235        }
2236        return null;
2237    }
2238
2239    @Override
2240    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2241        if (!sUserManager.exists(userId)) return null;
2242        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2243        synchronized (mPackages) {
2244            PackageParser.Provider p = mProviders.mProviders.get(component);
2245            if (DEBUG_PACKAGE_INFO) Log.v(
2246                TAG, "getProviderInfo " + component + ": " + p);
2247            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2248                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2249                if (ps == null) return null;
2250                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2251                        userId);
2252            }
2253        }
2254        return null;
2255    }
2256
2257    @Override
2258    public String[] getSystemSharedLibraryNames() {
2259        Set<String> libSet;
2260        synchronized (mPackages) {
2261            libSet = mSharedLibraries.keySet();
2262            int size = libSet.size();
2263            if (size > 0) {
2264                String[] libs = new String[size];
2265                libSet.toArray(libs);
2266                return libs;
2267            }
2268        }
2269        return null;
2270    }
2271
2272    @Override
2273    public FeatureInfo[] getSystemAvailableFeatures() {
2274        Collection<FeatureInfo> featSet;
2275        synchronized (mPackages) {
2276            featSet = mAvailableFeatures.values();
2277            int size = featSet.size();
2278            if (size > 0) {
2279                FeatureInfo[] features = new FeatureInfo[size+1];
2280                featSet.toArray(features);
2281                FeatureInfo fi = new FeatureInfo();
2282                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2283                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2284                features[size] = fi;
2285                return features;
2286            }
2287        }
2288        return null;
2289    }
2290
2291    @Override
2292    public boolean hasSystemFeature(String name) {
2293        synchronized (mPackages) {
2294            return mAvailableFeatures.containsKey(name);
2295        }
2296    }
2297
2298    private void checkValidCaller(int uid, int userId) {
2299        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2300            return;
2301
2302        throw new SecurityException("Caller uid=" + uid
2303                + " is not privileged to communicate with user=" + userId);
2304    }
2305
2306    @Override
2307    public int checkPermission(String permName, String pkgName) {
2308        synchronized (mPackages) {
2309            PackageParser.Package p = mPackages.get(pkgName);
2310            if (p != null && p.mExtras != null) {
2311                PackageSetting ps = (PackageSetting)p.mExtras;
2312                if (ps.sharedUser != null) {
2313                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2314                        return PackageManager.PERMISSION_GRANTED;
2315                    }
2316                } else if (ps.grantedPermissions.contains(permName)) {
2317                    return PackageManager.PERMISSION_GRANTED;
2318                }
2319            }
2320        }
2321        return PackageManager.PERMISSION_DENIED;
2322    }
2323
2324    @Override
2325    public int checkUidPermission(String permName, int uid) {
2326        synchronized (mPackages) {
2327            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2328            if (obj != null) {
2329                GrantedPermissions gp = (GrantedPermissions)obj;
2330                if (gp.grantedPermissions.contains(permName)) {
2331                    return PackageManager.PERMISSION_GRANTED;
2332                }
2333            } else {
2334                HashSet<String> perms = mSystemPermissions.get(uid);
2335                if (perms != null && perms.contains(permName)) {
2336                    return PackageManager.PERMISSION_GRANTED;
2337                }
2338            }
2339        }
2340        return PackageManager.PERMISSION_DENIED;
2341    }
2342
2343    /**
2344     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2345     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2346     * @param message the message to log on security exception
2347     */
2348    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2349            String message) {
2350        if (userId < 0) {
2351            throw new IllegalArgumentException("Invalid userId " + userId);
2352        }
2353        if (userId == UserHandle.getUserId(callingUid)) return;
2354        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2355            if (requireFullPermission) {
2356                mContext.enforceCallingOrSelfPermission(
2357                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2358            } else {
2359                try {
2360                    mContext.enforceCallingOrSelfPermission(
2361                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2362                } catch (SecurityException se) {
2363                    mContext.enforceCallingOrSelfPermission(
2364                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2365                }
2366            }
2367        }
2368    }
2369
2370    private BasePermission findPermissionTreeLP(String permName) {
2371        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2372            if (permName.startsWith(bp.name) &&
2373                    permName.length() > bp.name.length() &&
2374                    permName.charAt(bp.name.length()) == '.') {
2375                return bp;
2376            }
2377        }
2378        return null;
2379    }
2380
2381    private BasePermission checkPermissionTreeLP(String permName) {
2382        if (permName != null) {
2383            BasePermission bp = findPermissionTreeLP(permName);
2384            if (bp != null) {
2385                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2386                    return bp;
2387                }
2388                throw new SecurityException("Calling uid "
2389                        + Binder.getCallingUid()
2390                        + " is not allowed to add to permission tree "
2391                        + bp.name + " owned by uid " + bp.uid);
2392            }
2393        }
2394        throw new SecurityException("No permission tree found for " + permName);
2395    }
2396
2397    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2398        if (s1 == null) {
2399            return s2 == null;
2400        }
2401        if (s2 == null) {
2402            return false;
2403        }
2404        if (s1.getClass() != s2.getClass()) {
2405            return false;
2406        }
2407        return s1.equals(s2);
2408    }
2409
2410    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2411        if (pi1.icon != pi2.icon) return false;
2412        if (pi1.logo != pi2.logo) return false;
2413        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2414        if (!compareStrings(pi1.name, pi2.name)) return false;
2415        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2416        // We'll take care of setting this one.
2417        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2418        // These are not currently stored in settings.
2419        //if (!compareStrings(pi1.group, pi2.group)) return false;
2420        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2421        //if (pi1.labelRes != pi2.labelRes) return false;
2422        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2423        return true;
2424    }
2425
2426    int permissionInfoFootprint(PermissionInfo info) {
2427        int size = info.name.length();
2428        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2429        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2430        return size;
2431    }
2432
2433    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2434        int size = 0;
2435        for (BasePermission perm : mSettings.mPermissions.values()) {
2436            if (perm.uid == tree.uid) {
2437                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2438            }
2439        }
2440        return size;
2441    }
2442
2443    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2444        // We calculate the max size of permissions defined by this uid and throw
2445        // if that plus the size of 'info' would exceed our stated maximum.
2446        if (tree.uid != Process.SYSTEM_UID) {
2447            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2448            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2449                throw new SecurityException("Permission tree size cap exceeded");
2450            }
2451        }
2452    }
2453
2454    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2455        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2456            throw new SecurityException("Label must be specified in permission");
2457        }
2458        BasePermission tree = checkPermissionTreeLP(info.name);
2459        BasePermission bp = mSettings.mPermissions.get(info.name);
2460        boolean added = bp == null;
2461        boolean changed = true;
2462        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2463        if (added) {
2464            enforcePermissionCapLocked(info, tree);
2465            bp = new BasePermission(info.name, tree.sourcePackage,
2466                    BasePermission.TYPE_DYNAMIC);
2467        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2468            throw new SecurityException(
2469                    "Not allowed to modify non-dynamic permission "
2470                    + info.name);
2471        } else {
2472            if (bp.protectionLevel == fixedLevel
2473                    && bp.perm.owner.equals(tree.perm.owner)
2474                    && bp.uid == tree.uid
2475                    && comparePermissionInfos(bp.perm.info, info)) {
2476                changed = false;
2477            }
2478        }
2479        bp.protectionLevel = fixedLevel;
2480        info = new PermissionInfo(info);
2481        info.protectionLevel = fixedLevel;
2482        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2483        bp.perm.info.packageName = tree.perm.info.packageName;
2484        bp.uid = tree.uid;
2485        if (added) {
2486            mSettings.mPermissions.put(info.name, bp);
2487        }
2488        if (changed) {
2489            if (!async) {
2490                mSettings.writeLPr();
2491            } else {
2492                scheduleWriteSettingsLocked();
2493            }
2494        }
2495        return added;
2496    }
2497
2498    @Override
2499    public boolean addPermission(PermissionInfo info) {
2500        synchronized (mPackages) {
2501            return addPermissionLocked(info, false);
2502        }
2503    }
2504
2505    @Override
2506    public boolean addPermissionAsync(PermissionInfo info) {
2507        synchronized (mPackages) {
2508            return addPermissionLocked(info, true);
2509        }
2510    }
2511
2512    @Override
2513    public void removePermission(String name) {
2514        synchronized (mPackages) {
2515            checkPermissionTreeLP(name);
2516            BasePermission bp = mSettings.mPermissions.get(name);
2517            if (bp != null) {
2518                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2519                    throw new SecurityException(
2520                            "Not allowed to modify non-dynamic permission "
2521                            + name);
2522                }
2523                mSettings.mPermissions.remove(name);
2524                mSettings.writeLPr();
2525            }
2526        }
2527    }
2528
2529    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2530        int index = pkg.requestedPermissions.indexOf(bp.name);
2531        if (index == -1) {
2532            throw new SecurityException("Package " + pkg.packageName
2533                    + " has not requested permission " + bp.name);
2534        }
2535        boolean isNormal =
2536                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2537                        == PermissionInfo.PROTECTION_NORMAL);
2538        boolean isDangerous =
2539                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2540                        == PermissionInfo.PROTECTION_DANGEROUS);
2541        boolean isDevelopment =
2542                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2543
2544        if (!isNormal && !isDangerous && !isDevelopment) {
2545            throw new SecurityException("Permission " + bp.name
2546                    + " is not a changeable permission type");
2547        }
2548
2549        if (isNormal || isDangerous) {
2550            if (pkg.requestedPermissionsRequired.get(index)) {
2551                throw new SecurityException("Can't change " + bp.name
2552                        + ". It is required by the application");
2553            }
2554        }
2555    }
2556
2557    @Override
2558    public void grantPermission(String packageName, String permissionName) {
2559        mContext.enforceCallingOrSelfPermission(
2560                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2561        synchronized (mPackages) {
2562            final PackageParser.Package pkg = mPackages.get(packageName);
2563            if (pkg == null) {
2564                throw new IllegalArgumentException("Unknown package: " + packageName);
2565            }
2566            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2567            if (bp == null) {
2568                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2569            }
2570
2571            checkGrantRevokePermissions(pkg, bp);
2572
2573            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2574            if (ps == null) {
2575                return;
2576            }
2577            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2578            if (gp.grantedPermissions.add(permissionName)) {
2579                if (ps.haveGids) {
2580                    gp.gids = appendInts(gp.gids, bp.gids);
2581                }
2582                mSettings.writeLPr();
2583            }
2584        }
2585    }
2586
2587    @Override
2588    public void revokePermission(String packageName, String permissionName) {
2589        int changedAppId = -1;
2590
2591        synchronized (mPackages) {
2592            final PackageParser.Package pkg = mPackages.get(packageName);
2593            if (pkg == null) {
2594                throw new IllegalArgumentException("Unknown package: " + packageName);
2595            }
2596            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2597                mContext.enforceCallingOrSelfPermission(
2598                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2599            }
2600            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2601            if (bp == null) {
2602                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2603            }
2604
2605            checkGrantRevokePermissions(pkg, bp);
2606
2607            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2608            if (ps == null) {
2609                return;
2610            }
2611            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2612            if (gp.grantedPermissions.remove(permissionName)) {
2613                gp.grantedPermissions.remove(permissionName);
2614                if (ps.haveGids) {
2615                    gp.gids = removeInts(gp.gids, bp.gids);
2616                }
2617                mSettings.writeLPr();
2618                changedAppId = ps.appId;
2619            }
2620        }
2621
2622        if (changedAppId >= 0) {
2623            // We changed the perm on someone, kill its processes.
2624            IActivityManager am = ActivityManagerNative.getDefault();
2625            if (am != null) {
2626                final int callingUserId = UserHandle.getCallingUserId();
2627                final long ident = Binder.clearCallingIdentity();
2628                try {
2629                    //XXX we should only revoke for the calling user's app permissions,
2630                    // but for now we impact all users.
2631                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2632                    //        "revoke " + permissionName);
2633                    int[] users = sUserManager.getUserIds();
2634                    for (int user : users) {
2635                        am.killUid(UserHandle.getUid(user, changedAppId),
2636                                "revoke " + permissionName);
2637                    }
2638                } catch (RemoteException e) {
2639                } finally {
2640                    Binder.restoreCallingIdentity(ident);
2641                }
2642            }
2643        }
2644    }
2645
2646    @Override
2647    public boolean isProtectedBroadcast(String actionName) {
2648        synchronized (mPackages) {
2649            return mProtectedBroadcasts.contains(actionName);
2650        }
2651    }
2652
2653    @Override
2654    public int checkSignatures(String pkg1, String pkg2) {
2655        synchronized (mPackages) {
2656            final PackageParser.Package p1 = mPackages.get(pkg1);
2657            final PackageParser.Package p2 = mPackages.get(pkg2);
2658            if (p1 == null || p1.mExtras == null
2659                    || p2 == null || p2.mExtras == null) {
2660                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2661            }
2662            return compareSignatures(p1.mSignatures, p2.mSignatures);
2663        }
2664    }
2665
2666    @Override
2667    public int checkUidSignatures(int uid1, int uid2) {
2668        // Map to base uids.
2669        uid1 = UserHandle.getAppId(uid1);
2670        uid2 = UserHandle.getAppId(uid2);
2671        // reader
2672        synchronized (mPackages) {
2673            Signature[] s1;
2674            Signature[] s2;
2675            Object obj = mSettings.getUserIdLPr(uid1);
2676            if (obj != null) {
2677                if (obj instanceof SharedUserSetting) {
2678                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2679                } else if (obj instanceof PackageSetting) {
2680                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2681                } else {
2682                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2683                }
2684            } else {
2685                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2686            }
2687            obj = mSettings.getUserIdLPr(uid2);
2688            if (obj != null) {
2689                if (obj instanceof SharedUserSetting) {
2690                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2691                } else if (obj instanceof PackageSetting) {
2692                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2693                } else {
2694                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2695                }
2696            } else {
2697                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2698            }
2699            return compareSignatures(s1, s2);
2700        }
2701    }
2702
2703    /**
2704     * Compares two sets of signatures. Returns:
2705     * <br />
2706     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2707     * <br />
2708     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2709     * <br />
2710     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2715     */
2716    static int compareSignatures(Signature[] s1, Signature[] s2) {
2717        if (s1 == null) {
2718            return s2 == null
2719                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2720                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2721        }
2722
2723        if (s2 == null) {
2724            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2725        }
2726
2727        if (s1.length != s2.length) {
2728            return PackageManager.SIGNATURE_NO_MATCH;
2729        }
2730
2731        // Since both signature sets are of size 1, we can compare without HashSets.
2732        if (s1.length == 1) {
2733            return s1[0].equals(s2[0]) ?
2734                    PackageManager.SIGNATURE_MATCH :
2735                    PackageManager.SIGNATURE_NO_MATCH;
2736        }
2737
2738        HashSet<Signature> set1 = new HashSet<Signature>();
2739        for (Signature sig : s1) {
2740            set1.add(sig);
2741        }
2742        HashSet<Signature> set2 = new HashSet<Signature>();
2743        for (Signature sig : s2) {
2744            set2.add(sig);
2745        }
2746        // Make sure s2 contains all signatures in s1.
2747        if (set1.equals(set2)) {
2748            return PackageManager.SIGNATURE_MATCH;
2749        }
2750        return PackageManager.SIGNATURE_NO_MATCH;
2751    }
2752
2753    /**
2754     * If the database version for this type of package (internal storage or
2755     * external storage) is less than the version where package signatures
2756     * were updated, return true.
2757     */
2758    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2759        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2760                DatabaseVersion.SIGNATURE_END_ENTITY))
2761                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2762                        DatabaseVersion.SIGNATURE_END_ENTITY));
2763    }
2764
2765    /**
2766     * Used for backward compatibility to make sure any packages with
2767     * certificate chains get upgraded to the new style. {@code existingSigs}
2768     * will be in the old format (since they were stored on disk from before the
2769     * system upgrade) and {@code scannedSigs} will be in the newer format.
2770     */
2771    private int compareSignaturesCompat(PackageSignatures existingSigs,
2772            PackageParser.Package scannedPkg) {
2773        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2774            return PackageManager.SIGNATURE_NO_MATCH;
2775        }
2776
2777        HashSet<Signature> existingSet = new HashSet<Signature>();
2778        for (Signature sig : existingSigs.mSignatures) {
2779            existingSet.add(sig);
2780        }
2781        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2782        for (Signature sig : scannedPkg.mSignatures) {
2783            try {
2784                Signature[] chainSignatures = sig.getChainSignatures();
2785                for (Signature chainSig : chainSignatures) {
2786                    scannedCompatSet.add(chainSig);
2787                }
2788            } catch (CertificateEncodingException e) {
2789                scannedCompatSet.add(sig);
2790            }
2791        }
2792        /*
2793         * Make sure the expanded scanned set contains all signatures in the
2794         * existing one.
2795         */
2796        if (scannedCompatSet.equals(existingSet)) {
2797            // Migrate the old signatures to the new scheme.
2798            existingSigs.assignSignatures(scannedPkg.mSignatures);
2799            // The new KeySets will be re-added later in the scanning process.
2800            synchronized (mPackages) {
2801                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2802            }
2803            return PackageManager.SIGNATURE_MATCH;
2804        }
2805        return PackageManager.SIGNATURE_NO_MATCH;
2806    }
2807
2808    @Override
2809    public String[] getPackagesForUid(int uid) {
2810        uid = UserHandle.getAppId(uid);
2811        // reader
2812        synchronized (mPackages) {
2813            Object obj = mSettings.getUserIdLPr(uid);
2814            if (obj instanceof SharedUserSetting) {
2815                final SharedUserSetting sus = (SharedUserSetting) obj;
2816                final int N = sus.packages.size();
2817                final String[] res = new String[N];
2818                final Iterator<PackageSetting> it = sus.packages.iterator();
2819                int i = 0;
2820                while (it.hasNext()) {
2821                    res[i++] = it.next().name;
2822                }
2823                return res;
2824            } else if (obj instanceof PackageSetting) {
2825                final PackageSetting ps = (PackageSetting) obj;
2826                return new String[] { ps.name };
2827            }
2828        }
2829        return null;
2830    }
2831
2832    @Override
2833    public String getNameForUid(int uid) {
2834        // reader
2835        synchronized (mPackages) {
2836            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2837            if (obj instanceof SharedUserSetting) {
2838                final SharedUserSetting sus = (SharedUserSetting) obj;
2839                return sus.name + ":" + sus.userId;
2840            } else if (obj instanceof PackageSetting) {
2841                final PackageSetting ps = (PackageSetting) obj;
2842                return ps.name;
2843            }
2844        }
2845        return null;
2846    }
2847
2848    @Override
2849    public int getUidForSharedUser(String sharedUserName) {
2850        if(sharedUserName == null) {
2851            return -1;
2852        }
2853        // reader
2854        synchronized (mPackages) {
2855            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2856            if (suid == null) {
2857                return -1;
2858            }
2859            return suid.userId;
2860        }
2861    }
2862
2863    @Override
2864    public int getFlagsForUid(int uid) {
2865        synchronized (mPackages) {
2866            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2867            if (obj instanceof SharedUserSetting) {
2868                final SharedUserSetting sus = (SharedUserSetting) obj;
2869                return sus.pkgFlags;
2870            } else if (obj instanceof PackageSetting) {
2871                final PackageSetting ps = (PackageSetting) obj;
2872                return ps.pkgFlags;
2873            }
2874        }
2875        return 0;
2876    }
2877
2878    @Override
2879    public String[] getAppOpPermissionPackages(String permissionName) {
2880        synchronized (mPackages) {
2881            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2882            if (pkgs == null) {
2883                return null;
2884            }
2885            return pkgs.toArray(new String[pkgs.size()]);
2886        }
2887    }
2888
2889    @Override
2890    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2891            int flags, int userId) {
2892        if (!sUserManager.exists(userId)) return null;
2893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2894        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2895        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2896    }
2897
2898    @Override
2899    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2900            IntentFilter filter, int match, ComponentName activity) {
2901        final int userId = UserHandle.getCallingUserId();
2902        if (DEBUG_PREFERRED) {
2903            Log.v(TAG, "setLastChosenActivity intent=" + intent
2904                + " resolvedType=" + resolvedType
2905                + " flags=" + flags
2906                + " filter=" + filter
2907                + " match=" + match
2908                + " activity=" + activity);
2909            filter.dump(new PrintStreamPrinter(System.out), "    ");
2910        }
2911        intent.setComponent(null);
2912        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2913        // Find any earlier preferred or last chosen entries and nuke them
2914        findPreferredActivity(intent, resolvedType,
2915                flags, query, 0, false, true, false, userId);
2916        // Add the new activity as the last chosen for this filter
2917        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2918    }
2919
2920    @Override
2921    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2922        final int userId = UserHandle.getCallingUserId();
2923        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2924        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2925        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2926                false, false, false, userId);
2927    }
2928
2929    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2930            int flags, List<ResolveInfo> query, int userId) {
2931        if (query != null) {
2932            final int N = query.size();
2933            if (N == 1) {
2934                return query.get(0);
2935            } else if (N > 1) {
2936                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2937                // If there is more than one activity with the same priority,
2938                // then let the user decide between them.
2939                ResolveInfo r0 = query.get(0);
2940                ResolveInfo r1 = query.get(1);
2941                if (DEBUG_INTENT_MATCHING || debug) {
2942                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2943                            + r1.activityInfo.name + "=" + r1.priority);
2944                }
2945                // If the first activity has a higher priority, or a different
2946                // default, then it is always desireable to pick it.
2947                if (r0.priority != r1.priority
2948                        || r0.preferredOrder != r1.preferredOrder
2949                        || r0.isDefault != r1.isDefault) {
2950                    return query.get(0);
2951                }
2952                // If we have saved a preference for a preferred activity for
2953                // this Intent, use that.
2954                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2955                        flags, query, r0.priority, true, false, debug, userId);
2956                if (ri != null) {
2957                    return ri;
2958                }
2959                if (userId != 0) {
2960                    ri = new ResolveInfo(mResolveInfo);
2961                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2962                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2963                            ri.activityInfo.applicationInfo);
2964                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2965                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2966                    return ri;
2967                }
2968                return mResolveInfo;
2969            }
2970        }
2971        return null;
2972    }
2973
2974    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2975            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2976        final int N = query.size();
2977        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2978                .get(userId);
2979        // Get the list of persistent preferred activities that handle the intent
2980        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2981        List<PersistentPreferredActivity> pprefs = ppir != null
2982                ? ppir.queryIntent(intent, resolvedType,
2983                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2984                : null;
2985        if (pprefs != null && pprefs.size() > 0) {
2986            final int M = pprefs.size();
2987            for (int i=0; i<M; i++) {
2988                final PersistentPreferredActivity ppa = pprefs.get(i);
2989                if (DEBUG_PREFERRED || debug) {
2990                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2991                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2992                            + "\n  component=" + ppa.mComponent);
2993                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2994                }
2995                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2996                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2997                if (DEBUG_PREFERRED || debug) {
2998                    Slog.v(TAG, "Found persistent preferred activity:");
2999                    if (ai != null) {
3000                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3001                    } else {
3002                        Slog.v(TAG, "  null");
3003                    }
3004                }
3005                if (ai == null) {
3006                    // This previously registered persistent preferred activity
3007                    // component is no longer known. Ignore it and do NOT remove it.
3008                    continue;
3009                }
3010                for (int j=0; j<N; j++) {
3011                    final ResolveInfo ri = query.get(j);
3012                    if (!ri.activityInfo.applicationInfo.packageName
3013                            .equals(ai.applicationInfo.packageName)) {
3014                        continue;
3015                    }
3016                    if (!ri.activityInfo.name.equals(ai.name)) {
3017                        continue;
3018                    }
3019                    //  Found a persistent preference that can handle the intent.
3020                    if (DEBUG_PREFERRED || debug) {
3021                        Slog.v(TAG, "Returning persistent preferred activity: " +
3022                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3023                    }
3024                    return ri;
3025                }
3026            }
3027        }
3028        return null;
3029    }
3030
3031    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3032            List<ResolveInfo> query, int priority, boolean always,
3033            boolean removeMatches, boolean debug, int userId) {
3034        if (!sUserManager.exists(userId)) return null;
3035        // writer
3036        synchronized (mPackages) {
3037            if (intent.getSelector() != null) {
3038                intent = intent.getSelector();
3039            }
3040            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3041
3042            // Try to find a matching persistent preferred activity.
3043            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3044                    debug, userId);
3045
3046            // If a persistent preferred activity matched, use it.
3047            if (pri != null) {
3048                return pri;
3049            }
3050
3051            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3052            // Get the list of preferred activities that handle the intent
3053            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3054            List<PreferredActivity> prefs = pir != null
3055                    ? pir.queryIntent(intent, resolvedType,
3056                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3057                    : null;
3058            if (prefs != null && prefs.size() > 0) {
3059                // First figure out how good the original match set is.
3060                // We will only allow preferred activities that came
3061                // from the same match quality.
3062                int match = 0;
3063
3064                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3065
3066                final int N = query.size();
3067                for (int j=0; j<N; j++) {
3068                    final ResolveInfo ri = query.get(j);
3069                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3070                            + ": 0x" + Integer.toHexString(match));
3071                    if (ri.match > match) {
3072                        match = ri.match;
3073                    }
3074                }
3075
3076                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3077                        + Integer.toHexString(match));
3078
3079                match &= IntentFilter.MATCH_CATEGORY_MASK;
3080                final int M = prefs.size();
3081                for (int i=0; i<M; i++) {
3082                    final PreferredActivity pa = prefs.get(i);
3083                    if (DEBUG_PREFERRED || debug) {
3084                        Slog.v(TAG, "Checking PreferredActivity ds="
3085                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3086                                + "\n  component=" + pa.mPref.mComponent);
3087                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3088                    }
3089                    if (pa.mPref.mMatch != match) {
3090                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3091                                + Integer.toHexString(pa.mPref.mMatch));
3092                        continue;
3093                    }
3094                    // If it's not an "always" type preferred activity and that's what we're
3095                    // looking for, skip it.
3096                    if (always && !pa.mPref.mAlways) {
3097                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3098                        continue;
3099                    }
3100                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3101                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3102                    if (DEBUG_PREFERRED || debug) {
3103                        Slog.v(TAG, "Found preferred activity:");
3104                        if (ai != null) {
3105                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3106                        } else {
3107                            Slog.v(TAG, "  null");
3108                        }
3109                    }
3110                    if (ai == null) {
3111                        // This previously registered preferred activity
3112                        // component is no longer known.  Most likely an update
3113                        // to the app was installed and in the new version this
3114                        // component no longer exists.  Clean it up by removing
3115                        // it from the preferred activities list, and skip it.
3116                        Slog.w(TAG, "Removing dangling preferred activity: "
3117                                + pa.mPref.mComponent);
3118                        pir.removeFilter(pa);
3119                        continue;
3120                    }
3121                    for (int j=0; j<N; j++) {
3122                        final ResolveInfo ri = query.get(j);
3123                        if (!ri.activityInfo.applicationInfo.packageName
3124                                .equals(ai.applicationInfo.packageName)) {
3125                            continue;
3126                        }
3127                        if (!ri.activityInfo.name.equals(ai.name)) {
3128                            continue;
3129                        }
3130
3131                        if (removeMatches) {
3132                            pir.removeFilter(pa);
3133                            if (DEBUG_PREFERRED) {
3134                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3135                            }
3136                            break;
3137                        }
3138
3139                        // Okay we found a previously set preferred or last chosen app.
3140                        // If the result set is different from when this
3141                        // was created, we need to clear it and re-ask the
3142                        // user their preference, if we're looking for an "always" type entry.
3143                        if (always && !pa.mPref.sameSet(query, priority)) {
3144                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3145                                    + intent + " type " + resolvedType);
3146                            if (DEBUG_PREFERRED) {
3147                                Slog.v(TAG, "Removing preferred activity since set changed "
3148                                        + pa.mPref.mComponent);
3149                            }
3150                            pir.removeFilter(pa);
3151                            // Re-add the filter as a "last chosen" entry (!always)
3152                            PreferredActivity lastChosen = new PreferredActivity(
3153                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3154                            pir.addFilter(lastChosen);
3155                            mSettings.writePackageRestrictionsLPr(userId);
3156                            return null;
3157                        }
3158
3159                        // Yay! Either the set matched or we're looking for the last chosen
3160                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3161                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3162                        mSettings.writePackageRestrictionsLPr(userId);
3163                        return ri;
3164                    }
3165                }
3166            }
3167            mSettings.writePackageRestrictionsLPr(userId);
3168        }
3169        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3170        return null;
3171    }
3172
3173    /*
3174     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3175     */
3176    @Override
3177    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3178            int targetUserId) {
3179        mContext.enforceCallingOrSelfPermission(
3180                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3181        List<CrossProfileIntentFilter> matches =
3182                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3183        if (matches != null) {
3184            int size = matches.size();
3185            for (int i = 0; i < size; i++) {
3186                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3187            }
3188        }
3189
3190        ArrayList<String> packageNames = null;
3191        SparseArray<ArrayList<String>> fromSource =
3192                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3193        if (fromSource != null) {
3194            packageNames = fromSource.get(targetUserId);
3195        }
3196        if (packageNames.contains(intent.getPackage())) {
3197            return true;
3198        }
3199        // We need the package name, so we try to resolve with the loosest flags possible
3200        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3201                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3202        int count = resolveInfos.size();
3203        for (int i = 0; i < count; i++) {
3204            ResolveInfo resolveInfo = resolveInfos.get(i);
3205            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3206                return true;
3207            }
3208        }
3209        return false;
3210    }
3211
3212    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3213            String resolvedType, int userId) {
3214        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3215        if (resolver != null) {
3216            return resolver.queryIntent(intent, resolvedType, false, userId);
3217        }
3218        return null;
3219    }
3220
3221    @Override
3222    public List<ResolveInfo> queryIntentActivities(Intent intent,
3223            String resolvedType, int flags, int userId) {
3224        if (!sUserManager.exists(userId)) return Collections.emptyList();
3225        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3226        ComponentName comp = intent.getComponent();
3227        if (comp == null) {
3228            if (intent.getSelector() != null) {
3229                intent = intent.getSelector();
3230                comp = intent.getComponent();
3231            }
3232        }
3233
3234        if (comp != null) {
3235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3236            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3237            if (ai != null) {
3238                final ResolveInfo ri = new ResolveInfo();
3239                ri.activityInfo = ai;
3240                list.add(ri);
3241            }
3242            return list;
3243        }
3244
3245        // reader
3246        synchronized (mPackages) {
3247            final String pkgName = intent.getPackage();
3248            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3249            if (pkgName == null) {
3250                ResolveInfo resolveInfo = null;
3251                if (queryCrossProfile) {
3252                    // Check if the intent needs to be forwarded to another user for this package
3253                    ArrayList<ResolveInfo> crossProfileResult =
3254                            queryIntentActivitiesCrossProfilePackage(
3255                                    intent, resolvedType, flags, userId);
3256                    if (!crossProfileResult.isEmpty()) {
3257                        // Skip the current profile
3258                        return crossProfileResult;
3259                    }
3260                    List<CrossProfileIntentFilter> matchingFilters =
3261                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3262                    // Check for results that need to skip the current profile.
3263                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3264                            resolvedType, flags, userId);
3265                    if (resolveInfo != null) {
3266                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3267                        result.add(resolveInfo);
3268                        return result;
3269                    }
3270                    // Check for cross profile results.
3271                    resolveInfo = queryCrossProfileIntents(
3272                            matchingFilters, intent, resolvedType, flags, userId);
3273                }
3274                // Check for results in the current profile.
3275                List<ResolveInfo> result = mActivities.queryIntent(
3276                        intent, resolvedType, flags, userId);
3277                if (resolveInfo != null) {
3278                    result.add(resolveInfo);
3279                }
3280                return result;
3281            }
3282            final PackageParser.Package pkg = mPackages.get(pkgName);
3283            if (pkg != null) {
3284                if (queryCrossProfile) {
3285                    ArrayList<ResolveInfo> crossProfileResult =
3286                            queryIntentActivitiesCrossProfilePackage(
3287                                    intent, resolvedType, flags, userId, pkg, pkgName);
3288                    if (!crossProfileResult.isEmpty()) {
3289                        // Skip the current profile
3290                        return crossProfileResult;
3291                    }
3292                }
3293                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3294                        pkg.activities, userId);
3295            }
3296            return new ArrayList<ResolveInfo>();
3297        }
3298    }
3299
3300    private ResolveInfo querySkipCurrentProfileIntents(
3301            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3302            int flags, int sourceUserId) {
3303        if (matchingFilters != null) {
3304            int size = matchingFilters.size();
3305            for (int i = 0; i < size; i ++) {
3306                CrossProfileIntentFilter filter = matchingFilters.get(i);
3307                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3308                    // Checking if there are activities in the target user that can handle the
3309                    // intent.
3310                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3311                            flags, sourceUserId);
3312                    if (resolveInfo != null) {
3313                        return resolveInfo;
3314                    }
3315                }
3316            }
3317        }
3318        return null;
3319    }
3320
3321    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3322            Intent intent, String resolvedType, int flags, int userId) {
3323        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3324        SparseArray<ArrayList<String>> sourceForwardingInfo =
3325                mSettings.mCrossProfilePackageInfo.get(userId);
3326        if (sourceForwardingInfo != null) {
3327            int NI = sourceForwardingInfo.size();
3328            for (int i = 0; i < NI; i++) {
3329                int targetUserId = sourceForwardingInfo.keyAt(i);
3330                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3331                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3332                        intent, resolvedType, flags, targetUserId);
3333                int NJ = resolveInfos.size();
3334                for (int j = 0; j < NJ; j++) {
3335                    ResolveInfo resolveInfo = resolveInfos.get(j);
3336                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3337                        matchingResolveInfos.add(createForwardingResolveInfo(
3338                                resolveInfo.filter, userId, targetUserId));
3339                    }
3340                }
3341            }
3342        }
3343        return matchingResolveInfos;
3344    }
3345
3346    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3347            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3348            String packageName) {
3349        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3350        SparseArray<ArrayList<String>> sourceForwardingInfo =
3351                mSettings.mCrossProfilePackageInfo.get(userId);
3352        if (sourceForwardingInfo != null) {
3353            int NI = sourceForwardingInfo.size();
3354            for (int i = 0; i < NI; i++) {
3355                int targetUserId = sourceForwardingInfo.keyAt(i);
3356                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3357                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3358                            intent, resolvedType, flags, pkg.activities, targetUserId);
3359                    int NJ = resolveInfos.size();
3360                    for (int j = 0; j < NJ; j++) {
3361                        ResolveInfo resolveInfo = resolveInfos.get(j);
3362                        matchingResolveInfos.add(createForwardingResolveInfo(
3363                                resolveInfo.filter, userId, targetUserId));
3364                    }
3365                }
3366            }
3367        }
3368        return matchingResolveInfos;
3369    }
3370
3371    // Return matching ResolveInfo if any for skip current profile intent filters.
3372    private ResolveInfo queryCrossProfileIntents(
3373            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3374            int flags, int sourceUserId) {
3375        if (matchingFilters != null) {
3376            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3377            // match the same intent. For performance reasons, it is better not to
3378            // run queryIntent twice for the same userId
3379            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3380            int size = matchingFilters.size();
3381            for (int i = 0; i < size; i++) {
3382                CrossProfileIntentFilter filter = matchingFilters.get(i);
3383                int targetUserId = filter.getTargetUserId();
3384                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3385                        && !alreadyTriedUserIds.get(targetUserId)) {
3386                    // Checking if there are activities in the target user that can handle the
3387                    // intent.
3388                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3389                            flags, sourceUserId);
3390                    if (resolveInfo != null) return resolveInfo;
3391                    alreadyTriedUserIds.put(targetUserId, true);
3392                }
3393            }
3394        }
3395        return null;
3396    }
3397
3398    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3399            String resolvedType, int flags, int sourceUserId) {
3400        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3401                resolvedType, flags, filter.getTargetUserId());
3402        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3403            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3404        }
3405        return null;
3406    }
3407
3408    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3409            int sourceUserId, int targetUserId) {
3410        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3411        String className;
3412        if (targetUserId == UserHandle.USER_OWNER) {
3413            className = FORWARD_INTENT_TO_USER_OWNER;
3414        } else {
3415            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3416        }
3417        ComponentName forwardingActivityComponentName = new ComponentName(
3418                mAndroidApplication.packageName, className);
3419        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3420                sourceUserId);
3421        if (targetUserId == UserHandle.USER_OWNER) {
3422            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3423            forwardingResolveInfo.noResourceId = true;
3424        }
3425        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3426        forwardingResolveInfo.priority = 0;
3427        forwardingResolveInfo.preferredOrder = 0;
3428        forwardingResolveInfo.match = 0;
3429        forwardingResolveInfo.isDefault = true;
3430        forwardingResolveInfo.filter = filter;
3431        forwardingResolveInfo.targetUserId = targetUserId;
3432        return forwardingResolveInfo;
3433    }
3434
3435    @Override
3436    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3437            Intent[] specifics, String[] specificTypes, Intent intent,
3438            String resolvedType, int flags, int userId) {
3439        if (!sUserManager.exists(userId)) return Collections.emptyList();
3440        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3441                "query intent activity options");
3442        final String resultsAction = intent.getAction();
3443
3444        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3445                | PackageManager.GET_RESOLVED_FILTER, userId);
3446
3447        if (DEBUG_INTENT_MATCHING) {
3448            Log.v(TAG, "Query " + intent + ": " + results);
3449        }
3450
3451        int specificsPos = 0;
3452        int N;
3453
3454        // todo: note that the algorithm used here is O(N^2).  This
3455        // isn't a problem in our current environment, but if we start running
3456        // into situations where we have more than 5 or 10 matches then this
3457        // should probably be changed to something smarter...
3458
3459        // First we go through and resolve each of the specific items
3460        // that were supplied, taking care of removing any corresponding
3461        // duplicate items in the generic resolve list.
3462        if (specifics != null) {
3463            for (int i=0; i<specifics.length; i++) {
3464                final Intent sintent = specifics[i];
3465                if (sintent == null) {
3466                    continue;
3467                }
3468
3469                if (DEBUG_INTENT_MATCHING) {
3470                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3471                }
3472
3473                String action = sintent.getAction();
3474                if (resultsAction != null && resultsAction.equals(action)) {
3475                    // If this action was explicitly requested, then don't
3476                    // remove things that have it.
3477                    action = null;
3478                }
3479
3480                ResolveInfo ri = null;
3481                ActivityInfo ai = null;
3482
3483                ComponentName comp = sintent.getComponent();
3484                if (comp == null) {
3485                    ri = resolveIntent(
3486                        sintent,
3487                        specificTypes != null ? specificTypes[i] : null,
3488                            flags, userId);
3489                    if (ri == null) {
3490                        continue;
3491                    }
3492                    if (ri == mResolveInfo) {
3493                        // ACK!  Must do something better with this.
3494                    }
3495                    ai = ri.activityInfo;
3496                    comp = new ComponentName(ai.applicationInfo.packageName,
3497                            ai.name);
3498                } else {
3499                    ai = getActivityInfo(comp, flags, userId);
3500                    if (ai == null) {
3501                        continue;
3502                    }
3503                }
3504
3505                // Look for any generic query activities that are duplicates
3506                // of this specific one, and remove them from the results.
3507                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3508                N = results.size();
3509                int j;
3510                for (j=specificsPos; j<N; j++) {
3511                    ResolveInfo sri = results.get(j);
3512                    if ((sri.activityInfo.name.equals(comp.getClassName())
3513                            && sri.activityInfo.applicationInfo.packageName.equals(
3514                                    comp.getPackageName()))
3515                        || (action != null && sri.filter.matchAction(action))) {
3516                        results.remove(j);
3517                        if (DEBUG_INTENT_MATCHING) Log.v(
3518                            TAG, "Removing duplicate item from " + j
3519                            + " due to specific " + specificsPos);
3520                        if (ri == null) {
3521                            ri = sri;
3522                        }
3523                        j--;
3524                        N--;
3525                    }
3526                }
3527
3528                // Add this specific item to its proper place.
3529                if (ri == null) {
3530                    ri = new ResolveInfo();
3531                    ri.activityInfo = ai;
3532                }
3533                results.add(specificsPos, ri);
3534                ri.specificIndex = i;
3535                specificsPos++;
3536            }
3537        }
3538
3539        // Now we go through the remaining generic results and remove any
3540        // duplicate actions that are found here.
3541        N = results.size();
3542        for (int i=specificsPos; i<N-1; i++) {
3543            final ResolveInfo rii = results.get(i);
3544            if (rii.filter == null) {
3545                continue;
3546            }
3547
3548            // Iterate over all of the actions of this result's intent
3549            // filter...  typically this should be just one.
3550            final Iterator<String> it = rii.filter.actionsIterator();
3551            if (it == null) {
3552                continue;
3553            }
3554            while (it.hasNext()) {
3555                final String action = it.next();
3556                if (resultsAction != null && resultsAction.equals(action)) {
3557                    // If this action was explicitly requested, then don't
3558                    // remove things that have it.
3559                    continue;
3560                }
3561                for (int j=i+1; j<N; j++) {
3562                    final ResolveInfo rij = results.get(j);
3563                    if (rij.filter != null && rij.filter.hasAction(action)) {
3564                        results.remove(j);
3565                        if (DEBUG_INTENT_MATCHING) Log.v(
3566                            TAG, "Removing duplicate item from " + j
3567                            + " due to action " + action + " at " + i);
3568                        j--;
3569                        N--;
3570                    }
3571                }
3572            }
3573
3574            // If the caller didn't request filter information, drop it now
3575            // so we don't have to marshall/unmarshall it.
3576            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3577                rii.filter = null;
3578            }
3579        }
3580
3581        // Filter out the caller activity if so requested.
3582        if (caller != null) {
3583            N = results.size();
3584            for (int i=0; i<N; i++) {
3585                ActivityInfo ainfo = results.get(i).activityInfo;
3586                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3587                        && caller.getClassName().equals(ainfo.name)) {
3588                    results.remove(i);
3589                    break;
3590                }
3591            }
3592        }
3593
3594        // If the caller didn't request filter information,
3595        // drop them now so we don't have to
3596        // marshall/unmarshall it.
3597        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3598            N = results.size();
3599            for (int i=0; i<N; i++) {
3600                results.get(i).filter = null;
3601            }
3602        }
3603
3604        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3605        return results;
3606    }
3607
3608    @Override
3609    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3610            int userId) {
3611        if (!sUserManager.exists(userId)) return Collections.emptyList();
3612        ComponentName comp = intent.getComponent();
3613        if (comp == null) {
3614            if (intent.getSelector() != null) {
3615                intent = intent.getSelector();
3616                comp = intent.getComponent();
3617            }
3618        }
3619        if (comp != null) {
3620            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3621            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3622            if (ai != null) {
3623                ResolveInfo ri = new ResolveInfo();
3624                ri.activityInfo = ai;
3625                list.add(ri);
3626            }
3627            return list;
3628        }
3629
3630        // reader
3631        synchronized (mPackages) {
3632            String pkgName = intent.getPackage();
3633            if (pkgName == null) {
3634                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3635            }
3636            final PackageParser.Package pkg = mPackages.get(pkgName);
3637            if (pkg != null) {
3638                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3639                        userId);
3640            }
3641            return null;
3642        }
3643    }
3644
3645    @Override
3646    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3647        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3648        if (!sUserManager.exists(userId)) return null;
3649        if (query != null) {
3650            if (query.size() >= 1) {
3651                // If there is more than one service with the same priority,
3652                // just arbitrarily pick the first one.
3653                return query.get(0);
3654            }
3655        }
3656        return null;
3657    }
3658
3659    @Override
3660    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3661            int userId) {
3662        if (!sUserManager.exists(userId)) return Collections.emptyList();
3663        ComponentName comp = intent.getComponent();
3664        if (comp == null) {
3665            if (intent.getSelector() != null) {
3666                intent = intent.getSelector();
3667                comp = intent.getComponent();
3668            }
3669        }
3670        if (comp != null) {
3671            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3672            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3673            if (si != null) {
3674                final ResolveInfo ri = new ResolveInfo();
3675                ri.serviceInfo = si;
3676                list.add(ri);
3677            }
3678            return list;
3679        }
3680
3681        // reader
3682        synchronized (mPackages) {
3683            String pkgName = intent.getPackage();
3684            if (pkgName == null) {
3685                return mServices.queryIntent(intent, resolvedType, flags, userId);
3686            }
3687            final PackageParser.Package pkg = mPackages.get(pkgName);
3688            if (pkg != null) {
3689                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3690                        userId);
3691            }
3692            return null;
3693        }
3694    }
3695
3696    @Override
3697    public List<ResolveInfo> queryIntentContentProviders(
3698            Intent intent, String resolvedType, int flags, int userId) {
3699        if (!sUserManager.exists(userId)) return Collections.emptyList();
3700        ComponentName comp = intent.getComponent();
3701        if (comp == null) {
3702            if (intent.getSelector() != null) {
3703                intent = intent.getSelector();
3704                comp = intent.getComponent();
3705            }
3706        }
3707        if (comp != null) {
3708            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3709            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3710            if (pi != null) {
3711                final ResolveInfo ri = new ResolveInfo();
3712                ri.providerInfo = pi;
3713                list.add(ri);
3714            }
3715            return list;
3716        }
3717
3718        // reader
3719        synchronized (mPackages) {
3720            String pkgName = intent.getPackage();
3721            if (pkgName == null) {
3722                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3723            }
3724            final PackageParser.Package pkg = mPackages.get(pkgName);
3725            if (pkg != null) {
3726                return mProviders.queryIntentForPackage(
3727                        intent, resolvedType, flags, pkg.providers, userId);
3728            }
3729            return null;
3730        }
3731    }
3732
3733    @Override
3734    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3735        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3736
3737        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3738
3739        // writer
3740        synchronized (mPackages) {
3741            ArrayList<PackageInfo> list;
3742            if (listUninstalled) {
3743                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3744                for (PackageSetting ps : mSettings.mPackages.values()) {
3745                    PackageInfo pi;
3746                    if (ps.pkg != null) {
3747                        pi = generatePackageInfo(ps.pkg, flags, userId);
3748                    } else {
3749                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3750                    }
3751                    if (pi != null) {
3752                        list.add(pi);
3753                    }
3754                }
3755            } else {
3756                list = new ArrayList<PackageInfo>(mPackages.size());
3757                for (PackageParser.Package p : mPackages.values()) {
3758                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3759                    if (pi != null) {
3760                        list.add(pi);
3761                    }
3762                }
3763            }
3764
3765            return new ParceledListSlice<PackageInfo>(list);
3766        }
3767    }
3768
3769    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3770            String[] permissions, boolean[] tmp, int flags, int userId) {
3771        int numMatch = 0;
3772        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3773        for (int i=0; i<permissions.length; i++) {
3774            if (gp.grantedPermissions.contains(permissions[i])) {
3775                tmp[i] = true;
3776                numMatch++;
3777            } else {
3778                tmp[i] = false;
3779            }
3780        }
3781        if (numMatch == 0) {
3782            return;
3783        }
3784        PackageInfo pi;
3785        if (ps.pkg != null) {
3786            pi = generatePackageInfo(ps.pkg, flags, userId);
3787        } else {
3788            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3789        }
3790        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3791            if (numMatch == permissions.length) {
3792                pi.requestedPermissions = permissions;
3793            } else {
3794                pi.requestedPermissions = new String[numMatch];
3795                numMatch = 0;
3796                for (int i=0; i<permissions.length; i++) {
3797                    if (tmp[i]) {
3798                        pi.requestedPermissions[numMatch] = permissions[i];
3799                        numMatch++;
3800                    }
3801                }
3802            }
3803        }
3804        list.add(pi);
3805    }
3806
3807    @Override
3808    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3809            String[] permissions, int flags, int userId) {
3810        if (!sUserManager.exists(userId)) return null;
3811        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3812
3813        // writer
3814        synchronized (mPackages) {
3815            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3816            boolean[] tmpBools = new boolean[permissions.length];
3817            if (listUninstalled) {
3818                for (PackageSetting ps : mSettings.mPackages.values()) {
3819                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3820                }
3821            } else {
3822                for (PackageParser.Package pkg : mPackages.values()) {
3823                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3824                    if (ps != null) {
3825                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3826                                userId);
3827                    }
3828                }
3829            }
3830
3831            return new ParceledListSlice<PackageInfo>(list);
3832        }
3833    }
3834
3835    @Override
3836    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3837        if (!sUserManager.exists(userId)) return null;
3838        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3839
3840        // writer
3841        synchronized (mPackages) {
3842            ArrayList<ApplicationInfo> list;
3843            if (listUninstalled) {
3844                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3845                for (PackageSetting ps : mSettings.mPackages.values()) {
3846                    ApplicationInfo ai;
3847                    if (ps.pkg != null) {
3848                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3849                                ps.readUserState(userId), userId);
3850                    } else {
3851                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3852                    }
3853                    if (ai != null) {
3854                        list.add(ai);
3855                    }
3856                }
3857            } else {
3858                list = new ArrayList<ApplicationInfo>(mPackages.size());
3859                for (PackageParser.Package p : mPackages.values()) {
3860                    if (p.mExtras != null) {
3861                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3862                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3863                        if (ai != null) {
3864                            list.add(ai);
3865                        }
3866                    }
3867                }
3868            }
3869
3870            return new ParceledListSlice<ApplicationInfo>(list);
3871        }
3872    }
3873
3874    public List<ApplicationInfo> getPersistentApplications(int flags) {
3875        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3876
3877        // reader
3878        synchronized (mPackages) {
3879            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3880            final int userId = UserHandle.getCallingUserId();
3881            while (i.hasNext()) {
3882                final PackageParser.Package p = i.next();
3883                if (p.applicationInfo != null
3884                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3885                        && (!mSafeMode || isSystemApp(p))) {
3886                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3887                    if (ps != null) {
3888                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3889                                ps.readUserState(userId), userId);
3890                        if (ai != null) {
3891                            finalList.add(ai);
3892                        }
3893                    }
3894                }
3895            }
3896        }
3897
3898        return finalList;
3899    }
3900
3901    @Override
3902    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3903        if (!sUserManager.exists(userId)) return null;
3904        // reader
3905        synchronized (mPackages) {
3906            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3907            PackageSetting ps = provider != null
3908                    ? mSettings.mPackages.get(provider.owner.packageName)
3909                    : null;
3910            return ps != null
3911                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3912                    && (!mSafeMode || (provider.info.applicationInfo.flags
3913                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3914                    ? PackageParser.generateProviderInfo(provider, flags,
3915                            ps.readUserState(userId), userId)
3916                    : null;
3917        }
3918    }
3919
3920    /**
3921     * @deprecated
3922     */
3923    @Deprecated
3924    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3925        // reader
3926        synchronized (mPackages) {
3927            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3928                    .entrySet().iterator();
3929            final int userId = UserHandle.getCallingUserId();
3930            while (i.hasNext()) {
3931                Map.Entry<String, PackageParser.Provider> entry = i.next();
3932                PackageParser.Provider p = entry.getValue();
3933                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3934
3935                if (ps != null && p.syncable
3936                        && (!mSafeMode || (p.info.applicationInfo.flags
3937                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3938                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3939                            ps.readUserState(userId), userId);
3940                    if (info != null) {
3941                        outNames.add(entry.getKey());
3942                        outInfo.add(info);
3943                    }
3944                }
3945            }
3946        }
3947    }
3948
3949    @Override
3950    public List<ProviderInfo> queryContentProviders(String processName,
3951            int uid, int flags) {
3952        ArrayList<ProviderInfo> finalList = null;
3953        // reader
3954        synchronized (mPackages) {
3955            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3956            final int userId = processName != null ?
3957                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3958            while (i.hasNext()) {
3959                final PackageParser.Provider p = i.next();
3960                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3961                if (ps != null && p.info.authority != null
3962                        && (processName == null
3963                                || (p.info.processName.equals(processName)
3964                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3965                        && mSettings.isEnabledLPr(p.info, flags, userId)
3966                        && (!mSafeMode
3967                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3968                    if (finalList == null) {
3969                        finalList = new ArrayList<ProviderInfo>(3);
3970                    }
3971                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3972                            ps.readUserState(userId), userId);
3973                    if (info != null) {
3974                        finalList.add(info);
3975                    }
3976                }
3977            }
3978        }
3979
3980        if (finalList != null) {
3981            Collections.sort(finalList, mProviderInitOrderSorter);
3982        }
3983
3984        return finalList;
3985    }
3986
3987    @Override
3988    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3989            int flags) {
3990        // reader
3991        synchronized (mPackages) {
3992            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3993            return PackageParser.generateInstrumentationInfo(i, flags);
3994        }
3995    }
3996
3997    @Override
3998    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3999            int flags) {
4000        ArrayList<InstrumentationInfo> finalList =
4001            new ArrayList<InstrumentationInfo>();
4002
4003        // reader
4004        synchronized (mPackages) {
4005            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4006            while (i.hasNext()) {
4007                final PackageParser.Instrumentation p = i.next();
4008                if (targetPackage == null
4009                        || targetPackage.equals(p.info.targetPackage)) {
4010                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4011                            flags);
4012                    if (ii != null) {
4013                        finalList.add(ii);
4014                    }
4015                }
4016            }
4017        }
4018
4019        return finalList;
4020    }
4021
4022    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4023        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4024        if (overlays == null) {
4025            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4026            return;
4027        }
4028        for (PackageParser.Package opkg : overlays.values()) {
4029            // Not much to do if idmap fails: we already logged the error
4030            // and we certainly don't want to abort installation of pkg simply
4031            // because an overlay didn't fit properly. For these reasons,
4032            // ignore the return value of createIdmapForPackagePairLI.
4033            createIdmapForPackagePairLI(pkg, opkg);
4034        }
4035    }
4036
4037    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4038            PackageParser.Package opkg) {
4039        if (!opkg.mTrustedOverlay) {
4040            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4041                    opkg.baseCodePath + ": overlay not trusted");
4042            return false;
4043        }
4044        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4045        if (overlaySet == null) {
4046            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4047                    opkg.baseCodePath + " but target package has no known overlays");
4048            return false;
4049        }
4050        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4051        // TODO: generate idmap for split APKs
4052        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4053            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4054                    + opkg.baseCodePath);
4055            return false;
4056        }
4057        PackageParser.Package[] overlayArray =
4058            overlaySet.values().toArray(new PackageParser.Package[0]);
4059        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4060            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4061                return p1.mOverlayPriority - p2.mOverlayPriority;
4062            }
4063        };
4064        Arrays.sort(overlayArray, cmp);
4065
4066        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4067        int i = 0;
4068        for (PackageParser.Package p : overlayArray) {
4069            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4070        }
4071        return true;
4072    }
4073
4074    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4075        final File[] files = dir.listFiles();
4076        if (ArrayUtils.isEmpty(files)) {
4077            Log.d(TAG, "No files in app dir " + dir);
4078            return;
4079        }
4080
4081        if (DEBUG_PACKAGE_SCANNING) {
4082            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4083                    + " flags=0x" + Integer.toHexString(flags));
4084        }
4085
4086        for (File file : files) {
4087            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4088                    && !PackageInstallerService.isStageFile(file);
4089            if (!isPackage) {
4090                // Ignore entries which are not apk's
4091                continue;
4092            }
4093            try {
4094                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime,
4095                        null, null);
4096            } catch (PackageManagerException e) {
4097                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4098
4099                // Don't mess around with apps in system partition.
4100                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4101                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4102                    // Delete the apk
4103                    Slog.w(TAG, "Cleaning up failed install of " + file);
4104                    file.delete();
4105                }
4106            }
4107        }
4108    }
4109
4110    private static File getSettingsProblemFile() {
4111        File dataDir = Environment.getDataDirectory();
4112        File systemDir = new File(dataDir, "system");
4113        File fname = new File(systemDir, "uiderrors.txt");
4114        return fname;
4115    }
4116
4117    static void reportSettingsProblem(int priority, String msg) {
4118        try {
4119            File fname = getSettingsProblemFile();
4120            FileOutputStream out = new FileOutputStream(fname, true);
4121            PrintWriter pw = new FastPrintWriter(out);
4122            SimpleDateFormat formatter = new SimpleDateFormat();
4123            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4124            pw.println(dateString + ": " + msg);
4125            pw.close();
4126            FileUtils.setPermissions(
4127                    fname.toString(),
4128                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4129                    -1, -1);
4130        } catch (java.io.IOException e) {
4131        }
4132        Slog.println(priority, TAG, msg);
4133    }
4134
4135    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4136            PackageParser.Package pkg, File srcFile, int parseFlags)
4137            throws PackageManagerException {
4138        if (ps != null
4139                && ps.codePath.equals(srcFile)
4140                && ps.timeStamp == srcFile.lastModified()
4141                && !isCompatSignatureUpdateNeeded(pkg)) {
4142            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4143            if (ps.signatures.mSignatures != null
4144                    && ps.signatures.mSignatures.length != 0
4145                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4146                // Optimization: reuse the existing cached certificates
4147                // if the package appears to be unchanged.
4148                pkg.mSignatures = ps.signatures.mSignatures;
4149                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4150                synchronized (mPackages) {
4151                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4152                }
4153                return;
4154            }
4155
4156            Slog.w(TAG, "PackageSetting for " + ps.name
4157                    + " is missing signatures.  Collecting certs again to recover them.");
4158        } else {
4159            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4160        }
4161
4162        try {
4163            pp.collectCertificates(pkg, parseFlags);
4164            pp.collectManifestDigest(pkg);
4165        } catch (PackageParserException e) {
4166            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4167                    + pkg.packageName + ": " + e.getMessage());
4168        }
4169    }
4170
4171    /*
4172     *  Scan a package and return the newly parsed package.
4173     *  Returns null in case of errors and the error code is stored in mLastScanError
4174     */
4175    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4176            long currentTime, UserHandle user, String abiOverride) throws PackageManagerException {
4177        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4178        parseFlags |= mDefParseFlags;
4179        PackageParser pp = new PackageParser();
4180        pp.setSeparateProcesses(mSeparateProcesses);
4181        pp.setOnlyCoreApps(mOnlyCore);
4182        pp.setDisplayMetrics(mMetrics);
4183
4184        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4185            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4186        }
4187
4188        final PackageParser.Package pkg;
4189        try {
4190            pkg = pp.parsePackage(scanFile, parseFlags);
4191        } catch (PackageParserException e) {
4192            throw new PackageManagerException(e.error,
4193                    "Failed to scan " + scanFile + ": " + e.getMessage());
4194        }
4195
4196        PackageSetting ps = null;
4197        PackageSetting updatedPkg;
4198        // reader
4199        synchronized (mPackages) {
4200            // Look to see if we already know about this package.
4201            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4202            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4203                // This package has been renamed to its original name.  Let's
4204                // use that.
4205                ps = mSettings.peekPackageLPr(oldName);
4206            }
4207            // If there was no original package, see one for the real package name.
4208            if (ps == null) {
4209                ps = mSettings.peekPackageLPr(pkg.packageName);
4210            }
4211            // Check to see if this package could be hiding/updating a system
4212            // package.  Must look for it either under the original or real
4213            // package name depending on our state.
4214            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4215            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4216        }
4217        boolean updatedPkgBetter = false;
4218        // First check if this is a system package that may involve an update
4219        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4220            if (ps != null && !ps.codePath.equals(scanFile)) {
4221                // The path has changed from what was last scanned...  check the
4222                // version of the new path against what we have stored to determine
4223                // what to do.
4224                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4225                if (pkg.mVersionCode < ps.versionCode) {
4226                    // The system package has been updated and the code path does not match
4227                    // Ignore entry. Skip it.
4228                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4229                            + " ignored: updated version " + ps.versionCode
4230                            + " better than this " + pkg.mVersionCode);
4231                    if (!updatedPkg.codePath.equals(scanFile)) {
4232                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4233                                + ps.name + " changing from " + updatedPkg.codePathString
4234                                + " to " + scanFile);
4235                        updatedPkg.codePath = scanFile;
4236                        updatedPkg.codePathString = scanFile.toString();
4237                        // This is the point at which we know that the system-disk APK
4238                        // for this package has moved during a reboot (e.g. due to an OTA),
4239                        // so we need to reevaluate it for privilege policy.
4240                        if (locationIsPrivileged(scanFile)) {
4241                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4242                        }
4243                    }
4244                    updatedPkg.pkg = pkg;
4245                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4246                } else {
4247                    // The current app on the system partition is better than
4248                    // what we have updated to on the data partition; switch
4249                    // back to the system partition version.
4250                    // At this point, its safely assumed that package installation for
4251                    // apps in system partition will go through. If not there won't be a working
4252                    // version of the app
4253                    // writer
4254                    synchronized (mPackages) {
4255                        // Just remove the loaded entries from package lists.
4256                        mPackages.remove(ps.name);
4257                    }
4258                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4259                            + "reverting from " + ps.codePathString
4260                            + ": new version " + pkg.mVersionCode
4261                            + " better than installed " + ps.versionCode);
4262
4263                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4264                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4265                            getAppDexInstructionSets(ps), isMultiArch(ps));
4266                    synchronized (mInstallLock) {
4267                        args.cleanUpResourcesLI();
4268                    }
4269                    synchronized (mPackages) {
4270                        mSettings.enableSystemPackageLPw(ps.name);
4271                    }
4272                    updatedPkgBetter = true;
4273                }
4274            }
4275        }
4276
4277        if (updatedPkg != null) {
4278            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4279            // initially
4280            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4281
4282            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4283            // flag set initially
4284            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4285                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4286            }
4287        }
4288
4289        // Verify certificates against what was last scanned
4290        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4291
4292        /*
4293         * A new system app appeared, but we already had a non-system one of the
4294         * same name installed earlier.
4295         */
4296        boolean shouldHideSystemApp = false;
4297        if (updatedPkg == null && ps != null
4298                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4299            /*
4300             * Check to make sure the signatures match first. If they don't,
4301             * wipe the installed application and its data.
4302             */
4303            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4304                    != PackageManager.SIGNATURE_MATCH) {
4305                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4306                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4307                ps = null;
4308            } else {
4309                /*
4310                 * If the newly-added system app is an older version than the
4311                 * already installed version, hide it. It will be scanned later
4312                 * and re-added like an update.
4313                 */
4314                if (pkg.mVersionCode < ps.versionCode) {
4315                    shouldHideSystemApp = true;
4316                } else {
4317                    /*
4318                     * The newly found system app is a newer version that the
4319                     * one previously installed. Simply remove the
4320                     * already-installed application and replace it with our own
4321                     * while keeping the application data.
4322                     */
4323                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4324                            + ps.codePathString + ": new version " + pkg.mVersionCode
4325                            + " better than installed " + ps.versionCode);
4326                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4327                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4328                            getAppDexInstructionSets(ps), isMultiArch(ps));
4329                    synchronized (mInstallLock) {
4330                        args.cleanUpResourcesLI();
4331                    }
4332                }
4333            }
4334        }
4335
4336        // The apk is forward locked (not public) if its code and resources
4337        // are kept in different files. (except for app in either system or
4338        // vendor path).
4339        // TODO grab this value from PackageSettings
4340        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4341            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4342                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4343            }
4344        }
4345
4346        // TODO: extend to support forward-locked splits
4347        String resourcePath = null;
4348        String baseResourcePath = null;
4349        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4350            if (ps != null && ps.resourcePathString != null) {
4351                resourcePath = ps.resourcePathString;
4352                baseResourcePath = ps.resourcePathString;
4353            } else {
4354                // Should not happen at all. Just log an error.
4355                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4356            }
4357        } else {
4358            resourcePath = pkg.codePath;
4359            baseResourcePath = pkg.baseCodePath;
4360        }
4361
4362        // Set application objects path explicitly.
4363        pkg.applicationInfo.setCodePath(pkg.codePath);
4364        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4365        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4366        pkg.applicationInfo.setResourcePath(resourcePath);
4367        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4368        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4369
4370        // Note that we invoke the following method only if we are about to unpack an application
4371        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4372                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4373
4374        /*
4375         * If the system app should be overridden by a previously installed
4376         * data, hide the system app now and let the /data/app scan pick it up
4377         * again.
4378         */
4379        if (shouldHideSystemApp) {
4380            synchronized (mPackages) {
4381                /*
4382                 * We have to grant systems permissions before we hide, because
4383                 * grantPermissions will assume the package update is trying to
4384                 * expand its permissions.
4385                 */
4386                grantPermissionsLPw(pkg, true);
4387                mSettings.disableSystemPackageLPw(pkg.packageName);
4388            }
4389        }
4390
4391        return scannedPkg;
4392    }
4393
4394    private static String fixProcessName(String defProcessName,
4395            String processName, int uid) {
4396        if (processName == null) {
4397            return defProcessName;
4398        }
4399        return processName;
4400    }
4401
4402    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4403            throws PackageManagerException {
4404        if (pkgSetting.signatures.mSignatures != null) {
4405            // Already existing package. Make sure signatures match
4406            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4407                    == PackageManager.SIGNATURE_MATCH;
4408            if (!match) {
4409                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4410                        == PackageManager.SIGNATURE_MATCH;
4411            }
4412            if (!match) {
4413                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4414                        + pkg.packageName + " signatures do not match the "
4415                        + "previously installed version; ignoring!");
4416            }
4417        }
4418
4419        // Check for shared user signatures
4420        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4421            // Already existing package. Make sure signatures match
4422            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4423                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4424            if (!match) {
4425                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4426                        == PackageManager.SIGNATURE_MATCH;
4427            }
4428            if (!match) {
4429                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4430                        "Package " + pkg.packageName
4431                        + " has no signatures that match those in shared user "
4432                        + pkgSetting.sharedUser.name + "; ignoring!");
4433            }
4434        }
4435    }
4436
4437    /**
4438     * Enforces that only the system UID or root's UID can call a method exposed
4439     * via Binder.
4440     *
4441     * @param message used as message if SecurityException is thrown
4442     * @throws SecurityException if the caller is not system or root
4443     */
4444    private static final void enforceSystemOrRoot(String message) {
4445        final int uid = Binder.getCallingUid();
4446        if (uid != Process.SYSTEM_UID && uid != 0) {
4447            throw new SecurityException(message);
4448        }
4449    }
4450
4451    @Override
4452    public void performBootDexOpt() {
4453        enforceSystemOrRoot("Only the system can request dexopt be performed");
4454
4455        final HashSet<PackageParser.Package> pkgs;
4456        synchronized (mPackages) {
4457            pkgs = mDeferredDexOpt;
4458            mDeferredDexOpt = null;
4459        }
4460
4461        if (pkgs != null) {
4462            // Filter out packages that aren't recently used.
4463            //
4464            // The exception is first boot of a non-eng device, which
4465            // should do a full dexopt.
4466            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4467            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4468                // TODO: add a property to control this?
4469                long dexOptLRUThresholdInMinutes;
4470                if (eng) {
4471                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4472                } else {
4473                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4474                }
4475                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4476
4477                int total = pkgs.size();
4478                int skipped = 0;
4479                long now = System.currentTimeMillis();
4480                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4481                    PackageParser.Package pkg = i.next();
4482                    long then = pkg.mLastPackageUsageTimeInMills;
4483                    if (then + dexOptLRUThresholdInMills < now) {
4484                        if (DEBUG_DEXOPT) {
4485                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4486                                  ((then == 0) ? "never" : new Date(then)));
4487                        }
4488                        i.remove();
4489                        skipped++;
4490                    }
4491                }
4492                if (DEBUG_DEXOPT) {
4493                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4494                }
4495            }
4496
4497            int i = 0;
4498            for (PackageParser.Package pkg : pkgs) {
4499                i++;
4500                if (DEBUG_DEXOPT) {
4501                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4502                          + ": " + pkg.packageName);
4503                }
4504                if (!isFirstBoot()) {
4505                    try {
4506                        ActivityManagerNative.getDefault().showBootMessage(
4507                                mContext.getResources().getString(
4508                                        R.string.android_upgrading_apk,
4509                                        i, pkgs.size()), true);
4510                    } catch (RemoteException e) {
4511                    }
4512                }
4513                PackageParser.Package p = pkg;
4514                synchronized (mInstallLock) {
4515                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4516                            true /* include dependencies */);
4517                }
4518            }
4519        }
4520    }
4521
4522    @Override
4523    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4524        return performDexOpt(packageName, instructionSet, true);
4525    }
4526
4527    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4528        if (info.primaryCpuAbi == null) {
4529            return getPreferredInstructionSet();
4530        }
4531
4532        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4533    }
4534
4535    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4536        PackageParser.Package p;
4537        final String targetInstructionSet;
4538        synchronized (mPackages) {
4539            p = mPackages.get(packageName);
4540            if (p == null) {
4541                return false;
4542            }
4543            if (updateUsage) {
4544                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4545            }
4546            mPackageUsage.write(false);
4547
4548            targetInstructionSet = instructionSet != null ? instructionSet :
4549                    getPrimaryInstructionSet(p.applicationInfo);
4550            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4551                return false;
4552            }
4553        }
4554
4555        synchronized (mInstallLock) {
4556            final String[] instructionSets = new String[] { targetInstructionSet };
4557            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4558                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4559        }
4560    }
4561
4562    public HashSet<String> getPackagesThatNeedDexOpt() {
4563        HashSet<String> pkgs = null;
4564        synchronized (mPackages) {
4565            for (PackageParser.Package p : mPackages.values()) {
4566                if (DEBUG_DEXOPT) {
4567                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4568                }
4569                if (!p.mDexOptPerformed.isEmpty()) {
4570                    continue;
4571                }
4572                if (pkgs == null) {
4573                    pkgs = new HashSet<String>();
4574                }
4575                pkgs.add(p.packageName);
4576            }
4577        }
4578        return pkgs;
4579    }
4580
4581    public void shutdown() {
4582        mPackageUsage.write(true);
4583    }
4584
4585    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4586             boolean forceDex, boolean defer, HashSet<String> done) {
4587        for (int i=0; i<libs.size(); i++) {
4588            PackageParser.Package libPkg;
4589            String libName;
4590            synchronized (mPackages) {
4591                libName = libs.get(i);
4592                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4593                if (lib != null && lib.apk != null) {
4594                    libPkg = mPackages.get(lib.apk);
4595                } else {
4596                    libPkg = null;
4597                }
4598            }
4599            if (libPkg != null && !done.contains(libName)) {
4600                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4601            }
4602        }
4603    }
4604
4605    static final int DEX_OPT_SKIPPED = 0;
4606    static final int DEX_OPT_PERFORMED = 1;
4607    static final int DEX_OPT_DEFERRED = 2;
4608    static final int DEX_OPT_FAILED = -1;
4609
4610    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4611            boolean forceDex, boolean defer, HashSet<String> done) {
4612        final String[] instructionSets = targetInstructionSets != null ?
4613                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4614
4615        if (done != null) {
4616            done.add(pkg.packageName);
4617            if (pkg.usesLibraries != null) {
4618                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4619            }
4620            if (pkg.usesOptionalLibraries != null) {
4621                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4622            }
4623        }
4624
4625        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4626            return DEX_OPT_SKIPPED;
4627        }
4628
4629        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4630        boolean performedDexOpt = false;
4631        // There are three basic cases here:
4632        // 1.) we need to dexopt, either because we are forced or it is needed
4633        // 2.) we are defering a needed dexopt
4634        // 3.) we are skipping an unneeded dexopt
4635        for (String path : paths) {
4636            for (String instructionSet : instructionSets) {
4637                if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) {
4638                    continue;
4639                }
4640
4641                try {
4642                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4643                    // patckage or the one we find does not match the image checksum (i.e. it was
4644                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4645                    // odex file and it matches the checksum of the image but not its base address,
4646                    // meaning we need to move it.
4647                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4648                            pkg.packageName, instructionSet, defer);
4649                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4650                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4651                                + pkg.applicationInfo.packageName + " isa=" + instructionSet);
4652                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4653                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4654                                pkg.packageName, instructionSet);
4655
4656                        if (ret < 0) {
4657                            // Don't bother running dexopt again if we failed, it will probably
4658                            // just result in an error again. Also, don't bother dexopting for other
4659                            // paths & ISAs.
4660                            return DEX_OPT_FAILED;
4661                        } else {
4662                            performedDexOpt = true;
4663                            pkg.mDexOptPerformed.add(instructionSet);
4664                        }
4665                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4666                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4667                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4668                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4669                                pkg.packageName, instructionSet);
4670
4671                        if (ret < 0) {
4672                            // Don't bother running patchoat again if we failed, it will probably
4673                            // just result in an error again. Also, don't bother dexopting for other
4674                            // paths & ISAs.
4675                            return DEX_OPT_FAILED;
4676                        } else {
4677                            performedDexOpt = true;
4678                            pkg.mDexOptPerformed.add(instructionSet);
4679                        }
4680                    }
4681
4682                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4683                    // paths and instruction sets. We'll deal with them all together when we process
4684                    // our list of deferred dexopts.
4685                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4686                        if (mDeferredDexOpt == null) {
4687                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4688                        }
4689                        mDeferredDexOpt.add(pkg);
4690                        return DEX_OPT_DEFERRED;
4691                    }
4692                } catch (FileNotFoundException e) {
4693                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4694                    return DEX_OPT_FAILED;
4695                } catch (IOException e) {
4696                    Slog.w(TAG, "IOException reading apk: " + path, e);
4697                    return DEX_OPT_FAILED;
4698                } catch (StaleDexCacheError e) {
4699                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4700                    return DEX_OPT_FAILED;
4701                } catch (Exception e) {
4702                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4703                    return DEX_OPT_FAILED;
4704                }
4705            }
4706        }
4707
4708        // If we've gotten here, we're sure that no error occurred and that we haven't
4709        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4710        // we've skipped all of them because they are up to date. In both cases this
4711        // package doesn't need dexopt any longer.
4712        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4713    }
4714
4715    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4716        if (info.primaryCpuAbi != null) {
4717            if (info.secondaryCpuAbi != null) {
4718                return new String[] {
4719                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4720                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4721            } else {
4722                return new String[] {
4723                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4724            }
4725        }
4726
4727        return new String[] { getPreferredInstructionSet() };
4728    }
4729
4730    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4731        if (ps.primaryCpuAbiString != null) {
4732            if (ps.secondaryCpuAbiString != null) {
4733                return new String[] {
4734                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4735                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4736            } else {
4737                return new String[] {
4738                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4739            }
4740        }
4741
4742        return new String[] { getPreferredInstructionSet() };
4743    }
4744
4745    private static String getPreferredInstructionSet() {
4746        if (sPreferredInstructionSet == null) {
4747            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4748        }
4749
4750        return sPreferredInstructionSet;
4751    }
4752
4753    private static List<String> getAllInstructionSets() {
4754        final String[] allAbis = Build.SUPPORTED_ABIS;
4755        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4756
4757        for (String abi : allAbis) {
4758            final String instructionSet = VMRuntime.getInstructionSet(abi);
4759            if (!allInstructionSets.contains(instructionSet)) {
4760                allInstructionSets.add(instructionSet);
4761            }
4762        }
4763
4764        return allInstructionSets;
4765    }
4766
4767    @Override
4768    public void forceDexOpt(String packageName) {
4769        enforceSystemOrRoot("forceDexOpt");
4770
4771        PackageParser.Package pkg;
4772        synchronized (mPackages) {
4773            pkg = mPackages.get(packageName);
4774            if (pkg == null) {
4775                throw new IllegalArgumentException("Missing package: " + packageName);
4776            }
4777        }
4778
4779        synchronized (mInstallLock) {
4780            final String[] instructionSets = new String[] {
4781                    getPrimaryInstructionSet(pkg.applicationInfo) };
4782            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4783            if (res != DEX_OPT_PERFORMED) {
4784                throw new IllegalStateException("Failed to dexopt: " + res);
4785            }
4786        }
4787    }
4788
4789    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4790                                boolean forceDex, boolean defer, boolean inclDependencies) {
4791        HashSet<String> done;
4792        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4793            done = new HashSet<String>();
4794            done.add(pkg.packageName);
4795        } else {
4796            done = null;
4797        }
4798        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4799    }
4800
4801    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4802        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4803            Slog.w(TAG, "Unable to update from " + oldPkg.name
4804                    + " to " + newPkg.packageName
4805                    + ": old package not in system partition");
4806            return false;
4807        } else if (mPackages.get(oldPkg.name) != null) {
4808            Slog.w(TAG, "Unable to update from " + oldPkg.name
4809                    + " to " + newPkg.packageName
4810                    + ": old package still exists");
4811            return false;
4812        }
4813        return true;
4814    }
4815
4816    File getDataPathForUser(int userId) {
4817        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4818    }
4819
4820    private File getDataPathForPackage(String packageName, int userId) {
4821        /*
4822         * Until we fully support multiple users, return the directory we
4823         * previously would have. The PackageManagerTests will need to be
4824         * revised when this is changed back..
4825         */
4826        if (userId == 0) {
4827            return new File(mAppDataDir, packageName);
4828        } else {
4829            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4830                + File.separator + packageName);
4831        }
4832    }
4833
4834    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4835        int[] users = sUserManager.getUserIds();
4836        int res = mInstaller.install(packageName, uid, uid, seinfo);
4837        if (res < 0) {
4838            return res;
4839        }
4840        for (int user : users) {
4841            if (user != 0) {
4842                res = mInstaller.createUserData(packageName,
4843                        UserHandle.getUid(user, uid), user, seinfo);
4844                if (res < 0) {
4845                    return res;
4846                }
4847            }
4848        }
4849        return res;
4850    }
4851
4852    private int removeDataDirsLI(String packageName) {
4853        int[] users = sUserManager.getUserIds();
4854        int res = 0;
4855        for (int user : users) {
4856            int resInner = mInstaller.remove(packageName, user);
4857            if (resInner < 0) {
4858                res = resInner;
4859            }
4860        }
4861
4862        return res;
4863    }
4864
4865    private int deleteCodeCacheDirsLI(String packageName) {
4866        int[] users = sUserManager.getUserIds();
4867        int res = 0;
4868        for (int user : users) {
4869            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4870            if (resInner < 0) {
4871                res = resInner;
4872            }
4873        }
4874        return res;
4875    }
4876
4877    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4878            PackageParser.Package changingLib) {
4879        if (file.path != null) {
4880            usesLibraryFiles.add(file.path);
4881            return;
4882        }
4883        PackageParser.Package p = mPackages.get(file.apk);
4884        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4885            // If we are doing this while in the middle of updating a library apk,
4886            // then we need to make sure to use that new apk for determining the
4887            // dependencies here.  (We haven't yet finished committing the new apk
4888            // to the package manager state.)
4889            if (p == null || p.packageName.equals(changingLib.packageName)) {
4890                p = changingLib;
4891            }
4892        }
4893        if (p != null) {
4894            usesLibraryFiles.addAll(p.getAllCodePaths());
4895        }
4896    }
4897
4898    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4899            PackageParser.Package changingLib) throws PackageManagerException {
4900        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4901            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4902            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4903            for (int i=0; i<N; i++) {
4904                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4905                if (file == null) {
4906                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4907                            "Package " + pkg.packageName + " requires unavailable shared library "
4908                            + pkg.usesLibraries.get(i) + "; failing!");
4909                }
4910                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4911            }
4912            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4913            for (int i=0; i<N; i++) {
4914                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4915                if (file == null) {
4916                    Slog.w(TAG, "Package " + pkg.packageName
4917                            + " desires unavailable shared library "
4918                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4919                } else {
4920                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4921                }
4922            }
4923            N = usesLibraryFiles.size();
4924            if (N > 0) {
4925                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4926            } else {
4927                pkg.usesLibraryFiles = null;
4928            }
4929        }
4930    }
4931
4932    private static boolean hasString(List<String> list, List<String> which) {
4933        if (list == null) {
4934            return false;
4935        }
4936        for (int i=list.size()-1; i>=0; i--) {
4937            for (int j=which.size()-1; j>=0; j--) {
4938                if (which.get(j).equals(list.get(i))) {
4939                    return true;
4940                }
4941            }
4942        }
4943        return false;
4944    }
4945
4946    private void updateAllSharedLibrariesLPw() {
4947        for (PackageParser.Package pkg : mPackages.values()) {
4948            try {
4949                updateSharedLibrariesLPw(pkg, null);
4950            } catch (PackageManagerException e) {
4951                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4952            }
4953        }
4954    }
4955
4956    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4957            PackageParser.Package changingPkg) {
4958        ArrayList<PackageParser.Package> res = null;
4959        for (PackageParser.Package pkg : mPackages.values()) {
4960            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4961                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4962                if (res == null) {
4963                    res = new ArrayList<PackageParser.Package>();
4964                }
4965                res.add(pkg);
4966                try {
4967                    updateSharedLibrariesLPw(pkg, changingPkg);
4968                } catch (PackageManagerException e) {
4969                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4970                }
4971            }
4972        }
4973        return res;
4974    }
4975
4976    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4977            int scanMode, long currentTime, UserHandle user, String abiOverride)
4978            throws PackageManagerException {
4979        final File scanFile = new File(pkg.codePath);
4980        if (pkg.applicationInfo.getCodePath() == null ||
4981                pkg.applicationInfo.getResourcePath() == null) {
4982            // Bail out. The resource and code paths haven't been set.
4983            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4984                    "Code and resource paths haven't been set correctly");
4985        }
4986
4987        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4988            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4989        }
4990
4991        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4992            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4993        }
4994
4995        if (mCustomResolverComponentName != null &&
4996                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4997            setUpCustomResolverActivity(pkg);
4998        }
4999
5000        if (pkg.packageName.equals("android")) {
5001            synchronized (mPackages) {
5002                if (mAndroidApplication != null) {
5003                    Slog.w(TAG, "*************************************************");
5004                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5005                    Slog.w(TAG, " file=" + scanFile);
5006                    Slog.w(TAG, "*************************************************");
5007                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5008                            "Core android package being redefined.  Skipping.");
5009                }
5010
5011                // Set up information for our fall-back user intent resolution activity.
5012                mPlatformPackage = pkg;
5013                pkg.mVersionCode = mSdkVersion;
5014                mAndroidApplication = pkg.applicationInfo;
5015
5016                if (!mResolverReplaced) {
5017                    mResolveActivity.applicationInfo = mAndroidApplication;
5018                    mResolveActivity.name = ResolverActivity.class.getName();
5019                    mResolveActivity.packageName = mAndroidApplication.packageName;
5020                    mResolveActivity.processName = "system:ui";
5021                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5022                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5023                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5024                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5025                    mResolveActivity.exported = true;
5026                    mResolveActivity.enabled = true;
5027                    mResolveInfo.activityInfo = mResolveActivity;
5028                    mResolveInfo.priority = 0;
5029                    mResolveInfo.preferredOrder = 0;
5030                    mResolveInfo.match = 0;
5031                    mResolveComponentName = new ComponentName(
5032                            mAndroidApplication.packageName, mResolveActivity.name);
5033                }
5034            }
5035        }
5036
5037        if (DEBUG_PACKAGE_SCANNING) {
5038            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5039                Log.d(TAG, "Scanning package " + pkg.packageName);
5040        }
5041
5042        if (mPackages.containsKey(pkg.packageName)
5043                || mSharedLibraries.containsKey(pkg.packageName)) {
5044            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5045                    "Application package " + pkg.packageName
5046                    + " already installed.  Skipping duplicate.");
5047        }
5048
5049        // Initialize package source and resource directories
5050        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5051        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5052
5053        SharedUserSetting suid = null;
5054        PackageSetting pkgSetting = null;
5055
5056        if (!isSystemApp(pkg)) {
5057            // Only system apps can use these features.
5058            pkg.mOriginalPackages = null;
5059            pkg.mRealPackage = null;
5060            pkg.mAdoptPermissions = null;
5061        }
5062
5063        // writer
5064        synchronized (mPackages) {
5065            if (pkg.mSharedUserId != null) {
5066                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5067                if (suid == null) {
5068                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5069                            "Creating application package " + pkg.packageName
5070                            + " for shared user failed");
5071                }
5072                if (DEBUG_PACKAGE_SCANNING) {
5073                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5074                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5075                                + "): packages=" + suid.packages);
5076                }
5077            }
5078
5079            // Check if we are renaming from an original package name.
5080            PackageSetting origPackage = null;
5081            String realName = null;
5082            if (pkg.mOriginalPackages != null) {
5083                // This package may need to be renamed to a previously
5084                // installed name.  Let's check on that...
5085                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5086                if (pkg.mOriginalPackages.contains(renamed)) {
5087                    // This package had originally been installed as the
5088                    // original name, and we have already taken care of
5089                    // transitioning to the new one.  Just update the new
5090                    // one to continue using the old name.
5091                    realName = pkg.mRealPackage;
5092                    if (!pkg.packageName.equals(renamed)) {
5093                        // Callers into this function may have already taken
5094                        // care of renaming the package; only do it here if
5095                        // it is not already done.
5096                        pkg.setPackageName(renamed);
5097                    }
5098
5099                } else {
5100                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5101                        if ((origPackage = mSettings.peekPackageLPr(
5102                                pkg.mOriginalPackages.get(i))) != null) {
5103                            // We do have the package already installed under its
5104                            // original name...  should we use it?
5105                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5106                                // New package is not compatible with original.
5107                                origPackage = null;
5108                                continue;
5109                            } else if (origPackage.sharedUser != null) {
5110                                // Make sure uid is compatible between packages.
5111                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5112                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5113                                            + " to " + pkg.packageName + ": old uid "
5114                                            + origPackage.sharedUser.name
5115                                            + " differs from " + pkg.mSharedUserId);
5116                                    origPackage = null;
5117                                    continue;
5118                                }
5119                            } else {
5120                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5121                                        + pkg.packageName + " to old name " + origPackage.name);
5122                            }
5123                            break;
5124                        }
5125                    }
5126                }
5127            }
5128
5129            if (mTransferedPackages.contains(pkg.packageName)) {
5130                Slog.w(TAG, "Package " + pkg.packageName
5131                        + " was transferred to another, but its .apk remains");
5132            }
5133
5134            // Just create the setting, don't add it yet. For already existing packages
5135            // the PkgSetting exists already and doesn't have to be created.
5136            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5137                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5138                    pkg.applicationInfo.primaryCpuAbi,
5139                    pkg.applicationInfo.secondaryCpuAbi,
5140                    pkg.applicationInfo.flags, user, false);
5141            if (pkgSetting == null) {
5142                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5143                        "Creating application package " + pkg.packageName + " failed");
5144            }
5145
5146            if (pkgSetting.origPackage != null) {
5147                // If we are first transitioning from an original package,
5148                // fix up the new package's name now.  We need to do this after
5149                // looking up the package under its new name, so getPackageLP
5150                // can take care of fiddling things correctly.
5151                pkg.setPackageName(origPackage.name);
5152
5153                // File a report about this.
5154                String msg = "New package " + pkgSetting.realName
5155                        + " renamed to replace old package " + pkgSetting.name;
5156                reportSettingsProblem(Log.WARN, msg);
5157
5158                // Make a note of it.
5159                mTransferedPackages.add(origPackage.name);
5160
5161                // No longer need to retain this.
5162                pkgSetting.origPackage = null;
5163            }
5164
5165            if (realName != null) {
5166                // Make a note of it.
5167                mTransferedPackages.add(pkg.packageName);
5168            }
5169
5170            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5171                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5172            }
5173
5174            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5175                // Check all shared libraries and map to their actual file path.
5176                // We only do this here for apps not on a system dir, because those
5177                // are the only ones that can fail an install due to this.  We
5178                // will take care of the system apps by updating all of their
5179                // library paths after the scan is done.
5180                updateSharedLibrariesLPw(pkg, null);
5181            }
5182
5183            if (mFoundPolicyFile) {
5184                SELinuxMMAC.assignSeinfoValue(pkg);
5185            }
5186
5187            pkg.applicationInfo.uid = pkgSetting.appId;
5188            pkg.mExtras = pkgSetting;
5189            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5190                try {
5191                    verifySignaturesLP(pkgSetting, pkg);
5192                } catch (PackageManagerException e) {
5193                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5194                        throw e;
5195                    }
5196                    // The signature has changed, but this package is in the system
5197                    // image...  let's recover!
5198                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5199                    // However...  if this package is part of a shared user, but it
5200                    // doesn't match the signature of the shared user, let's fail.
5201                    // What this means is that you can't change the signatures
5202                    // associated with an overall shared user, which doesn't seem all
5203                    // that unreasonable.
5204                    if (pkgSetting.sharedUser != null) {
5205                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5206                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5207                            throw new PackageManagerException(
5208                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5209                                            "Signature mismatch for shared user : "
5210                                            + pkgSetting.sharedUser);
5211                        }
5212                    }
5213                    // File a report about this.
5214                    String msg = "System package " + pkg.packageName
5215                        + " signature changed; retaining data.";
5216                    reportSettingsProblem(Log.WARN, msg);
5217                }
5218            } else {
5219                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5220                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5221                            + pkg.packageName + " upgrade keys do not match the "
5222                            + "previously installed version");
5223                } else {
5224                    // signatures may have changed as result of upgrade
5225                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5226                }
5227            }
5228            // Verify that this new package doesn't have any content providers
5229            // that conflict with existing packages.  Only do this if the
5230            // package isn't already installed, since we don't want to break
5231            // things that are installed.
5232            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5233                final int N = pkg.providers.size();
5234                int i;
5235                for (i=0; i<N; i++) {
5236                    PackageParser.Provider p = pkg.providers.get(i);
5237                    if (p.info.authority != null) {
5238                        String names[] = p.info.authority.split(";");
5239                        for (int j = 0; j < names.length; j++) {
5240                            if (mProvidersByAuthority.containsKey(names[j])) {
5241                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5242                                final String otherPackageName =
5243                                        ((other != null && other.getComponentName() != null) ?
5244                                                other.getComponentName().getPackageName() : "?");
5245                                throw new PackageManagerException(
5246                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5247                                                "Can't install because provider name " + names[j]
5248                                                + " (in package " + pkg.applicationInfo.packageName
5249                                                + ") is already used by " + otherPackageName);
5250                            }
5251                        }
5252                    }
5253                }
5254            }
5255
5256            if (pkg.mAdoptPermissions != null) {
5257                // This package wants to adopt ownership of permissions from
5258                // another package.
5259                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5260                    final String origName = pkg.mAdoptPermissions.get(i);
5261                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5262                    if (orig != null) {
5263                        if (verifyPackageUpdateLPr(orig, pkg)) {
5264                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5265                                    + pkg.packageName);
5266                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5267                        }
5268                    }
5269                }
5270            }
5271        }
5272
5273        final String pkgName = pkg.packageName;
5274
5275        final long scanFileTime = scanFile.lastModified();
5276        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5277        pkg.applicationInfo.processName = fixProcessName(
5278                pkg.applicationInfo.packageName,
5279                pkg.applicationInfo.processName,
5280                pkg.applicationInfo.uid);
5281
5282        File dataPath;
5283        if (mPlatformPackage == pkg) {
5284            // The system package is special.
5285            dataPath = new File (Environment.getDataDirectory(), "system");
5286            pkg.applicationInfo.dataDir = dataPath.getPath();
5287
5288        } else {
5289            // This is a normal package, need to make its data directory.
5290            dataPath = getDataPathForPackage(pkg.packageName, 0);
5291
5292            boolean uidError = false;
5293
5294            if (dataPath.exists()) {
5295                int currentUid = 0;
5296                try {
5297                    StructStat stat = Os.stat(dataPath.getPath());
5298                    currentUid = stat.st_uid;
5299                } catch (ErrnoException e) {
5300                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5301                }
5302
5303                // If we have mismatched owners for the data path, we have a problem.
5304                if (currentUid != pkg.applicationInfo.uid) {
5305                    boolean recovered = false;
5306                    if (currentUid == 0) {
5307                        // The directory somehow became owned by root.  Wow.
5308                        // This is probably because the system was stopped while
5309                        // installd was in the middle of messing with its libs
5310                        // directory.  Ask installd to fix that.
5311                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5312                                pkg.applicationInfo.uid);
5313                        if (ret >= 0) {
5314                            recovered = true;
5315                            String msg = "Package " + pkg.packageName
5316                                    + " unexpectedly changed to uid 0; recovered to " +
5317                                    + pkg.applicationInfo.uid;
5318                            reportSettingsProblem(Log.WARN, msg);
5319                        }
5320                    }
5321                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5322                            || (scanMode&SCAN_BOOTING) != 0)) {
5323                        // If this is a system app, we can at least delete its
5324                        // current data so the application will still work.
5325                        int ret = removeDataDirsLI(pkgName);
5326                        if (ret >= 0) {
5327                            // TODO: Kill the processes first
5328                            // Old data gone!
5329                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5330                                    ? "System package " : "Third party package ";
5331                            String msg = prefix + pkg.packageName
5332                                    + " has changed from uid: "
5333                                    + currentUid + " to "
5334                                    + pkg.applicationInfo.uid + "; old data erased";
5335                            reportSettingsProblem(Log.WARN, msg);
5336                            recovered = true;
5337
5338                            // And now re-install the app.
5339                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5340                                                   pkg.applicationInfo.seinfo);
5341                            if (ret == -1) {
5342                                // Ack should not happen!
5343                                msg = prefix + pkg.packageName
5344                                        + " could not have data directory re-created after delete.";
5345                                reportSettingsProblem(Log.WARN, msg);
5346                                throw new PackageManagerException(
5347                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5348                            }
5349                        }
5350                        if (!recovered) {
5351                            mHasSystemUidErrors = true;
5352                        }
5353                    } else if (!recovered) {
5354                        // If we allow this install to proceed, we will be broken.
5355                        // Abort, abort!
5356                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5357                                "scanPackageLI");
5358                    }
5359                    if (!recovered) {
5360                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5361                            + pkg.applicationInfo.uid + "/fs_"
5362                            + currentUid;
5363                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5364                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5365                        String msg = "Package " + pkg.packageName
5366                                + " has mismatched uid: "
5367                                + currentUid + " on disk, "
5368                                + pkg.applicationInfo.uid + " in settings";
5369                        // writer
5370                        synchronized (mPackages) {
5371                            mSettings.mReadMessages.append(msg);
5372                            mSettings.mReadMessages.append('\n');
5373                            uidError = true;
5374                            if (!pkgSetting.uidError) {
5375                                reportSettingsProblem(Log.ERROR, msg);
5376                            }
5377                        }
5378                    }
5379                }
5380                pkg.applicationInfo.dataDir = dataPath.getPath();
5381                if (mShouldRestoreconData) {
5382                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5383                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5384                                pkg.applicationInfo.uid);
5385                }
5386            } else {
5387                if (DEBUG_PACKAGE_SCANNING) {
5388                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5389                        Log.v(TAG, "Want this data dir: " + dataPath);
5390                }
5391                //invoke installer to do the actual installation
5392                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5393                                           pkg.applicationInfo.seinfo);
5394                if (ret < 0) {
5395                    // Error from installer
5396                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5397                            "Unable to create data dirs [errorCode=" + ret + "]");
5398                }
5399
5400                if (dataPath.exists()) {
5401                    pkg.applicationInfo.dataDir = dataPath.getPath();
5402                } else {
5403                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5404                    pkg.applicationInfo.dataDir = null;
5405                }
5406            }
5407
5408            pkgSetting.uidError = uidError;
5409        }
5410
5411        final String path = scanFile.getPath();
5412        final String codePath = pkg.applicationInfo.getCodePath();
5413        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5414            // For the case where we had previously uninstalled an update, get rid
5415            // of any native binaries we might have unpackaged. Note that this assumes
5416            // that system app updates were not installed via ASEC.
5417            //
5418            // TODO(multiArch): Is this cleanup really necessary ?
5419            NativeLibraryHelper.removeNativeBinariesFromDirLI(
5420                    new File(codePath, LIB_DIR_NAME), false /* delete dirs */);
5421            setBundledAppAbisAndRoots(pkg, pkgSetting);
5422
5423            // If we haven't found any native libraries for the app, check if it has
5424            // renderscript code. We'll need to force the app to 32 bit if it has
5425            // renderscript bitcode.
5426            if (pkg.applicationInfo.primaryCpuAbi == null
5427                    && pkg.applicationInfo.secondaryCpuAbi == null
5428                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5429                NativeLibraryHelper.Handle handle = null;
5430                try {
5431                    handle = NativeLibraryHelper.Handle.create(scanFile);
5432                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5433                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5434                    }
5435                } catch (IOException ioe) {
5436                    Slog.w(TAG, "Error scanning system app : " + ioe);
5437                } finally {
5438                    IoUtils.closeQuietly(handle);
5439                }
5440            }
5441
5442            setNativeLibraryPaths(pkg);
5443        } else {
5444            // TODO: We can probably be smarter about this stuff. For installed apps,
5445            // we can calculate this information at install time once and for all. For
5446            // system apps, we can probably assume that this information doesn't change
5447            // after the first boot scan. As things stand, we do lots of unnecessary work.
5448
5449            // Give ourselves some initial paths; we'll come back for another
5450            // pass once we've determined ABI below.
5451            setNativeLibraryPaths(pkg);
5452
5453            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5454            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5455            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5456
5457            NativeLibraryHelper.Handle handle = null;
5458            try {
5459                handle = NativeLibraryHelper.Handle.create(scanFile);
5460                // TODO(multiArch): This can be null for apps that didn't go through the
5461                // usual installation process. We can calculate it again, like we
5462                // do during install time.
5463                //
5464                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5465                // unnecessary.
5466                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5467
5468                // Null out the abis so that they can be recalculated.
5469                pkg.applicationInfo.primaryCpuAbi = null;
5470                pkg.applicationInfo.secondaryCpuAbi = null;
5471                if (isMultiArch(pkg.applicationInfo)) {
5472                    // Warn if we've set an abiOverride for multi-lib packages..
5473                    // By definition, we need to copy both 32 and 64 bit libraries for
5474                    // such packages.
5475                    if (abiOverride != null) {
5476                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5477                    }
5478
5479                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5480                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5481                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5482                        if (isAsec) {
5483                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5484                        } else {
5485                            abi32 = copyNativeLibrariesForInternalApp(handle,
5486                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5487                        }
5488                    }
5489
5490                    maybeThrowExceptionForMultiArchCopy(
5491                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5492
5493                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5494                        if (isAsec) {
5495                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5496                        } else {
5497                            abi64 = copyNativeLibrariesForInternalApp(handle,
5498                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5499                        }
5500                    }
5501
5502                    maybeThrowExceptionForMultiArchCopy(
5503                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5504
5505                    if (abi64 >= 0) {
5506                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5507                    }
5508
5509                    if (abi32 >= 0) {
5510                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5511                        if (abi64 >= 0) {
5512                            pkg.applicationInfo.secondaryCpuAbi = abi;
5513                        } else {
5514                            pkg.applicationInfo.primaryCpuAbi = abi;
5515                        }
5516                    }
5517                } else {
5518                    String[] abiList = (abiOverride != null) ?
5519                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
5520
5521                    // Enable gross and lame hacks for apps that are built with old
5522                    // SDK tools. We must scan their APKs for renderscript bitcode and
5523                    // not launch them if it's present. Don't bother checking on devices
5524                    // that don't have 64 bit support.
5525                    boolean needsRenderScriptOverride = false;
5526                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
5527                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5528                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5529                        needsRenderScriptOverride = true;
5530                    }
5531
5532                    final int copyRet;
5533                    if (isAsec) {
5534                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5535                    } else {
5536                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5537                                useIsaSpecificSubdirs);
5538                    }
5539
5540                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5541                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5542                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5543                    }
5544
5545                    if (copyRet >= 0) {
5546                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5547                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) {
5548                        pkg.applicationInfo.primaryCpuAbi = abiOverride;
5549                    } else if (needsRenderScriptOverride) {
5550                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5551                    }
5552                }
5553            } catch (IOException ioe) {
5554                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5555            } finally {
5556                IoUtils.closeQuietly(handle);
5557            }
5558
5559            // Now that we've calculated the ABIs and determined if it's an internal app,
5560            // we will go ahead and populate the nativeLibraryPath.
5561            setNativeLibraryPaths(pkg);
5562
5563            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5564            final int[] userIds = sUserManager.getUserIds();
5565            synchronized (mInstallLock) {
5566                // Create a native library symlink only if we have native libraries
5567                // and if the native libraries are 32 bit libraries. We do not provide
5568                // this symlink for 64 bit libraries.
5569                if (pkg.applicationInfo.primaryCpuAbi != null &&
5570                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5571                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5572                    for (int userId : userIds) {
5573                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5574                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5575                                    "Failed linking native library dir (user=" + userId + ")");
5576                        }
5577                    }
5578                }
5579            }
5580        }
5581
5582        // This is a special case for the "system" package, where the ABI is
5583        // dictated by the zygote configuration (and init.rc). We should keep track
5584        // of this ABI so that we can deal with "normal" applications that run under
5585        // the same UID correctly.
5586        if (mPlatformPackage == pkg) {
5587            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5588                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5589        }
5590
5591        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5592        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5593
5594        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5595                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5596                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5597
5598        // Push the derived path down into PackageSettings so we know what to
5599        // clean up at uninstall time.
5600        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5601
5602        if (DEBUG_ABI_SELECTION) {
5603            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5604                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5605                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5606        }
5607
5608        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5609            // We don't do this here during boot because we can do it all
5610            // at once after scanning all existing packages.
5611            //
5612            // We also do this *before* we perform dexopt on this package, so that
5613            // we can avoid redundant dexopts, and also to make sure we've got the
5614            // code and package path correct.
5615            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5616                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5617        }
5618
5619        if ((scanMode&SCAN_NO_DEX) == 0) {
5620            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5621                    == DEX_OPT_FAILED) {
5622                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5623                    removeDataDirsLI(pkg.packageName);
5624                }
5625
5626                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5627            }
5628        }
5629
5630        if (mFactoryTest && pkg.requestedPermissions.contains(
5631                android.Manifest.permission.FACTORY_TEST)) {
5632            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5633        }
5634
5635        ArrayList<PackageParser.Package> clientLibPkgs = null;
5636
5637        // writer
5638        synchronized (mPackages) {
5639            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5640                // Only system apps can add new shared libraries.
5641                if (pkg.libraryNames != null) {
5642                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5643                        String name = pkg.libraryNames.get(i);
5644                        boolean allowed = false;
5645                        if (isUpdatedSystemApp(pkg)) {
5646                            // New library entries can only be added through the
5647                            // system image.  This is important to get rid of a lot
5648                            // of nasty edge cases: for example if we allowed a non-
5649                            // system update of the app to add a library, then uninstalling
5650                            // the update would make the library go away, and assumptions
5651                            // we made such as through app install filtering would now
5652                            // have allowed apps on the device which aren't compatible
5653                            // with it.  Better to just have the restriction here, be
5654                            // conservative, and create many fewer cases that can negatively
5655                            // impact the user experience.
5656                            final PackageSetting sysPs = mSettings
5657                                    .getDisabledSystemPkgLPr(pkg.packageName);
5658                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5659                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5660                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5661                                        allowed = true;
5662                                        allowed = true;
5663                                        break;
5664                                    }
5665                                }
5666                            }
5667                        } else {
5668                            allowed = true;
5669                        }
5670                        if (allowed) {
5671                            if (!mSharedLibraries.containsKey(name)) {
5672                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5673                            } else if (!name.equals(pkg.packageName)) {
5674                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5675                                        + name + " already exists; skipping");
5676                            }
5677                        } else {
5678                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5679                                    + name + " that is not declared on system image; skipping");
5680                        }
5681                    }
5682                    if ((scanMode&SCAN_BOOTING) == 0) {
5683                        // If we are not booting, we need to update any applications
5684                        // that are clients of our shared library.  If we are booting,
5685                        // this will all be done once the scan is complete.
5686                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5687                    }
5688                }
5689            }
5690        }
5691
5692        // We also need to dexopt any apps that are dependent on this library.  Note that
5693        // if these fail, we should abort the install since installing the library will
5694        // result in some apps being broken.
5695        if (clientLibPkgs != null) {
5696            if ((scanMode&SCAN_NO_DEX) == 0) {
5697                for (int i=0; i<clientLibPkgs.size(); i++) {
5698                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5699                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5700                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5701                            == DEX_OPT_FAILED) {
5702                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5703                            removeDataDirsLI(pkg.packageName);
5704                        }
5705
5706                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5707                                "scanPackageLI failed to dexopt clientLibPkgs");
5708                    }
5709                }
5710            }
5711        }
5712
5713        // Request the ActivityManager to kill the process(only for existing packages)
5714        // so that we do not end up in a confused state while the user is still using the older
5715        // version of the application while the new one gets installed.
5716        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5717            // If the package lives in an asec, tell everyone that the container is going
5718            // away so they can clean up any references to its resources (which would prevent
5719            // vold from being able to unmount the asec)
5720            if (isForwardLocked(pkg) || isExternal(pkg)) {
5721                if (DEBUG_INSTALL) {
5722                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5723                }
5724                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5725                final ArrayList<String> pkgList = new ArrayList<String>(1);
5726                pkgList.add(pkg.applicationInfo.packageName);
5727                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5728            }
5729
5730            // Post the request that it be killed now that the going-away broadcast is en route
5731            killApplication(pkg.applicationInfo.packageName,
5732                        pkg.applicationInfo.uid, "update pkg");
5733        }
5734
5735        // Also need to kill any apps that are dependent on the library.
5736        if (clientLibPkgs != null) {
5737            for (int i=0; i<clientLibPkgs.size(); i++) {
5738                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5739                killApplication(clientPkg.applicationInfo.packageName,
5740                        clientPkg.applicationInfo.uid, "update lib");
5741            }
5742        }
5743
5744        // writer
5745        synchronized (mPackages) {
5746            // We don't expect installation to fail beyond this point,
5747            if ((scanMode&SCAN_MONITOR) != 0) {
5748                mAppDirs.put(pkg.codePath, pkg);
5749            }
5750            // Add the new setting to mSettings
5751            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5752            // Add the new setting to mPackages
5753            mPackages.put(pkg.applicationInfo.packageName, pkg);
5754            // Make sure we don't accidentally delete its data.
5755            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5756            while (iter.hasNext()) {
5757                PackageCleanItem item = iter.next();
5758                if (pkgName.equals(item.packageName)) {
5759                    iter.remove();
5760                }
5761            }
5762
5763            // Take care of first install / last update times.
5764            if (currentTime != 0) {
5765                if (pkgSetting.firstInstallTime == 0) {
5766                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5767                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5768                    pkgSetting.lastUpdateTime = currentTime;
5769                }
5770            } else if (pkgSetting.firstInstallTime == 0) {
5771                // We need *something*.  Take time time stamp of the file.
5772                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5773            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5774                if (scanFileTime != pkgSetting.timeStamp) {
5775                    // A package on the system image has changed; consider this
5776                    // to be an update.
5777                    pkgSetting.lastUpdateTime = scanFileTime;
5778                }
5779            }
5780
5781            // Add the package's KeySets to the global KeySetManagerService
5782            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5783            try {
5784                // Old KeySetData no longer valid.
5785                ksms.removeAppKeySetDataLPw(pkg.packageName);
5786                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5787                if (pkg.mKeySetMapping != null) {
5788                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5789                            pkg.mKeySetMapping.entrySet()) {
5790                        if (entry.getValue() != null) {
5791                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5792                                                          entry.getValue(), entry.getKey());
5793                        }
5794                    }
5795                    if (pkg.mUpgradeKeySets != null) {
5796                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5797                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5798                        }
5799                    }
5800                }
5801            } catch (NullPointerException e) {
5802                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5803            } catch (IllegalArgumentException e) {
5804                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5805            }
5806
5807            int N = pkg.providers.size();
5808            StringBuilder r = null;
5809            int i;
5810            for (i=0; i<N; i++) {
5811                PackageParser.Provider p = pkg.providers.get(i);
5812                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5813                        p.info.processName, pkg.applicationInfo.uid);
5814                mProviders.addProvider(p);
5815                p.syncable = p.info.isSyncable;
5816                if (p.info.authority != null) {
5817                    String names[] = p.info.authority.split(";");
5818                    p.info.authority = null;
5819                    for (int j = 0; j < names.length; j++) {
5820                        if (j == 1 && p.syncable) {
5821                            // We only want the first authority for a provider to possibly be
5822                            // syncable, so if we already added this provider using a different
5823                            // authority clear the syncable flag. We copy the provider before
5824                            // changing it because the mProviders object contains a reference
5825                            // to a provider that we don't want to change.
5826                            // Only do this for the second authority since the resulting provider
5827                            // object can be the same for all future authorities for this provider.
5828                            p = new PackageParser.Provider(p);
5829                            p.syncable = false;
5830                        }
5831                        if (!mProvidersByAuthority.containsKey(names[j])) {
5832                            mProvidersByAuthority.put(names[j], p);
5833                            if (p.info.authority == null) {
5834                                p.info.authority = names[j];
5835                            } else {
5836                                p.info.authority = p.info.authority + ";" + names[j];
5837                            }
5838                            if (DEBUG_PACKAGE_SCANNING) {
5839                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5840                                    Log.d(TAG, "Registered content provider: " + names[j]
5841                                            + ", className = " + p.info.name + ", isSyncable = "
5842                                            + p.info.isSyncable);
5843                            }
5844                        } else {
5845                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5846                            Slog.w(TAG, "Skipping provider name " + names[j] +
5847                                    " (in package " + pkg.applicationInfo.packageName +
5848                                    "): name already used by "
5849                                    + ((other != null && other.getComponentName() != null)
5850                                            ? other.getComponentName().getPackageName() : "?"));
5851                        }
5852                    }
5853                }
5854                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5855                    if (r == null) {
5856                        r = new StringBuilder(256);
5857                    } else {
5858                        r.append(' ');
5859                    }
5860                    r.append(p.info.name);
5861                }
5862            }
5863            if (r != null) {
5864                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5865            }
5866
5867            N = pkg.services.size();
5868            r = null;
5869            for (i=0; i<N; i++) {
5870                PackageParser.Service s = pkg.services.get(i);
5871                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5872                        s.info.processName, pkg.applicationInfo.uid);
5873                mServices.addService(s);
5874                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5875                    if (r == null) {
5876                        r = new StringBuilder(256);
5877                    } else {
5878                        r.append(' ');
5879                    }
5880                    r.append(s.info.name);
5881                }
5882            }
5883            if (r != null) {
5884                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5885            }
5886
5887            N = pkg.receivers.size();
5888            r = null;
5889            for (i=0; i<N; i++) {
5890                PackageParser.Activity a = pkg.receivers.get(i);
5891                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5892                        a.info.processName, pkg.applicationInfo.uid);
5893                mReceivers.addActivity(a, "receiver");
5894                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5895                    if (r == null) {
5896                        r = new StringBuilder(256);
5897                    } else {
5898                        r.append(' ');
5899                    }
5900                    r.append(a.info.name);
5901                }
5902            }
5903            if (r != null) {
5904                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5905            }
5906
5907            N = pkg.activities.size();
5908            r = null;
5909            for (i=0; i<N; i++) {
5910                PackageParser.Activity a = pkg.activities.get(i);
5911                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5912                        a.info.processName, pkg.applicationInfo.uid);
5913                mActivities.addActivity(a, "activity");
5914                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5915                    if (r == null) {
5916                        r = new StringBuilder(256);
5917                    } else {
5918                        r.append(' ');
5919                    }
5920                    r.append(a.info.name);
5921                }
5922            }
5923            if (r != null) {
5924                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5925            }
5926
5927            N = pkg.permissionGroups.size();
5928            r = null;
5929            for (i=0; i<N; i++) {
5930                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5931                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5932                if (cur == null) {
5933                    mPermissionGroups.put(pg.info.name, pg);
5934                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5935                        if (r == null) {
5936                            r = new StringBuilder(256);
5937                        } else {
5938                            r.append(' ');
5939                        }
5940                        r.append(pg.info.name);
5941                    }
5942                } else {
5943                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5944                            + pg.info.packageName + " ignored: original from "
5945                            + cur.info.packageName);
5946                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5947                        if (r == null) {
5948                            r = new StringBuilder(256);
5949                        } else {
5950                            r.append(' ');
5951                        }
5952                        r.append("DUP:");
5953                        r.append(pg.info.name);
5954                    }
5955                }
5956            }
5957            if (r != null) {
5958                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5959            }
5960
5961            N = pkg.permissions.size();
5962            r = null;
5963            for (i=0; i<N; i++) {
5964                PackageParser.Permission p = pkg.permissions.get(i);
5965                HashMap<String, BasePermission> permissionMap =
5966                        p.tree ? mSettings.mPermissionTrees
5967                        : mSettings.mPermissions;
5968                p.group = mPermissionGroups.get(p.info.group);
5969                if (p.info.group == null || p.group != null) {
5970                    BasePermission bp = permissionMap.get(p.info.name);
5971                    if (bp == null) {
5972                        bp = new BasePermission(p.info.name, p.info.packageName,
5973                                BasePermission.TYPE_NORMAL);
5974                        permissionMap.put(p.info.name, bp);
5975                    }
5976                    if (bp.perm == null) {
5977                        if (bp.sourcePackage != null
5978                                && !bp.sourcePackage.equals(p.info.packageName)) {
5979                            // If this is a permission that was formerly defined by a non-system
5980                            // app, but is now defined by a system app (following an upgrade),
5981                            // discard the previous declaration and consider the system's to be
5982                            // canonical.
5983                            if (isSystemApp(p.owner)) {
5984                                String msg = "New decl " + p.owner + " of permission  "
5985                                        + p.info.name + " is system";
5986                                reportSettingsProblem(Log.WARN, msg);
5987                                bp.sourcePackage = null;
5988                            }
5989                        }
5990                        if (bp.sourcePackage == null
5991                                || bp.sourcePackage.equals(p.info.packageName)) {
5992                            BasePermission tree = findPermissionTreeLP(p.info.name);
5993                            if (tree == null
5994                                    || tree.sourcePackage.equals(p.info.packageName)) {
5995                                bp.packageSetting = pkgSetting;
5996                                bp.perm = p;
5997                                bp.uid = pkg.applicationInfo.uid;
5998                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5999                                    if (r == null) {
6000                                        r = new StringBuilder(256);
6001                                    } else {
6002                                        r.append(' ');
6003                                    }
6004                                    r.append(p.info.name);
6005                                }
6006                            } else {
6007                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6008                                        + p.info.packageName + " ignored: base tree "
6009                                        + tree.name + " is from package "
6010                                        + tree.sourcePackage);
6011                            }
6012                        } else {
6013                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6014                                    + p.info.packageName + " ignored: original from "
6015                                    + bp.sourcePackage);
6016                        }
6017                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6018                        if (r == null) {
6019                            r = new StringBuilder(256);
6020                        } else {
6021                            r.append(' ');
6022                        }
6023                        r.append("DUP:");
6024                        r.append(p.info.name);
6025                    }
6026                    if (bp.perm == p) {
6027                        bp.protectionLevel = p.info.protectionLevel;
6028                    }
6029                } else {
6030                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6031                            + p.info.packageName + " ignored: no group "
6032                            + p.group);
6033                }
6034            }
6035            if (r != null) {
6036                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6037            }
6038
6039            N = pkg.instrumentation.size();
6040            r = null;
6041            for (i=0; i<N; i++) {
6042                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6043                a.info.packageName = pkg.applicationInfo.packageName;
6044                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6045                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6046                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6047                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6048                a.info.dataDir = pkg.applicationInfo.dataDir;
6049
6050                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6051                // need other information about the application, like the ABI and what not ?
6052                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6053                mInstrumentation.put(a.getComponentName(), a);
6054                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6055                    if (r == null) {
6056                        r = new StringBuilder(256);
6057                    } else {
6058                        r.append(' ');
6059                    }
6060                    r.append(a.info.name);
6061                }
6062            }
6063            if (r != null) {
6064                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6065            }
6066
6067            if (pkg.protectedBroadcasts != null) {
6068                N = pkg.protectedBroadcasts.size();
6069                for (i=0; i<N; i++) {
6070                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6071                }
6072            }
6073
6074            pkgSetting.setTimeStamp(scanFileTime);
6075
6076            // Create idmap files for pairs of (packages, overlay packages).
6077            // Note: "android", ie framework-res.apk, is handled by native layers.
6078            if (pkg.mOverlayTarget != null) {
6079                // This is an overlay package.
6080                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6081                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6082                        mOverlays.put(pkg.mOverlayTarget,
6083                                new HashMap<String, PackageParser.Package>());
6084                    }
6085                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6086                    map.put(pkg.packageName, pkg);
6087                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6088                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6089                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6090                                "scanPackageLI failed to createIdmap");
6091                    }
6092                }
6093            } else if (mOverlays.containsKey(pkg.packageName) &&
6094                    !pkg.packageName.equals("android")) {
6095                // This is a regular package, with one or more known overlay packages.
6096                createIdmapsForPackageLI(pkg);
6097            }
6098        }
6099
6100        return pkg;
6101    }
6102
6103    /**
6104     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6105     * i.e, so that all packages can be run inside a single process if required.
6106     *
6107     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6108     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6109     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6110     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6111     * updating a package that belongs to a shared user.
6112     *
6113     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6114     * adds unnecessary complexity.
6115     */
6116    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6117            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6118        String requiredInstructionSet = null;
6119        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6120            requiredInstructionSet = VMRuntime.getInstructionSet(
6121                     scannedPackage.applicationInfo.primaryCpuAbi);
6122        }
6123
6124        PackageSetting requirer = null;
6125        for (PackageSetting ps : packagesForUser) {
6126            // If packagesForUser contains scannedPackage, we skip it. This will happen
6127            // when scannedPackage is an update of an existing package. Without this check,
6128            // we will never be able to change the ABI of any package belonging to a shared
6129            // user, even if it's compatible with other packages.
6130            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6131                if (ps.primaryCpuAbiString == null) {
6132                    continue;
6133                }
6134
6135                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6136                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6137                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6138                    // this but there's not much we can do.
6139                    String errorMessage = "Instruction set mismatch, "
6140                            + ((requirer == null) ? "[caller]" : requirer)
6141                            + " requires " + requiredInstructionSet + " whereas " + ps
6142                            + " requires " + instructionSet;
6143                    Slog.w(TAG, errorMessage);
6144                }
6145
6146                if (requiredInstructionSet == null) {
6147                    requiredInstructionSet = instructionSet;
6148                    requirer = ps;
6149                }
6150            }
6151        }
6152
6153        if (requiredInstructionSet != null) {
6154            String adjustedAbi;
6155            if (requirer != null) {
6156                // requirer != null implies that either scannedPackage was null or that scannedPackage
6157                // did not require an ABI, in which case we have to adjust scannedPackage to match
6158                // the ABI of the set (which is the same as requirer's ABI)
6159                adjustedAbi = requirer.primaryCpuAbiString;
6160                if (scannedPackage != null) {
6161                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6162                }
6163            } else {
6164                // requirer == null implies that we're updating all ABIs in the set to
6165                // match scannedPackage.
6166                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6167            }
6168
6169            for (PackageSetting ps : packagesForUser) {
6170                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6171                    if (ps.primaryCpuAbiString != null) {
6172                        continue;
6173                    }
6174
6175                    ps.primaryCpuAbiString = adjustedAbi;
6176                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6177                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6178                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6179
6180                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6181                                deferDexOpt, true) == DEX_OPT_FAILED) {
6182                            ps.primaryCpuAbiString = null;
6183                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6184                            return;
6185                        } else {
6186                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6187                        }
6188                    }
6189                }
6190            }
6191        }
6192    }
6193
6194    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6195        synchronized (mPackages) {
6196            mResolverReplaced = true;
6197            // Set up information for custom user intent resolution activity.
6198            mResolveActivity.applicationInfo = pkg.applicationInfo;
6199            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6200            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6201            mResolveActivity.processName = null;
6202            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6203            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6204                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6205            mResolveActivity.theme = 0;
6206            mResolveActivity.exported = true;
6207            mResolveActivity.enabled = true;
6208            mResolveInfo.activityInfo = mResolveActivity;
6209            mResolveInfo.priority = 0;
6210            mResolveInfo.preferredOrder = 0;
6211            mResolveInfo.match = 0;
6212            mResolveComponentName = mCustomResolverComponentName;
6213            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6214                    mResolveComponentName);
6215        }
6216    }
6217
6218    private static String calculateApkRoot(final String codePathString) {
6219        final File codePath = new File(codePathString);
6220        final File codeRoot;
6221        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6222            codeRoot = Environment.getRootDirectory();
6223        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6224            codeRoot = Environment.getOemDirectory();
6225        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6226            codeRoot = Environment.getVendorDirectory();
6227        } else {
6228            // Unrecognized code path; take its top real segment as the apk root:
6229            // e.g. /something/app/blah.apk => /something
6230            try {
6231                File f = codePath.getCanonicalFile();
6232                File parent = f.getParentFile();    // non-null because codePath is a file
6233                File tmp;
6234                while ((tmp = parent.getParentFile()) != null) {
6235                    f = parent;
6236                    parent = tmp;
6237                }
6238                codeRoot = f;
6239                Slog.w(TAG, "Unrecognized code path "
6240                        + codePath + " - using " + codeRoot);
6241            } catch (IOException e) {
6242                // Can't canonicalize the code path -- shenanigans?
6243                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6244                return Environment.getRootDirectory().getPath();
6245            }
6246        }
6247        return codeRoot.getPath();
6248    }
6249
6250    /**
6251     * Derive and set the location of native libraries for the given package,
6252     * which varies depending on where and how the package was installed.
6253     */
6254    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6255        final ApplicationInfo info = pkg.applicationInfo;
6256        final String codePath = pkg.codePath;
6257        final File codeFile = new File(codePath);
6258        // If "/system/lib64/apkname" exists, assume that is the per-package
6259        // native library directory to use; otherwise use "/system/lib/apkname".
6260        final String apkRoot = calculateApkRoot(info.sourceDir);
6261
6262        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6263        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6264
6265
6266        info.nativeLibraryRootDir = null;
6267        info.nativeLibraryRootRequiresIsa = false;
6268        info.nativeLibraryDir = null;
6269        info.secondaryNativeLibraryDir = null;
6270
6271        if (isApkFile(codeFile)) {
6272            // Monolithic install
6273            if (bundledApp) {
6274                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6275                        getPrimaryInstructionSet(info));
6276
6277                // This is a bundled system app so choose the path based on the ABI.
6278                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6279                // is just the default path.
6280                final String apkName = deriveCodePathName(codePath);
6281                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6282                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6283                        apkName).getAbsolutePath();
6284
6285                if (info.secondaryCpuAbi != null) {
6286                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6287                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6288                            secondaryLibDir, apkName).getAbsolutePath();
6289                }
6290            } else if (asecApp) {
6291                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6292                        .getAbsolutePath();
6293            } else {
6294                final String apkName = deriveCodePathName(codePath);
6295                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6296                        .getAbsolutePath();
6297            }
6298
6299            info.nativeLibraryRootRequiresIsa = false;
6300            info.nativeLibraryDir = info.nativeLibraryRootDir;
6301        } else {
6302            // Cluster install
6303            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6304            info.nativeLibraryRootRequiresIsa = true;
6305
6306            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6307                    getPrimaryInstructionSet(info)).getAbsolutePath();
6308
6309            if (info.secondaryCpuAbi != null) {
6310                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6311                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6312            }
6313        }
6314    }
6315
6316    /**
6317     * Calculate the abis and roots for a bundled app. These can uniquely
6318     * be determined from the contents of the system partition, i.e whether
6319     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6320     * of this information, and instead assume that the system was built
6321     * sensibly.
6322     */
6323    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6324                                           PackageSetting pkgSetting) {
6325        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6326
6327        // If "/system/lib64/apkname" exists, assume that is the per-package
6328        // native library directory to use; otherwise use "/system/lib/apkname".
6329        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6330        setBundledAppAbi(pkg, apkRoot, apkName);
6331        // pkgSetting might be null during rescan following uninstall of updates
6332        // to a bundled app, so accommodate that possibility.  The settings in
6333        // that case will be established later from the parsed package.
6334        //
6335        // If the settings aren't null, sync them up with what we've just derived.
6336        // note that apkRoot isn't stored in the package settings.
6337        if (pkgSetting != null) {
6338            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6339            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6340        }
6341    }
6342
6343    /**
6344     * Deduces the ABI of a bundled app and sets the relevant fields on the
6345     * parsed pkg object.
6346     *
6347     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6348     *        under which system libraries are installed.
6349     * @param apkName the name of the installed package.
6350     */
6351    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6352        final File codeFile = new File(pkg.codePath);
6353
6354        final boolean has64BitLibs;
6355        final boolean has32BitLibs;
6356        if (isApkFile(codeFile)) {
6357            // Monolithic install
6358            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6359            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6360        } else {
6361            // Cluster install
6362            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6363            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6364                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6365                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6366                has64BitLibs = (new File(rootDir, isa)).exists();
6367            } else {
6368                has64BitLibs = false;
6369            }
6370            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6371                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6372                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6373                has32BitLibs = (new File(rootDir, isa)).exists();
6374            } else {
6375                has32BitLibs = false;
6376            }
6377        }
6378
6379        if (has64BitLibs && !has32BitLibs) {
6380            // The package has 64 bit libs, but not 32 bit libs. Its primary
6381            // ABI should be 64 bit. We can safely assume here that the bundled
6382            // native libraries correspond to the most preferred ABI in the list.
6383
6384            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6385            pkg.applicationInfo.secondaryCpuAbi = null;
6386        } else if (has32BitLibs && !has64BitLibs) {
6387            // The package has 32 bit libs but not 64 bit libs. Its primary
6388            // ABI should be 32 bit.
6389
6390            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6391            pkg.applicationInfo.secondaryCpuAbi = null;
6392        } else if (has32BitLibs && has64BitLibs) {
6393            // The application has both 64 and 32 bit bundled libraries. We check
6394            // here that the app declares multiArch support, and warn if it doesn't.
6395            //
6396            // We will be lenient here and record both ABIs. The primary will be the
6397            // ABI that's higher on the list, i.e, a device that's configured to prefer
6398            // 64 bit apps will see a 64 bit primary ABI,
6399
6400            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6401                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6402            }
6403
6404            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6405                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6406                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6407            } else {
6408                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6409                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6410            }
6411        } else {
6412            pkg.applicationInfo.primaryCpuAbi = null;
6413            pkg.applicationInfo.secondaryCpuAbi = null;
6414        }
6415    }
6416
6417    private static void createNativeLibrarySubdir(File path) throws IOException {
6418        if (!path.isDirectory()) {
6419            path.delete();
6420
6421            if (!path.mkdir()) {
6422                throw new IOException("Cannot create " + path.getPath());
6423            }
6424
6425            try {
6426                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6427            } catch (ErrnoException e) {
6428                throw new IOException("Cannot chmod native library directory "
6429                        + path.getPath(), e);
6430            }
6431        } else if (!SELinux.restorecon(path)) {
6432            throw new IOException("Cannot set SELinux context for " + path.getPath());
6433        }
6434    }
6435
6436    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6437            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6438        createNativeLibrarySubdir(nativeLibraryRoot);
6439
6440        /*
6441         * If this is an internal application or our nativeLibraryPath points to
6442         * the app-lib directory, unpack the libraries if necessary.
6443         */
6444        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6445        if (abi >= 0) {
6446            /*
6447             * If we have a matching instruction set, construct a subdir under the native
6448             * library root that corresponds to this instruction set.
6449             */
6450            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6451            final File subDir;
6452            if (useIsaSubdir) {
6453                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6454                createNativeLibrarySubdir(isaSubdir);
6455                subDir = isaSubdir;
6456            } else {
6457                subDir = nativeLibraryRoot;
6458            }
6459
6460            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6461            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6462                return copyRet;
6463            }
6464        }
6465
6466        return abi;
6467    }
6468
6469    private void killApplication(String pkgName, int appId, String reason) {
6470        // Request the ActivityManager to kill the process(only for existing packages)
6471        // so that we do not end up in a confused state while the user is still using the older
6472        // version of the application while the new one gets installed.
6473        IActivityManager am = ActivityManagerNative.getDefault();
6474        if (am != null) {
6475            try {
6476                am.killApplicationWithAppId(pkgName, appId, reason);
6477            } catch (RemoteException e) {
6478            }
6479        }
6480    }
6481
6482    void removePackageLI(PackageSetting ps, boolean chatty) {
6483        if (DEBUG_INSTALL) {
6484            if (chatty)
6485                Log.d(TAG, "Removing package " + ps.name);
6486        }
6487
6488        // writer
6489        synchronized (mPackages) {
6490            mPackages.remove(ps.name);
6491            if (ps.codePathString != null) {
6492                mAppDirs.remove(ps.codePathString);
6493            }
6494
6495            final PackageParser.Package pkg = ps.pkg;
6496            if (pkg != null) {
6497                cleanPackageDataStructuresLILPw(pkg, chatty);
6498            }
6499        }
6500    }
6501
6502    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6503        if (DEBUG_INSTALL) {
6504            if (chatty)
6505                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6506        }
6507
6508        // writer
6509        synchronized (mPackages) {
6510            mPackages.remove(pkg.applicationInfo.packageName);
6511            if (pkg.codePath != null) {
6512                mAppDirs.remove(pkg.codePath);
6513            }
6514            cleanPackageDataStructuresLILPw(pkg, chatty);
6515        }
6516    }
6517
6518    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6519        int N = pkg.providers.size();
6520        StringBuilder r = null;
6521        int i;
6522        for (i=0; i<N; i++) {
6523            PackageParser.Provider p = pkg.providers.get(i);
6524            mProviders.removeProvider(p);
6525            if (p.info.authority == null) {
6526
6527                /* There was another ContentProvider with this authority when
6528                 * this app was installed so this authority is null,
6529                 * Ignore it as we don't have to unregister the provider.
6530                 */
6531                continue;
6532            }
6533            String names[] = p.info.authority.split(";");
6534            for (int j = 0; j < names.length; j++) {
6535                if (mProvidersByAuthority.get(names[j]) == p) {
6536                    mProvidersByAuthority.remove(names[j]);
6537                    if (DEBUG_REMOVE) {
6538                        if (chatty)
6539                            Log.d(TAG, "Unregistered content provider: " + names[j]
6540                                    + ", className = " + p.info.name + ", isSyncable = "
6541                                    + p.info.isSyncable);
6542                    }
6543                }
6544            }
6545            if (DEBUG_REMOVE && chatty) {
6546                if (r == null) {
6547                    r = new StringBuilder(256);
6548                } else {
6549                    r.append(' ');
6550                }
6551                r.append(p.info.name);
6552            }
6553        }
6554        if (r != null) {
6555            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6556        }
6557
6558        N = pkg.services.size();
6559        r = null;
6560        for (i=0; i<N; i++) {
6561            PackageParser.Service s = pkg.services.get(i);
6562            mServices.removeService(s);
6563            if (chatty) {
6564                if (r == null) {
6565                    r = new StringBuilder(256);
6566                } else {
6567                    r.append(' ');
6568                }
6569                r.append(s.info.name);
6570            }
6571        }
6572        if (r != null) {
6573            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6574        }
6575
6576        N = pkg.receivers.size();
6577        r = null;
6578        for (i=0; i<N; i++) {
6579            PackageParser.Activity a = pkg.receivers.get(i);
6580            mReceivers.removeActivity(a, "receiver");
6581            if (DEBUG_REMOVE && chatty) {
6582                if (r == null) {
6583                    r = new StringBuilder(256);
6584                } else {
6585                    r.append(' ');
6586                }
6587                r.append(a.info.name);
6588            }
6589        }
6590        if (r != null) {
6591            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6592        }
6593
6594        N = pkg.activities.size();
6595        r = null;
6596        for (i=0; i<N; i++) {
6597            PackageParser.Activity a = pkg.activities.get(i);
6598            mActivities.removeActivity(a, "activity");
6599            if (DEBUG_REMOVE && chatty) {
6600                if (r == null) {
6601                    r = new StringBuilder(256);
6602                } else {
6603                    r.append(' ');
6604                }
6605                r.append(a.info.name);
6606            }
6607        }
6608        if (r != null) {
6609            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6610        }
6611
6612        N = pkg.permissions.size();
6613        r = null;
6614        for (i=0; i<N; i++) {
6615            PackageParser.Permission p = pkg.permissions.get(i);
6616            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6617            if (bp == null) {
6618                bp = mSettings.mPermissionTrees.get(p.info.name);
6619            }
6620            if (bp != null && bp.perm == p) {
6621                bp.perm = null;
6622                if (DEBUG_REMOVE && chatty) {
6623                    if (r == null) {
6624                        r = new StringBuilder(256);
6625                    } else {
6626                        r.append(' ');
6627                    }
6628                    r.append(p.info.name);
6629                }
6630            }
6631            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6632                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6633                if (appOpPerms != null) {
6634                    appOpPerms.remove(pkg.packageName);
6635                }
6636            }
6637        }
6638        if (r != null) {
6639            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6640        }
6641
6642        N = pkg.requestedPermissions.size();
6643        r = null;
6644        for (i=0; i<N; i++) {
6645            String perm = pkg.requestedPermissions.get(i);
6646            BasePermission bp = mSettings.mPermissions.get(perm);
6647            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6648                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6649                if (appOpPerms != null) {
6650                    appOpPerms.remove(pkg.packageName);
6651                    if (appOpPerms.isEmpty()) {
6652                        mAppOpPermissionPackages.remove(perm);
6653                    }
6654                }
6655            }
6656        }
6657        if (r != null) {
6658            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6659        }
6660
6661        N = pkg.instrumentation.size();
6662        r = null;
6663        for (i=0; i<N; i++) {
6664            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6665            mInstrumentation.remove(a.getComponentName());
6666            if (DEBUG_REMOVE && chatty) {
6667                if (r == null) {
6668                    r = new StringBuilder(256);
6669                } else {
6670                    r.append(' ');
6671                }
6672                r.append(a.info.name);
6673            }
6674        }
6675        if (r != null) {
6676            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6677        }
6678
6679        r = null;
6680        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6681            // Only system apps can hold shared libraries.
6682            if (pkg.libraryNames != null) {
6683                for (i=0; i<pkg.libraryNames.size(); i++) {
6684                    String name = pkg.libraryNames.get(i);
6685                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6686                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6687                        mSharedLibraries.remove(name);
6688                        if (DEBUG_REMOVE && chatty) {
6689                            if (r == null) {
6690                                r = new StringBuilder(256);
6691                            } else {
6692                                r.append(' ');
6693                            }
6694                            r.append(name);
6695                        }
6696                    }
6697                }
6698            }
6699        }
6700        if (r != null) {
6701            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6702        }
6703    }
6704
6705    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6706        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6707            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6708                return true;
6709            }
6710        }
6711        return false;
6712    }
6713
6714    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6715    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6716    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6717
6718    private void updatePermissionsLPw(String changingPkg,
6719            PackageParser.Package pkgInfo, int flags) {
6720        // Make sure there are no dangling permission trees.
6721        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6722        while (it.hasNext()) {
6723            final BasePermission bp = it.next();
6724            if (bp.packageSetting == null) {
6725                // We may not yet have parsed the package, so just see if
6726                // we still know about its settings.
6727                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6728            }
6729            if (bp.packageSetting == null) {
6730                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6731                        + " from package " + bp.sourcePackage);
6732                it.remove();
6733            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6734                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6735                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6736                            + " from package " + bp.sourcePackage);
6737                    flags |= UPDATE_PERMISSIONS_ALL;
6738                    it.remove();
6739                }
6740            }
6741        }
6742
6743        // Make sure all dynamic permissions have been assigned to a package,
6744        // and make sure there are no dangling permissions.
6745        it = mSettings.mPermissions.values().iterator();
6746        while (it.hasNext()) {
6747            final BasePermission bp = it.next();
6748            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6749                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6750                        + bp.name + " pkg=" + bp.sourcePackage
6751                        + " info=" + bp.pendingInfo);
6752                if (bp.packageSetting == null && bp.pendingInfo != null) {
6753                    final BasePermission tree = findPermissionTreeLP(bp.name);
6754                    if (tree != null && tree.perm != null) {
6755                        bp.packageSetting = tree.packageSetting;
6756                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6757                                new PermissionInfo(bp.pendingInfo));
6758                        bp.perm.info.packageName = tree.perm.info.packageName;
6759                        bp.perm.info.name = bp.name;
6760                        bp.uid = tree.uid;
6761                    }
6762                }
6763            }
6764            if (bp.packageSetting == null) {
6765                // We may not yet have parsed the package, so just see if
6766                // we still know about its settings.
6767                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6768            }
6769            if (bp.packageSetting == null) {
6770                Slog.w(TAG, "Removing dangling permission: " + bp.name
6771                        + " from package " + bp.sourcePackage);
6772                it.remove();
6773            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6774                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6775                    Slog.i(TAG, "Removing old permission: " + bp.name
6776                            + " from package " + bp.sourcePackage);
6777                    flags |= UPDATE_PERMISSIONS_ALL;
6778                    it.remove();
6779                }
6780            }
6781        }
6782
6783        // Now update the permissions for all packages, in particular
6784        // replace the granted permissions of the system packages.
6785        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6786            for (PackageParser.Package pkg : mPackages.values()) {
6787                if (pkg != pkgInfo) {
6788                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6789                }
6790            }
6791        }
6792
6793        if (pkgInfo != null) {
6794            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6795        }
6796    }
6797
6798    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6799        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6800        if (ps == null) {
6801            return;
6802        }
6803        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6804        HashSet<String> origPermissions = gp.grantedPermissions;
6805        boolean changedPermission = false;
6806
6807        if (replace) {
6808            ps.permissionsFixed = false;
6809            if (gp == ps) {
6810                origPermissions = new HashSet<String>(gp.grantedPermissions);
6811                gp.grantedPermissions.clear();
6812                gp.gids = mGlobalGids;
6813            }
6814        }
6815
6816        if (gp.gids == null) {
6817            gp.gids = mGlobalGids;
6818        }
6819
6820        final int N = pkg.requestedPermissions.size();
6821        for (int i=0; i<N; i++) {
6822            final String name = pkg.requestedPermissions.get(i);
6823            final boolean required = pkg.requestedPermissionsRequired.get(i);
6824            final BasePermission bp = mSettings.mPermissions.get(name);
6825            if (DEBUG_INSTALL) {
6826                if (gp != ps) {
6827                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6828                }
6829            }
6830
6831            if (bp == null || bp.packageSetting == null) {
6832                Slog.w(TAG, "Unknown permission " + name
6833                        + " in package " + pkg.packageName);
6834                continue;
6835            }
6836
6837            final String perm = bp.name;
6838            boolean allowed;
6839            boolean allowedSig = false;
6840            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6841                // Keep track of app op permissions.
6842                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6843                if (pkgs == null) {
6844                    pkgs = new ArraySet<>();
6845                    mAppOpPermissionPackages.put(bp.name, pkgs);
6846                }
6847                pkgs.add(pkg.packageName);
6848            }
6849            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6850            if (level == PermissionInfo.PROTECTION_NORMAL
6851                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6852                // We grant a normal or dangerous permission if any of the following
6853                // are true:
6854                // 1) The permission is required
6855                // 2) The permission is optional, but was granted in the past
6856                // 3) The permission is optional, but was requested by an
6857                //    app in /system (not /data)
6858                //
6859                // Otherwise, reject the permission.
6860                allowed = (required || origPermissions.contains(perm)
6861                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6862            } else if (bp.packageSetting == null) {
6863                // This permission is invalid; skip it.
6864                allowed = false;
6865            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6866                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6867                if (allowed) {
6868                    allowedSig = true;
6869                }
6870            } else {
6871                allowed = false;
6872            }
6873            if (DEBUG_INSTALL) {
6874                if (gp != ps) {
6875                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6876                }
6877            }
6878            if (allowed) {
6879                if (!isSystemApp(ps) && ps.permissionsFixed) {
6880                    // If this is an existing, non-system package, then
6881                    // we can't add any new permissions to it.
6882                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6883                        // Except...  if this is a permission that was added
6884                        // to the platform (note: need to only do this when
6885                        // updating the platform).
6886                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6887                    }
6888                }
6889                if (allowed) {
6890                    if (!gp.grantedPermissions.contains(perm)) {
6891                        changedPermission = true;
6892                        gp.grantedPermissions.add(perm);
6893                        gp.gids = appendInts(gp.gids, bp.gids);
6894                    } else if (!ps.haveGids) {
6895                        gp.gids = appendInts(gp.gids, bp.gids);
6896                    }
6897                } else {
6898                    Slog.w(TAG, "Not granting permission " + perm
6899                            + " to package " + pkg.packageName
6900                            + " because it was previously installed without");
6901                }
6902            } else {
6903                if (gp.grantedPermissions.remove(perm)) {
6904                    changedPermission = true;
6905                    gp.gids = removeInts(gp.gids, bp.gids);
6906                    Slog.i(TAG, "Un-granting permission " + perm
6907                            + " from package " + pkg.packageName
6908                            + " (protectionLevel=" + bp.protectionLevel
6909                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6910                            + ")");
6911                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6912                    // Don't print warning for app op permissions, since it is fine for them
6913                    // not to be granted, there is a UI for the user to decide.
6914                    Slog.w(TAG, "Not granting permission " + perm
6915                            + " to package " + pkg.packageName
6916                            + " (protectionLevel=" + bp.protectionLevel
6917                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6918                            + ")");
6919                }
6920            }
6921        }
6922
6923        if ((changedPermission || replace) && !ps.permissionsFixed &&
6924                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6925            // This is the first that we have heard about this package, so the
6926            // permissions we have now selected are fixed until explicitly
6927            // changed.
6928            ps.permissionsFixed = true;
6929        }
6930        ps.haveGids = true;
6931    }
6932
6933    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6934        boolean allowed = false;
6935        final int NP = PackageParser.NEW_PERMISSIONS.length;
6936        for (int ip=0; ip<NP; ip++) {
6937            final PackageParser.NewPermissionInfo npi
6938                    = PackageParser.NEW_PERMISSIONS[ip];
6939            if (npi.name.equals(perm)
6940                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6941                allowed = true;
6942                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6943                        + pkg.packageName);
6944                break;
6945            }
6946        }
6947        return allowed;
6948    }
6949
6950    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6951                                          BasePermission bp, HashSet<String> origPermissions) {
6952        boolean allowed;
6953        allowed = (compareSignatures(
6954                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6955                        == PackageManager.SIGNATURE_MATCH)
6956                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6957                        == PackageManager.SIGNATURE_MATCH);
6958        if (!allowed && (bp.protectionLevel
6959                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6960            if (isSystemApp(pkg)) {
6961                // For updated system applications, a system permission
6962                // is granted only if it had been defined by the original application.
6963                if (isUpdatedSystemApp(pkg)) {
6964                    final PackageSetting sysPs = mSettings
6965                            .getDisabledSystemPkgLPr(pkg.packageName);
6966                    final GrantedPermissions origGp = sysPs.sharedUser != null
6967                            ? sysPs.sharedUser : sysPs;
6968
6969                    if (origGp.grantedPermissions.contains(perm)) {
6970                        // If the original was granted this permission, we take
6971                        // that grant decision as read and propagate it to the
6972                        // update.
6973                        allowed = true;
6974                    } else {
6975                        // The system apk may have been updated with an older
6976                        // version of the one on the data partition, but which
6977                        // granted a new system permission that it didn't have
6978                        // before.  In this case we do want to allow the app to
6979                        // now get the new permission if the ancestral apk is
6980                        // privileged to get it.
6981                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6982                            for (int j=0;
6983                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6984                                if (perm.equals(
6985                                        sysPs.pkg.requestedPermissions.get(j))) {
6986                                    allowed = true;
6987                                    break;
6988                                }
6989                            }
6990                        }
6991                    }
6992                } else {
6993                    allowed = isPrivilegedApp(pkg);
6994                }
6995            }
6996        }
6997        if (!allowed && (bp.protectionLevel
6998                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6999            // For development permissions, a development permission
7000            // is granted only if it was already granted.
7001            allowed = origPermissions.contains(perm);
7002        }
7003        return allowed;
7004    }
7005
7006    final class ActivityIntentResolver
7007            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7008        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7009                boolean defaultOnly, int userId) {
7010            if (!sUserManager.exists(userId)) return null;
7011            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7012            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7013        }
7014
7015        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7016                int userId) {
7017            if (!sUserManager.exists(userId)) return null;
7018            mFlags = flags;
7019            return super.queryIntent(intent, resolvedType,
7020                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7021        }
7022
7023        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7024                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7025            if (!sUserManager.exists(userId)) return null;
7026            if (packageActivities == null) {
7027                return null;
7028            }
7029            mFlags = flags;
7030            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7031            final int N = packageActivities.size();
7032            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7033                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7034
7035            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7036            for (int i = 0; i < N; ++i) {
7037                intentFilters = packageActivities.get(i).intents;
7038                if (intentFilters != null && intentFilters.size() > 0) {
7039                    PackageParser.ActivityIntentInfo[] array =
7040                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7041                    intentFilters.toArray(array);
7042                    listCut.add(array);
7043                }
7044            }
7045            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7046        }
7047
7048        public final void addActivity(PackageParser.Activity a, String type) {
7049            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7050            mActivities.put(a.getComponentName(), a);
7051            if (DEBUG_SHOW_INFO)
7052                Log.v(
7053                TAG, "  " + type + " " +
7054                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7055            if (DEBUG_SHOW_INFO)
7056                Log.v(TAG, "    Class=" + a.info.name);
7057            final int NI = a.intents.size();
7058            for (int j=0; j<NI; j++) {
7059                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7060                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7061                    intent.setPriority(0);
7062                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7063                            + a.className + " with priority > 0, forcing to 0");
7064                }
7065                if (DEBUG_SHOW_INFO) {
7066                    Log.v(TAG, "    IntentFilter:");
7067                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7068                }
7069                if (!intent.debugCheck()) {
7070                    Log.w(TAG, "==> For Activity " + a.info.name);
7071                }
7072                addFilter(intent);
7073            }
7074        }
7075
7076        public final void removeActivity(PackageParser.Activity a, String type) {
7077            mActivities.remove(a.getComponentName());
7078            if (DEBUG_SHOW_INFO) {
7079                Log.v(TAG, "  " + type + " "
7080                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7081                                : a.info.name) + ":");
7082                Log.v(TAG, "    Class=" + a.info.name);
7083            }
7084            final int NI = a.intents.size();
7085            for (int j=0; j<NI; j++) {
7086                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7087                if (DEBUG_SHOW_INFO) {
7088                    Log.v(TAG, "    IntentFilter:");
7089                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7090                }
7091                removeFilter(intent);
7092            }
7093        }
7094
7095        @Override
7096        protected boolean allowFilterResult(
7097                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7098            ActivityInfo filterAi = filter.activity.info;
7099            for (int i=dest.size()-1; i>=0; i--) {
7100                ActivityInfo destAi = dest.get(i).activityInfo;
7101                if (destAi.name == filterAi.name
7102                        && destAi.packageName == filterAi.packageName) {
7103                    return false;
7104                }
7105            }
7106            return true;
7107        }
7108
7109        @Override
7110        protected ActivityIntentInfo[] newArray(int size) {
7111            return new ActivityIntentInfo[size];
7112        }
7113
7114        @Override
7115        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7116            if (!sUserManager.exists(userId)) return true;
7117            PackageParser.Package p = filter.activity.owner;
7118            if (p != null) {
7119                PackageSetting ps = (PackageSetting)p.mExtras;
7120                if (ps != null) {
7121                    // System apps are never considered stopped for purposes of
7122                    // filtering, because there may be no way for the user to
7123                    // actually re-launch them.
7124                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7125                            && ps.getStopped(userId);
7126                }
7127            }
7128            return false;
7129        }
7130
7131        @Override
7132        protected boolean isPackageForFilter(String packageName,
7133                PackageParser.ActivityIntentInfo info) {
7134            return packageName.equals(info.activity.owner.packageName);
7135        }
7136
7137        @Override
7138        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7139                int match, int userId) {
7140            if (!sUserManager.exists(userId)) return null;
7141            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7142                return null;
7143            }
7144            final PackageParser.Activity activity = info.activity;
7145            if (mSafeMode && (activity.info.applicationInfo.flags
7146                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7147                return null;
7148            }
7149            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7150            if (ps == null) {
7151                return null;
7152            }
7153            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7154                    ps.readUserState(userId), userId);
7155            if (ai == null) {
7156                return null;
7157            }
7158            final ResolveInfo res = new ResolveInfo();
7159            res.activityInfo = ai;
7160            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7161                res.filter = info;
7162            }
7163            res.priority = info.getPriority();
7164            res.preferredOrder = activity.owner.mPreferredOrder;
7165            //System.out.println("Result: " + res.activityInfo.className +
7166            //                   " = " + res.priority);
7167            res.match = match;
7168            res.isDefault = info.hasDefault;
7169            res.labelRes = info.labelRes;
7170            res.nonLocalizedLabel = info.nonLocalizedLabel;
7171            if (userNeedsBadging(userId)) {
7172                res.noResourceId = true;
7173            } else {
7174                res.icon = info.icon;
7175            }
7176            res.system = isSystemApp(res.activityInfo.applicationInfo);
7177            return res;
7178        }
7179
7180        @Override
7181        protected void sortResults(List<ResolveInfo> results) {
7182            Collections.sort(results, mResolvePrioritySorter);
7183        }
7184
7185        @Override
7186        protected void dumpFilter(PrintWriter out, String prefix,
7187                PackageParser.ActivityIntentInfo filter) {
7188            out.print(prefix); out.print(
7189                    Integer.toHexString(System.identityHashCode(filter.activity)));
7190                    out.print(' ');
7191                    filter.activity.printComponentShortName(out);
7192                    out.print(" filter ");
7193                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7194        }
7195
7196//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7197//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7198//            final List<ResolveInfo> retList = Lists.newArrayList();
7199//            while (i.hasNext()) {
7200//                final ResolveInfo resolveInfo = i.next();
7201//                if (isEnabledLP(resolveInfo.activityInfo)) {
7202//                    retList.add(resolveInfo);
7203//                }
7204//            }
7205//            return retList;
7206//        }
7207
7208        // Keys are String (activity class name), values are Activity.
7209        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7210                = new HashMap<ComponentName, PackageParser.Activity>();
7211        private int mFlags;
7212    }
7213
7214    private final class ServiceIntentResolver
7215            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7216        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7217                boolean defaultOnly, int userId) {
7218            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7219            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7220        }
7221
7222        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7223                int userId) {
7224            if (!sUserManager.exists(userId)) return null;
7225            mFlags = flags;
7226            return super.queryIntent(intent, resolvedType,
7227                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7228        }
7229
7230        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7231                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7232            if (!sUserManager.exists(userId)) return null;
7233            if (packageServices == null) {
7234                return null;
7235            }
7236            mFlags = flags;
7237            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7238            final int N = packageServices.size();
7239            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7240                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7241
7242            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7243            for (int i = 0; i < N; ++i) {
7244                intentFilters = packageServices.get(i).intents;
7245                if (intentFilters != null && intentFilters.size() > 0) {
7246                    PackageParser.ServiceIntentInfo[] array =
7247                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7248                    intentFilters.toArray(array);
7249                    listCut.add(array);
7250                }
7251            }
7252            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7253        }
7254
7255        public final void addService(PackageParser.Service s) {
7256            mServices.put(s.getComponentName(), s);
7257            if (DEBUG_SHOW_INFO) {
7258                Log.v(TAG, "  "
7259                        + (s.info.nonLocalizedLabel != null
7260                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7261                Log.v(TAG, "    Class=" + s.info.name);
7262            }
7263            final int NI = s.intents.size();
7264            int j;
7265            for (j=0; j<NI; j++) {
7266                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7267                if (DEBUG_SHOW_INFO) {
7268                    Log.v(TAG, "    IntentFilter:");
7269                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7270                }
7271                if (!intent.debugCheck()) {
7272                    Log.w(TAG, "==> For Service " + s.info.name);
7273                }
7274                addFilter(intent);
7275            }
7276        }
7277
7278        public final void removeService(PackageParser.Service s) {
7279            mServices.remove(s.getComponentName());
7280            if (DEBUG_SHOW_INFO) {
7281                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7282                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7283                Log.v(TAG, "    Class=" + s.info.name);
7284            }
7285            final int NI = s.intents.size();
7286            int j;
7287            for (j=0; j<NI; j++) {
7288                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7289                if (DEBUG_SHOW_INFO) {
7290                    Log.v(TAG, "    IntentFilter:");
7291                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7292                }
7293                removeFilter(intent);
7294            }
7295        }
7296
7297        @Override
7298        protected boolean allowFilterResult(
7299                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7300            ServiceInfo filterSi = filter.service.info;
7301            for (int i=dest.size()-1; i>=0; i--) {
7302                ServiceInfo destAi = dest.get(i).serviceInfo;
7303                if (destAi.name == filterSi.name
7304                        && destAi.packageName == filterSi.packageName) {
7305                    return false;
7306                }
7307            }
7308            return true;
7309        }
7310
7311        @Override
7312        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7313            return new PackageParser.ServiceIntentInfo[size];
7314        }
7315
7316        @Override
7317        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7318            if (!sUserManager.exists(userId)) return true;
7319            PackageParser.Package p = filter.service.owner;
7320            if (p != null) {
7321                PackageSetting ps = (PackageSetting)p.mExtras;
7322                if (ps != null) {
7323                    // System apps are never considered stopped for purposes of
7324                    // filtering, because there may be no way for the user to
7325                    // actually re-launch them.
7326                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7327                            && ps.getStopped(userId);
7328                }
7329            }
7330            return false;
7331        }
7332
7333        @Override
7334        protected boolean isPackageForFilter(String packageName,
7335                PackageParser.ServiceIntentInfo info) {
7336            return packageName.equals(info.service.owner.packageName);
7337        }
7338
7339        @Override
7340        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7341                int match, int userId) {
7342            if (!sUserManager.exists(userId)) return null;
7343            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7344            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7345                return null;
7346            }
7347            final PackageParser.Service service = info.service;
7348            if (mSafeMode && (service.info.applicationInfo.flags
7349                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7350                return null;
7351            }
7352            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7353            if (ps == null) {
7354                return null;
7355            }
7356            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7357                    ps.readUserState(userId), userId);
7358            if (si == null) {
7359                return null;
7360            }
7361            final ResolveInfo res = new ResolveInfo();
7362            res.serviceInfo = si;
7363            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7364                res.filter = filter;
7365            }
7366            res.priority = info.getPriority();
7367            res.preferredOrder = service.owner.mPreferredOrder;
7368            //System.out.println("Result: " + res.activityInfo.className +
7369            //                   " = " + res.priority);
7370            res.match = match;
7371            res.isDefault = info.hasDefault;
7372            res.labelRes = info.labelRes;
7373            res.nonLocalizedLabel = info.nonLocalizedLabel;
7374            res.icon = info.icon;
7375            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7376            return res;
7377        }
7378
7379        @Override
7380        protected void sortResults(List<ResolveInfo> results) {
7381            Collections.sort(results, mResolvePrioritySorter);
7382        }
7383
7384        @Override
7385        protected void dumpFilter(PrintWriter out, String prefix,
7386                PackageParser.ServiceIntentInfo filter) {
7387            out.print(prefix); out.print(
7388                    Integer.toHexString(System.identityHashCode(filter.service)));
7389                    out.print(' ');
7390                    filter.service.printComponentShortName(out);
7391                    out.print(" filter ");
7392                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7393        }
7394
7395//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7396//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7397//            final List<ResolveInfo> retList = Lists.newArrayList();
7398//            while (i.hasNext()) {
7399//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7400//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7401//                    retList.add(resolveInfo);
7402//                }
7403//            }
7404//            return retList;
7405//        }
7406
7407        // Keys are String (activity class name), values are Activity.
7408        private final HashMap<ComponentName, PackageParser.Service> mServices
7409                = new HashMap<ComponentName, PackageParser.Service>();
7410        private int mFlags;
7411    };
7412
7413    private final class ProviderIntentResolver
7414            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7415        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7416                boolean defaultOnly, int userId) {
7417            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7418            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7419        }
7420
7421        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7422                int userId) {
7423            if (!sUserManager.exists(userId))
7424                return null;
7425            mFlags = flags;
7426            return super.queryIntent(intent, resolvedType,
7427                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7428        }
7429
7430        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7431                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7432            if (!sUserManager.exists(userId))
7433                return null;
7434            if (packageProviders == null) {
7435                return null;
7436            }
7437            mFlags = flags;
7438            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7439            final int N = packageProviders.size();
7440            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7441                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7442
7443            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7444            for (int i = 0; i < N; ++i) {
7445                intentFilters = packageProviders.get(i).intents;
7446                if (intentFilters != null && intentFilters.size() > 0) {
7447                    PackageParser.ProviderIntentInfo[] array =
7448                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7449                    intentFilters.toArray(array);
7450                    listCut.add(array);
7451                }
7452            }
7453            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7454        }
7455
7456        public final void addProvider(PackageParser.Provider p) {
7457            if (mProviders.containsKey(p.getComponentName())) {
7458                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7459                return;
7460            }
7461
7462            mProviders.put(p.getComponentName(), p);
7463            if (DEBUG_SHOW_INFO) {
7464                Log.v(TAG, "  "
7465                        + (p.info.nonLocalizedLabel != null
7466                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7467                Log.v(TAG, "    Class=" + p.info.name);
7468            }
7469            final int NI = p.intents.size();
7470            int j;
7471            for (j = 0; j < NI; j++) {
7472                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7473                if (DEBUG_SHOW_INFO) {
7474                    Log.v(TAG, "    IntentFilter:");
7475                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7476                }
7477                if (!intent.debugCheck()) {
7478                    Log.w(TAG, "==> For Provider " + p.info.name);
7479                }
7480                addFilter(intent);
7481            }
7482        }
7483
7484        public final void removeProvider(PackageParser.Provider p) {
7485            mProviders.remove(p.getComponentName());
7486            if (DEBUG_SHOW_INFO) {
7487                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7488                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7489                Log.v(TAG, "    Class=" + p.info.name);
7490            }
7491            final int NI = p.intents.size();
7492            int j;
7493            for (j = 0; j < NI; j++) {
7494                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7495                if (DEBUG_SHOW_INFO) {
7496                    Log.v(TAG, "    IntentFilter:");
7497                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7498                }
7499                removeFilter(intent);
7500            }
7501        }
7502
7503        @Override
7504        protected boolean allowFilterResult(
7505                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7506            ProviderInfo filterPi = filter.provider.info;
7507            for (int i = dest.size() - 1; i >= 0; i--) {
7508                ProviderInfo destPi = dest.get(i).providerInfo;
7509                if (destPi.name == filterPi.name
7510                        && destPi.packageName == filterPi.packageName) {
7511                    return false;
7512                }
7513            }
7514            return true;
7515        }
7516
7517        @Override
7518        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7519            return new PackageParser.ProviderIntentInfo[size];
7520        }
7521
7522        @Override
7523        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7524            if (!sUserManager.exists(userId))
7525                return true;
7526            PackageParser.Package p = filter.provider.owner;
7527            if (p != null) {
7528                PackageSetting ps = (PackageSetting) p.mExtras;
7529                if (ps != null) {
7530                    // System apps are never considered stopped for purposes of
7531                    // filtering, because there may be no way for the user to
7532                    // actually re-launch them.
7533                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7534                            && ps.getStopped(userId);
7535                }
7536            }
7537            return false;
7538        }
7539
7540        @Override
7541        protected boolean isPackageForFilter(String packageName,
7542                PackageParser.ProviderIntentInfo info) {
7543            return packageName.equals(info.provider.owner.packageName);
7544        }
7545
7546        @Override
7547        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7548                int match, int userId) {
7549            if (!sUserManager.exists(userId))
7550                return null;
7551            final PackageParser.ProviderIntentInfo info = filter;
7552            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7553                return null;
7554            }
7555            final PackageParser.Provider provider = info.provider;
7556            if (mSafeMode && (provider.info.applicationInfo.flags
7557                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7558                return null;
7559            }
7560            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7561            if (ps == null) {
7562                return null;
7563            }
7564            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7565                    ps.readUserState(userId), userId);
7566            if (pi == null) {
7567                return null;
7568            }
7569            final ResolveInfo res = new ResolveInfo();
7570            res.providerInfo = pi;
7571            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7572                res.filter = filter;
7573            }
7574            res.priority = info.getPriority();
7575            res.preferredOrder = provider.owner.mPreferredOrder;
7576            res.match = match;
7577            res.isDefault = info.hasDefault;
7578            res.labelRes = info.labelRes;
7579            res.nonLocalizedLabel = info.nonLocalizedLabel;
7580            res.icon = info.icon;
7581            res.system = isSystemApp(res.providerInfo.applicationInfo);
7582            return res;
7583        }
7584
7585        @Override
7586        protected void sortResults(List<ResolveInfo> results) {
7587            Collections.sort(results, mResolvePrioritySorter);
7588        }
7589
7590        @Override
7591        protected void dumpFilter(PrintWriter out, String prefix,
7592                PackageParser.ProviderIntentInfo filter) {
7593            out.print(prefix);
7594            out.print(
7595                    Integer.toHexString(System.identityHashCode(filter.provider)));
7596            out.print(' ');
7597            filter.provider.printComponentShortName(out);
7598            out.print(" filter ");
7599            out.println(Integer.toHexString(System.identityHashCode(filter)));
7600        }
7601
7602        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7603                = new HashMap<ComponentName, PackageParser.Provider>();
7604        private int mFlags;
7605    };
7606
7607    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7608            new Comparator<ResolveInfo>() {
7609        public int compare(ResolveInfo r1, ResolveInfo r2) {
7610            int v1 = r1.priority;
7611            int v2 = r2.priority;
7612            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7613            if (v1 != v2) {
7614                return (v1 > v2) ? -1 : 1;
7615            }
7616            v1 = r1.preferredOrder;
7617            v2 = r2.preferredOrder;
7618            if (v1 != v2) {
7619                return (v1 > v2) ? -1 : 1;
7620            }
7621            if (r1.isDefault != r2.isDefault) {
7622                return r1.isDefault ? -1 : 1;
7623            }
7624            v1 = r1.match;
7625            v2 = r2.match;
7626            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7627            if (v1 != v2) {
7628                return (v1 > v2) ? -1 : 1;
7629            }
7630            if (r1.system != r2.system) {
7631                return r1.system ? -1 : 1;
7632            }
7633            return 0;
7634        }
7635    };
7636
7637    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7638            new Comparator<ProviderInfo>() {
7639        public int compare(ProviderInfo p1, ProviderInfo p2) {
7640            final int v1 = p1.initOrder;
7641            final int v2 = p2.initOrder;
7642            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7643        }
7644    };
7645
7646    static final void sendPackageBroadcast(String action, String pkg,
7647            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7648            int[] userIds) {
7649        IActivityManager am = ActivityManagerNative.getDefault();
7650        if (am != null) {
7651            try {
7652                if (userIds == null) {
7653                    userIds = am.getRunningUserIds();
7654                }
7655                for (int id : userIds) {
7656                    final Intent intent = new Intent(action,
7657                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7658                    if (extras != null) {
7659                        intent.putExtras(extras);
7660                    }
7661                    if (targetPkg != null) {
7662                        intent.setPackage(targetPkg);
7663                    }
7664                    // Modify the UID when posting to other users
7665                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7666                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7667                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7668                        intent.putExtra(Intent.EXTRA_UID, uid);
7669                    }
7670                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7671                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7672                    if (DEBUG_BROADCASTS) {
7673                        RuntimeException here = new RuntimeException("here");
7674                        here.fillInStackTrace();
7675                        Slog.d(TAG, "Sending to user " + id + ": "
7676                                + intent.toShortString(false, true, false, false)
7677                                + " " + intent.getExtras(), here);
7678                    }
7679                    am.broadcastIntent(null, intent, null, finishedReceiver,
7680                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7681                            finishedReceiver != null, false, id);
7682                }
7683            } catch (RemoteException ex) {
7684            }
7685        }
7686    }
7687
7688    /**
7689     * Check if the external storage media is available. This is true if there
7690     * is a mounted external storage medium or if the external storage is
7691     * emulated.
7692     */
7693    private boolean isExternalMediaAvailable() {
7694        return mMediaMounted || Environment.isExternalStorageEmulated();
7695    }
7696
7697    @Override
7698    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7699        // writer
7700        synchronized (mPackages) {
7701            if (!isExternalMediaAvailable()) {
7702                // If the external storage is no longer mounted at this point,
7703                // the caller may not have been able to delete all of this
7704                // packages files and can not delete any more.  Bail.
7705                return null;
7706            }
7707            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7708            if (lastPackage != null) {
7709                pkgs.remove(lastPackage);
7710            }
7711            if (pkgs.size() > 0) {
7712                return pkgs.get(0);
7713            }
7714        }
7715        return null;
7716    }
7717
7718    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7719        if (false) {
7720            RuntimeException here = new RuntimeException("here");
7721            here.fillInStackTrace();
7722            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7723                    + " andCode=" + andCode, here);
7724        }
7725        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7726                userId, andCode ? 1 : 0, packageName));
7727    }
7728
7729    void startCleaningPackages() {
7730        // reader
7731        synchronized (mPackages) {
7732            if (!isExternalMediaAvailable()) {
7733                return;
7734            }
7735            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7736                return;
7737            }
7738        }
7739        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7740        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7741        IActivityManager am = ActivityManagerNative.getDefault();
7742        if (am != null) {
7743            try {
7744                am.startService(null, intent, null, UserHandle.USER_OWNER);
7745            } catch (RemoteException e) {
7746            }
7747        }
7748    }
7749
7750    @Override
7751    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7752            String installerPackageName, VerificationParams verificationParams,
7753            String packageAbiOverride) {
7754        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7755                null);
7756
7757        final File originFile = new File(originPath);
7758        final int uid = Binder.getCallingUid();
7759        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7760            try {
7761                if (observer != null) {
7762                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7763                }
7764            } catch (RemoteException re) {
7765            }
7766            return;
7767        }
7768
7769        UserHandle user;
7770        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7771            user = UserHandle.ALL;
7772        } else {
7773            user = new UserHandle(UserHandle.getUserId(uid));
7774        }
7775
7776        final int filteredFlags;
7777        if (uid == Process.SHELL_UID || uid == 0) {
7778            if (DEBUG_INSTALL) {
7779                Slog.v(TAG, "Install from ADB");
7780            }
7781            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7782        } else {
7783            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7784        }
7785
7786        verificationParams.setInstallerUid(uid);
7787
7788        final Message msg = mHandler.obtainMessage(INIT_COPY);
7789        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7790                installerPackageName, verificationParams, user, packageAbiOverride);
7791        mHandler.sendMessage(msg);
7792    }
7793
7794    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7795            InstallSessionParams params, String installerPackageName, int installerUid,
7796            UserHandle user) {
7797        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7798                params.referrerUri, installerUid, null);
7799
7800        final Message msg = mHandler.obtainMessage(INIT_COPY);
7801        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7802                installerPackageName, verifParams, user, params.abiOverride);
7803        mHandler.sendMessage(msg);
7804    }
7805
7806    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7807        Bundle extras = new Bundle(1);
7808        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7809
7810        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7811                packageName, extras, null, null, new int[] {userId});
7812        try {
7813            IActivityManager am = ActivityManagerNative.getDefault();
7814            final boolean isSystem =
7815                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7816            if (isSystem && am.isUserRunning(userId, false)) {
7817                // The just-installed/enabled app is bundled on the system, so presumed
7818                // to be able to run automatically without needing an explicit launch.
7819                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7820                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7821                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7822                        .setPackage(packageName);
7823                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7824                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7825            }
7826        } catch (RemoteException e) {
7827            // shouldn't happen
7828            Slog.w(TAG, "Unable to bootstrap installed package", e);
7829        }
7830    }
7831
7832    @Override
7833    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7834            int userId) {
7835        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7836        PackageSetting pkgSetting;
7837        final int uid = Binder.getCallingUid();
7838        if (UserHandle.getUserId(uid) != userId) {
7839            mContext.enforceCallingOrSelfPermission(
7840                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7841                    "setApplicationHiddenSetting for user " + userId);
7842        }
7843
7844        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7845            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7846            return false;
7847        }
7848
7849        long callingId = Binder.clearCallingIdentity();
7850        try {
7851            boolean sendAdded = false;
7852            boolean sendRemoved = false;
7853            // writer
7854            synchronized (mPackages) {
7855                pkgSetting = mSettings.mPackages.get(packageName);
7856                if (pkgSetting == null) {
7857                    return false;
7858                }
7859                if (pkgSetting.getHidden(userId) != hidden) {
7860                    pkgSetting.setHidden(hidden, userId);
7861                    mSettings.writePackageRestrictionsLPr(userId);
7862                    if (hidden) {
7863                        sendRemoved = true;
7864                    } else {
7865                        sendAdded = true;
7866                    }
7867                }
7868            }
7869            if (sendAdded) {
7870                sendPackageAddedForUser(packageName, pkgSetting, userId);
7871                return true;
7872            }
7873            if (sendRemoved) {
7874                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7875                        "hiding pkg");
7876                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7877            }
7878        } finally {
7879            Binder.restoreCallingIdentity(callingId);
7880        }
7881        return false;
7882    }
7883
7884    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7885            int userId) {
7886        final PackageRemovedInfo info = new PackageRemovedInfo();
7887        info.removedPackage = packageName;
7888        info.removedUsers = new int[] {userId};
7889        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7890        info.sendBroadcast(false, false, false);
7891    }
7892
7893    /**
7894     * Returns true if application is not found or there was an error. Otherwise it returns
7895     * the hidden state of the package for the given user.
7896     */
7897    @Override
7898    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7899        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7900        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7901                "getApplicationHidden for user " + userId);
7902        PackageSetting pkgSetting;
7903        long callingId = Binder.clearCallingIdentity();
7904        try {
7905            // writer
7906            synchronized (mPackages) {
7907                pkgSetting = mSettings.mPackages.get(packageName);
7908                if (pkgSetting == null) {
7909                    return true;
7910                }
7911                return pkgSetting.getHidden(userId);
7912            }
7913        } finally {
7914            Binder.restoreCallingIdentity(callingId);
7915        }
7916    }
7917
7918    /**
7919     * @hide
7920     */
7921    @Override
7922    public int installExistingPackageAsUser(String packageName, int userId) {
7923        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7924                null);
7925        PackageSetting pkgSetting;
7926        final int uid = Binder.getCallingUid();
7927        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7928        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7929            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7930        }
7931
7932        long callingId = Binder.clearCallingIdentity();
7933        try {
7934            boolean sendAdded = false;
7935            Bundle extras = new Bundle(1);
7936
7937            // writer
7938            synchronized (mPackages) {
7939                pkgSetting = mSettings.mPackages.get(packageName);
7940                if (pkgSetting == null) {
7941                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7942                }
7943                if (!pkgSetting.getInstalled(userId)) {
7944                    pkgSetting.setInstalled(true, userId);
7945                    pkgSetting.setHidden(false, userId);
7946                    mSettings.writePackageRestrictionsLPr(userId);
7947                    sendAdded = true;
7948                }
7949            }
7950
7951            if (sendAdded) {
7952                sendPackageAddedForUser(packageName, pkgSetting, userId);
7953            }
7954        } finally {
7955            Binder.restoreCallingIdentity(callingId);
7956        }
7957
7958        return PackageManager.INSTALL_SUCCEEDED;
7959    }
7960
7961    boolean isUserRestricted(int userId, String restrictionKey) {
7962        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7963        if (restrictions.getBoolean(restrictionKey, false)) {
7964            Log.w(TAG, "User is restricted: " + restrictionKey);
7965            return true;
7966        }
7967        return false;
7968    }
7969
7970    @Override
7971    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7972        mContext.enforceCallingOrSelfPermission(
7973                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7974                "Only package verification agents can verify applications");
7975
7976        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7977        final PackageVerificationResponse response = new PackageVerificationResponse(
7978                verificationCode, Binder.getCallingUid());
7979        msg.arg1 = id;
7980        msg.obj = response;
7981        mHandler.sendMessage(msg);
7982    }
7983
7984    @Override
7985    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7986            long millisecondsToDelay) {
7987        mContext.enforceCallingOrSelfPermission(
7988                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7989                "Only package verification agents can extend verification timeouts");
7990
7991        final PackageVerificationState state = mPendingVerification.get(id);
7992        final PackageVerificationResponse response = new PackageVerificationResponse(
7993                verificationCodeAtTimeout, Binder.getCallingUid());
7994
7995        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7996            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7997        }
7998        if (millisecondsToDelay < 0) {
7999            millisecondsToDelay = 0;
8000        }
8001        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8002                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8003            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8004        }
8005
8006        if ((state != null) && !state.timeoutExtended()) {
8007            state.extendTimeout();
8008
8009            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8010            msg.arg1 = id;
8011            msg.obj = response;
8012            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8013        }
8014    }
8015
8016    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8017            int verificationCode, UserHandle user) {
8018        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8019        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8020        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8021        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8022        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8023
8024        mContext.sendBroadcastAsUser(intent, user,
8025                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8026    }
8027
8028    private ComponentName matchComponentForVerifier(String packageName,
8029            List<ResolveInfo> receivers) {
8030        ActivityInfo targetReceiver = null;
8031
8032        final int NR = receivers.size();
8033        for (int i = 0; i < NR; i++) {
8034            final ResolveInfo info = receivers.get(i);
8035            if (info.activityInfo == null) {
8036                continue;
8037            }
8038
8039            if (packageName.equals(info.activityInfo.packageName)) {
8040                targetReceiver = info.activityInfo;
8041                break;
8042            }
8043        }
8044
8045        if (targetReceiver == null) {
8046            return null;
8047        }
8048
8049        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8050    }
8051
8052    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8053            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8054        if (pkgInfo.verifiers.length == 0) {
8055            return null;
8056        }
8057
8058        final int N = pkgInfo.verifiers.length;
8059        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8060        for (int i = 0; i < N; i++) {
8061            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8062
8063            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8064                    receivers);
8065            if (comp == null) {
8066                continue;
8067            }
8068
8069            final int verifierUid = getUidForVerifier(verifierInfo);
8070            if (verifierUid == -1) {
8071                continue;
8072            }
8073
8074            if (DEBUG_VERIFY) {
8075                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8076                        + " with the correct signature");
8077            }
8078            sufficientVerifiers.add(comp);
8079            verificationState.addSufficientVerifier(verifierUid);
8080        }
8081
8082        return sufficientVerifiers;
8083    }
8084
8085    private int getUidForVerifier(VerifierInfo verifierInfo) {
8086        synchronized (mPackages) {
8087            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8088            if (pkg == null) {
8089                return -1;
8090            } else if (pkg.mSignatures.length != 1) {
8091                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8092                        + " has more than one signature; ignoring");
8093                return -1;
8094            }
8095
8096            /*
8097             * If the public key of the package's signature does not match
8098             * our expected public key, then this is a different package and
8099             * we should skip.
8100             */
8101
8102            final byte[] expectedPublicKey;
8103            try {
8104                final Signature verifierSig = pkg.mSignatures[0];
8105                final PublicKey publicKey = verifierSig.getPublicKey();
8106                expectedPublicKey = publicKey.getEncoded();
8107            } catch (CertificateException e) {
8108                return -1;
8109            }
8110
8111            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8112
8113            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8114                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8115                        + " does not have the expected public key; ignoring");
8116                return -1;
8117            }
8118
8119            return pkg.applicationInfo.uid;
8120        }
8121    }
8122
8123    @Override
8124    public void finishPackageInstall(int token) {
8125        enforceSystemOrRoot("Only the system is allowed to finish installs");
8126
8127        if (DEBUG_INSTALL) {
8128            Slog.v(TAG, "BM finishing package install for " + token);
8129        }
8130
8131        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8132        mHandler.sendMessage(msg);
8133    }
8134
8135    /**
8136     * Get the verification agent timeout.
8137     *
8138     * @return verification timeout in milliseconds
8139     */
8140    private long getVerificationTimeout() {
8141        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8142                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8143                DEFAULT_VERIFICATION_TIMEOUT);
8144    }
8145
8146    /**
8147     * Get the default verification agent response code.
8148     *
8149     * @return default verification response code
8150     */
8151    private int getDefaultVerificationResponse() {
8152        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8153                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8154                DEFAULT_VERIFICATION_RESPONSE);
8155    }
8156
8157    /**
8158     * Check whether or not package verification has been enabled.
8159     *
8160     * @return true if verification should be performed
8161     */
8162    private boolean isVerificationEnabled(int userId, int flags) {
8163        if (!DEFAULT_VERIFY_ENABLE) {
8164            return false;
8165        }
8166
8167        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8168
8169        // Check if installing from ADB
8170        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8171            // Do not run verification in a test harness environment
8172            if (ActivityManager.isRunningInTestHarness()) {
8173                return false;
8174            }
8175            if (ensureVerifyAppsEnabled) {
8176                return true;
8177            }
8178            // Check if the developer does not want package verification for ADB installs
8179            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8180                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8181                return false;
8182            }
8183        }
8184
8185        if (ensureVerifyAppsEnabled) {
8186            return true;
8187        }
8188
8189        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8190                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8191    }
8192
8193    /**
8194     * Get the "allow unknown sources" setting.
8195     *
8196     * @return the current "allow unknown sources" setting
8197     */
8198    private int getUnknownSourcesSettings() {
8199        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8200                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8201                -1);
8202    }
8203
8204    @Override
8205    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8206        final int uid = Binder.getCallingUid();
8207        // writer
8208        synchronized (mPackages) {
8209            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8210            if (targetPackageSetting == null) {
8211                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8212            }
8213
8214            PackageSetting installerPackageSetting;
8215            if (installerPackageName != null) {
8216                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8217                if (installerPackageSetting == null) {
8218                    throw new IllegalArgumentException("Unknown installer package: "
8219                            + installerPackageName);
8220                }
8221            } else {
8222                installerPackageSetting = null;
8223            }
8224
8225            Signature[] callerSignature;
8226            Object obj = mSettings.getUserIdLPr(uid);
8227            if (obj != null) {
8228                if (obj instanceof SharedUserSetting) {
8229                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8230                } else if (obj instanceof PackageSetting) {
8231                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8232                } else {
8233                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8234                }
8235            } else {
8236                throw new SecurityException("Unknown calling uid " + uid);
8237            }
8238
8239            // Verify: can't set installerPackageName to a package that is
8240            // not signed with the same cert as the caller.
8241            if (installerPackageSetting != null) {
8242                if (compareSignatures(callerSignature,
8243                        installerPackageSetting.signatures.mSignatures)
8244                        != PackageManager.SIGNATURE_MATCH) {
8245                    throw new SecurityException(
8246                            "Caller does not have same cert as new installer package "
8247                            + installerPackageName);
8248                }
8249            }
8250
8251            // Verify: if target already has an installer package, it must
8252            // be signed with the same cert as the caller.
8253            if (targetPackageSetting.installerPackageName != null) {
8254                PackageSetting setting = mSettings.mPackages.get(
8255                        targetPackageSetting.installerPackageName);
8256                // If the currently set package isn't valid, then it's always
8257                // okay to change it.
8258                if (setting != null) {
8259                    if (compareSignatures(callerSignature,
8260                            setting.signatures.mSignatures)
8261                            != PackageManager.SIGNATURE_MATCH) {
8262                        throw new SecurityException(
8263                                "Caller does not have same cert as old installer package "
8264                                + targetPackageSetting.installerPackageName);
8265                    }
8266                }
8267            }
8268
8269            // Okay!
8270            targetPackageSetting.installerPackageName = installerPackageName;
8271            scheduleWriteSettingsLocked();
8272        }
8273    }
8274
8275    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8276        // Queue up an async operation since the package installation may take a little while.
8277        mHandler.post(new Runnable() {
8278            public void run() {
8279                mHandler.removeCallbacks(this);
8280                 // Result object to be returned
8281                PackageInstalledInfo res = new PackageInstalledInfo();
8282                res.returnCode = currentStatus;
8283                res.uid = -1;
8284                res.pkg = null;
8285                res.removedInfo = new PackageRemovedInfo();
8286                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8287                    args.doPreInstall(res.returnCode);
8288                    synchronized (mInstallLock) {
8289                        installPackageLI(args, true, res);
8290                    }
8291                    args.doPostInstall(res.returnCode, res.uid);
8292                }
8293
8294                // A restore should be performed at this point if (a) the install
8295                // succeeded, (b) the operation is not an update, and (c) the new
8296                // package has not opted out of backup participation.
8297                final boolean update = res.removedInfo.removedPackage != null;
8298                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8299                boolean doRestore = !update
8300                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8301
8302                // Set up the post-install work request bookkeeping.  This will be used
8303                // and cleaned up by the post-install event handling regardless of whether
8304                // there's a restore pass performed.  Token values are >= 1.
8305                int token;
8306                if (mNextInstallToken < 0) mNextInstallToken = 1;
8307                token = mNextInstallToken++;
8308
8309                PostInstallData data = new PostInstallData(args, res);
8310                mRunningInstalls.put(token, data);
8311                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8312
8313                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8314                    // Pass responsibility to the Backup Manager.  It will perform a
8315                    // restore if appropriate, then pass responsibility back to the
8316                    // Package Manager to run the post-install observer callbacks
8317                    // and broadcasts.
8318                    IBackupManager bm = IBackupManager.Stub.asInterface(
8319                            ServiceManager.getService(Context.BACKUP_SERVICE));
8320                    if (bm != null) {
8321                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8322                                + " to BM for possible restore");
8323                        try {
8324                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8325                        } catch (RemoteException e) {
8326                            // can't happen; the backup manager is local
8327                        } catch (Exception e) {
8328                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8329                            doRestore = false;
8330                        }
8331                    } else {
8332                        Slog.e(TAG, "Backup Manager not found!");
8333                        doRestore = false;
8334                    }
8335                }
8336
8337                if (!doRestore) {
8338                    // No restore possible, or the Backup Manager was mysteriously not
8339                    // available -- just fire the post-install work request directly.
8340                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8341                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8342                    mHandler.sendMessage(msg);
8343                }
8344            }
8345        });
8346    }
8347
8348    private abstract class HandlerParams {
8349        private static final int MAX_RETRIES = 4;
8350
8351        /**
8352         * Number of times startCopy() has been attempted and had a non-fatal
8353         * error.
8354         */
8355        private int mRetries = 0;
8356
8357        /** User handle for the user requesting the information or installation. */
8358        private final UserHandle mUser;
8359
8360        HandlerParams(UserHandle user) {
8361            mUser = user;
8362        }
8363
8364        UserHandle getUser() {
8365            return mUser;
8366        }
8367
8368        final boolean startCopy() {
8369            boolean res;
8370            try {
8371                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8372
8373                if (++mRetries > MAX_RETRIES) {
8374                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8375                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8376                    handleServiceError();
8377                    return false;
8378                } else {
8379                    handleStartCopy();
8380                    res = true;
8381                }
8382            } catch (RemoteException e) {
8383                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8384                mHandler.sendEmptyMessage(MCS_RECONNECT);
8385                res = false;
8386            }
8387            handleReturnCode();
8388            return res;
8389        }
8390
8391        final void serviceError() {
8392            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8393            handleServiceError();
8394            handleReturnCode();
8395        }
8396
8397        abstract void handleStartCopy() throws RemoteException;
8398        abstract void handleServiceError();
8399        abstract void handleReturnCode();
8400    }
8401
8402    class MeasureParams extends HandlerParams {
8403        private final PackageStats mStats;
8404        private boolean mSuccess;
8405
8406        private final IPackageStatsObserver mObserver;
8407
8408        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8409            super(new UserHandle(stats.userHandle));
8410            mObserver = observer;
8411            mStats = stats;
8412        }
8413
8414        @Override
8415        public String toString() {
8416            return "MeasureParams{"
8417                + Integer.toHexString(System.identityHashCode(this))
8418                + " " + mStats.packageName + "}";
8419        }
8420
8421        @Override
8422        void handleStartCopy() throws RemoteException {
8423            synchronized (mInstallLock) {
8424                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8425            }
8426
8427            if (mSuccess) {
8428                final boolean mounted;
8429                if (Environment.isExternalStorageEmulated()) {
8430                    mounted = true;
8431                } else {
8432                    final String status = Environment.getExternalStorageState();
8433                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8434                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8435                }
8436
8437                if (mounted) {
8438                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8439
8440                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8441                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8442
8443                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8444                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8445
8446                    // Always subtract cache size, since it's a subdirectory
8447                    mStats.externalDataSize -= mStats.externalCacheSize;
8448
8449                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8450                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8451
8452                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8453                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8454                }
8455            }
8456        }
8457
8458        @Override
8459        void handleReturnCode() {
8460            if (mObserver != null) {
8461                try {
8462                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8463                } catch (RemoteException e) {
8464                    Slog.i(TAG, "Observer no longer exists.");
8465                }
8466            }
8467        }
8468
8469        @Override
8470        void handleServiceError() {
8471            Slog.e(TAG, "Could not measure application " + mStats.packageName
8472                            + " external storage");
8473        }
8474    }
8475
8476    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8477            throws RemoteException {
8478        long result = 0;
8479        for (File path : paths) {
8480            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8481        }
8482        return result;
8483    }
8484
8485    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8486        for (File path : paths) {
8487            try {
8488                mcs.clearDirectory(path.getAbsolutePath());
8489            } catch (RemoteException e) {
8490            }
8491        }
8492    }
8493
8494    class InstallParams extends HandlerParams {
8495        /**
8496         * Location where install is coming from, before it has been
8497         * copied/renamed into place. This could be a single monolithic APK
8498         * file, or a cluster directory. This location may be untrusted.
8499         */
8500        final File originFile;
8501
8502        /**
8503         * Flag indicating that {@link #originFile} has already been staged,
8504         * meaning downstream users don't need to defensively copy the contents.
8505         */
8506        boolean originStaged;
8507
8508        final IPackageInstallObserver2 observer;
8509        int flags;
8510        final String installerPackageName;
8511        final VerificationParams verificationParams;
8512        private InstallArgs mArgs;
8513        private int mRet;
8514        final String packageAbiOverride;
8515        boolean multiArch;
8516
8517        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8518                int flags, String installerPackageName, VerificationParams verificationParams,
8519                UserHandle user, String packageAbiOverride) {
8520            super(user);
8521            this.originFile = Preconditions.checkNotNull(originFile);
8522            this.originStaged = originStaged;
8523            this.observer = observer;
8524            this.flags = flags;
8525            this.installerPackageName = installerPackageName;
8526            this.verificationParams = verificationParams;
8527            this.packageAbiOverride = packageAbiOverride;
8528        }
8529
8530        @Override
8531        public String toString() {
8532            return "InstallParams{"
8533                + Integer.toHexString(System.identityHashCode(this))
8534                + " " + originFile + "}";
8535        }
8536
8537        public ManifestDigest getManifestDigest() {
8538            if (verificationParams == null) {
8539                return null;
8540            }
8541            return verificationParams.getManifestDigest();
8542        }
8543
8544        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8545            String packageName = pkgLite.packageName;
8546            int installLocation = pkgLite.installLocation;
8547            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8548            // reader
8549            synchronized (mPackages) {
8550                PackageParser.Package pkg = mPackages.get(packageName);
8551                if (pkg != null) {
8552                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8553                        // Check for downgrading.
8554                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8555                            if (pkgLite.versionCode < pkg.mVersionCode) {
8556                                Slog.w(TAG, "Can't install update of " + packageName
8557                                        + " update version " + pkgLite.versionCode
8558                                        + " is older than installed version "
8559                                        + pkg.mVersionCode);
8560                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8561                            }
8562                        }
8563                        // Check for updated system application.
8564                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8565                            if (onSd) {
8566                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8567                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8568                            }
8569                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8570                        } else {
8571                            if (onSd) {
8572                                // Install flag overrides everything.
8573                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8574                            }
8575                            // If current upgrade specifies particular preference
8576                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8577                                // Application explicitly specified internal.
8578                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8579                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8580                                // App explictly prefers external. Let policy decide
8581                            } else {
8582                                // Prefer previous location
8583                                if (isExternal(pkg)) {
8584                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8585                                }
8586                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8587                            }
8588                        }
8589                    } else {
8590                        // Invalid install. Return error code
8591                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8592                    }
8593                }
8594            }
8595            // All the special cases have been taken care of.
8596            // Return result based on recommended install location.
8597            if (onSd) {
8598                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8599            }
8600            return pkgLite.recommendedInstallLocation;
8601        }
8602
8603        private long getMemoryLowThreshold() {
8604            final DeviceStorageMonitorInternal
8605                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8606            if (dsm == null) {
8607                return 0L;
8608            }
8609            return dsm.getMemoryLowThreshold();
8610        }
8611
8612        /*
8613         * Invoke remote method to get package information and install
8614         * location values. Override install location based on default
8615         * policy if needed and then create install arguments based
8616         * on the install location.
8617         */
8618        public void handleStartCopy() throws RemoteException {
8619            int ret = PackageManager.INSTALL_SUCCEEDED;
8620            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8621            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8622            PackageInfoLite pkgLite = null;
8623
8624            if (onInt && onSd) {
8625                // Check if both bits are set.
8626                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8627                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8628            } else {
8629                final long lowThreshold = getMemoryLowThreshold();
8630                if (lowThreshold == 0L) {
8631                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8632                }
8633
8634                // Remote call to find out default install location
8635                final String originPath = originFile.getAbsolutePath();
8636                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8637                        packageAbiOverride);
8638                // Keep track of whether this package is a multiArch package until
8639                // we perform a full scan of it. We need to do this because we might
8640                // end up extracting the package shared libraries before we perform
8641                // a full scan.
8642                multiArch = pkgLite.multiArch;
8643
8644                /*
8645                 * If we have too little free space, try to free cache
8646                 * before giving up.
8647                 */
8648                if (pkgLite.recommendedInstallLocation
8649                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8650                    final long size = mContainerService.calculateInstalledSize(
8651                            originPath, isForwardLocked(), packageAbiOverride);
8652                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8653                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8654                                lowThreshold, packageAbiOverride);
8655                    }
8656                    /*
8657                     * The cache free must have deleted the file we
8658                     * downloaded to install.
8659                     *
8660                     * TODO: fix the "freeCache" call to not delete
8661                     *       the file we care about.
8662                     */
8663                    if (pkgLite.recommendedInstallLocation
8664                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8665                        pkgLite.recommendedInstallLocation
8666                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8667                    }
8668                }
8669            }
8670
8671            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8672                int loc = pkgLite.recommendedInstallLocation;
8673                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8674                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8675                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8676                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8677                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8678                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8679                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8680                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8681                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8682                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8683                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8684                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8685                } else {
8686                    // Override with defaults if needed.
8687                    loc = installLocationPolicy(pkgLite, flags);
8688                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8689                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8690                    } else if (!onSd && !onInt) {
8691                        // Override install location with flags
8692                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8693                            // Set the flag to install on external media.
8694                            flags |= PackageManager.INSTALL_EXTERNAL;
8695                            flags &= ~PackageManager.INSTALL_INTERNAL;
8696                        } else {
8697                            // Make sure the flag for installing on external
8698                            // media is unset
8699                            flags |= PackageManager.INSTALL_INTERNAL;
8700                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8701                        }
8702                    }
8703                }
8704            }
8705
8706            final InstallArgs args = createInstallArgs(this);
8707            mArgs = args;
8708
8709            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8710                 /*
8711                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8712                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8713                 */
8714                int userIdentifier = getUser().getIdentifier();
8715                if (userIdentifier == UserHandle.USER_ALL
8716                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8717                    userIdentifier = UserHandle.USER_OWNER;
8718                }
8719
8720                /*
8721                 * Determine if we have any installed package verifiers. If we
8722                 * do, then we'll defer to them to verify the packages.
8723                 */
8724                final int requiredUid = mRequiredVerifierPackage == null ? -1
8725                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8726                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8727                    // TODO: send verifier the install session instead of uri
8728                    final Intent verification = new Intent(
8729                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8730                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8731                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8732
8733                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8734                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8735                            0 /* TODO: Which userId? */);
8736
8737                    if (DEBUG_VERIFY) {
8738                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8739                                + verification.toString() + " with " + pkgLite.verifiers.length
8740                                + " optional verifiers");
8741                    }
8742
8743                    final int verificationId = mPendingVerificationToken++;
8744
8745                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8746
8747                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8748                            installerPackageName);
8749
8750                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8751
8752                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8753                            pkgLite.packageName);
8754
8755                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8756                            pkgLite.versionCode);
8757
8758                    if (verificationParams != null) {
8759                        if (verificationParams.getVerificationURI() != null) {
8760                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8761                                 verificationParams.getVerificationURI());
8762                        }
8763                        if (verificationParams.getOriginatingURI() != null) {
8764                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8765                                  verificationParams.getOriginatingURI());
8766                        }
8767                        if (verificationParams.getReferrer() != null) {
8768                            verification.putExtra(Intent.EXTRA_REFERRER,
8769                                  verificationParams.getReferrer());
8770                        }
8771                        if (verificationParams.getOriginatingUid() >= 0) {
8772                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8773                                  verificationParams.getOriginatingUid());
8774                        }
8775                        if (verificationParams.getInstallerUid() >= 0) {
8776                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8777                                  verificationParams.getInstallerUid());
8778                        }
8779                    }
8780
8781                    final PackageVerificationState verificationState = new PackageVerificationState(
8782                            requiredUid, args);
8783
8784                    mPendingVerification.append(verificationId, verificationState);
8785
8786                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8787                            receivers, verificationState);
8788
8789                    /*
8790                     * If any sufficient verifiers were listed in the package
8791                     * manifest, attempt to ask them.
8792                     */
8793                    if (sufficientVerifiers != null) {
8794                        final int N = sufficientVerifiers.size();
8795                        if (N == 0) {
8796                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8797                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8798                        } else {
8799                            for (int i = 0; i < N; i++) {
8800                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8801
8802                                final Intent sufficientIntent = new Intent(verification);
8803                                sufficientIntent.setComponent(verifierComponent);
8804
8805                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8806                            }
8807                        }
8808                    }
8809
8810                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8811                            mRequiredVerifierPackage, receivers);
8812                    if (ret == PackageManager.INSTALL_SUCCEEDED
8813                            && mRequiredVerifierPackage != null) {
8814                        /*
8815                         * Send the intent to the required verification agent,
8816                         * but only start the verification timeout after the
8817                         * target BroadcastReceivers have run.
8818                         */
8819                        verification.setComponent(requiredVerifierComponent);
8820                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8821                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8822                                new BroadcastReceiver() {
8823                                    @Override
8824                                    public void onReceive(Context context, Intent intent) {
8825                                        final Message msg = mHandler
8826                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8827                                        msg.arg1 = verificationId;
8828                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8829                                    }
8830                                }, null, 0, null, null);
8831
8832                        /*
8833                         * We don't want the copy to proceed until verification
8834                         * succeeds, so null out this field.
8835                         */
8836                        mArgs = null;
8837                    }
8838                } else {
8839                    /*
8840                     * No package verification is enabled, so immediately start
8841                     * the remote call to initiate copy using temporary file.
8842                     */
8843                    ret = args.copyApk(mContainerService, true);
8844                }
8845            }
8846
8847            mRet = ret;
8848        }
8849
8850        @Override
8851        void handleReturnCode() {
8852            // If mArgs is null, then MCS couldn't be reached. When it
8853            // reconnects, it will try again to install. At that point, this
8854            // will succeed.
8855            if (mArgs != null) {
8856                processPendingInstall(mArgs, mRet);
8857            }
8858        }
8859
8860        @Override
8861        void handleServiceError() {
8862            mArgs = createInstallArgs(this);
8863            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8864        }
8865
8866        public boolean isForwardLocked() {
8867            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8868        }
8869    }
8870
8871    /*
8872     * Utility class used in movePackage api.
8873     * srcArgs and targetArgs are not set for invalid flags and make
8874     * sure to do null checks when invoking methods on them.
8875     * We probably want to return ErrorPrams for both failed installs
8876     * and moves.
8877     */
8878    class MoveParams extends HandlerParams {
8879        final IPackageMoveObserver observer;
8880        final int flags;
8881        final String packageName;
8882        final InstallArgs srcArgs;
8883        final InstallArgs targetArgs;
8884        int uid;
8885        int mRet;
8886
8887        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8888                String packageName, String[] instructionSets, int uid, UserHandle user,
8889                boolean isMultiArch) {
8890            super(user);
8891            this.srcArgs = srcArgs;
8892            this.observer = observer;
8893            this.flags = flags;
8894            this.packageName = packageName;
8895            this.uid = uid;
8896            if (srcArgs != null) {
8897                final String codePath = srcArgs.getCodePath();
8898                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8899                        instructionSets, isMultiArch);
8900            } else {
8901                targetArgs = null;
8902            }
8903        }
8904
8905        @Override
8906        public String toString() {
8907            return "MoveParams{"
8908                + Integer.toHexString(System.identityHashCode(this))
8909                + " " + packageName + "}";
8910        }
8911
8912        public void handleStartCopy() throws RemoteException {
8913            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8914            // Check for storage space on target medium
8915            if (!targetArgs.checkFreeStorage(mContainerService)) {
8916                Log.w(TAG, "Insufficient storage to install");
8917                return;
8918            }
8919
8920            mRet = srcArgs.doPreCopy();
8921            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8922                return;
8923            }
8924
8925            mRet = targetArgs.copyApk(mContainerService, false);
8926            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8927                srcArgs.doPostCopy(uid);
8928                return;
8929            }
8930
8931            mRet = srcArgs.doPostCopy(uid);
8932            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8933                return;
8934            }
8935
8936            mRet = targetArgs.doPreInstall(mRet);
8937            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8938                return;
8939            }
8940
8941            if (DEBUG_SD_INSTALL) {
8942                StringBuilder builder = new StringBuilder();
8943                if (srcArgs != null) {
8944                    builder.append("src: ");
8945                    builder.append(srcArgs.getCodePath());
8946                }
8947                if (targetArgs != null) {
8948                    builder.append(" target : ");
8949                    builder.append(targetArgs.getCodePath());
8950                }
8951                Log.i(TAG, builder.toString());
8952            }
8953        }
8954
8955        @Override
8956        void handleReturnCode() {
8957            targetArgs.doPostInstall(mRet, uid);
8958            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8959            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8960                currentStatus = PackageManager.MOVE_SUCCEEDED;
8961            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8962                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8963            }
8964            processPendingMove(this, currentStatus);
8965        }
8966
8967        @Override
8968        void handleServiceError() {
8969            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8970        }
8971    }
8972
8973    /**
8974     * Used during creation of InstallArgs
8975     *
8976     * @param flags package installation flags
8977     * @return true if should be installed on external storage
8978     */
8979    private static boolean installOnSd(int flags) {
8980        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8981            return false;
8982        }
8983        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8984            return true;
8985        }
8986        return false;
8987    }
8988
8989    /**
8990     * Used during creation of InstallArgs
8991     *
8992     * @param flags package installation flags
8993     * @return true if should be installed as forward locked
8994     */
8995    private static boolean installForwardLocked(int flags) {
8996        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8997    }
8998
8999    private InstallArgs createInstallArgs(InstallParams params) {
9000        // TODO: extend to support incoming zero-copy locations
9001
9002        if (installOnSd(params.flags) || params.isForwardLocked()) {
9003            return new AsecInstallArgs(params);
9004        } else {
9005            return new FileInstallArgs(params);
9006        }
9007    }
9008
9009    /**
9010     * Create args that describe an existing installed package. Typically used
9011     * when cleaning up old installs, or used as a move source.
9012     */
9013    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9014            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9015            boolean isMultiArch) {
9016        final boolean isInAsec;
9017        if (installOnSd(flags)) {
9018            /* Apps on SD card are always in ASEC containers. */
9019            isInAsec = true;
9020        } else if (installForwardLocked(flags)
9021                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9022            /*
9023             * Forward-locked apps are only in ASEC containers if they're the
9024             * new style
9025             */
9026            isInAsec = true;
9027        } else {
9028            isInAsec = false;
9029        }
9030
9031        if (isInAsec) {
9032            return new AsecInstallArgs(codePath, instructionSets,
9033                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9034        } else {
9035            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9036                    instructionSets, isMultiArch);
9037        }
9038    }
9039
9040    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9041            String[] instructionSets, boolean isMultiArch) {
9042        final File codeFile = new File(codePath);
9043        if (installOnSd(flags) || installForwardLocked(flags)) {
9044            String cid = getNextCodePath(codePath, pkgName, "/"
9045                    + AsecInstallArgs.RES_FILE_NAME);
9046            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9047                    installForwardLocked(flags), isMultiArch);
9048        } else {
9049            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9050        }
9051    }
9052
9053    static abstract class InstallArgs {
9054        /** @see InstallParams#originFile */
9055        final File originFile;
9056        /** @see InstallParams#originStaged */
9057        final boolean originStaged;
9058
9059        // TODO: define inherit location
9060
9061        final IPackageInstallObserver2 observer;
9062        // Always refers to PackageManager flags only
9063        final int flags;
9064        final String installerPackageName;
9065        final ManifestDigest manifestDigest;
9066        final UserHandle user;
9067        final String abiOverride;
9068        final boolean multiArch;
9069
9070        // The list of instruction sets supported by this app. This is currently
9071        // only used during the rmdex() phase to clean up resources. We can get rid of this
9072        // if we move dex files under the common app path.
9073        /* nullable */ String[] instructionSets;
9074
9075        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9076                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9077                    UserHandle user, String[] instructionSets,
9078                    String abiOverride, boolean multiArch) {
9079            this.originFile = originFile;
9080            this.originStaged = originStaged;
9081            this.flags = flags;
9082            this.observer = observer;
9083            this.installerPackageName = installerPackageName;
9084            this.manifestDigest = manifestDigest;
9085            this.user = user;
9086            this.instructionSets = instructionSets;
9087            this.abiOverride = abiOverride;
9088            this.multiArch = multiArch;
9089        }
9090
9091        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9092        abstract int doPreInstall(int status);
9093
9094        /**
9095         * Rename package into final resting place. All paths on the given
9096         * scanned package should be updated to reflect the rename.
9097         */
9098        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9099        abstract int doPostInstall(int status, int uid);
9100
9101        /** @see PackageSettingBase#codePathString */
9102        abstract String getCodePath();
9103        /** @see PackageSettingBase#resourcePathString */
9104        abstract String getResourcePath();
9105        abstract String getLegacyNativeLibraryPath();
9106
9107        // Need installer lock especially for dex file removal.
9108        abstract void cleanUpResourcesLI();
9109        abstract boolean doPostDeleteLI(boolean delete);
9110        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9111
9112        /**
9113         * Called before the source arguments are copied. This is used mostly
9114         * for MoveParams when it needs to read the source file to put it in the
9115         * destination.
9116         */
9117        int doPreCopy() {
9118            return PackageManager.INSTALL_SUCCEEDED;
9119        }
9120
9121        /**
9122         * Called after the source arguments are copied. This is used mostly for
9123         * MoveParams when it needs to read the source file to put it in the
9124         * destination.
9125         *
9126         * @return
9127         */
9128        int doPostCopy(int uid) {
9129            return PackageManager.INSTALL_SUCCEEDED;
9130        }
9131
9132        protected boolean isFwdLocked() {
9133            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9134        }
9135
9136        UserHandle getUser() {
9137            return user;
9138        }
9139    }
9140
9141    /**
9142     * Logic to handle installation of non-ASEC applications, including copying
9143     * and renaming logic.
9144     */
9145    class FileInstallArgs extends InstallArgs {
9146        private File codeFile;
9147        private File resourceFile;
9148        private File legacyNativeLibraryPath;
9149
9150        // Example topology:
9151        // /data/app/com.example/base.apk
9152        // /data/app/com.example/split_foo.apk
9153        // /data/app/com.example/lib/arm/libfoo.so
9154        // /data/app/com.example/lib/arm64/libfoo.so
9155        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9156
9157        /** New install */
9158        FileInstallArgs(InstallParams params) {
9159            super(params.originFile, params.originStaged, params.observer, params.flags,
9160                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9161                    null /* instruction sets */, params.packageAbiOverride,
9162                    params.multiArch);
9163            if (isFwdLocked()) {
9164                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9165            }
9166        }
9167
9168        /** Existing install */
9169        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9170                String[] instructionSets, boolean isMultiArch) {
9171            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9172            this.codeFile = (codePath != null) ? new File(codePath) : null;
9173            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9174            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9175                    new File(legacyNativeLibraryPath) : null;
9176        }
9177
9178        /** New install from existing */
9179        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9180            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9181                    isMultiArch);
9182        }
9183
9184        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9185            final long lowThreshold;
9186
9187            final DeviceStorageMonitorInternal
9188                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9189            if (dsm == null) {
9190                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9191                lowThreshold = 0L;
9192            } else {
9193                if (dsm.isMemoryLow()) {
9194                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9195                    return false;
9196                }
9197
9198                lowThreshold = dsm.getMemoryLowThreshold();
9199            }
9200
9201            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9202                    lowThreshold);
9203        }
9204
9205        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9206            int ret = PackageManager.INSTALL_SUCCEEDED;
9207
9208            if (originStaged) {
9209                Slog.d(TAG, originFile + " already staged; skipping copy");
9210                codeFile = originFile;
9211                resourceFile = originFile;
9212            } else {
9213                try {
9214                    final File tempDir = mInstallerService.allocateSessionDir();
9215                    codeFile = tempDir;
9216                    resourceFile = tempDir;
9217                } catch (IOException e) {
9218                    Slog.w(TAG, "Failed to create copy file: " + e);
9219                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9220                }
9221
9222                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9223                    @Override
9224                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9225                        if (!FileUtils.isValidExtFilename(name)) {
9226                            throw new IllegalArgumentException("Invalid filename: " + name);
9227                        }
9228                        try {
9229                            final File file = new File(codeFile, name);
9230                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9231                                    O_RDWR | O_CREAT, 0644);
9232                            Os.chmod(file.getAbsolutePath(), 0644);
9233                            return new ParcelFileDescriptor(fd);
9234                        } catch (ErrnoException e) {
9235                            throw new RemoteException("Failed to open: " + e.getMessage());
9236                        }
9237                    }
9238                };
9239
9240                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9241                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9242                    Slog.e(TAG, "Failed to copy package");
9243                    return ret;
9244                }
9245            }
9246
9247            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9248            NativeLibraryHelper.Handle handle = null;
9249            try {
9250                handle = NativeLibraryHelper.Handle.create(codeFile);
9251                if (multiArch) {
9252                    // Warn if we've set an abiOverride for multi-lib packages..
9253                    // By definition, we need to copy both 32 and 64 bit libraries for
9254                    // such packages.
9255                    if (abiOverride != null) {
9256                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9257                    }
9258
9259                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9260                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9261                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9262                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9263                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9264                    }
9265
9266                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9267                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9268                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9269                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9270                    }
9271                } else {
9272                    String[] abiList = (abiOverride != null) ?
9273                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9274
9275                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
9276                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9277                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9278                    }
9279
9280                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9281                            true /* use isa specific subdirs */);
9282                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9283                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9284                        return copyRet;
9285                    }
9286                }
9287            } catch (IOException e) {
9288                Slog.e(TAG, "Copying native libraries failed", e);
9289                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9290            } catch (PackageManagerException pme) {
9291                Slog.e(TAG, "Copying native libraries failed", pme);
9292                ret = pme.error;
9293            } finally {
9294                IoUtils.closeQuietly(handle);
9295            }
9296
9297            return ret;
9298        }
9299
9300        int doPreInstall(int status) {
9301            if (status != PackageManager.INSTALL_SUCCEEDED) {
9302                cleanUp();
9303            }
9304            return status;
9305        }
9306
9307        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9308            if (status != PackageManager.INSTALL_SUCCEEDED) {
9309                cleanUp();
9310                return false;
9311            } else {
9312                final File beforeCodeFile = codeFile;
9313                final File afterCodeFile = getNextCodePath(pkg.packageName);
9314
9315                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9316                try {
9317                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9318                } catch (ErrnoException e) {
9319                    Slog.d(TAG, "Failed to rename", e);
9320                    return false;
9321                }
9322
9323                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9324                    Slog.d(TAG, "Failed to restorecon");
9325                    return false;
9326                }
9327
9328                // Reflect the rename internally
9329                codeFile = afterCodeFile;
9330                resourceFile = afterCodeFile;
9331
9332                // Reflect the rename in scanned details
9333                pkg.codePath = afterCodeFile.getAbsolutePath();
9334                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9335                        pkg.baseCodePath);
9336                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9337                        pkg.splitCodePaths);
9338
9339                // Reflect the rename in app info
9340                pkg.applicationInfo.setCodePath(pkg.codePath);
9341                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9342                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9343                pkg.applicationInfo.setResourcePath(pkg.codePath);
9344                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9345                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9346
9347                return true;
9348            }
9349        }
9350
9351        int doPostInstall(int status, int uid) {
9352            if (status != PackageManager.INSTALL_SUCCEEDED) {
9353                cleanUp();
9354            }
9355            return status;
9356        }
9357
9358        @Override
9359        String getCodePath() {
9360            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9361        }
9362
9363        @Override
9364        String getResourcePath() {
9365            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9366        }
9367
9368        @Override
9369        String getLegacyNativeLibraryPath() {
9370            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9371        }
9372
9373        private boolean cleanUp() {
9374            if (codeFile == null || !codeFile.exists()) {
9375                return false;
9376            }
9377
9378            if (codeFile.isDirectory()) {
9379                FileUtils.deleteContents(codeFile);
9380            }
9381            codeFile.delete();
9382
9383            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9384                resourceFile.delete();
9385            }
9386
9387            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9388                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9389                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9390                }
9391                legacyNativeLibraryPath.delete();
9392            }
9393
9394            return true;
9395        }
9396
9397        void cleanUpResourcesLI() {
9398            // Try enumerating all code paths before deleting
9399            List<String> allCodePaths = Collections.EMPTY_LIST;
9400            if (codeFile != null && codeFile.exists()) {
9401                try {
9402                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9403                    allCodePaths = pkg.getAllCodePaths();
9404                } catch (PackageParserException e) {
9405                    // Ignored; we tried our best
9406                }
9407            }
9408
9409            cleanUp();
9410
9411            if (!allCodePaths.isEmpty()) {
9412                if (instructionSets == null) {
9413                    throw new IllegalStateException("instructionSet == null");
9414                }
9415
9416                for (String codePath : allCodePaths) {
9417                    for (String instructionSet : instructionSets) {
9418                        int retCode = mInstaller.rmdex(codePath, instructionSet);
9419                        if (retCode < 0) {
9420                            Slog.w(TAG, "Couldn't remove dex file for package: "
9421                                    + " at location " + codePath + ", retcode=" + retCode);
9422                            // we don't consider this to be a failure of the core package deletion
9423                        }
9424                    }
9425                }
9426            }
9427        }
9428
9429        boolean doPostDeleteLI(boolean delete) {
9430            // XXX err, shouldn't we respect the delete flag?
9431            cleanUpResourcesLI();
9432            return true;
9433        }
9434    }
9435
9436    private boolean isAsecExternal(String cid) {
9437        final String asecPath = PackageHelper.getSdFilesystem(cid);
9438        return !asecPath.startsWith(mAsecInternalPath);
9439    }
9440
9441    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9442            PackageManagerException {
9443        if (copyRet < 0) {
9444            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9445                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9446                throw new PackageManagerException(copyRet, message);
9447            }
9448        }
9449    }
9450
9451    /**
9452     * Extract the MountService "container ID" from the full code path of an
9453     * .apk.
9454     */
9455    static String cidFromCodePath(String fullCodePath) {
9456        int eidx = fullCodePath.lastIndexOf("/");
9457        String subStr1 = fullCodePath.substring(0, eidx);
9458        int sidx = subStr1.lastIndexOf("/");
9459        return subStr1.substring(sidx+1, eidx);
9460    }
9461
9462    /**
9463     * Logic to handle installation of ASEC applications, including copying and
9464     * renaming logic.
9465     */
9466    class AsecInstallArgs extends InstallArgs {
9467        // TODO: teach about handling cluster directories
9468
9469        static final String RES_FILE_NAME = "pkg.apk";
9470        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9471
9472        String cid;
9473        String packagePath;
9474        String resourcePath;
9475        String legacyNativeLibraryDir;
9476
9477        /** New install */
9478        AsecInstallArgs(InstallParams params) {
9479            super(params.originFile, params.originStaged, params.observer, params.flags,
9480                    params.installerPackageName, params.getManifestDigest(),
9481                    params.getUser(), null /* instruction sets */,
9482                    params.packageAbiOverride, params.multiArch);
9483        }
9484
9485        /** Existing install */
9486        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9487                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9488            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9489                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9490                    instructionSets, null, isMultiArch);
9491            // Extract cid from fullCodePath
9492            int eidx = fullCodePath.lastIndexOf("/");
9493            String subStr1 = fullCodePath.substring(0, eidx);
9494            int sidx = subStr1.lastIndexOf("/");
9495            cid = subStr1.substring(sidx+1, eidx);
9496            setCachePath(subStr1);
9497        }
9498
9499        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9500                        boolean isMultiArch) {
9501            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9502                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9503                    instructionSets, null, isMultiArch);
9504            this.cid = cid;
9505            setCachePath(PackageHelper.getSdDir(cid));
9506        }
9507
9508        /** New install from existing */
9509        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9510                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9511            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9512                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9513                    instructionSets, null, isMultiArch);
9514            this.cid = cid;
9515        }
9516
9517        void createCopyFile() {
9518            cid = getTempContainerId();
9519        }
9520
9521        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9522            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9523                    abiOverride);
9524        }
9525
9526        private final boolean isExternal() {
9527            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9528        }
9529
9530        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9531            if (temp) {
9532                createCopyFile();
9533            } else {
9534                /*
9535                 * Pre-emptively destroy the container since it's destroyed if
9536                 * copying fails due to it existing anyway.
9537                 */
9538                PackageHelper.destroySdDir(cid);
9539            }
9540
9541            final String newCachePath = imcs.copyPackageToContainer(
9542                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9543                    isFwdLocked(), abiOverride);
9544
9545            if (newCachePath != null) {
9546                setCachePath(newCachePath);
9547                return PackageManager.INSTALL_SUCCEEDED;
9548            } else {
9549                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9550            }
9551        }
9552
9553        @Override
9554        String getCodePath() {
9555            return packagePath;
9556        }
9557
9558        @Override
9559        String getResourcePath() {
9560            return resourcePath;
9561        }
9562
9563        @Override
9564        String getLegacyNativeLibraryPath() {
9565            return legacyNativeLibraryDir;
9566        }
9567
9568        int doPreInstall(int status) {
9569            if (status != PackageManager.INSTALL_SUCCEEDED) {
9570                // Destroy container
9571                PackageHelper.destroySdDir(cid);
9572            } else {
9573                boolean mounted = PackageHelper.isContainerMounted(cid);
9574                if (!mounted) {
9575                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9576                            Process.SYSTEM_UID);
9577                    if (newCachePath != null) {
9578                        setCachePath(newCachePath);
9579                    } else {
9580                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9581                    }
9582                }
9583            }
9584            return status;
9585        }
9586
9587        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9588            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9589            String newCachePath = null;
9590            if (PackageHelper.isContainerMounted(cid)) {
9591                // Unmount the container
9592                if (!PackageHelper.unMountSdDir(cid)) {
9593                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9594                    return false;
9595                }
9596            }
9597            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9598                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9599                        " which might be stale. Will try to clean up.");
9600                // Clean up the stale container and proceed to recreate.
9601                if (!PackageHelper.destroySdDir(newCacheId)) {
9602                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9603                    return false;
9604                }
9605                // Successfully cleaned up stale container. Try to rename again.
9606                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9607                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9608                            + " inspite of cleaning it up.");
9609                    return false;
9610                }
9611            }
9612            if (!PackageHelper.isContainerMounted(newCacheId)) {
9613                Slog.w(TAG, "Mounting container " + newCacheId);
9614                newCachePath = PackageHelper.mountSdDir(newCacheId,
9615                        getEncryptKey(), Process.SYSTEM_UID);
9616            } else {
9617                newCachePath = PackageHelper.getSdDir(newCacheId);
9618            }
9619            if (newCachePath == null) {
9620                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9621                return false;
9622            }
9623            Log.i(TAG, "Succesfully renamed " + cid +
9624                    " to " + newCacheId +
9625                    " at new path: " + newCachePath);
9626            cid = newCacheId;
9627            setCachePath(newCachePath);
9628
9629            // TODO: extend to support split APKs
9630            pkg.codePath = getCodePath();
9631            pkg.baseCodePath = getCodePath();
9632            pkg.splitCodePaths = null;
9633
9634            pkg.applicationInfo.setCodePath(getCodePath());
9635            pkg.applicationInfo.setBaseCodePath(getCodePath());
9636            pkg.applicationInfo.setSplitCodePaths(null);
9637            pkg.applicationInfo.setResourcePath(getResourcePath());
9638            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9639            pkg.applicationInfo.setSplitResourcePaths(null);
9640
9641            return true;
9642        }
9643
9644        private void setCachePath(String newCachePath) {
9645            File cachePath = new File(newCachePath);
9646            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9647            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9648
9649            if (isFwdLocked()) {
9650                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9651            } else {
9652                resourcePath = packagePath;
9653            }
9654        }
9655
9656        int doPostInstall(int status, int uid) {
9657            if (status != PackageManager.INSTALL_SUCCEEDED) {
9658                cleanUp();
9659            } else {
9660                final int groupOwner;
9661                final String protectedFile;
9662                if (isFwdLocked()) {
9663                    groupOwner = UserHandle.getSharedAppGid(uid);
9664                    protectedFile = RES_FILE_NAME;
9665                } else {
9666                    groupOwner = -1;
9667                    protectedFile = null;
9668                }
9669
9670                if (uid < Process.FIRST_APPLICATION_UID
9671                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9672                    Slog.e(TAG, "Failed to finalize " + cid);
9673                    PackageHelper.destroySdDir(cid);
9674                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9675                }
9676
9677                boolean mounted = PackageHelper.isContainerMounted(cid);
9678                if (!mounted) {
9679                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9680                }
9681            }
9682            return status;
9683        }
9684
9685        private void cleanUp() {
9686            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9687
9688            // Destroy secure container
9689            PackageHelper.destroySdDir(cid);
9690        }
9691
9692        void cleanUpResourcesLI() {
9693            String sourceFile = getCodePath();
9694            // Remove dex file
9695            if (instructionSets == null) {
9696                throw new IllegalStateException("instructionSet == null");
9697            }
9698            for (String instructionSet : instructionSets) {
9699                int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9700                if (retCode < 0) {
9701                    Slog.w(TAG, "Couldn't remove dex file for package: "
9702                            + " at location "
9703                            + sourceFile.toString() + ", retcode=" + retCode);
9704                    // we don't consider this to be a failure of the core package deletion
9705                }
9706            }
9707            cleanUp();
9708        }
9709
9710        boolean matchContainer(String app) {
9711            if (cid.startsWith(app)) {
9712                return true;
9713            }
9714            return false;
9715        }
9716
9717        String getPackageName() {
9718            return getAsecPackageName(cid);
9719        }
9720
9721        boolean doPostDeleteLI(boolean delete) {
9722            boolean ret = false;
9723            boolean mounted = PackageHelper.isContainerMounted(cid);
9724            if (mounted) {
9725                // Unmount first
9726                ret = PackageHelper.unMountSdDir(cid);
9727            }
9728            if (ret && delete) {
9729                cleanUpResourcesLI();
9730            }
9731            return ret;
9732        }
9733
9734        @Override
9735        int doPreCopy() {
9736            if (isFwdLocked()) {
9737                if (!PackageHelper.fixSdPermissions(cid,
9738                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9739                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9740                }
9741            }
9742
9743            return PackageManager.INSTALL_SUCCEEDED;
9744        }
9745
9746        @Override
9747        int doPostCopy(int uid) {
9748            if (isFwdLocked()) {
9749                if (uid < Process.FIRST_APPLICATION_UID
9750                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9751                                RES_FILE_NAME)) {
9752                    Slog.e(TAG, "Failed to finalize " + cid);
9753                    PackageHelper.destroySdDir(cid);
9754                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9755                }
9756            }
9757
9758            return PackageManager.INSTALL_SUCCEEDED;
9759        }
9760    }
9761
9762    static String getAsecPackageName(String packageCid) {
9763        int idx = packageCid.lastIndexOf("-");
9764        if (idx == -1) {
9765            return packageCid;
9766        }
9767        return packageCid.substring(0, idx);
9768    }
9769
9770    // Utility method used to create code paths based on package name and available index.
9771    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9772        String idxStr = "";
9773        int idx = 1;
9774        // Fall back to default value of idx=1 if prefix is not
9775        // part of oldCodePath
9776        if (oldCodePath != null) {
9777            String subStr = oldCodePath;
9778            // Drop the suffix right away
9779            if (suffix != null && subStr.endsWith(suffix)) {
9780                subStr = subStr.substring(0, subStr.length() - suffix.length());
9781            }
9782            // If oldCodePath already contains prefix find out the
9783            // ending index to either increment or decrement.
9784            int sidx = subStr.lastIndexOf(prefix);
9785            if (sidx != -1) {
9786                subStr = subStr.substring(sidx + prefix.length());
9787                if (subStr != null) {
9788                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9789                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9790                    }
9791                    try {
9792                        idx = Integer.parseInt(subStr);
9793                        if (idx <= 1) {
9794                            idx++;
9795                        } else {
9796                            idx--;
9797                        }
9798                    } catch(NumberFormatException e) {
9799                    }
9800                }
9801            }
9802        }
9803        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9804        return prefix + idxStr;
9805    }
9806
9807    private File getNextCodePath(String packageName) {
9808        int suffix = 1;
9809        File result;
9810        do {
9811            result = new File(mAppInstallDir, packageName + "-" + suffix);
9812            suffix++;
9813        } while (result.exists());
9814        return result;
9815    }
9816
9817    // Utility method used to ignore ADD/REMOVE events
9818    // by directory observer.
9819    private static boolean ignoreCodePath(String fullPathStr) {
9820        String apkName = deriveCodePathName(fullPathStr);
9821        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9822        if (idx != -1 && ((idx+1) < apkName.length())) {
9823            // Make sure the package ends with a numeral
9824            String version = apkName.substring(idx+1);
9825            try {
9826                Integer.parseInt(version);
9827                return true;
9828            } catch (NumberFormatException e) {}
9829        }
9830        return false;
9831    }
9832
9833    // Utility method that returns the relative package path with respect
9834    // to the installation directory. Like say for /data/data/com.test-1.apk
9835    // string com.test-1 is returned.
9836    static String deriveCodePathName(String codePath) {
9837        if (codePath == null) {
9838            return null;
9839        }
9840        final File codeFile = new File(codePath);
9841        final String name = codeFile.getName();
9842        if (codeFile.isDirectory()) {
9843            return name;
9844        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9845            final int lastDot = name.lastIndexOf('.');
9846            return name.substring(0, lastDot);
9847        } else {
9848            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9849            return null;
9850        }
9851    }
9852
9853    class PackageInstalledInfo {
9854        String name;
9855        int uid;
9856        // The set of users that originally had this package installed.
9857        int[] origUsers;
9858        // The set of users that now have this package installed.
9859        int[] newUsers;
9860        PackageParser.Package pkg;
9861        int returnCode;
9862        String returnMsg;
9863        PackageRemovedInfo removedInfo;
9864
9865        public void setError(int code, String msg) {
9866            returnCode = code;
9867            returnMsg = msg;
9868            Slog.w(TAG, msg);
9869        }
9870
9871        public void setError(String msg, PackageParserException e) {
9872            returnCode = e.error;
9873            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9874            Slog.w(TAG, msg, e);
9875        }
9876
9877        public void setError(String msg, PackageManagerException e) {
9878            returnCode = e.error;
9879            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9880            Slog.w(TAG, msg, e);
9881        }
9882
9883        // In some error cases we want to convey more info back to the observer
9884        String origPackage;
9885        String origPermission;
9886    }
9887
9888    /*
9889     * Install a non-existing package.
9890     */
9891    private void installNewPackageLI(PackageParser.Package pkg,
9892            int parseFlags, int scanMode, UserHandle user,
9893            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9894        // Remember this for later, in case we need to rollback this install
9895        String pkgName = pkg.packageName;
9896
9897        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9898        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9899        synchronized(mPackages) {
9900            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9901                // A package with the same name is already installed, though
9902                // it has been renamed to an older name.  The package we
9903                // are trying to install should be installed as an update to
9904                // the existing one, but that has not been requested, so bail.
9905                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9906                        + " without first uninstalling package running as "
9907                        + mSettings.mRenamedPackages.get(pkgName));
9908                return;
9909            }
9910            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9911                // Don't allow installation over an existing package with the same name.
9912                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9913                        + " without first uninstalling.");
9914                return;
9915            }
9916        }
9917
9918        try {
9919            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9920                    System.currentTimeMillis(), user, abiOverride);
9921
9922            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9923            // delete the partially installed application. the data directory will have to be
9924            // restored if it was already existing
9925            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9926                // remove package from internal structures.  Note that we want deletePackageX to
9927                // delete the package data and cache directories that it created in
9928                // scanPackageLocked, unless those directories existed before we even tried to
9929                // install.
9930                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9931                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9932                                res.removedInfo, true);
9933            }
9934
9935        } catch (PackageManagerException e) {
9936            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9937        }
9938    }
9939
9940    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9941        // Upgrade keysets are being used.  Determine if new package has a superset of the
9942        // required keys.
9943        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9944        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9945        for (int i = 0; i < upgradeKeySets.length; i++) {
9946            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9947            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9948                return true;
9949            }
9950        }
9951        return false;
9952    }
9953
9954    private void replacePackageLI(PackageParser.Package pkg,
9955            int parseFlags, int scanMode, UserHandle user,
9956            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9957        PackageParser.Package oldPackage;
9958        String pkgName = pkg.packageName;
9959        int[] allUsers;
9960        boolean[] perUserInstalled;
9961
9962        // First find the old package info and check signatures
9963        synchronized(mPackages) {
9964            oldPackage = mPackages.get(pkgName);
9965            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9966            PackageSetting ps = mSettings.mPackages.get(pkgName);
9967            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9968                // default to original signature matching
9969                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9970                    != PackageManager.SIGNATURE_MATCH) {
9971                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9972                            "New package has a different signature: " + pkgName);
9973                    return;
9974                }
9975            } else {
9976                if(!checkUpgradeKeySetLP(ps, pkg)) {
9977                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9978                            "New package not signed by keys specified by upgrade-keysets: "
9979                            + pkgName);
9980                    return;
9981                }
9982            }
9983
9984            // In case of rollback, remember per-user/profile install state
9985            allUsers = sUserManager.getUserIds();
9986            perUserInstalled = new boolean[allUsers.length];
9987            for (int i = 0; i < allUsers.length; i++) {
9988                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9989            }
9990        }
9991
9992        boolean sysPkg = (isSystemApp(oldPackage));
9993        if (sysPkg) {
9994            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9995                    user, allUsers, perUserInstalled, installerPackageName, res,
9996                    abiOverride);
9997        } else {
9998            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9999                    user, allUsers, perUserInstalled, installerPackageName, res,
10000                    abiOverride);
10001        }
10002    }
10003
10004    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10005            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10006            int[] allUsers, boolean[] perUserInstalled,
10007            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10008        String pkgName = deletedPackage.packageName;
10009        boolean deletedPkg = true;
10010        boolean updatedSettings = false;
10011
10012        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10013                + deletedPackage);
10014        long origUpdateTime;
10015        if (pkg.mExtras != null) {
10016            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10017        } else {
10018            origUpdateTime = 0;
10019        }
10020
10021        // First delete the existing package while retaining the data directory
10022        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10023                res.removedInfo, true)) {
10024            // If the existing package wasn't successfully deleted
10025            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10026            deletedPkg = false;
10027        } else {
10028            // Successfully deleted the old package. Now proceed with re-installation
10029            deleteCodeCacheDirsLI(pkgName);
10030            try {
10031                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10032                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride);
10033                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10034                updatedSettings = true;
10035            } catch (PackageManagerException e) {
10036                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10037            }
10038        }
10039
10040        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10041            // remove package from internal structures.  Note that we want deletePackageX to
10042            // delete the package data and cache directories that it created in
10043            // scanPackageLocked, unless those directories existed before we even tried to
10044            // install.
10045            if(updatedSettings) {
10046                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10047                deletePackageLI(
10048                        pkgName, null, true, allUsers, perUserInstalled,
10049                        PackageManager.DELETE_KEEP_DATA,
10050                                res.removedInfo, true);
10051            }
10052            // Since we failed to install the new package we need to restore the old
10053            // package that we deleted.
10054            if (deletedPkg) {
10055                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10056                File restoreFile = new File(deletedPackage.codePath);
10057                // Parse old package
10058                boolean oldOnSd = isExternal(deletedPackage);
10059                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10060                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10061                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10062                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10063                        | SCAN_UPDATE_TIME;
10064                try {
10065                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null,
10066                            null);
10067                } catch (PackageManagerException e) {
10068                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10069                            + e.getMessage());
10070                    return;
10071                }
10072                // Restore of old package succeeded. Update permissions.
10073                // writer
10074                synchronized (mPackages) {
10075                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10076                            UPDATE_PERMISSIONS_ALL);
10077                    // can downgrade to reader
10078                    mSettings.writeLPr();
10079                }
10080                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10081            }
10082        }
10083    }
10084
10085    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10086            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10087            int[] allUsers, boolean[] perUserInstalled,
10088            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10089        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10090                + ", old=" + deletedPackage);
10091        boolean updatedSettings = false;
10092        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10093                PackageParser.PARSE_IS_SYSTEM;
10094        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10095            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10096        }
10097        String packageName = deletedPackage.packageName;
10098        if (packageName == null) {
10099            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10100                    "Attempt to delete null packageName.");
10101            return;
10102        }
10103        PackageParser.Package oldPkg;
10104        PackageSetting oldPkgSetting;
10105        // reader
10106        synchronized (mPackages) {
10107            oldPkg = mPackages.get(packageName);
10108            oldPkgSetting = mSettings.mPackages.get(packageName);
10109            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10110                    (oldPkgSetting == null)) {
10111                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10112                        "Couldn't find package:" + packageName + " information");
10113                return;
10114            }
10115        }
10116
10117        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10118
10119        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10120        res.removedInfo.removedPackage = packageName;
10121        // Remove existing system package
10122        removePackageLI(oldPkgSetting, true);
10123        // writer
10124        synchronized (mPackages) {
10125            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10126                // We didn't need to disable the .apk as a current system package,
10127                // which means we are replacing another update that is already
10128                // installed.  We need to make sure to delete the older one's .apk.
10129                res.removedInfo.args = createInstallArgsForExisting(0,
10130                        deletedPackage.applicationInfo.getCodePath(),
10131                        deletedPackage.applicationInfo.getResourcePath(),
10132                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10133                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10134                        isMultiArch(deletedPackage.applicationInfo));
10135            } else {
10136                res.removedInfo.args = null;
10137            }
10138        }
10139
10140        // Successfully disabled the old package. Now proceed with re-installation
10141        deleteCodeCacheDirsLI(packageName);
10142
10143        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10144        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10145
10146        PackageParser.Package newPackage = null;
10147        try {
10148            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10149            if (newPackage.mExtras != null) {
10150                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10151                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10152                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10153
10154                // is the update attempting to change shared user? that isn't going to work...
10155                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10156                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10157                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10158                            + " to " + newPkgSetting.sharedUser);
10159                    updatedSettings = true;
10160                }
10161            }
10162
10163            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10164                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10165                updatedSettings = true;
10166            }
10167
10168        } catch (PackageManagerException e) {
10169            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10170        }
10171
10172        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10173            // Re installation failed. Restore old information
10174            // Remove new pkg information
10175            if (newPackage != null) {
10176                removeInstalledPackageLI(newPackage, true);
10177            }
10178            // Add back the old system package
10179            try {
10180                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user,
10181                        null);
10182            } catch (PackageManagerException e) {
10183                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10184            }
10185            // Restore the old system information in Settings
10186            synchronized(mPackages) {
10187                if (updatedSettings) {
10188                    mSettings.enableSystemPackageLPw(packageName);
10189                    mSettings.setInstallerPackageName(packageName,
10190                            oldPkgSetting.installerPackageName);
10191                }
10192                mSettings.writeLPr();
10193            }
10194        }
10195    }
10196
10197    // Utility method used to move dex files during install.
10198    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10199        // TODO: extend to move split APK dex files
10200        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10201            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10202            for (String instructionSet : instructionSets) {
10203                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10204                        instructionSet);
10205                if (retCode != 0) {
10206                /*
10207                 * Programs may be lazily run through dexopt, so the
10208                 * source may not exist. However, something seems to
10209                 * have gone wrong, so note that dexopt needs to be
10210                 * run again and remove the source file. In addition,
10211                 * remove the target to make sure there isn't a stale
10212                 * file from a previous version of the package.
10213                 */
10214                    newPackage.mDexOptPerformed.clear();
10215                    mInstaller.rmdex(oldCodePath, instructionSet);
10216                    mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10217                }
10218            }
10219        }
10220        return PackageManager.INSTALL_SUCCEEDED;
10221    }
10222
10223    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10224            int[] allUsers, boolean[] perUserInstalled,
10225            PackageInstalledInfo res) {
10226        String pkgName = newPackage.packageName;
10227        synchronized (mPackages) {
10228            //write settings. the installStatus will be incomplete at this stage.
10229            //note that the new package setting would have already been
10230            //added to mPackages. It hasn't been persisted yet.
10231            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10232            mSettings.writeLPr();
10233        }
10234
10235        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10236
10237        synchronized (mPackages) {
10238            updatePermissionsLPw(newPackage.packageName, newPackage,
10239                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10240                            ? UPDATE_PERMISSIONS_ALL : 0));
10241            // For system-bundled packages, we assume that installing an upgraded version
10242            // of the package implies that the user actually wants to run that new code,
10243            // so we enable the package.
10244            if (isSystemApp(newPackage)) {
10245                // NB: implicit assumption that system package upgrades apply to all users
10246                if (DEBUG_INSTALL) {
10247                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10248                }
10249                PackageSetting ps = mSettings.mPackages.get(pkgName);
10250                if (ps != null) {
10251                    if (res.origUsers != null) {
10252                        for (int userHandle : res.origUsers) {
10253                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10254                                    userHandle, installerPackageName);
10255                        }
10256                    }
10257                    // Also convey the prior install/uninstall state
10258                    if (allUsers != null && perUserInstalled != null) {
10259                        for (int i = 0; i < allUsers.length; i++) {
10260                            if (DEBUG_INSTALL) {
10261                                Slog.d(TAG, "    user " + allUsers[i]
10262                                        + " => " + perUserInstalled[i]);
10263                            }
10264                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10265                        }
10266                        // these install state changes will be persisted in the
10267                        // upcoming call to mSettings.writeLPr().
10268                    }
10269                }
10270            }
10271            res.name = pkgName;
10272            res.uid = newPackage.applicationInfo.uid;
10273            res.pkg = newPackage;
10274            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10275            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10276            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10277            //to update install status
10278            mSettings.writeLPr();
10279        }
10280    }
10281
10282    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10283        int pFlags = args.flags;
10284        String installerPackageName = args.installerPackageName;
10285        File tmpPackageFile = new File(args.getCodePath());
10286        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10287        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10288        boolean replace = false;
10289        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10290                | (newInstall ? SCAN_NEW_INSTALL : 0);
10291        // Result object to be returned
10292        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10293
10294        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10295        // Retrieve PackageSettings and parse package
10296        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10297                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10298                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10299        PackageParser pp = new PackageParser();
10300        pp.setSeparateProcesses(mSeparateProcesses);
10301        pp.setDisplayMetrics(mMetrics);
10302
10303        final PackageParser.Package pkg;
10304        try {
10305            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10306        } catch (PackageParserException e) {
10307            res.setError("Failed parse during installPackageLI", e);
10308            return;
10309        }
10310
10311        String pkgName = res.name = pkg.packageName;
10312        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10313            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10314                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10315                return;
10316            }
10317        }
10318
10319        try {
10320            pp.collectCertificates(pkg, parseFlags);
10321            pp.collectManifestDigest(pkg);
10322        } catch (PackageParserException e) {
10323            res.setError("Failed collect during installPackageLI", e);
10324            return;
10325        }
10326
10327        /* If the installer passed in a manifest digest, compare it now. */
10328        if (args.manifestDigest != null) {
10329            if (DEBUG_INSTALL) {
10330                final String parsedManifest = pkg.manifestDigest == null ? "null"
10331                        : pkg.manifestDigest.toString();
10332                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10333                        + parsedManifest);
10334            }
10335
10336            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10337                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10338                return;
10339            }
10340        } else if (DEBUG_INSTALL) {
10341            final String parsedManifest = pkg.manifestDigest == null
10342                    ? "null" : pkg.manifestDigest.toString();
10343            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10344        }
10345
10346        // Get rid of all references to package scan path via parser.
10347        pp = null;
10348        String oldCodePath = null;
10349        boolean systemApp = false;
10350        synchronized (mPackages) {
10351            // Check whether the newly-scanned package wants to define an already-defined perm
10352            int N = pkg.permissions.size();
10353            for (int i = N-1; i >= 0; i--) {
10354                PackageParser.Permission perm = pkg.permissions.get(i);
10355                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10356                if (bp != null) {
10357                    // If the defining package is signed with our cert, it's okay.  This
10358                    // also includes the "updating the same package" case, of course.
10359                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10360                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10361                        // If the owning package is the system itself, we log but allow
10362                        // install to proceed; we fail the install on all other permission
10363                        // redefinitions.
10364                        if (!bp.sourcePackage.equals("android")) {
10365                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10366                                    + pkg.packageName + " attempting to redeclare permission "
10367                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10368                            res.origPermission = perm.info.name;
10369                            res.origPackage = bp.sourcePackage;
10370                            return;
10371                        } else {
10372                            Slog.w(TAG, "Package " + pkg.packageName
10373                                    + " attempting to redeclare system permission "
10374                                    + perm.info.name + "; ignoring new declaration");
10375                            pkg.permissions.remove(i);
10376                        }
10377                    }
10378                }
10379            }
10380
10381            // Check if installing already existing package
10382            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10383                String oldName = mSettings.mRenamedPackages.get(pkgName);
10384                if (pkg.mOriginalPackages != null
10385                        && pkg.mOriginalPackages.contains(oldName)
10386                        && mPackages.containsKey(oldName)) {
10387                    // This package is derived from an original package,
10388                    // and this device has been updating from that original
10389                    // name.  We must continue using the original name, so
10390                    // rename the new package here.
10391                    pkg.setPackageName(oldName);
10392                    pkgName = pkg.packageName;
10393                    replace = true;
10394                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10395                            + oldName + " pkgName=" + pkgName);
10396                } else if (mPackages.containsKey(pkgName)) {
10397                    // This package, under its official name, already exists
10398                    // on the device; we should replace it.
10399                    replace = true;
10400                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10401                }
10402            }
10403            PackageSetting ps = mSettings.mPackages.get(pkgName);
10404            if (ps != null) {
10405                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10406                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10407                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10408                    systemApp = (ps.pkg.applicationInfo.flags &
10409                            ApplicationInfo.FLAG_SYSTEM) != 0;
10410                }
10411                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10412            }
10413        }
10414
10415        if (systemApp && onSd) {
10416            // Disable updates to system apps on sdcard
10417            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10418                    "Cannot install updates to system apps on sdcard");
10419            return;
10420        }
10421
10422        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10423            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10424            return;
10425        }
10426
10427        if (replace) {
10428            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10429                    installerPackageName, res, args.abiOverride);
10430        } else {
10431            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10432                    installerPackageName, res, args.abiOverride);
10433        }
10434        synchronized (mPackages) {
10435            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10436            if (ps != null) {
10437                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10438            }
10439        }
10440    }
10441
10442    private static boolean isForwardLocked(PackageParser.Package pkg) {
10443        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10444    }
10445
10446    private static boolean isForwardLocked(ApplicationInfo info) {
10447        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10448    }
10449
10450    private boolean isForwardLocked(PackageSetting ps) {
10451        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10452    }
10453
10454    private static boolean isMultiArch(PackageSetting ps) {
10455        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10456    }
10457
10458    private static boolean isMultiArch(ApplicationInfo info) {
10459        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10460    }
10461
10462    private static boolean isExternal(PackageParser.Package pkg) {
10463        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10464    }
10465
10466    private static boolean isExternal(PackageSetting ps) {
10467        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10468    }
10469
10470    private static boolean isExternal(ApplicationInfo info) {
10471        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10472    }
10473
10474    private static boolean isSystemApp(PackageParser.Package pkg) {
10475        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10476    }
10477
10478    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10479        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10480    }
10481
10482    private static boolean isSystemApp(ApplicationInfo info) {
10483        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10484    }
10485
10486    private static boolean isSystemApp(PackageSetting ps) {
10487        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10488    }
10489
10490    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10491        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10492    }
10493
10494    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10495        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10496    }
10497
10498    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10499        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10500    }
10501
10502    private int packageFlagsToInstallFlags(PackageSetting ps) {
10503        int installFlags = 0;
10504        if (isExternal(ps)) {
10505            installFlags |= PackageManager.INSTALL_EXTERNAL;
10506        }
10507        if (isForwardLocked(ps)) {
10508            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10509        }
10510        return installFlags;
10511    }
10512
10513    private void deleteTempPackageFiles() {
10514        final FilenameFilter filter = new FilenameFilter() {
10515            public boolean accept(File dir, String name) {
10516                return name.startsWith("vmdl") && name.endsWith(".tmp");
10517            }
10518        };
10519        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10520            file.delete();
10521        }
10522    }
10523
10524    @Override
10525    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10526            int flags) {
10527        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10528                flags);
10529    }
10530
10531    @Override
10532    public void deletePackage(final String packageName,
10533            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10534        mContext.enforceCallingOrSelfPermission(
10535                android.Manifest.permission.DELETE_PACKAGES, null);
10536        final int uid = Binder.getCallingUid();
10537        if (UserHandle.getUserId(uid) != userId) {
10538            mContext.enforceCallingPermission(
10539                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10540                    "deletePackage for user " + userId);
10541        }
10542        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10543            try {
10544                observer.onPackageDeleted(packageName,
10545                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10546            } catch (RemoteException re) {
10547            }
10548            return;
10549        }
10550
10551        boolean uninstallBlocked = false;
10552        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10553            int[] users = sUserManager.getUserIds();
10554            for (int i = 0; i < users.length; ++i) {
10555                if (getBlockUninstallForUser(packageName, users[i])) {
10556                    uninstallBlocked = true;
10557                    break;
10558                }
10559            }
10560        } else {
10561            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10562        }
10563        if (uninstallBlocked) {
10564            try {
10565                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10566                        null);
10567            } catch (RemoteException re) {
10568            }
10569            return;
10570        }
10571
10572        if (DEBUG_REMOVE) {
10573            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10574        }
10575        // Queue up an async operation since the package deletion may take a little while.
10576        mHandler.post(new Runnable() {
10577            public void run() {
10578                mHandler.removeCallbacks(this);
10579                final int returnCode = deletePackageX(packageName, userId, flags);
10580                if (observer != null) {
10581                    try {
10582                        observer.onPackageDeleted(packageName, returnCode, null);
10583                    } catch (RemoteException e) {
10584                        Log.i(TAG, "Observer no longer exists.");
10585                    } //end catch
10586                } //end if
10587            } //end run
10588        });
10589    }
10590
10591    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10592        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10593                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10594        try {
10595            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10596                    || dpm.isDeviceOwner(packageName))) {
10597                return true;
10598            }
10599        } catch (RemoteException e) {
10600        }
10601        return false;
10602    }
10603
10604    /**
10605     *  This method is an internal method that could be get invoked either
10606     *  to delete an installed package or to clean up a failed installation.
10607     *  After deleting an installed package, a broadcast is sent to notify any
10608     *  listeners that the package has been installed. For cleaning up a failed
10609     *  installation, the broadcast is not necessary since the package's
10610     *  installation wouldn't have sent the initial broadcast either
10611     *  The key steps in deleting a package are
10612     *  deleting the package information in internal structures like mPackages,
10613     *  deleting the packages base directories through installd
10614     *  updating mSettings to reflect current status
10615     *  persisting settings for later use
10616     *  sending a broadcast if necessary
10617     */
10618    private int deletePackageX(String packageName, int userId, int flags) {
10619        final PackageRemovedInfo info = new PackageRemovedInfo();
10620        final boolean res;
10621
10622        if (isPackageDeviceAdmin(packageName, userId)) {
10623            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10624            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10625        }
10626
10627        boolean removedForAllUsers = false;
10628        boolean systemUpdate = false;
10629
10630        // for the uninstall-updates case and restricted profiles, remember the per-
10631        // userhandle installed state
10632        int[] allUsers;
10633        boolean[] perUserInstalled;
10634        synchronized (mPackages) {
10635            PackageSetting ps = mSettings.mPackages.get(packageName);
10636            allUsers = sUserManager.getUserIds();
10637            perUserInstalled = new boolean[allUsers.length];
10638            for (int i = 0; i < allUsers.length; i++) {
10639                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10640            }
10641        }
10642
10643        synchronized (mInstallLock) {
10644            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10645            res = deletePackageLI(packageName,
10646                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10647                            ? UserHandle.ALL : new UserHandle(userId),
10648                    true, allUsers, perUserInstalled,
10649                    flags | REMOVE_CHATTY, info, true);
10650            systemUpdate = info.isRemovedPackageSystemUpdate;
10651            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10652                removedForAllUsers = true;
10653            }
10654            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10655                    + " removedForAllUsers=" + removedForAllUsers);
10656        }
10657
10658        if (res) {
10659            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10660
10661            // If the removed package was a system update, the old system package
10662            // was re-enabled; we need to broadcast this information
10663            if (systemUpdate) {
10664                Bundle extras = new Bundle(1);
10665                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10666                        ? info.removedAppId : info.uid);
10667                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10668
10669                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10670                        extras, null, null, null);
10671                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10672                        extras, null, null, null);
10673                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10674                        null, packageName, null, null);
10675            }
10676        }
10677        // Force a gc here.
10678        Runtime.getRuntime().gc();
10679        // Delete the resources here after sending the broadcast to let
10680        // other processes clean up before deleting resources.
10681        if (info.args != null) {
10682            synchronized (mInstallLock) {
10683                info.args.doPostDeleteLI(true);
10684            }
10685        }
10686
10687        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10688    }
10689
10690    static class PackageRemovedInfo {
10691        String removedPackage;
10692        int uid = -1;
10693        int removedAppId = -1;
10694        int[] removedUsers = null;
10695        boolean isRemovedPackageSystemUpdate = false;
10696        // Clean up resources deleted packages.
10697        InstallArgs args = null;
10698
10699        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10700            Bundle extras = new Bundle(1);
10701            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10702            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10703            if (replacing) {
10704                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10705            }
10706            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10707            if (removedPackage != null) {
10708                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10709                        extras, null, null, removedUsers);
10710                if (fullRemove && !replacing) {
10711                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10712                            extras, null, null, removedUsers);
10713                }
10714            }
10715            if (removedAppId >= 0) {
10716                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10717                        removedUsers);
10718            }
10719        }
10720    }
10721
10722    /*
10723     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10724     * flag is not set, the data directory is removed as well.
10725     * make sure this flag is set for partially installed apps. If not its meaningless to
10726     * delete a partially installed application.
10727     */
10728    private void removePackageDataLI(PackageSetting ps,
10729            int[] allUserHandles, boolean[] perUserInstalled,
10730            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10731        String packageName = ps.name;
10732        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10733        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10734        // Retrieve object to delete permissions for shared user later on
10735        final PackageSetting deletedPs;
10736        // reader
10737        synchronized (mPackages) {
10738            deletedPs = mSettings.mPackages.get(packageName);
10739            if (outInfo != null) {
10740                outInfo.removedPackage = packageName;
10741                outInfo.removedUsers = deletedPs != null
10742                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10743                        : null;
10744            }
10745        }
10746        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10747            removeDataDirsLI(packageName);
10748            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10749        }
10750        // writer
10751        synchronized (mPackages) {
10752            if (deletedPs != null) {
10753                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10754                    if (outInfo != null) {
10755                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10756                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10757                    }
10758                    if (deletedPs != null) {
10759                        updatePermissionsLPw(deletedPs.name, null, 0);
10760                        if (deletedPs.sharedUser != null) {
10761                            // remove permissions associated with package
10762                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10763                        }
10764                    }
10765                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10766                }
10767                // make sure to preserve per-user disabled state if this removal was just
10768                // a downgrade of a system app to the factory package
10769                if (allUserHandles != null && perUserInstalled != null) {
10770                    if (DEBUG_REMOVE) {
10771                        Slog.d(TAG, "Propagating install state across downgrade");
10772                    }
10773                    for (int i = 0; i < allUserHandles.length; i++) {
10774                        if (DEBUG_REMOVE) {
10775                            Slog.d(TAG, "    user " + allUserHandles[i]
10776                                    + " => " + perUserInstalled[i]);
10777                        }
10778                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10779                    }
10780                }
10781            }
10782            // can downgrade to reader
10783            if (writeSettings) {
10784                // Save settings now
10785                mSettings.writeLPr();
10786            }
10787        }
10788        if (outInfo != null) {
10789            // A user ID was deleted here. Go through all users and remove it
10790            // from KeyStore.
10791            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10792        }
10793    }
10794
10795    static boolean locationIsPrivileged(File path) {
10796        try {
10797            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10798                    .getCanonicalPath();
10799            return path.getCanonicalPath().startsWith(privilegedAppDir);
10800        } catch (IOException e) {
10801            Slog.e(TAG, "Unable to access code path " + path);
10802        }
10803        return false;
10804    }
10805
10806    /*
10807     * Tries to delete system package.
10808     */
10809    private boolean deleteSystemPackageLI(PackageSetting newPs,
10810            int[] allUserHandles, boolean[] perUserInstalled,
10811            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10812        final boolean applyUserRestrictions
10813                = (allUserHandles != null) && (perUserInstalled != null);
10814        PackageSetting disabledPs = null;
10815        // Confirm if the system package has been updated
10816        // An updated system app can be deleted. This will also have to restore
10817        // the system pkg from system partition
10818        // reader
10819        synchronized (mPackages) {
10820            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10821        }
10822        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10823                + " disabledPs=" + disabledPs);
10824        if (disabledPs == null) {
10825            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10826            return false;
10827        } else if (DEBUG_REMOVE) {
10828            Slog.d(TAG, "Deleting system pkg from data partition");
10829        }
10830        if (DEBUG_REMOVE) {
10831            if (applyUserRestrictions) {
10832                Slog.d(TAG, "Remembering install states:");
10833                for (int i = 0; i < allUserHandles.length; i++) {
10834                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10835                }
10836            }
10837        }
10838        // Delete the updated package
10839        outInfo.isRemovedPackageSystemUpdate = true;
10840        if (disabledPs.versionCode < newPs.versionCode) {
10841            // Delete data for downgrades
10842            flags &= ~PackageManager.DELETE_KEEP_DATA;
10843        } else {
10844            // Preserve data by setting flag
10845            flags |= PackageManager.DELETE_KEEP_DATA;
10846        }
10847        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10848                allUserHandles, perUserInstalled, outInfo, writeSettings);
10849        if (!ret) {
10850            return false;
10851        }
10852        // writer
10853        synchronized (mPackages) {
10854            // Reinstate the old system package
10855            mSettings.enableSystemPackageLPw(newPs.name);
10856            // Remove any native libraries from the upgraded package.
10857            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10858        }
10859        // Install the system package
10860        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10861        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10862        if (locationIsPrivileged(disabledPs.codePath)) {
10863            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10864        }
10865
10866        final PackageParser.Package newPkg;
10867        try {
10868            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0,
10869                    null, null);
10870        } catch (PackageManagerException e) {
10871            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10872            return false;
10873        }
10874
10875        // writer
10876        synchronized (mPackages) {
10877            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10878            updatePermissionsLPw(newPkg.packageName, newPkg,
10879                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10880            if (applyUserRestrictions) {
10881                if (DEBUG_REMOVE) {
10882                    Slog.d(TAG, "Propagating install state across reinstall");
10883                }
10884                for (int i = 0; i < allUserHandles.length; i++) {
10885                    if (DEBUG_REMOVE) {
10886                        Slog.d(TAG, "    user " + allUserHandles[i]
10887                                + " => " + perUserInstalled[i]);
10888                    }
10889                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10890                }
10891                // Regardless of writeSettings we need to ensure that this restriction
10892                // state propagation is persisted
10893                mSettings.writeAllUsersPackageRestrictionsLPr();
10894            }
10895            // can downgrade to reader here
10896            if (writeSettings) {
10897                mSettings.writeLPr();
10898            }
10899        }
10900        return true;
10901    }
10902
10903    private boolean deleteInstalledPackageLI(PackageSetting ps,
10904            boolean deleteCodeAndResources, int flags,
10905            int[] allUserHandles, boolean[] perUserInstalled,
10906            PackageRemovedInfo outInfo, boolean writeSettings) {
10907        if (outInfo != null) {
10908            outInfo.uid = ps.appId;
10909        }
10910
10911        // Delete package data from internal structures and also remove data if flag is set
10912        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10913
10914        // Delete application code and resources
10915        if (deleteCodeAndResources && (outInfo != null)) {
10916            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10917                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10918                    getAppDexInstructionSets(ps), isMultiArch(ps));
10919        }
10920        return true;
10921    }
10922
10923    @Override
10924    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10925            int userId) {
10926        mContext.enforceCallingOrSelfPermission(
10927                android.Manifest.permission.DELETE_PACKAGES, null);
10928        synchronized (mPackages) {
10929            PackageSetting ps = mSettings.mPackages.get(packageName);
10930            if (ps == null) {
10931                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10932                return false;
10933            }
10934            if (!ps.getInstalled(userId)) {
10935                // Can't block uninstall for an app that is not installed or enabled.
10936                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10937                return false;
10938            }
10939            ps.setBlockUninstall(blockUninstall, userId);
10940            mSettings.writePackageRestrictionsLPr(userId);
10941        }
10942        return true;
10943    }
10944
10945    @Override
10946    public boolean getBlockUninstallForUser(String packageName, int userId) {
10947        synchronized (mPackages) {
10948            PackageSetting ps = mSettings.mPackages.get(packageName);
10949            if (ps == null) {
10950                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10951                return false;
10952            }
10953            return ps.getBlockUninstall(userId);
10954        }
10955    }
10956
10957    /*
10958     * This method handles package deletion in general
10959     */
10960    private boolean deletePackageLI(String packageName, UserHandle user,
10961            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10962            int flags, PackageRemovedInfo outInfo,
10963            boolean writeSettings) {
10964        if (packageName == null) {
10965            Slog.w(TAG, "Attempt to delete null packageName.");
10966            return false;
10967        }
10968        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10969        PackageSetting ps;
10970        boolean dataOnly = false;
10971        int removeUser = -1;
10972        int appId = -1;
10973        synchronized (mPackages) {
10974            ps = mSettings.mPackages.get(packageName);
10975            if (ps == null) {
10976                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10977                return false;
10978            }
10979            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10980                    && user.getIdentifier() != UserHandle.USER_ALL) {
10981                // The caller is asking that the package only be deleted for a single
10982                // user.  To do this, we just mark its uninstalled state and delete
10983                // its data.  If this is a system app, we only allow this to happen if
10984                // they have set the special DELETE_SYSTEM_APP which requests different
10985                // semantics than normal for uninstalling system apps.
10986                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10987                ps.setUserState(user.getIdentifier(),
10988                        COMPONENT_ENABLED_STATE_DEFAULT,
10989                        false, //installed
10990                        true,  //stopped
10991                        true,  //notLaunched
10992                        false, //hidden
10993                        null, null, null,
10994                        false // blockUninstall
10995                        );
10996                if (!isSystemApp(ps)) {
10997                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10998                        // Other user still have this package installed, so all
10999                        // we need to do is clear this user's data and save that
11000                        // it is uninstalled.
11001                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11002                        removeUser = user.getIdentifier();
11003                        appId = ps.appId;
11004                        mSettings.writePackageRestrictionsLPr(removeUser);
11005                    } else {
11006                        // We need to set it back to 'installed' so the uninstall
11007                        // broadcasts will be sent correctly.
11008                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11009                        ps.setInstalled(true, user.getIdentifier());
11010                    }
11011                } else {
11012                    // This is a system app, so we assume that the
11013                    // other users still have this package installed, so all
11014                    // we need to do is clear this user's data and save that
11015                    // it is uninstalled.
11016                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11017                    removeUser = user.getIdentifier();
11018                    appId = ps.appId;
11019                    mSettings.writePackageRestrictionsLPr(removeUser);
11020                }
11021            }
11022        }
11023
11024        if (removeUser >= 0) {
11025            // From above, we determined that we are deleting this only
11026            // for a single user.  Continue the work here.
11027            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11028            if (outInfo != null) {
11029                outInfo.removedPackage = packageName;
11030                outInfo.removedAppId = appId;
11031                outInfo.removedUsers = new int[] {removeUser};
11032            }
11033            mInstaller.clearUserData(packageName, removeUser);
11034            removeKeystoreDataIfNeeded(removeUser, appId);
11035            schedulePackageCleaning(packageName, removeUser, false);
11036            return true;
11037        }
11038
11039        if (dataOnly) {
11040            // Delete application data first
11041            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11042            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11043            return true;
11044        }
11045
11046        boolean ret = false;
11047        if (isSystemApp(ps)) {
11048            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11049            // When an updated system application is deleted we delete the existing resources as well and
11050            // fall back to existing code in system partition
11051            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11052                    flags, outInfo, writeSettings);
11053        } else {
11054            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11055            // Kill application pre-emptively especially for apps on sd.
11056            killApplication(packageName, ps.appId, "uninstall pkg");
11057            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11058                    allUserHandles, perUserInstalled,
11059                    outInfo, writeSettings);
11060        }
11061
11062        return ret;
11063    }
11064
11065    private final class ClearStorageConnection implements ServiceConnection {
11066        IMediaContainerService mContainerService;
11067
11068        @Override
11069        public void onServiceConnected(ComponentName name, IBinder service) {
11070            synchronized (this) {
11071                mContainerService = IMediaContainerService.Stub.asInterface(service);
11072                notifyAll();
11073            }
11074        }
11075
11076        @Override
11077        public void onServiceDisconnected(ComponentName name) {
11078        }
11079    }
11080
11081    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11082        final boolean mounted;
11083        if (Environment.isExternalStorageEmulated()) {
11084            mounted = true;
11085        } else {
11086            final String status = Environment.getExternalStorageState();
11087
11088            mounted = status.equals(Environment.MEDIA_MOUNTED)
11089                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11090        }
11091
11092        if (!mounted) {
11093            return;
11094        }
11095
11096        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11097        int[] users;
11098        if (userId == UserHandle.USER_ALL) {
11099            users = sUserManager.getUserIds();
11100        } else {
11101            users = new int[] { userId };
11102        }
11103        final ClearStorageConnection conn = new ClearStorageConnection();
11104        if (mContext.bindServiceAsUser(
11105                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11106            try {
11107                for (int curUser : users) {
11108                    long timeout = SystemClock.uptimeMillis() + 5000;
11109                    synchronized (conn) {
11110                        long now = SystemClock.uptimeMillis();
11111                        while (conn.mContainerService == null && now < timeout) {
11112                            try {
11113                                conn.wait(timeout - now);
11114                            } catch (InterruptedException e) {
11115                            }
11116                        }
11117                    }
11118                    if (conn.mContainerService == null) {
11119                        return;
11120                    }
11121
11122                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11123                    clearDirectory(conn.mContainerService,
11124                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11125                    if (allData) {
11126                        clearDirectory(conn.mContainerService,
11127                                userEnv.buildExternalStorageAppDataDirs(packageName));
11128                        clearDirectory(conn.mContainerService,
11129                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11130                    }
11131                }
11132            } finally {
11133                mContext.unbindService(conn);
11134            }
11135        }
11136    }
11137
11138    @Override
11139    public void clearApplicationUserData(final String packageName,
11140            final IPackageDataObserver observer, final int userId) {
11141        mContext.enforceCallingOrSelfPermission(
11142                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11143        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11144        // Queue up an async operation since the package deletion may take a little while.
11145        mHandler.post(new Runnable() {
11146            public void run() {
11147                mHandler.removeCallbacks(this);
11148                final boolean succeeded;
11149                synchronized (mInstallLock) {
11150                    succeeded = clearApplicationUserDataLI(packageName, userId);
11151                }
11152                clearExternalStorageDataSync(packageName, userId, true);
11153                if (succeeded) {
11154                    // invoke DeviceStorageMonitor's update method to clear any notifications
11155                    DeviceStorageMonitorInternal
11156                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11157                    if (dsm != null) {
11158                        dsm.checkMemory();
11159                    }
11160                }
11161                if(observer != null) {
11162                    try {
11163                        observer.onRemoveCompleted(packageName, succeeded);
11164                    } catch (RemoteException e) {
11165                        Log.i(TAG, "Observer no longer exists.");
11166                    }
11167                } //end if observer
11168            } //end run
11169        });
11170    }
11171
11172    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11173        if (packageName == null) {
11174            Slog.w(TAG, "Attempt to delete null packageName.");
11175            return false;
11176        }
11177        PackageParser.Package p;
11178        boolean dataOnly = false;
11179        final int appId;
11180        synchronized (mPackages) {
11181            p = mPackages.get(packageName);
11182            if (p == null) {
11183                dataOnly = true;
11184                PackageSetting ps = mSettings.mPackages.get(packageName);
11185                if ((ps == null) || (ps.pkg == null)) {
11186                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11187                    return false;
11188                }
11189                p = ps.pkg;
11190            }
11191            if (!dataOnly) {
11192                // need to check this only for fully installed applications
11193                if (p == null) {
11194                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11195                    return false;
11196                }
11197                final ApplicationInfo applicationInfo = p.applicationInfo;
11198                if (applicationInfo == null) {
11199                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11200                    return false;
11201                }
11202            }
11203            if (p != null && p.applicationInfo != null) {
11204                appId = p.applicationInfo.uid;
11205            } else {
11206                appId = -1;
11207            }
11208        }
11209        int retCode = mInstaller.clearUserData(packageName, userId);
11210        if (retCode < 0) {
11211            Slog.w(TAG, "Couldn't remove cache files for package: "
11212                    + packageName);
11213            return false;
11214        }
11215        removeKeystoreDataIfNeeded(userId, appId);
11216        return true;
11217    }
11218
11219    /**
11220     * Remove entries from the keystore daemon. Will only remove it if the
11221     * {@code appId} is valid.
11222     */
11223    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11224        if (appId < 0) {
11225            return;
11226        }
11227
11228        final KeyStore keyStore = KeyStore.getInstance();
11229        if (keyStore != null) {
11230            if (userId == UserHandle.USER_ALL) {
11231                for (final int individual : sUserManager.getUserIds()) {
11232                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11233                }
11234            } else {
11235                keyStore.clearUid(UserHandle.getUid(userId, appId));
11236            }
11237        } else {
11238            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11239        }
11240    }
11241
11242    @Override
11243    public void deleteApplicationCacheFiles(final String packageName,
11244            final IPackageDataObserver observer) {
11245        mContext.enforceCallingOrSelfPermission(
11246                android.Manifest.permission.DELETE_CACHE_FILES, null);
11247        // Queue up an async operation since the package deletion may take a little while.
11248        final int userId = UserHandle.getCallingUserId();
11249        mHandler.post(new Runnable() {
11250            public void run() {
11251                mHandler.removeCallbacks(this);
11252                final boolean succeded;
11253                synchronized (mInstallLock) {
11254                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11255                }
11256                clearExternalStorageDataSync(packageName, userId, false);
11257                if(observer != null) {
11258                    try {
11259                        observer.onRemoveCompleted(packageName, succeded);
11260                    } catch (RemoteException e) {
11261                        Log.i(TAG, "Observer no longer exists.");
11262                    }
11263                } //end if observer
11264            } //end run
11265        });
11266    }
11267
11268    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11269        if (packageName == null) {
11270            Slog.w(TAG, "Attempt to delete null packageName.");
11271            return false;
11272        }
11273        PackageParser.Package p;
11274        synchronized (mPackages) {
11275            p = mPackages.get(packageName);
11276        }
11277        if (p == null) {
11278            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11279            return false;
11280        }
11281        final ApplicationInfo applicationInfo = p.applicationInfo;
11282        if (applicationInfo == null) {
11283            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11284            return false;
11285        }
11286        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11287        if (retCode < 0) {
11288            Slog.w(TAG, "Couldn't remove cache files for package: "
11289                       + packageName + " u" + userId);
11290            return false;
11291        }
11292        return true;
11293    }
11294
11295    @Override
11296    public void getPackageSizeInfo(final String packageName, int userHandle,
11297            final IPackageStatsObserver observer) {
11298        mContext.enforceCallingOrSelfPermission(
11299                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11300        if (packageName == null) {
11301            throw new IllegalArgumentException("Attempt to get size of null packageName");
11302        }
11303
11304        PackageStats stats = new PackageStats(packageName, userHandle);
11305
11306        /*
11307         * Queue up an async operation since the package measurement may take a
11308         * little while.
11309         */
11310        Message msg = mHandler.obtainMessage(INIT_COPY);
11311        msg.obj = new MeasureParams(stats, observer);
11312        mHandler.sendMessage(msg);
11313    }
11314
11315    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11316            PackageStats pStats) {
11317        if (packageName == null) {
11318            Slog.w(TAG, "Attempt to get size of null packageName.");
11319            return false;
11320        }
11321        PackageParser.Package p;
11322        boolean dataOnly = false;
11323        String libDirRoot = null;
11324        String asecPath = null;
11325        PackageSetting ps = null;
11326        synchronized (mPackages) {
11327            p = mPackages.get(packageName);
11328            ps = mSettings.mPackages.get(packageName);
11329            if(p == null) {
11330                dataOnly = true;
11331                if((ps == null) || (ps.pkg == null)) {
11332                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11333                    return false;
11334                }
11335                p = ps.pkg;
11336            }
11337            if (ps != null) {
11338                libDirRoot = ps.legacyNativeLibraryPathString;
11339            }
11340            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11341                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11342                if (secureContainerId != null) {
11343                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11344                }
11345            }
11346        }
11347        String publicSrcDir = null;
11348        if(!dataOnly) {
11349            final ApplicationInfo applicationInfo = p.applicationInfo;
11350            if (applicationInfo == null) {
11351                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11352                return false;
11353            }
11354            if (isForwardLocked(p)) {
11355                publicSrcDir = applicationInfo.getBaseResourcePath();
11356            }
11357        }
11358        // TODO: extend to measure size of split APKs
11359        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11360        // not just the first level.
11361        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11362        // just the primary.
11363        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11364                publicSrcDir, asecPath, getAppDexInstructionSets(ps),
11365                pStats);
11366        if (res < 0) {
11367            return false;
11368        }
11369
11370        // Fix-up for forward-locked applications in ASEC containers.
11371        if (!isExternal(p)) {
11372            pStats.codeSize += pStats.externalCodeSize;
11373            pStats.externalCodeSize = 0L;
11374        }
11375
11376        return true;
11377    }
11378
11379
11380    @Override
11381    public void addPackageToPreferred(String packageName) {
11382        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11383    }
11384
11385    @Override
11386    public void removePackageFromPreferred(String packageName) {
11387        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11388    }
11389
11390    @Override
11391    public List<PackageInfo> getPreferredPackages(int flags) {
11392        return new ArrayList<PackageInfo>();
11393    }
11394
11395    private int getUidTargetSdkVersionLockedLPr(int uid) {
11396        Object obj = mSettings.getUserIdLPr(uid);
11397        if (obj instanceof SharedUserSetting) {
11398            final SharedUserSetting sus = (SharedUserSetting) obj;
11399            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11400            final Iterator<PackageSetting> it = sus.packages.iterator();
11401            while (it.hasNext()) {
11402                final PackageSetting ps = it.next();
11403                if (ps.pkg != null) {
11404                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11405                    if (v < vers) vers = v;
11406                }
11407            }
11408            return vers;
11409        } else if (obj instanceof PackageSetting) {
11410            final PackageSetting ps = (PackageSetting) obj;
11411            if (ps.pkg != null) {
11412                return ps.pkg.applicationInfo.targetSdkVersion;
11413            }
11414        }
11415        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11416    }
11417
11418    @Override
11419    public void addPreferredActivity(IntentFilter filter, int match,
11420            ComponentName[] set, ComponentName activity, int userId) {
11421        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11422    }
11423
11424    private void addPreferredActivityInternal(IntentFilter filter, int match,
11425            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11426        // writer
11427        int callingUid = Binder.getCallingUid();
11428        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11429        if (filter.countActions() == 0) {
11430            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11431            return;
11432        }
11433        synchronized (mPackages) {
11434            if (mContext.checkCallingOrSelfPermission(
11435                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11436                    != PackageManager.PERMISSION_GRANTED) {
11437                if (getUidTargetSdkVersionLockedLPr(callingUid)
11438                        < Build.VERSION_CODES.FROYO) {
11439                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11440                            + callingUid);
11441                    return;
11442                }
11443                mContext.enforceCallingOrSelfPermission(
11444                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11445            }
11446
11447            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11448            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11449            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11450                    new PreferredActivity(filter, match, set, activity, always));
11451            mSettings.writePackageRestrictionsLPr(userId);
11452        }
11453    }
11454
11455    @Override
11456    public void replacePreferredActivity(IntentFilter filter, int match,
11457            ComponentName[] set, ComponentName activity, int userId) {
11458        if (filter.countActions() != 1) {
11459            throw new IllegalArgumentException(
11460                    "replacePreferredActivity expects filter to have only 1 action.");
11461        }
11462        if (filter.countDataAuthorities() != 0
11463                || filter.countDataPaths() != 0
11464                || filter.countDataSchemes() > 1
11465                || filter.countDataTypes() != 0) {
11466            throw new IllegalArgumentException(
11467                    "replacePreferredActivity expects filter to have no data authorities, " +
11468                    "paths, or types; and at most one scheme.");
11469        }
11470
11471        final int callingUid = Binder.getCallingUid();
11472        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11473        final int callingUserId = UserHandle.getUserId(callingUid);
11474        synchronized (mPackages) {
11475            if (mContext.checkCallingOrSelfPermission(
11476                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11477                    != PackageManager.PERMISSION_GRANTED) {
11478                if (getUidTargetSdkVersionLockedLPr(callingUid)
11479                        < Build.VERSION_CODES.FROYO) {
11480                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11481                            + Binder.getCallingUid());
11482                    return;
11483                }
11484                mContext.enforceCallingOrSelfPermission(
11485                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11486            }
11487
11488            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11489            if (pir != null) {
11490                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11491                if (filter.countDataSchemes() == 1) {
11492                    Uri.Builder builder = new Uri.Builder();
11493                    builder.scheme(filter.getDataScheme(0));
11494                    intent.setData(builder.build());
11495                }
11496                List<PreferredActivity> matches = pir.queryIntent(
11497                        intent, null, true, callingUserId);
11498                if (DEBUG_PREFERRED) {
11499                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11500                }
11501                for (int i = 0; i < matches.size(); i++) {
11502                    PreferredActivity pa = matches.get(i);
11503                    if (DEBUG_PREFERRED) {
11504                        Slog.i(TAG, "Removing preferred activity "
11505                                + pa.mPref.mComponent + ":");
11506                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11507                    }
11508                    pir.removeFilter(pa);
11509                }
11510            }
11511            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11512        }
11513    }
11514
11515    @Override
11516    public void clearPackagePreferredActivities(String packageName) {
11517        final int uid = Binder.getCallingUid();
11518        // writer
11519        synchronized (mPackages) {
11520            PackageParser.Package pkg = mPackages.get(packageName);
11521            if (pkg == null || pkg.applicationInfo.uid != uid) {
11522                if (mContext.checkCallingOrSelfPermission(
11523                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11524                        != PackageManager.PERMISSION_GRANTED) {
11525                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11526                            < Build.VERSION_CODES.FROYO) {
11527                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11528                                + Binder.getCallingUid());
11529                        return;
11530                    }
11531                    mContext.enforceCallingOrSelfPermission(
11532                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11533                }
11534            }
11535
11536            int user = UserHandle.getCallingUserId();
11537            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11538                mSettings.writePackageRestrictionsLPr(user);
11539                scheduleWriteSettingsLocked();
11540            }
11541        }
11542    }
11543
11544    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11545    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11546        ArrayList<PreferredActivity> removed = null;
11547        boolean changed = false;
11548        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11549            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11550            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11551            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11552                continue;
11553            }
11554            Iterator<PreferredActivity> it = pir.filterIterator();
11555            while (it.hasNext()) {
11556                PreferredActivity pa = it.next();
11557                // Mark entry for removal only if it matches the package name
11558                // and the entry is of type "always".
11559                if (packageName == null ||
11560                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11561                                && pa.mPref.mAlways)) {
11562                    if (removed == null) {
11563                        removed = new ArrayList<PreferredActivity>();
11564                    }
11565                    removed.add(pa);
11566                }
11567            }
11568            if (removed != null) {
11569                for (int j=0; j<removed.size(); j++) {
11570                    PreferredActivity pa = removed.get(j);
11571                    pir.removeFilter(pa);
11572                }
11573                changed = true;
11574            }
11575        }
11576        return changed;
11577    }
11578
11579    @Override
11580    public void resetPreferredActivities(int userId) {
11581        mContext.enforceCallingOrSelfPermission(
11582                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11583        // writer
11584        synchronized (mPackages) {
11585            int user = UserHandle.getCallingUserId();
11586            clearPackagePreferredActivitiesLPw(null, user);
11587            mSettings.readDefaultPreferredAppsLPw(this, user);
11588            mSettings.writePackageRestrictionsLPr(user);
11589            scheduleWriteSettingsLocked();
11590        }
11591    }
11592
11593    @Override
11594    public int getPreferredActivities(List<IntentFilter> outFilters,
11595            List<ComponentName> outActivities, String packageName) {
11596
11597        int num = 0;
11598        final int userId = UserHandle.getCallingUserId();
11599        // reader
11600        synchronized (mPackages) {
11601            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11602            if (pir != null) {
11603                final Iterator<PreferredActivity> it = pir.filterIterator();
11604                while (it.hasNext()) {
11605                    final PreferredActivity pa = it.next();
11606                    if (packageName == null
11607                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11608                                    && pa.mPref.mAlways)) {
11609                        if (outFilters != null) {
11610                            outFilters.add(new IntentFilter(pa));
11611                        }
11612                        if (outActivities != null) {
11613                            outActivities.add(pa.mPref.mComponent);
11614                        }
11615                    }
11616                }
11617            }
11618        }
11619
11620        return num;
11621    }
11622
11623    @Override
11624    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11625            int userId) {
11626        int callingUid = Binder.getCallingUid();
11627        if (callingUid != Process.SYSTEM_UID) {
11628            throw new SecurityException(
11629                    "addPersistentPreferredActivity can only be run by the system");
11630        }
11631        if (filter.countActions() == 0) {
11632            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11633            return;
11634        }
11635        synchronized (mPackages) {
11636            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11637                    " :");
11638            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11639            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11640                    new PersistentPreferredActivity(filter, activity));
11641            mSettings.writePackageRestrictionsLPr(userId);
11642        }
11643    }
11644
11645    @Override
11646    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11647        int callingUid = Binder.getCallingUid();
11648        if (callingUid != Process.SYSTEM_UID) {
11649            throw new SecurityException(
11650                    "clearPackagePersistentPreferredActivities can only be run by the system");
11651        }
11652        ArrayList<PersistentPreferredActivity> removed = null;
11653        boolean changed = false;
11654        synchronized (mPackages) {
11655            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11656                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11657                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11658                        .valueAt(i);
11659                if (userId != thisUserId) {
11660                    continue;
11661                }
11662                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11663                while (it.hasNext()) {
11664                    PersistentPreferredActivity ppa = it.next();
11665                    // Mark entry for removal only if it matches the package name.
11666                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11667                        if (removed == null) {
11668                            removed = new ArrayList<PersistentPreferredActivity>();
11669                        }
11670                        removed.add(ppa);
11671                    }
11672                }
11673                if (removed != null) {
11674                    for (int j=0; j<removed.size(); j++) {
11675                        PersistentPreferredActivity ppa = removed.get(j);
11676                        ppir.removeFilter(ppa);
11677                    }
11678                    changed = true;
11679                }
11680            }
11681
11682            if (changed) {
11683                mSettings.writePackageRestrictionsLPr(userId);
11684            }
11685        }
11686    }
11687
11688    @Override
11689    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11690            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11691        mContext.enforceCallingOrSelfPermission(
11692                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11693        int callingUid = Binder.getCallingUid();
11694        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11695        if (intentFilter.countActions() == 0) {
11696            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11697            return;
11698        }
11699        synchronized (mPackages) {
11700            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11701                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11702            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11703            mSettings.writePackageRestrictionsLPr(sourceUserId);
11704        }
11705    }
11706
11707    @Override
11708    public void addCrossProfileIntentsForPackage(String packageName,
11709            int sourceUserId, int targetUserId) {
11710        mContext.enforceCallingOrSelfPermission(
11711                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11712        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11713        mSettings.writePackageRestrictionsLPr(sourceUserId);
11714    }
11715
11716    @Override
11717    public void removeCrossProfileIntentsForPackage(String packageName,
11718            int sourceUserId, int targetUserId) {
11719        mContext.enforceCallingOrSelfPermission(
11720                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11721        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11722        mSettings.writePackageRestrictionsLPr(sourceUserId);
11723    }
11724
11725    @Override
11726    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11727            int ownerUserId) {
11728        mContext.enforceCallingOrSelfPermission(
11729                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11730        int callingUid = Binder.getCallingUid();
11731        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11732        int callingUserId = UserHandle.getUserId(callingUid);
11733        synchronized (mPackages) {
11734            CrossProfileIntentResolver resolver =
11735                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11736            HashSet<CrossProfileIntentFilter> set =
11737                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11738            for (CrossProfileIntentFilter filter : set) {
11739                if (filter.getOwnerPackage().equals(ownerPackage)
11740                        && filter.getOwnerUserId() == callingUserId) {
11741                    resolver.removeFilter(filter);
11742                }
11743            }
11744            mSettings.writePackageRestrictionsLPr(sourceUserId);
11745        }
11746    }
11747
11748    // Enforcing that callingUid is owning pkg on userId
11749    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11750        // The system owns everything.
11751        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11752            return;
11753        }
11754        int callingUserId = UserHandle.getUserId(callingUid);
11755        if (callingUserId != userId) {
11756            throw new SecurityException("calling uid " + callingUid
11757                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11758                    + callingUserId);
11759        }
11760        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11761        if (pi == null) {
11762            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11763                    + callingUserId);
11764        }
11765        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11766            throw new SecurityException("Calling uid " + callingUid
11767                    + " does not own package " + pkg);
11768        }
11769    }
11770
11771    @Override
11772    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11773        Intent intent = new Intent(Intent.ACTION_MAIN);
11774        intent.addCategory(Intent.CATEGORY_HOME);
11775
11776        final int callingUserId = UserHandle.getCallingUserId();
11777        List<ResolveInfo> list = queryIntentActivities(intent, null,
11778                PackageManager.GET_META_DATA, callingUserId);
11779        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11780                true, false, false, callingUserId);
11781
11782        allHomeCandidates.clear();
11783        if (list != null) {
11784            for (ResolveInfo ri : list) {
11785                allHomeCandidates.add(ri);
11786            }
11787        }
11788        return (preferred == null || preferred.activityInfo == null)
11789                ? null
11790                : new ComponentName(preferred.activityInfo.packageName,
11791                        preferred.activityInfo.name);
11792    }
11793
11794    /**
11795     * Check if calling UID is the current home app. This handles both the case
11796     * where the user has selected a specific home app, and where there is only
11797     * one home app.
11798     */
11799    public boolean checkCallerIsHomeApp() {
11800        final Intent intent = new Intent(Intent.ACTION_MAIN);
11801        intent.addCategory(Intent.CATEGORY_HOME);
11802
11803        final int callingUid = Binder.getCallingUid();
11804        final int callingUserId = UserHandle.getCallingUserId();
11805        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11806        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11807                false, false, callingUserId);
11808
11809        if (preferredHome != null) {
11810            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11811                return true;
11812            }
11813        } else {
11814            for (ResolveInfo info : allHomes) {
11815                if (callingUid == info.activityInfo.applicationInfo.uid) {
11816                    return true;
11817                }
11818            }
11819        }
11820
11821        return false;
11822    }
11823
11824    /**
11825     * Enforce that calling UID is the current home app. This handles both the
11826     * case where the user has selected a specific home app, and where there is
11827     * only one home app.
11828     */
11829    public void enforceCallerIsHomeApp() {
11830        if (!checkCallerIsHomeApp()) {
11831            throw new SecurityException("Caller is not currently selected home app");
11832        }
11833    }
11834
11835    @Override
11836    public void setApplicationEnabledSetting(String appPackageName,
11837            int newState, int flags, int userId, String callingPackage) {
11838        if (!sUserManager.exists(userId)) return;
11839        if (callingPackage == null) {
11840            callingPackage = Integer.toString(Binder.getCallingUid());
11841        }
11842        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11843    }
11844
11845    @Override
11846    public void setComponentEnabledSetting(ComponentName componentName,
11847            int newState, int flags, int userId) {
11848        if (!sUserManager.exists(userId)) return;
11849        setEnabledSetting(componentName.getPackageName(),
11850                componentName.getClassName(), newState, flags, userId, null);
11851    }
11852
11853    private void setEnabledSetting(final String packageName, String className, int newState,
11854            final int flags, int userId, String callingPackage) {
11855        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11856              || newState == COMPONENT_ENABLED_STATE_ENABLED
11857              || newState == COMPONENT_ENABLED_STATE_DISABLED
11858              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11859              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11860            throw new IllegalArgumentException("Invalid new component state: "
11861                    + newState);
11862        }
11863        PackageSetting pkgSetting;
11864        final int uid = Binder.getCallingUid();
11865        final int permission = mContext.checkCallingOrSelfPermission(
11866                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11867        enforceCrossUserPermission(uid, userId, false, "set enabled");
11868        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11869        boolean sendNow = false;
11870        boolean isApp = (className == null);
11871        String componentName = isApp ? packageName : className;
11872        int packageUid = -1;
11873        ArrayList<String> components;
11874
11875        // writer
11876        synchronized (mPackages) {
11877            pkgSetting = mSettings.mPackages.get(packageName);
11878            if (pkgSetting == null) {
11879                if (className == null) {
11880                    throw new IllegalArgumentException(
11881                            "Unknown package: " + packageName);
11882                }
11883                throw new IllegalArgumentException(
11884                        "Unknown component: " + packageName
11885                        + "/" + className);
11886            }
11887            // Allow root and verify that userId is not being specified by a different user
11888            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11889                throw new SecurityException(
11890                        "Permission Denial: attempt to change component state from pid="
11891                        + Binder.getCallingPid()
11892                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11893            }
11894            if (className == null) {
11895                // We're dealing with an application/package level state change
11896                if (pkgSetting.getEnabled(userId) == newState) {
11897                    // Nothing to do
11898                    return;
11899                }
11900                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11901                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11902                    // Don't care about who enables an app.
11903                    callingPackage = null;
11904                }
11905                pkgSetting.setEnabled(newState, userId, callingPackage);
11906                // pkgSetting.pkg.mSetEnabled = newState;
11907            } else {
11908                // We're dealing with a component level state change
11909                // First, verify that this is a valid class name.
11910                PackageParser.Package pkg = pkgSetting.pkg;
11911                if (pkg == null || !pkg.hasComponentClassName(className)) {
11912                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11913                        throw new IllegalArgumentException("Component class " + className
11914                                + " does not exist in " + packageName);
11915                    } else {
11916                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11917                                + className + " does not exist in " + packageName);
11918                    }
11919                }
11920                switch (newState) {
11921                case COMPONENT_ENABLED_STATE_ENABLED:
11922                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11923                        return;
11924                    }
11925                    break;
11926                case COMPONENT_ENABLED_STATE_DISABLED:
11927                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11928                        return;
11929                    }
11930                    break;
11931                case COMPONENT_ENABLED_STATE_DEFAULT:
11932                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11933                        return;
11934                    }
11935                    break;
11936                default:
11937                    Slog.e(TAG, "Invalid new component state: " + newState);
11938                    return;
11939                }
11940            }
11941            mSettings.writePackageRestrictionsLPr(userId);
11942            components = mPendingBroadcasts.get(userId, packageName);
11943            final boolean newPackage = components == null;
11944            if (newPackage) {
11945                components = new ArrayList<String>();
11946            }
11947            if (!components.contains(componentName)) {
11948                components.add(componentName);
11949            }
11950            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11951                sendNow = true;
11952                // Purge entry from pending broadcast list if another one exists already
11953                // since we are sending one right away.
11954                mPendingBroadcasts.remove(userId, packageName);
11955            } else {
11956                if (newPackage) {
11957                    mPendingBroadcasts.put(userId, packageName, components);
11958                }
11959                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11960                    // Schedule a message
11961                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11962                }
11963            }
11964        }
11965
11966        long callingId = Binder.clearCallingIdentity();
11967        try {
11968            if (sendNow) {
11969                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11970                sendPackageChangedBroadcast(packageName,
11971                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11972            }
11973        } finally {
11974            Binder.restoreCallingIdentity(callingId);
11975        }
11976    }
11977
11978    private void sendPackageChangedBroadcast(String packageName,
11979            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11980        if (DEBUG_INSTALL)
11981            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11982                    + componentNames);
11983        Bundle extras = new Bundle(4);
11984        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11985        String nameList[] = new String[componentNames.size()];
11986        componentNames.toArray(nameList);
11987        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11988        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11989        extras.putInt(Intent.EXTRA_UID, packageUid);
11990        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11991                new int[] {UserHandle.getUserId(packageUid)});
11992    }
11993
11994    @Override
11995    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11996        if (!sUserManager.exists(userId)) return;
11997        final int uid = Binder.getCallingUid();
11998        final int permission = mContext.checkCallingOrSelfPermission(
11999                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12000        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12001        enforceCrossUserPermission(uid, userId, true, "stop package");
12002        // writer
12003        synchronized (mPackages) {
12004            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12005                    uid, userId)) {
12006                scheduleWritePackageRestrictionsLocked(userId);
12007            }
12008        }
12009    }
12010
12011    @Override
12012    public String getInstallerPackageName(String packageName) {
12013        // reader
12014        synchronized (mPackages) {
12015            return mSettings.getInstallerPackageNameLPr(packageName);
12016        }
12017    }
12018
12019    @Override
12020    public int getApplicationEnabledSetting(String packageName, int userId) {
12021        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12022        int uid = Binder.getCallingUid();
12023        enforceCrossUserPermission(uid, userId, false, "get enabled");
12024        // reader
12025        synchronized (mPackages) {
12026            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12027        }
12028    }
12029
12030    @Override
12031    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12032        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12033        int uid = Binder.getCallingUid();
12034        enforceCrossUserPermission(uid, userId, false, "get component enabled");
12035        // reader
12036        synchronized (mPackages) {
12037            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12038        }
12039    }
12040
12041    @Override
12042    public void enterSafeMode() {
12043        enforceSystemOrRoot("Only the system can request entering safe mode");
12044
12045        if (!mSystemReady) {
12046            mSafeMode = true;
12047        }
12048    }
12049
12050    @Override
12051    public void systemReady() {
12052        mSystemReady = true;
12053
12054        // Read the compatibilty setting when the system is ready.
12055        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12056                mContext.getContentResolver(),
12057                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12058        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12059        if (DEBUG_SETTINGS) {
12060            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12061        }
12062
12063        synchronized (mPackages) {
12064            // Verify that all of the preferred activity components actually
12065            // exist.  It is possible for applications to be updated and at
12066            // that point remove a previously declared activity component that
12067            // had been set as a preferred activity.  We try to clean this up
12068            // the next time we encounter that preferred activity, but it is
12069            // possible for the user flow to never be able to return to that
12070            // situation so here we do a sanity check to make sure we haven't
12071            // left any junk around.
12072            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12073            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12074                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12075                removed.clear();
12076                for (PreferredActivity pa : pir.filterSet()) {
12077                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12078                        removed.add(pa);
12079                    }
12080                }
12081                if (removed.size() > 0) {
12082                    for (int r=0; r<removed.size(); r++) {
12083                        PreferredActivity pa = removed.get(r);
12084                        Slog.w(TAG, "Removing dangling preferred activity: "
12085                                + pa.mPref.mComponent);
12086                        pir.removeFilter(pa);
12087                    }
12088                    mSettings.writePackageRestrictionsLPr(
12089                            mSettings.mPreferredActivities.keyAt(i));
12090                }
12091            }
12092        }
12093        sUserManager.systemReady();
12094    }
12095
12096    @Override
12097    public boolean isSafeMode() {
12098        return mSafeMode;
12099    }
12100
12101    @Override
12102    public boolean hasSystemUidErrors() {
12103        return mHasSystemUidErrors;
12104    }
12105
12106    static String arrayToString(int[] array) {
12107        StringBuffer buf = new StringBuffer(128);
12108        buf.append('[');
12109        if (array != null) {
12110            for (int i=0; i<array.length; i++) {
12111                if (i > 0) buf.append(", ");
12112                buf.append(array[i]);
12113            }
12114        }
12115        buf.append(']');
12116        return buf.toString();
12117    }
12118
12119    static class DumpState {
12120        public static final int DUMP_LIBS = 1 << 0;
12121        public static final int DUMP_FEATURES = 1 << 1;
12122        public static final int DUMP_RESOLVERS = 1 << 2;
12123        public static final int DUMP_PERMISSIONS = 1 << 3;
12124        public static final int DUMP_PACKAGES = 1 << 4;
12125        public static final int DUMP_SHARED_USERS = 1 << 5;
12126        public static final int DUMP_MESSAGES = 1 << 6;
12127        public static final int DUMP_PROVIDERS = 1 << 7;
12128        public static final int DUMP_VERIFIERS = 1 << 8;
12129        public static final int DUMP_PREFERRED = 1 << 9;
12130        public static final int DUMP_PREFERRED_XML = 1 << 10;
12131        public static final int DUMP_KEYSETS = 1 << 11;
12132        public static final int DUMP_VERSION = 1 << 12;
12133        public static final int DUMP_INSTALLS = 1 << 13;
12134
12135        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12136
12137        private int mTypes;
12138
12139        private int mOptions;
12140
12141        private boolean mTitlePrinted;
12142
12143        private SharedUserSetting mSharedUser;
12144
12145        public boolean isDumping(int type) {
12146            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12147                return true;
12148            }
12149
12150            return (mTypes & type) != 0;
12151        }
12152
12153        public void setDump(int type) {
12154            mTypes |= type;
12155        }
12156
12157        public boolean isOptionEnabled(int option) {
12158            return (mOptions & option) != 0;
12159        }
12160
12161        public void setOptionEnabled(int option) {
12162            mOptions |= option;
12163        }
12164
12165        public boolean onTitlePrinted() {
12166            final boolean printed = mTitlePrinted;
12167            mTitlePrinted = true;
12168            return printed;
12169        }
12170
12171        public boolean getTitlePrinted() {
12172            return mTitlePrinted;
12173        }
12174
12175        public void setTitlePrinted(boolean enabled) {
12176            mTitlePrinted = enabled;
12177        }
12178
12179        public SharedUserSetting getSharedUser() {
12180            return mSharedUser;
12181        }
12182
12183        public void setSharedUser(SharedUserSetting user) {
12184            mSharedUser = user;
12185        }
12186    }
12187
12188    @Override
12189    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12190        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12191                != PackageManager.PERMISSION_GRANTED) {
12192            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12193                    + Binder.getCallingPid()
12194                    + ", uid=" + Binder.getCallingUid()
12195                    + " without permission "
12196                    + android.Manifest.permission.DUMP);
12197            return;
12198        }
12199
12200        DumpState dumpState = new DumpState();
12201        boolean fullPreferred = false;
12202        boolean checkin = false;
12203
12204        String packageName = null;
12205
12206        int opti = 0;
12207        while (opti < args.length) {
12208            String opt = args[opti];
12209            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12210                break;
12211            }
12212            opti++;
12213            if ("-a".equals(opt)) {
12214                // Right now we only know how to print all.
12215            } else if ("-h".equals(opt)) {
12216                pw.println("Package manager dump options:");
12217                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12218                pw.println("    --checkin: dump for a checkin");
12219                pw.println("    -f: print details of intent filters");
12220                pw.println("    -h: print this help");
12221                pw.println("  cmd may be one of:");
12222                pw.println("    l[ibraries]: list known shared libraries");
12223                pw.println("    f[ibraries]: list device features");
12224                pw.println("    k[eysets]: print known keysets");
12225                pw.println("    r[esolvers]: dump intent resolvers");
12226                pw.println("    perm[issions]: dump permissions");
12227                pw.println("    pref[erred]: print preferred package settings");
12228                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12229                pw.println("    prov[iders]: dump content providers");
12230                pw.println("    p[ackages]: dump installed packages");
12231                pw.println("    s[hared-users]: dump shared user IDs");
12232                pw.println("    m[essages]: print collected runtime messages");
12233                pw.println("    v[erifiers]: print package verifier info");
12234                pw.println("    version: print database version info");
12235                pw.println("    write: write current settings now");
12236                pw.println("    <package.name>: info about given package");
12237                pw.println("    installs: details about install sessions");
12238                return;
12239            } else if ("--checkin".equals(opt)) {
12240                checkin = true;
12241            } else if ("-f".equals(opt)) {
12242                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12243            } else {
12244                pw.println("Unknown argument: " + opt + "; use -h for help");
12245            }
12246        }
12247
12248        // Is the caller requesting to dump a particular piece of data?
12249        if (opti < args.length) {
12250            String cmd = args[opti];
12251            opti++;
12252            // Is this a package name?
12253            if ("android".equals(cmd) || cmd.contains(".")) {
12254                packageName = cmd;
12255                // When dumping a single package, we always dump all of its
12256                // filter information since the amount of data will be reasonable.
12257                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12258            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12259                dumpState.setDump(DumpState.DUMP_LIBS);
12260            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12261                dumpState.setDump(DumpState.DUMP_FEATURES);
12262            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12263                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12264            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12265                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12266            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12267                dumpState.setDump(DumpState.DUMP_PREFERRED);
12268            } else if ("preferred-xml".equals(cmd)) {
12269                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12270                if (opti < args.length && "--full".equals(args[opti])) {
12271                    fullPreferred = true;
12272                    opti++;
12273                }
12274            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12275                dumpState.setDump(DumpState.DUMP_PACKAGES);
12276            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12277                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12278            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12279                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12280            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12281                dumpState.setDump(DumpState.DUMP_MESSAGES);
12282            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12283                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12284            } else if ("version".equals(cmd)) {
12285                dumpState.setDump(DumpState.DUMP_VERSION);
12286            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12287                dumpState.setDump(DumpState.DUMP_KEYSETS);
12288            } else if ("write".equals(cmd)) {
12289                synchronized (mPackages) {
12290                    mSettings.writeLPr();
12291                    pw.println("Settings written.");
12292                    return;
12293                }
12294            } else if ("installs".equals(cmd)) {
12295                dumpState.setDump(DumpState.DUMP_INSTALLS);
12296            }
12297        }
12298
12299        if (checkin) {
12300            pw.println("vers,1");
12301        }
12302
12303        // reader
12304        synchronized (mPackages) {
12305            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12306                if (!checkin) {
12307                    if (dumpState.onTitlePrinted())
12308                        pw.println();
12309                    pw.println("Database versions:");
12310                    pw.print("  SDK Version:");
12311                    pw.print(" internal=");
12312                    pw.print(mSettings.mInternalSdkPlatform);
12313                    pw.print(" external=");
12314                    pw.println(mSettings.mExternalSdkPlatform);
12315                    pw.print("  DB Version:");
12316                    pw.print(" internal=");
12317                    pw.print(mSettings.mInternalDatabaseVersion);
12318                    pw.print(" external=");
12319                    pw.println(mSettings.mExternalDatabaseVersion);
12320                }
12321            }
12322
12323            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12324                if (!checkin) {
12325                    if (dumpState.onTitlePrinted())
12326                        pw.println();
12327                    pw.println("Verifiers:");
12328                    pw.print("  Required: ");
12329                    pw.print(mRequiredVerifierPackage);
12330                    pw.print(" (uid=");
12331                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12332                    pw.println(")");
12333                } else if (mRequiredVerifierPackage != null) {
12334                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12335                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12336                }
12337            }
12338
12339            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12340                boolean printedHeader = false;
12341                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12342                while (it.hasNext()) {
12343                    String name = it.next();
12344                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12345                    if (!checkin) {
12346                        if (!printedHeader) {
12347                            if (dumpState.onTitlePrinted())
12348                                pw.println();
12349                            pw.println("Libraries:");
12350                            printedHeader = true;
12351                        }
12352                        pw.print("  ");
12353                    } else {
12354                        pw.print("lib,");
12355                    }
12356                    pw.print(name);
12357                    if (!checkin) {
12358                        pw.print(" -> ");
12359                    }
12360                    if (ent.path != null) {
12361                        if (!checkin) {
12362                            pw.print("(jar) ");
12363                            pw.print(ent.path);
12364                        } else {
12365                            pw.print(",jar,");
12366                            pw.print(ent.path);
12367                        }
12368                    } else {
12369                        if (!checkin) {
12370                            pw.print("(apk) ");
12371                            pw.print(ent.apk);
12372                        } else {
12373                            pw.print(",apk,");
12374                            pw.print(ent.apk);
12375                        }
12376                    }
12377                    pw.println();
12378                }
12379            }
12380
12381            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12382                if (dumpState.onTitlePrinted())
12383                    pw.println();
12384                if (!checkin) {
12385                    pw.println("Features:");
12386                }
12387                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12388                while (it.hasNext()) {
12389                    String name = it.next();
12390                    if (!checkin) {
12391                        pw.print("  ");
12392                    } else {
12393                        pw.print("feat,");
12394                    }
12395                    pw.println(name);
12396                }
12397            }
12398
12399            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12400                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12401                        : "Activity Resolver Table:", "  ", packageName,
12402                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12403                    dumpState.setTitlePrinted(true);
12404                }
12405                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12406                        : "Receiver Resolver Table:", "  ", packageName,
12407                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12408                    dumpState.setTitlePrinted(true);
12409                }
12410                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12411                        : "Service Resolver Table:", "  ", packageName,
12412                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12413                    dumpState.setTitlePrinted(true);
12414                }
12415                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12416                        : "Provider Resolver Table:", "  ", packageName,
12417                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12418                    dumpState.setTitlePrinted(true);
12419                }
12420            }
12421
12422            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12423                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12424                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12425                    int user = mSettings.mPreferredActivities.keyAt(i);
12426                    if (pir.dump(pw,
12427                            dumpState.getTitlePrinted()
12428                                ? "\nPreferred Activities User " + user + ":"
12429                                : "Preferred Activities User " + user + ":", "  ",
12430                            packageName, true)) {
12431                        dumpState.setTitlePrinted(true);
12432                    }
12433                }
12434            }
12435
12436            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12437                pw.flush();
12438                FileOutputStream fout = new FileOutputStream(fd);
12439                BufferedOutputStream str = new BufferedOutputStream(fout);
12440                XmlSerializer serializer = new FastXmlSerializer();
12441                try {
12442                    serializer.setOutput(str, "utf-8");
12443                    serializer.startDocument(null, true);
12444                    serializer.setFeature(
12445                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12446                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12447                    serializer.endDocument();
12448                    serializer.flush();
12449                } catch (IllegalArgumentException e) {
12450                    pw.println("Failed writing: " + e);
12451                } catch (IllegalStateException e) {
12452                    pw.println("Failed writing: " + e);
12453                } catch (IOException e) {
12454                    pw.println("Failed writing: " + e);
12455                }
12456            }
12457
12458            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12459                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12460                if (packageName == null) {
12461                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12462                        if (iperm == 0) {
12463                            if (dumpState.onTitlePrinted())
12464                                pw.println();
12465                            pw.println("AppOp Permissions:");
12466                        }
12467                        pw.print("  AppOp Permission ");
12468                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12469                        pw.println(":");
12470                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12471                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12472                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12473                        }
12474                    }
12475                }
12476            }
12477
12478            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12479                boolean printedSomething = false;
12480                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12481                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12482                        continue;
12483                    }
12484                    if (!printedSomething) {
12485                        if (dumpState.onTitlePrinted())
12486                            pw.println();
12487                        pw.println("Registered ContentProviders:");
12488                        printedSomething = true;
12489                    }
12490                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12491                    pw.print("    "); pw.println(p.toString());
12492                }
12493                printedSomething = false;
12494                for (Map.Entry<String, PackageParser.Provider> entry :
12495                        mProvidersByAuthority.entrySet()) {
12496                    PackageParser.Provider p = entry.getValue();
12497                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12498                        continue;
12499                    }
12500                    if (!printedSomething) {
12501                        if (dumpState.onTitlePrinted())
12502                            pw.println();
12503                        pw.println("ContentProvider Authorities:");
12504                        printedSomething = true;
12505                    }
12506                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12507                    pw.print("    "); pw.println(p.toString());
12508                    if (p.info != null && p.info.applicationInfo != null) {
12509                        final String appInfo = p.info.applicationInfo.toString();
12510                        pw.print("      applicationInfo="); pw.println(appInfo);
12511                    }
12512                }
12513            }
12514
12515            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12516                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12517            }
12518
12519            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12520                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12521            }
12522
12523            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12524                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12525            }
12526
12527            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12528                if (dumpState.onTitlePrinted()) pw.println();
12529                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12530            }
12531
12532            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12533                if (dumpState.onTitlePrinted()) pw.println();
12534                mSettings.dumpReadMessagesLPr(pw, dumpState);
12535
12536                pw.println();
12537                pw.println("Package warning messages:");
12538                final File fname = getSettingsProblemFile();
12539                FileInputStream in = null;
12540                try {
12541                    in = new FileInputStream(fname);
12542                    final int avail = in.available();
12543                    final byte[] data = new byte[avail];
12544                    in.read(data);
12545                    pw.print(new String(data));
12546                } catch (FileNotFoundException e) {
12547                } catch (IOException e) {
12548                } finally {
12549                    if (in != null) {
12550                        try {
12551                            in.close();
12552                        } catch (IOException e) {
12553                        }
12554                    }
12555                }
12556            }
12557        }
12558    }
12559
12560    // ------- apps on sdcard specific code -------
12561    static final boolean DEBUG_SD_INSTALL = false;
12562
12563    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12564
12565    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12566
12567    private boolean mMediaMounted = false;
12568
12569    private String getEncryptKey() {
12570        try {
12571            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12572                    SD_ENCRYPTION_KEYSTORE_NAME);
12573            if (sdEncKey == null) {
12574                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12575                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12576                if (sdEncKey == null) {
12577                    Slog.e(TAG, "Failed to create encryption keys");
12578                    return null;
12579                }
12580            }
12581            return sdEncKey;
12582        } catch (NoSuchAlgorithmException nsae) {
12583            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12584            return null;
12585        } catch (IOException ioe) {
12586            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12587            return null;
12588        }
12589
12590    }
12591
12592    /* package */static String getTempContainerId() {
12593        int tmpIdx = 1;
12594        String list[] = PackageHelper.getSecureContainerList();
12595        if (list != null) {
12596            for (final String name : list) {
12597                // Ignore null and non-temporary container entries
12598                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12599                    continue;
12600                }
12601
12602                String subStr = name.substring(mTempContainerPrefix.length());
12603                try {
12604                    int cid = Integer.parseInt(subStr);
12605                    if (cid >= tmpIdx) {
12606                        tmpIdx = cid + 1;
12607                    }
12608                } catch (NumberFormatException e) {
12609                }
12610            }
12611        }
12612        return mTempContainerPrefix + tmpIdx;
12613    }
12614
12615    /*
12616     * Update media status on PackageManager.
12617     */
12618    @Override
12619    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12620        int callingUid = Binder.getCallingUid();
12621        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12622            throw new SecurityException("Media status can only be updated by the system");
12623        }
12624        // reader; this apparently protects mMediaMounted, but should probably
12625        // be a different lock in that case.
12626        synchronized (mPackages) {
12627            Log.i(TAG, "Updating external media status from "
12628                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12629                    + (mediaStatus ? "mounted" : "unmounted"));
12630            if (DEBUG_SD_INSTALL)
12631                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12632                        + ", mMediaMounted=" + mMediaMounted);
12633            if (mediaStatus == mMediaMounted) {
12634                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12635                        : 0, -1);
12636                mHandler.sendMessage(msg);
12637                return;
12638            }
12639            mMediaMounted = mediaStatus;
12640        }
12641        // Queue up an async operation since the package installation may take a
12642        // little while.
12643        mHandler.post(new Runnable() {
12644            public void run() {
12645                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12646            }
12647        });
12648    }
12649
12650    /**
12651     * Called by MountService when the initial ASECs to scan are available.
12652     * Should block until all the ASEC containers are finished being scanned.
12653     */
12654    public void scanAvailableAsecs() {
12655        updateExternalMediaStatusInner(true, false, false);
12656        if (mShouldRestoreconData) {
12657            SELinuxMMAC.setRestoreconDone();
12658            mShouldRestoreconData = false;
12659        }
12660    }
12661
12662    /*
12663     * Collect information of applications on external media, map them against
12664     * existing containers and update information based on current mount status.
12665     * Please note that we always have to report status if reportStatus has been
12666     * set to true especially when unloading packages.
12667     */
12668    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12669            boolean externalStorage) {
12670        // Collection of uids
12671        int uidArr[] = null;
12672        // Collection of stale containers
12673        HashSet<String> removeCids = new HashSet<String>();
12674        // Collection of packages on external media with valid containers.
12675        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12676        // Get list of secure containers.
12677        final String list[] = PackageHelper.getSecureContainerList();
12678        if (list == null || list.length == 0) {
12679            Log.i(TAG, "No secure containers on sdcard");
12680        } else {
12681            // Process list of secure containers and categorize them
12682            // as active or stale based on their package internal state.
12683            int uidList[] = new int[list.length];
12684            int num = 0;
12685            // reader
12686            synchronized (mPackages) {
12687                for (String cid : list) {
12688                    if (DEBUG_SD_INSTALL)
12689                        Log.i(TAG, "Processing container " + cid);
12690                    String pkgName = getAsecPackageName(cid);
12691                    if (pkgName == null) {
12692                        if (DEBUG_SD_INSTALL)
12693                            Log.i(TAG, "Container : " + cid + " stale");
12694                        removeCids.add(cid);
12695                        continue;
12696                    }
12697                    if (DEBUG_SD_INSTALL)
12698                        Log.i(TAG, "Looking for pkg : " + pkgName);
12699
12700                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12701                    if (ps == null) {
12702                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12703                        removeCids.add(cid);
12704                        continue;
12705                    }
12706
12707                    /*
12708                     * Skip packages that are not external if we're unmounting
12709                     * external storage.
12710                     */
12711                    if (externalStorage && !isMounted && !isExternal(ps)) {
12712                        continue;
12713                    }
12714
12715                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12716                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12717                    // The package status is changed only if the code path
12718                    // matches between settings and the container id.
12719                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12720                        if (DEBUG_SD_INSTALL) {
12721                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12722                                    + " at code path: " + ps.codePathString);
12723                        }
12724
12725                        // We do have a valid package installed on sdcard
12726                        processCids.put(args, ps.codePathString);
12727                        final int uid = ps.appId;
12728                        if (uid != -1) {
12729                            uidList[num++] = uid;
12730                        }
12731                    } else {
12732                        Log.i(TAG, "Deleting stale container for " + cid);
12733                        removeCids.add(cid);
12734                    }
12735                }
12736            }
12737
12738            if (num > 0) {
12739                // Sort uid list
12740                Arrays.sort(uidList, 0, num);
12741                // Throw away duplicates
12742                uidArr = new int[num];
12743                uidArr[0] = uidList[0];
12744                int di = 0;
12745                for (int i = 1; i < num; i++) {
12746                    if (uidList[i - 1] != uidList[i]) {
12747                        uidArr[di++] = uidList[i];
12748                    }
12749                }
12750            }
12751        }
12752        // Process packages with valid entries.
12753        if (isMounted) {
12754            if (DEBUG_SD_INSTALL)
12755                Log.i(TAG, "Loading packages");
12756            loadMediaPackages(processCids, uidArr, removeCids);
12757            startCleaningPackages();
12758        } else {
12759            if (DEBUG_SD_INSTALL)
12760                Log.i(TAG, "Unloading packages");
12761            unloadMediaPackages(processCids, uidArr, reportStatus);
12762        }
12763    }
12764
12765   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12766           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12767        int size = pkgList.size();
12768        if (size > 0) {
12769            // Send broadcasts here
12770            Bundle extras = new Bundle();
12771            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12772                    .toArray(new String[size]));
12773            if (uidArr != null) {
12774                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12775            }
12776            if (replacing) {
12777                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12778            }
12779            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12780                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12781            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12782        }
12783    }
12784
12785   /*
12786     * Look at potentially valid container ids from processCids If package
12787     * information doesn't match the one on record or package scanning fails,
12788     * the cid is added to list of removeCids. We currently don't delete stale
12789     * containers.
12790     */
12791   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12792            HashSet<String> removeCids) {
12793        ArrayList<String> pkgList = new ArrayList<String>();
12794        Set<AsecInstallArgs> keys = processCids.keySet();
12795        boolean doGc = false;
12796        for (AsecInstallArgs args : keys) {
12797            String codePath = processCids.get(args);
12798            if (DEBUG_SD_INSTALL)
12799                Log.i(TAG, "Loading container : " + args.cid);
12800            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12801            try {
12802                // Make sure there are no container errors first.
12803                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12804                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12805                            + " when installing from sdcard");
12806                    continue;
12807                }
12808                // Check code path here.
12809                if (codePath == null || !codePath.equals(args.getCodePath())) {
12810                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12811                            + " does not match one in settings " + codePath);
12812                    continue;
12813                }
12814                // Parse package
12815                int parseFlags = mDefParseFlags;
12816                if (args.isExternal()) {
12817                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12818                }
12819                if (args.isFwdLocked()) {
12820                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12821                }
12822
12823                doGc = true;
12824                synchronized (mInstallLock) {
12825                    PackageParser.Package pkg = null;
12826                    try {
12827                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null);
12828                    } catch (PackageManagerException e) {
12829                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12830                    }
12831                    // Scan the package
12832                    if (pkg != null) {
12833                        /*
12834                         * TODO why is the lock being held? doPostInstall is
12835                         * called in other places without the lock. This needs
12836                         * to be straightened out.
12837                         */
12838                        // writer
12839                        synchronized (mPackages) {
12840                            retCode = PackageManager.INSTALL_SUCCEEDED;
12841                            pkgList.add(pkg.packageName);
12842                            // Post process args
12843                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12844                                    pkg.applicationInfo.uid);
12845                        }
12846                    } else {
12847                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12848                    }
12849                }
12850
12851            } finally {
12852                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12853                    // Don't destroy container here. Wait till gc clears things
12854                    // up.
12855                    removeCids.add(args.cid);
12856                }
12857            }
12858        }
12859        // writer
12860        synchronized (mPackages) {
12861            // If the platform SDK has changed since the last time we booted,
12862            // we need to re-grant app permission to catch any new ones that
12863            // appear. This is really a hack, and means that apps can in some
12864            // cases get permissions that the user didn't initially explicitly
12865            // allow... it would be nice to have some better way to handle
12866            // this situation.
12867            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12868            if (regrantPermissions)
12869                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12870                        + mSdkVersion + "; regranting permissions for external storage");
12871            mSettings.mExternalSdkPlatform = mSdkVersion;
12872
12873            // Make sure group IDs have been assigned, and any permission
12874            // changes in other apps are accounted for
12875            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12876                    | (regrantPermissions
12877                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12878                            : 0));
12879
12880            mSettings.updateExternalDatabaseVersion();
12881
12882            // can downgrade to reader
12883            // Persist settings
12884            mSettings.writeLPr();
12885        }
12886        // Send a broadcast to let everyone know we are done processing
12887        if (pkgList.size() > 0) {
12888            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12889        }
12890        // Force gc to avoid any stale parser references that we might have.
12891        if (doGc) {
12892            Runtime.getRuntime().gc();
12893        }
12894        // List stale containers and destroy stale temporary containers.
12895        if (removeCids != null) {
12896            for (String cid : removeCids) {
12897                if (cid.startsWith(mTempContainerPrefix)) {
12898                    Log.i(TAG, "Destroying stale temporary container " + cid);
12899                    PackageHelper.destroySdDir(cid);
12900                } else {
12901                    Log.w(TAG, "Container " + cid + " is stale");
12902               }
12903           }
12904        }
12905    }
12906
12907   /*
12908     * Utility method to unload a list of specified containers
12909     */
12910    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12911        // Just unmount all valid containers.
12912        for (AsecInstallArgs arg : cidArgs) {
12913            synchronized (mInstallLock) {
12914                arg.doPostDeleteLI(false);
12915           }
12916       }
12917   }
12918
12919    /*
12920     * Unload packages mounted on external media. This involves deleting package
12921     * data from internal structures, sending broadcasts about diabled packages,
12922     * gc'ing to free up references, unmounting all secure containers
12923     * corresponding to packages on external media, and posting a
12924     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12925     * that we always have to post this message if status has been requested no
12926     * matter what.
12927     */
12928    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12929            final boolean reportStatus) {
12930        if (DEBUG_SD_INSTALL)
12931            Log.i(TAG, "unloading media packages");
12932        ArrayList<String> pkgList = new ArrayList<String>();
12933        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12934        final Set<AsecInstallArgs> keys = processCids.keySet();
12935        for (AsecInstallArgs args : keys) {
12936            String pkgName = args.getPackageName();
12937            if (DEBUG_SD_INSTALL)
12938                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12939            // Delete package internally
12940            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12941            synchronized (mInstallLock) {
12942                boolean res = deletePackageLI(pkgName, null, false, null, null,
12943                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12944                if (res) {
12945                    pkgList.add(pkgName);
12946                } else {
12947                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12948                    failedList.add(args);
12949                }
12950            }
12951        }
12952
12953        // reader
12954        synchronized (mPackages) {
12955            // We didn't update the settings after removing each package;
12956            // write them now for all packages.
12957            mSettings.writeLPr();
12958        }
12959
12960        // We have to absolutely send UPDATED_MEDIA_STATUS only
12961        // after confirming that all the receivers processed the ordered
12962        // broadcast when packages get disabled, force a gc to clean things up.
12963        // and unload all the containers.
12964        if (pkgList.size() > 0) {
12965            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12966                    new IIntentReceiver.Stub() {
12967                public void performReceive(Intent intent, int resultCode, String data,
12968                        Bundle extras, boolean ordered, boolean sticky,
12969                        int sendingUser) throws RemoteException {
12970                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12971                            reportStatus ? 1 : 0, 1, keys);
12972                    mHandler.sendMessage(msg);
12973                }
12974            });
12975        } else {
12976            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12977                    keys);
12978            mHandler.sendMessage(msg);
12979        }
12980    }
12981
12982    /** Binder call */
12983    @Override
12984    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12985            final int flags) {
12986        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12987        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12988        int returnCode = PackageManager.MOVE_SUCCEEDED;
12989        int currFlags = 0;
12990        int newFlags = 0;
12991        // reader
12992        synchronized (mPackages) {
12993            PackageParser.Package pkg = mPackages.get(packageName);
12994            if (pkg == null) {
12995                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12996            } else {
12997                // Disable moving fwd locked apps and system packages
12998                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12999                    Slog.w(TAG, "Cannot move system application");
13000                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13001                } else if (pkg.mOperationPending) {
13002                    Slog.w(TAG, "Attempt to move package which has pending operations");
13003                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13004                } else {
13005                    // Find install location first
13006                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13007                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13008                        Slog.w(TAG, "Ambigous flags specified for move location.");
13009                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13010                    } else {
13011                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
13012                                : PackageManager.INSTALL_INTERNAL;
13013                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
13014                                : PackageManager.INSTALL_INTERNAL;
13015
13016                        if (newFlags == currFlags) {
13017                            Slog.w(TAG, "No move required. Trying to move to same location");
13018                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13019                        } else {
13020                            if (isForwardLocked(pkg)) {
13021                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13022                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13023                            }
13024                        }
13025                    }
13026                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13027                        pkg.mOperationPending = true;
13028                    }
13029                }
13030            }
13031
13032            /*
13033             * TODO this next block probably shouldn't be inside the lock. We
13034             * can't guarantee these won't change after this is fired off
13035             * anyway.
13036             */
13037            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13038                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
13039                        returnCode);
13040            } else {
13041                Message msg = mHandler.obtainMessage(INIT_COPY);
13042                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
13043                final boolean multiArch = isMultiArch(pkg.applicationInfo);
13044                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
13045                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
13046                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
13047                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
13048                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
13049                msg.obj = mp;
13050                mHandler.sendMessage(msg);
13051            }
13052        }
13053    }
13054
13055    private void processPendingMove(final MoveParams mp, final int currentStatus) {
13056        // Queue up an async operation since the package deletion may take a
13057        // little while.
13058        mHandler.post(new Runnable() {
13059            public void run() {
13060                // TODO fix this; this does nothing.
13061                mHandler.removeCallbacks(this);
13062                int returnCode = currentStatus;
13063                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13064                    int uidArr[] = null;
13065                    ArrayList<String> pkgList = null;
13066                    synchronized (mPackages) {
13067                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13068                        if (pkg == null) {
13069                            Slog.w(TAG, " Package " + mp.packageName
13070                                    + " doesn't exist. Aborting move");
13071                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13072                        } else if (!mp.srcArgs.getCodePath().equals(
13073                                pkg.applicationInfo.getCodePath())) {
13074                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13075                                    + mp.srcArgs.getCodePath() + " to "
13076                                    + pkg.applicationInfo.getCodePath()
13077                                    + " Aborting move and returning error");
13078                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13079                        } else {
13080                            uidArr = new int[] {
13081                                pkg.applicationInfo.uid
13082                            };
13083                            pkgList = new ArrayList<String>();
13084                            pkgList.add(mp.packageName);
13085                        }
13086                    }
13087                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13088                        // Send resources unavailable broadcast
13089                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13090                        // Update package code and resource paths
13091                        synchronized (mInstallLock) {
13092                            synchronized (mPackages) {
13093                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13094                                // Recheck for package again.
13095                                if (pkg == null) {
13096                                    Slog.w(TAG, " Package " + mp.packageName
13097                                            + " doesn't exist. Aborting move");
13098                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13099                                } else if (!mp.srcArgs.getCodePath().equals(
13100                                        pkg.applicationInfo.getCodePath())) {
13101                                    Slog.w(TAG, "Package " + mp.packageName
13102                                            + " code path changed from " + mp.srcArgs.getCodePath()
13103                                            + " to " + pkg.applicationInfo.getCodePath()
13104                                            + " Aborting move and returning error");
13105                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13106                                } else {
13107                                    final String oldCodePath = pkg.codePath;
13108                                    final String newCodePath = mp.targetArgs.getCodePath();
13109                                    final String newResPath = mp.targetArgs.getResourcePath();
13110                                    // TODO: This assumes the new style of installation.
13111                                    // should we look at legacyNativeLibraryPath ?
13112                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13113                                    final File newNativeDir = new File(newNativeRoot);
13114
13115                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13116                                        // TODO(multiArch): Fix this so that it looks at the existing
13117                                        // recorded CPU abis from the package. There's no need for a separate
13118                                        // round of ABI scanning here.
13119                                        NativeLibraryHelper.Handle handle = null;
13120                                        try {
13121                                            handle = NativeLibraryHelper.Handle.create(
13122                                                    new File(newCodePath));
13123                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13124                                                    handle, Build.SUPPORTED_ABIS);
13125                                            if (abi >= 0) {
13126                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13127                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13128                                            }
13129                                        } catch (IOException ioe) {
13130                                            Slog.w(TAG, "Unable to extract native libs for package :"
13131                                                    + mp.packageName, ioe);
13132                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13133                                        } finally {
13134                                            IoUtils.closeQuietly(handle);
13135                                        }
13136                                    }
13137
13138                                    final int[] users = sUserManager.getUserIds();
13139                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13140                                        for (int user : users) {
13141                                            // TODO(multiArch): Fix this so that it links to the
13142                                            // correct directory. We're currently pointing to root. but we
13143                                            // must point to the arch specific subdirectory (if applicable).
13144                                            //
13145                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13146                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13147                                                    newNativeRoot, user) < 0) {
13148                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13149                                            }
13150                                        }
13151                                    }
13152
13153                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13154                                        pkg.codePath = newCodePath;
13155                                        pkg.baseCodePath = newCodePath;
13156                                        // Move dex files around
13157                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13158                                            // Moving of dex files failed. Set
13159                                            // error code and abort move.
13160                                            pkg.codePath = oldCodePath;
13161                                            pkg.baseCodePath = oldCodePath;
13162                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13163                                        }
13164                                    }
13165
13166                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13167                                        pkg.applicationInfo.setCodePath(newCodePath);
13168                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13169                                        pkg.applicationInfo.setSplitCodePaths(null);
13170                                        pkg.applicationInfo.setResourcePath(newResPath);
13171                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13172                                        pkg.applicationInfo.setSplitResourcePaths(null);
13173
13174                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13175                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13176                                        ps.codePathString = ps.codePath.getPath();
13177                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13178                                        ps.resourcePathString = ps.resourcePath.getPath();
13179
13180                                        // Note that we don't have to recalculate the primary and secondary
13181                                        // CPU ABIs because they must already have been calculated during the
13182                                        // initial install of the app.
13183                                        ps.legacyNativeLibraryPathString = null;
13184
13185                                        // Set the application info flag
13186                                        // correctly.
13187                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13188                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13189                                        } else {
13190                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13191                                        }
13192                                        ps.setFlags(pkg.applicationInfo.flags);
13193                                        mAppDirs.remove(oldCodePath);
13194                                        mAppDirs.put(newCodePath, pkg);
13195                                        // Persist settings
13196                                        mSettings.writeLPr();
13197                                    }
13198                                }
13199                            }
13200                        }
13201                        // Send resources available broadcast
13202                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13203                    }
13204                }
13205                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13206                    // Clean up failed installation
13207                    if (mp.targetArgs != null) {
13208                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13209                                -1);
13210                    }
13211                } else {
13212                    // Force a gc to clear things up.
13213                    Runtime.getRuntime().gc();
13214                    // Delete older code
13215                    synchronized (mInstallLock) {
13216                        mp.srcArgs.doPostDeleteLI(true);
13217                    }
13218                }
13219
13220                // Allow more operations on this file if we didn't fail because
13221                // an operation was already pending for this package.
13222                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13223                    synchronized (mPackages) {
13224                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13225                        if (pkg != null) {
13226                            pkg.mOperationPending = false;
13227                       }
13228                   }
13229                }
13230
13231                IPackageMoveObserver observer = mp.observer;
13232                if (observer != null) {
13233                    try {
13234                        observer.packageMoved(mp.packageName, returnCode);
13235                    } catch (RemoteException e) {
13236                        Log.i(TAG, "Observer no longer exists.");
13237                    }
13238                }
13239            }
13240        });
13241    }
13242
13243    @Override
13244    public boolean setInstallLocation(int loc) {
13245        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13246                null);
13247        if (getInstallLocation() == loc) {
13248            return true;
13249        }
13250        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13251                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13252            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13253                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13254            return true;
13255        }
13256        return false;
13257   }
13258
13259    @Override
13260    public int getInstallLocation() {
13261        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13262                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13263                PackageHelper.APP_INSTALL_AUTO);
13264    }
13265
13266    /** Called by UserManagerService */
13267    void cleanUpUserLILPw(int userHandle) {
13268        mDirtyUsers.remove(userHandle);
13269        mSettings.removeUserLPw(userHandle);
13270        mPendingBroadcasts.remove(userHandle);
13271        if (mInstaller != null) {
13272            // Technically, we shouldn't be doing this with the package lock
13273            // held.  However, this is very rare, and there is already so much
13274            // other disk I/O going on, that we'll let it slide for now.
13275            mInstaller.removeUserDataDirs(userHandle);
13276        }
13277        mUserNeedsBadging.delete(userHandle);
13278    }
13279
13280    /** Called by UserManagerService */
13281    void createNewUserLILPw(int userHandle, File path) {
13282        if (mInstaller != null) {
13283            mInstaller.createUserConfig(userHandle);
13284            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13285        }
13286    }
13287
13288    @Override
13289    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13290        mContext.enforceCallingOrSelfPermission(
13291                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13292                "Only package verification agents can read the verifier device identity");
13293
13294        synchronized (mPackages) {
13295            return mSettings.getVerifierDeviceIdentityLPw();
13296        }
13297    }
13298
13299    @Override
13300    public void setPermissionEnforced(String permission, boolean enforced) {
13301        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13302        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13303            synchronized (mPackages) {
13304                if (mSettings.mReadExternalStorageEnforced == null
13305                        || mSettings.mReadExternalStorageEnforced != enforced) {
13306                    mSettings.mReadExternalStorageEnforced = enforced;
13307                    mSettings.writeLPr();
13308                }
13309            }
13310            // kill any non-foreground processes so we restart them and
13311            // grant/revoke the GID.
13312            final IActivityManager am = ActivityManagerNative.getDefault();
13313            if (am != null) {
13314                final long token = Binder.clearCallingIdentity();
13315                try {
13316                    am.killProcessesBelowForeground("setPermissionEnforcement");
13317                } catch (RemoteException e) {
13318                } finally {
13319                    Binder.restoreCallingIdentity(token);
13320                }
13321            }
13322        } else {
13323            throw new IllegalArgumentException("No selective enforcement for " + permission);
13324        }
13325    }
13326
13327    @Override
13328    @Deprecated
13329    public boolean isPermissionEnforced(String permission) {
13330        return true;
13331    }
13332
13333    @Override
13334    public boolean isStorageLow() {
13335        final long token = Binder.clearCallingIdentity();
13336        try {
13337            final DeviceStorageMonitorInternal
13338                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13339            if (dsm != null) {
13340                return dsm.isMemoryLow();
13341            } else {
13342                return false;
13343            }
13344        } finally {
13345            Binder.restoreCallingIdentity(token);
13346        }
13347    }
13348
13349    @Override
13350    public IPackageInstaller getPackageInstaller() {
13351        return mInstallerService;
13352    }
13353
13354    private boolean userNeedsBadging(int userId) {
13355        int index = mUserNeedsBadging.indexOfKey(userId);
13356        if (index < 0) {
13357            final UserInfo userInfo;
13358            final long token = Binder.clearCallingIdentity();
13359            try {
13360                userInfo = sUserManager.getUserInfo(userId);
13361            } finally {
13362                Binder.restoreCallingIdentity(token);
13363            }
13364            final boolean b;
13365            if (userInfo != null && userInfo.isManagedProfile()) {
13366                b = true;
13367            } else {
13368                b = false;
13369            }
13370            mUserNeedsBadging.put(userId, b);
13371            return b;
13372        }
13373        return mUserNeedsBadging.valueAt(index);
13374    }
13375
13376    @Override
13377    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13378        if (packageName == null || alias == null) {
13379            return null;
13380        }
13381        synchronized(mPackages) {
13382            final PackageParser.Package pkg = mPackages.get(packageName);
13383            if (pkg == null) {
13384                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13385                throw new IllegalArgumentException("Unknown package: " + packageName);
13386            }
13387            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13388                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13389                throw new SecurityException("May not access KeySets defined by"
13390                        + " aliases in other applications.");
13391            }
13392            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13393            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13394        }
13395    }
13396
13397    @Override
13398    public KeySetHandle getSigningKeySet(String packageName) {
13399        if (packageName == null) {
13400            return null;
13401        }
13402        synchronized(mPackages) {
13403            final PackageParser.Package pkg = mPackages.get(packageName);
13404            if (pkg == null) {
13405                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13406                throw new IllegalArgumentException("Unknown package: " + packageName);
13407            }
13408            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13409                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13410                throw new SecurityException("May not access signing KeySet of other apps.");
13411            }
13412            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13413            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13414        }
13415    }
13416
13417    @Override
13418    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13419        if (packageName == null || ks == null) {
13420            return false;
13421        }
13422        synchronized(mPackages) {
13423            final PackageParser.Package pkg = mPackages.get(packageName);
13424            if (pkg == null) {
13425                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13426                throw new IllegalArgumentException("Unknown package: " + packageName);
13427            }
13428            if (ks instanceof KeySetHandle) {
13429                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13430                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13431            }
13432            return false;
13433        }
13434    }
13435
13436    @Override
13437    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13438        if (packageName == null || ks == null) {
13439            return false;
13440        }
13441        synchronized(mPackages) {
13442            final PackageParser.Package pkg = mPackages.get(packageName);
13443            if (pkg == null) {
13444                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13445                throw new IllegalArgumentException("Unknown package: " + packageName);
13446            }
13447            if (ks instanceof KeySetHandle) {
13448                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13449                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13450            }
13451            return false;
13452        }
13453    }
13454}
13455