PackageManagerService.java revision 54edd1cdc45773dc5c208d9dc4f26b768d200901
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    // Special value for {@code PackageParser.Package#cpuAbiOverride} to indicate
257    // that the cpuAbiOverride must be clear.
258    private static final String CLEAR_ABI_OVERRIDE = "-";
259
260    static final int SCAN_MONITOR = 1<<0;
261    static final int SCAN_NO_DEX = 1<<1;
262    static final int SCAN_FORCE_DEX = 1<<2;
263    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
264    static final int SCAN_NEW_INSTALL = 1<<4;
265    static final int SCAN_NO_PATHS = 1<<5;
266    static final int SCAN_UPDATE_TIME = 1<<6;
267    static final int SCAN_DEFER_DEX = 1<<7;
268    static final int SCAN_BOOTING = 1<<8;
269    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
270    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
271
272    static final int REMOVE_CHATTY = 1<<16;
273
274    /**
275     * Timeout (in milliseconds) after which the watchdog should declare that
276     * our handler thread is wedged.  The usual default for such things is one
277     * minute but we sometimes do very lengthy I/O operations on this thread,
278     * such as installing multi-gigabyte applications, so ours needs to be longer.
279     */
280    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
281
282    /**
283     * Whether verification is enabled by default.
284     */
285    private static final boolean DEFAULT_VERIFY_ENABLE = true;
286
287    /**
288     * The default maximum time to wait for the verification agent to return in
289     * milliseconds.
290     */
291    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
292
293    /**
294     * The default response for package verification timeout.
295     *
296     * This can be either PackageManager.VERIFICATION_ALLOW or
297     * PackageManager.VERIFICATION_REJECT.
298     */
299    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
300
301    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
302
303    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
304            DEFAULT_CONTAINER_PACKAGE,
305            "com.android.defcontainer.DefaultContainerService");
306
307    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
308
309    private static final String LIB_DIR_NAME = "lib";
310    private static final String LIB64_DIR_NAME = "lib64";
311
312    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
313
314    static final String mTempContainerPrefix = "smdl2tmp";
315
316    private static String sPreferredInstructionSet;
317
318    final ServiceThread mHandlerThread;
319
320    private static final String IDMAP_PREFIX = "/data/resource-cache/";
321    private static final String IDMAP_SUFFIX = "@idmap";
322
323    final PackageHandler mHandler;
324
325    final int mSdkVersion = Build.VERSION.SDK_INT;
326
327    final Context mContext;
328    final boolean mFactoryTest;
329    final boolean mOnlyCore;
330    final DisplayMetrics mMetrics;
331    final int mDefParseFlags;
332    final String[] mSeparateProcesses;
333
334    // This is where all application persistent data goes.
335    final File mAppDataDir;
336
337    // This is where all application persistent data goes for secondary users.
338    final File mUserAppDataDir;
339
340    /** The location for ASEC container files on internal storage. */
341    final String mAsecInternalPath;
342
343    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
344    // LOCK HELD.  Can be called with mInstallLock held.
345    final Installer mInstaller;
346
347    /** Directory where installed third-party apps stored */
348    final File mAppInstallDir;
349
350    /**
351     * Directory to which applications installed internally have their
352     * 32 bit native libraries copied.
353     */
354    private File mAppLib32InstallDir;
355
356    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
357    // apps.
358    final File mDrmAppPrivateInstallDir;
359
360    // ----------------------------------------------------------------
361
362    // Lock for state used when installing and doing other long running
363    // operations.  Methods that must be called with this lock held have
364    // the suffix "LI".
365    final Object mInstallLock = new Object();
366
367    // These are the directories in the 3rd party applications installed dir
368    // that we have currently loaded packages from.  Keys are the application's
369    // installed zip file (absolute codePath), and values are Package.
370    final HashMap<String, PackageParser.Package> mAppDirs =
371            new HashMap<String, PackageParser.Package>();
372
373    // ----------------------------------------------------------------
374
375    // Keys are String (package name), values are Package.  This also serves
376    // as the lock for the global state.  Methods that must be called with
377    // this lock held have the prefix "LP".
378    final HashMap<String, PackageParser.Package> mPackages =
379            new HashMap<String, PackageParser.Package>();
380
381    // Tracks available target package names -> overlay package paths.
382    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
383        new HashMap<String, HashMap<String, PackageParser.Package>>();
384
385    final Settings mSettings;
386    boolean mRestoredSettings;
387
388    // System configuration read by SystemConfig.
389    final int[] mGlobalGids;
390    final SparseArray<HashSet<String>> mSystemPermissions;
391    final HashMap<String, FeatureInfo> mAvailableFeatures;
392
393    // If mac_permissions.xml was found for seinfo labeling.
394    boolean mFoundPolicyFile;
395
396    // If a recursive restorecon of /data/data/<pkg> is needed.
397    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
398
399    public static final class SharedLibraryEntry {
400        public final String path;
401        public final String apk;
402
403        SharedLibraryEntry(String _path, String _apk) {
404            path = _path;
405            apk = _apk;
406        }
407    }
408
409    // Currently known shared libraries.
410    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
411            new HashMap<String, SharedLibraryEntry>();
412
413    // All available activities, for your resolving pleasure.
414    final ActivityIntentResolver mActivities =
415            new ActivityIntentResolver();
416
417    // All available receivers, for your resolving pleasure.
418    final ActivityIntentResolver mReceivers =
419            new ActivityIntentResolver();
420
421    // All available services, for your resolving pleasure.
422    final ServiceIntentResolver mServices = new ServiceIntentResolver();
423
424    // All available providers, for your resolving pleasure.
425    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
426
427    // Mapping from provider base names (first directory in content URI codePath)
428    // to the provider information.
429    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
430            new HashMap<String, PackageParser.Provider>();
431
432    // Mapping from instrumentation class names to info about them.
433    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
434            new HashMap<ComponentName, PackageParser.Instrumentation>();
435
436    // Mapping from permission names to info about them.
437    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
438            new HashMap<String, PackageParser.PermissionGroup>();
439
440    // Packages whose data we have transfered into another package, thus
441    // should no longer exist.
442    final HashSet<String> mTransferedPackages = new HashSet<String>();
443
444    // Broadcast actions that are only available to the system.
445    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
446
447    /** List of packages waiting for verification. */
448    final SparseArray<PackageVerificationState> mPendingVerification
449            = new SparseArray<PackageVerificationState>();
450
451    /** Set of packages associated with each app op permission. */
452    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
453
454    final PackageInstallerService mInstallerService;
455
456    HashSet<PackageParser.Package> mDeferredDexOpt = null;
457
458    // Cache of users who need badging.
459    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
460
461    /** Token for keys in mPendingVerification. */
462    private int mPendingVerificationToken = 0;
463
464    boolean mSystemReady;
465    boolean mSafeMode;
466    boolean mHasSystemUidErrors;
467
468    ApplicationInfo mAndroidApplication;
469    final ActivityInfo mResolveActivity = new ActivityInfo();
470    final ResolveInfo mResolveInfo = new ResolveInfo();
471    ComponentName mResolveComponentName;
472    PackageParser.Package mPlatformPackage;
473    ComponentName mCustomResolverComponentName;
474
475    boolean mResolverReplaced = false;
476
477    // Set of pending broadcasts for aggregating enable/disable of components.
478    static class PendingPackageBroadcasts {
479        // for each user id, a map of <package name -> components within that package>
480        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
481
482        public PendingPackageBroadcasts() {
483            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
484        }
485
486        public ArrayList<String> get(int userId, String packageName) {
487            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
488            return packages.get(packageName);
489        }
490
491        public void put(int userId, String packageName, ArrayList<String> components) {
492            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
493            packages.put(packageName, components);
494        }
495
496        public void remove(int userId, String packageName) {
497            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
498            if (packages != null) {
499                packages.remove(packageName);
500            }
501        }
502
503        public void remove(int userId) {
504            mUidMap.remove(userId);
505        }
506
507        public int userIdCount() {
508            return mUidMap.size();
509        }
510
511        public int userIdAt(int n) {
512            return mUidMap.keyAt(n);
513        }
514
515        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
516            return mUidMap.get(userId);
517        }
518
519        public int size() {
520            // total number of pending broadcast entries across all userIds
521            int num = 0;
522            for (int i = 0; i< mUidMap.size(); i++) {
523                num += mUidMap.valueAt(i).size();
524            }
525            return num;
526        }
527
528        public void clear() {
529            mUidMap.clear();
530        }
531
532        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
533            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
534            if (map == null) {
535                map = new HashMap<String, ArrayList<String>>();
536                mUidMap.put(userId, map);
537            }
538            return map;
539        }
540    }
541    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
542
543    // Service Connection to remote media container service to copy
544    // package uri's from external media onto secure containers
545    // or internal storage.
546    private IMediaContainerService mContainerService = null;
547
548    static final int SEND_PENDING_BROADCAST = 1;
549    static final int MCS_BOUND = 3;
550    static final int END_COPY = 4;
551    static final int INIT_COPY = 5;
552    static final int MCS_UNBIND = 6;
553    static final int START_CLEANING_PACKAGE = 7;
554    static final int FIND_INSTALL_LOC = 8;
555    static final int POST_INSTALL = 9;
556    static final int MCS_RECONNECT = 10;
557    static final int MCS_GIVE_UP = 11;
558    static final int UPDATED_MEDIA_STATUS = 12;
559    static final int WRITE_SETTINGS = 13;
560    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
561    static final int PACKAGE_VERIFIED = 15;
562    static final int CHECK_PENDING_VERIFICATION = 16;
563
564    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
565
566    // Delay time in millisecs
567    static final int BROADCAST_DELAY = 10 * 1000;
568
569    static UserManagerService sUserManager;
570
571    // Stores a list of users whose package restrictions file needs to be updated
572    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
573
574    final private DefaultContainerConnection mDefContainerConn =
575            new DefaultContainerConnection();
576    class DefaultContainerConnection implements ServiceConnection {
577        public void onServiceConnected(ComponentName name, IBinder service) {
578            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
579            IMediaContainerService imcs =
580                IMediaContainerService.Stub.asInterface(service);
581            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
582        }
583
584        public void onServiceDisconnected(ComponentName name) {
585            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
586        }
587    };
588
589    // Recordkeeping of restore-after-install operations that are currently in flight
590    // between the Package Manager and the Backup Manager
591    class PostInstallData {
592        public InstallArgs args;
593        public PackageInstalledInfo res;
594
595        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
596            args = _a;
597            res = _r;
598        }
599    };
600    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
601    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
602
603    private final String mRequiredVerifierPackage;
604
605    private final PackageUsage mPackageUsage = new PackageUsage();
606
607    private class PackageUsage {
608        private static final int WRITE_INTERVAL
609            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
610
611        private final Object mFileLock = new Object();
612        private final AtomicLong mLastWritten = new AtomicLong(0);
613        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
614
615        private boolean mIsHistoricalPackageUsageAvailable = true;
616
617        boolean isHistoricalPackageUsageAvailable() {
618            return mIsHistoricalPackageUsageAvailable;
619        }
620
621        void write(boolean force) {
622            if (force) {
623                writeInternal();
624                return;
625            }
626            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
627                && !DEBUG_DEXOPT) {
628                return;
629            }
630            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
631                new Thread("PackageUsage_DiskWriter") {
632                    @Override
633                    public void run() {
634                        try {
635                            writeInternal();
636                        } finally {
637                            mBackgroundWriteRunning.set(false);
638                        }
639                    }
640                }.start();
641            }
642        }
643
644        private void writeInternal() {
645            synchronized (mPackages) {
646                synchronized (mFileLock) {
647                    AtomicFile file = getFile();
648                    FileOutputStream f = null;
649                    try {
650                        f = file.startWrite();
651                        BufferedOutputStream out = new BufferedOutputStream(f);
652                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
653                        StringBuilder sb = new StringBuilder();
654                        for (PackageParser.Package pkg : mPackages.values()) {
655                            if (pkg.mLastPackageUsageTimeInMills == 0) {
656                                continue;
657                            }
658                            sb.setLength(0);
659                            sb.append(pkg.packageName);
660                            sb.append(' ');
661                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
662                            sb.append('\n');
663                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
664                        }
665                        out.flush();
666                        file.finishWrite(f);
667                    } catch (IOException e) {
668                        if (f != null) {
669                            file.failWrite(f);
670                        }
671                        Log.e(TAG, "Failed to write package usage times", e);
672                    }
673                }
674            }
675            mLastWritten.set(SystemClock.elapsedRealtime());
676        }
677
678        void readLP() {
679            synchronized (mFileLock) {
680                AtomicFile file = getFile();
681                BufferedInputStream in = null;
682                try {
683                    in = new BufferedInputStream(file.openRead());
684                    StringBuffer sb = new StringBuffer();
685                    while (true) {
686                        String packageName = readToken(in, sb, ' ');
687                        if (packageName == null) {
688                            break;
689                        }
690                        String timeInMillisString = readToken(in, sb, '\n');
691                        if (timeInMillisString == null) {
692                            throw new IOException("Failed to find last usage time for package "
693                                                  + packageName);
694                        }
695                        PackageParser.Package pkg = mPackages.get(packageName);
696                        if (pkg == null) {
697                            continue;
698                        }
699                        long timeInMillis;
700                        try {
701                            timeInMillis = Long.parseLong(timeInMillisString.toString());
702                        } catch (NumberFormatException e) {
703                            throw new IOException("Failed to parse " + timeInMillisString
704                                                  + " as a long.", e);
705                        }
706                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
707                    }
708                } catch (FileNotFoundException expected) {
709                    mIsHistoricalPackageUsageAvailable = false;
710                } catch (IOException e) {
711                    Log.w(TAG, "Failed to read package usage times", e);
712                } finally {
713                    IoUtils.closeQuietly(in);
714                }
715            }
716            mLastWritten.set(SystemClock.elapsedRealtime());
717        }
718
719        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
720                throws IOException {
721            sb.setLength(0);
722            while (true) {
723                int ch = in.read();
724                if (ch == -1) {
725                    if (sb.length() == 0) {
726                        return null;
727                    }
728                    throw new IOException("Unexpected EOF");
729                }
730                if (ch == endOfToken) {
731                    return sb.toString();
732                }
733                sb.append((char)ch);
734            }
735        }
736
737        private AtomicFile getFile() {
738            File dataDir = Environment.getDataDirectory();
739            File systemDir = new File(dataDir, "system");
740            File fname = new File(systemDir, "package-usage.list");
741            return new AtomicFile(fname);
742        }
743    }
744
745    class PackageHandler extends Handler {
746        private boolean mBound = false;
747        final ArrayList<HandlerParams> mPendingInstalls =
748            new ArrayList<HandlerParams>();
749
750        private boolean connectToService() {
751            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
752                    " DefaultContainerService");
753            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
754            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
755            if (mContext.bindServiceAsUser(service, mDefContainerConn,
756                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
757                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
758                mBound = true;
759                return true;
760            }
761            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
762            return false;
763        }
764
765        private void disconnectService() {
766            mContainerService = null;
767            mBound = false;
768            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
769            mContext.unbindService(mDefContainerConn);
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771        }
772
773        PackageHandler(Looper looper) {
774            super(looper);
775        }
776
777        public void handleMessage(Message msg) {
778            try {
779                doHandleMessage(msg);
780            } finally {
781                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
782            }
783        }
784
785        void doHandleMessage(Message msg) {
786            switch (msg.what) {
787                case INIT_COPY: {
788                    HandlerParams params = (HandlerParams) msg.obj;
789                    int idx = mPendingInstalls.size();
790                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
791                    // If a bind was already initiated we dont really
792                    // need to do anything. The pending install
793                    // will be processed later on.
794                    if (!mBound) {
795                        // If this is the only one pending we might
796                        // have to bind to the service again.
797                        if (!connectToService()) {
798                            Slog.e(TAG, "Failed to bind to media container service");
799                            params.serviceError();
800                            return;
801                        } else {
802                            // Once we bind to the service, the first
803                            // pending request will be processed.
804                            mPendingInstalls.add(idx, params);
805                        }
806                    } else {
807                        mPendingInstalls.add(idx, params);
808                        // Already bound to the service. Just make
809                        // sure we trigger off processing the first request.
810                        if (idx == 0) {
811                            mHandler.sendEmptyMessage(MCS_BOUND);
812                        }
813                    }
814                    break;
815                }
816                case MCS_BOUND: {
817                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
818                    if (msg.obj != null) {
819                        mContainerService = (IMediaContainerService) msg.obj;
820                    }
821                    if (mContainerService == null) {
822                        // Something seriously wrong. Bail out
823                        Slog.e(TAG, "Cannot bind to media container service");
824                        for (HandlerParams params : mPendingInstalls) {
825                            // Indicate service bind error
826                            params.serviceError();
827                        }
828                        mPendingInstalls.clear();
829                    } else if (mPendingInstalls.size() > 0) {
830                        HandlerParams params = mPendingInstalls.get(0);
831                        if (params != null) {
832                            if (params.startCopy()) {
833                                // We are done...  look for more work or to
834                                // go idle.
835                                if (DEBUG_SD_INSTALL) Log.i(TAG,
836                                        "Checking for more work or unbind...");
837                                // Delete pending install
838                                if (mPendingInstalls.size() > 0) {
839                                    mPendingInstalls.remove(0);
840                                }
841                                if (mPendingInstalls.size() == 0) {
842                                    if (mBound) {
843                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
844                                                "Posting delayed MCS_UNBIND");
845                                        removeMessages(MCS_UNBIND);
846                                        Message ubmsg = obtainMessage(MCS_UNBIND);
847                                        // Unbind after a little delay, to avoid
848                                        // continual thrashing.
849                                        sendMessageDelayed(ubmsg, 10000);
850                                    }
851                                } else {
852                                    // There are more pending requests in queue.
853                                    // Just post MCS_BOUND message to trigger processing
854                                    // of next pending install.
855                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
856                                            "Posting MCS_BOUND for next work");
857                                    mHandler.sendEmptyMessage(MCS_BOUND);
858                                }
859                            }
860                        }
861                    } else {
862                        // Should never happen ideally.
863                        Slog.w(TAG, "Empty queue");
864                    }
865                    break;
866                }
867                case MCS_RECONNECT: {
868                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
869                    if (mPendingInstalls.size() > 0) {
870                        if (mBound) {
871                            disconnectService();
872                        }
873                        if (!connectToService()) {
874                            Slog.e(TAG, "Failed to bind to media container service");
875                            for (HandlerParams params : mPendingInstalls) {
876                                // Indicate service bind error
877                                params.serviceError();
878                            }
879                            mPendingInstalls.clear();
880                        }
881                    }
882                    break;
883                }
884                case MCS_UNBIND: {
885                    // If there is no actual work left, then time to unbind.
886                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
887
888                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
889                        if (mBound) {
890                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
891
892                            disconnectService();
893                        }
894                    } else if (mPendingInstalls.size() > 0) {
895                        // There are more pending requests in queue.
896                        // Just post MCS_BOUND message to trigger processing
897                        // of next pending install.
898                        mHandler.sendEmptyMessage(MCS_BOUND);
899                    }
900
901                    break;
902                }
903                case MCS_GIVE_UP: {
904                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
905                    mPendingInstalls.remove(0);
906                    break;
907                }
908                case SEND_PENDING_BROADCAST: {
909                    String packages[];
910                    ArrayList<String> components[];
911                    int size = 0;
912                    int uids[];
913                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
914                    synchronized (mPackages) {
915                        if (mPendingBroadcasts == null) {
916                            return;
917                        }
918                        size = mPendingBroadcasts.size();
919                        if (size <= 0) {
920                            // Nothing to be done. Just return
921                            return;
922                        }
923                        packages = new String[size];
924                        components = new ArrayList[size];
925                        uids = new int[size];
926                        int i = 0;  // filling out the above arrays
927
928                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
929                            int packageUserId = mPendingBroadcasts.userIdAt(n);
930                            Iterator<Map.Entry<String, ArrayList<String>>> it
931                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
932                                            .entrySet().iterator();
933                            while (it.hasNext() && i < size) {
934                                Map.Entry<String, ArrayList<String>> ent = it.next();
935                                packages[i] = ent.getKey();
936                                components[i] = ent.getValue();
937                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
938                                uids[i] = (ps != null)
939                                        ? UserHandle.getUid(packageUserId, ps.appId)
940                                        : -1;
941                                i++;
942                            }
943                        }
944                        size = i;
945                        mPendingBroadcasts.clear();
946                    }
947                    // Send broadcasts
948                    for (int i = 0; i < size; i++) {
949                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
950                    }
951                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
952                    break;
953                }
954                case START_CLEANING_PACKAGE: {
955                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
956                    final String packageName = (String)msg.obj;
957                    final int userId = msg.arg1;
958                    final boolean andCode = msg.arg2 != 0;
959                    synchronized (mPackages) {
960                        if (userId == UserHandle.USER_ALL) {
961                            int[] users = sUserManager.getUserIds();
962                            for (int user : users) {
963                                mSettings.addPackageToCleanLPw(
964                                        new PackageCleanItem(user, packageName, andCode));
965                            }
966                        } else {
967                            mSettings.addPackageToCleanLPw(
968                                    new PackageCleanItem(userId, packageName, andCode));
969                        }
970                    }
971                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
972                    startCleaningPackages();
973                } break;
974                case POST_INSTALL: {
975                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
976                    PostInstallData data = mRunningInstalls.get(msg.arg1);
977                    mRunningInstalls.delete(msg.arg1);
978                    boolean deleteOld = false;
979
980                    if (data != null) {
981                        InstallArgs args = data.args;
982                        PackageInstalledInfo res = data.res;
983
984                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
985                            res.removedInfo.sendBroadcast(false, true, false);
986                            Bundle extras = new Bundle(1);
987                            extras.putInt(Intent.EXTRA_UID, res.uid);
988                            // Determine the set of users who are adding this
989                            // package for the first time vs. those who are seeing
990                            // an update.
991                            int[] firstUsers;
992                            int[] updateUsers = new int[0];
993                            if (res.origUsers == null || res.origUsers.length == 0) {
994                                firstUsers = res.newUsers;
995                            } else {
996                                firstUsers = new int[0];
997                                for (int i=0; i<res.newUsers.length; i++) {
998                                    int user = res.newUsers[i];
999                                    boolean isNew = true;
1000                                    for (int j=0; j<res.origUsers.length; j++) {
1001                                        if (res.origUsers[j] == user) {
1002                                            isNew = false;
1003                                            break;
1004                                        }
1005                                    }
1006                                    if (isNew) {
1007                                        int[] newFirst = new int[firstUsers.length+1];
1008                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1009                                                firstUsers.length);
1010                                        newFirst[firstUsers.length] = user;
1011                                        firstUsers = newFirst;
1012                                    } else {
1013                                        int[] newUpdate = new int[updateUsers.length+1];
1014                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1015                                                updateUsers.length);
1016                                        newUpdate[updateUsers.length] = user;
1017                                        updateUsers = newUpdate;
1018                                    }
1019                                }
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, firstUsers);
1024                            final boolean update = res.removedInfo.removedPackage != null;
1025                            if (update) {
1026                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1027                            }
1028                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1029                                    res.pkg.applicationInfo.packageName,
1030                                    extras, null, null, updateUsers);
1031                            if (update) {
1032                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1033                                        res.pkg.applicationInfo.packageName,
1034                                        extras, null, null, updateUsers);
1035                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1036                                        null, null,
1037                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1038
1039                                // treat asec-hosted packages like removable media on upgrade
1040                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1041                                    if (DEBUG_INSTALL) {
1042                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1043                                                + " is ASEC-hosted -> AVAILABLE");
1044                                    }
1045                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1046                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1047                                    pkgList.add(res.pkg.applicationInfo.packageName);
1048                                    sendResourcesChangedBroadcast(true, true,
1049                                            pkgList,uidArray, null);
1050                                }
1051                            }
1052                            if (res.removedInfo.args != null) {
1053                                // Remove the replaced package's older resources safely now
1054                                deleteOld = true;
1055                            }
1056
1057                            // Log current value of "unknown sources" setting
1058                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1059                                getUnknownSourcesSettings());
1060                        }
1061                        // Force a gc to clear up things
1062                        Runtime.getRuntime().gc();
1063                        // We delete after a gc for applications  on sdcard.
1064                        if (deleteOld) {
1065                            synchronized (mInstallLock) {
1066                                res.removedInfo.args.doPostDeleteLI(true);
1067                            }
1068                        }
1069                        if (args.observer != null) {
1070                            try {
1071                                Bundle extras = extrasForInstallResult(res);
1072                                args.observer.onPackageInstalled(res.name, res.returnCode,
1073                                        res.returnMsg, extras);
1074                            } catch (RemoteException e) {
1075                                Slog.i(TAG, "Observer no longer exists.");
1076                            }
1077                        }
1078                    } else {
1079                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1080                    }
1081                } break;
1082                case UPDATED_MEDIA_STATUS: {
1083                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1084                    boolean reportStatus = msg.arg1 == 1;
1085                    boolean doGc = msg.arg2 == 1;
1086                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1087                    if (doGc) {
1088                        // Force a gc to clear up stale containers.
1089                        Runtime.getRuntime().gc();
1090                    }
1091                    if (msg.obj != null) {
1092                        @SuppressWarnings("unchecked")
1093                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1094                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1095                        // Unload containers
1096                        unloadAllContainers(args);
1097                    }
1098                    if (reportStatus) {
1099                        try {
1100                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1101                            PackageHelper.getMountService().finishMediaUpdate();
1102                        } catch (RemoteException e) {
1103                            Log.e(TAG, "MountService not running?");
1104                        }
1105                    }
1106                } break;
1107                case WRITE_SETTINGS: {
1108                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109                    synchronized (mPackages) {
1110                        removeMessages(WRITE_SETTINGS);
1111                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1112                        mSettings.writeLPr();
1113                        mDirtyUsers.clear();
1114                    }
1115                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116                } break;
1117                case WRITE_PACKAGE_RESTRICTIONS: {
1118                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1119                    synchronized (mPackages) {
1120                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1121                        for (int userId : mDirtyUsers) {
1122                            mSettings.writePackageRestrictionsLPr(userId);
1123                        }
1124                        mDirtyUsers.clear();
1125                    }
1126                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127                } break;
1128                case CHECK_PENDING_VERIFICATION: {
1129                    final int verificationId = msg.arg1;
1130                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1131
1132                    if ((state != null) && !state.timeoutExtended()) {
1133                        final InstallArgs args = state.getInstallArgs();
1134                        final Uri originUri = Uri.fromFile(args.originFile);
1135
1136                        Slog.i(TAG, "Verification timed out for " + originUri);
1137                        mPendingVerification.remove(verificationId);
1138
1139                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1140
1141                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1142                            Slog.i(TAG, "Continuing with installation of " + originUri);
1143                            state.setVerifierResponse(Binder.getCallingUid(),
1144                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1145                            broadcastPackageVerified(verificationId, originUri,
1146                                    PackageManager.VERIFICATION_ALLOW,
1147                                    state.getInstallArgs().getUser());
1148                            try {
1149                                ret = args.copyApk(mContainerService, true);
1150                            } catch (RemoteException e) {
1151                                Slog.e(TAG, "Could not contact the ContainerService");
1152                            }
1153                        } else {
1154                            broadcastPackageVerified(verificationId, originUri,
1155                                    PackageManager.VERIFICATION_REJECT,
1156                                    state.getInstallArgs().getUser());
1157                        }
1158
1159                        processPendingInstall(args, ret);
1160                        mHandler.sendEmptyMessage(MCS_UNBIND);
1161                    }
1162                    break;
1163                }
1164                case PACKAGE_VERIFIED: {
1165                    final int verificationId = msg.arg1;
1166
1167                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1168                    if (state == null) {
1169                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1170                        break;
1171                    }
1172
1173                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1174
1175                    state.setVerifierResponse(response.callerUid, response.code);
1176
1177                    if (state.isVerificationComplete()) {
1178                        mPendingVerification.remove(verificationId);
1179
1180                        final InstallArgs args = state.getInstallArgs();
1181                        final Uri originUri = Uri.fromFile(args.originFile);
1182
1183                        int ret;
1184                        if (state.isInstallAllowed()) {
1185                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1186                            broadcastPackageVerified(verificationId, originUri,
1187                                    response.code, state.getInstallArgs().getUser());
1188                            try {
1189                                ret = args.copyApk(mContainerService, true);
1190                            } catch (RemoteException e) {
1191                                Slog.e(TAG, "Could not contact the ContainerService");
1192                            }
1193                        } else {
1194                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1195                        }
1196
1197                        processPendingInstall(args, ret);
1198
1199                        mHandler.sendEmptyMessage(MCS_UNBIND);
1200                    }
1201
1202                    break;
1203                }
1204            }
1205        }
1206    }
1207
1208    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1209        Bundle extras = null;
1210        switch (res.returnCode) {
1211            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1212                extras = new Bundle();
1213                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1214                        res.origPermission);
1215                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1216                        res.origPackage);
1217                break;
1218            }
1219        }
1220        return extras;
1221    }
1222
1223    void scheduleWriteSettingsLocked() {
1224        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1225            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1226        }
1227    }
1228
1229    void scheduleWritePackageRestrictionsLocked(int userId) {
1230        if (!sUserManager.exists(userId)) return;
1231        mDirtyUsers.add(userId);
1232        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1233            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1234        }
1235    }
1236
1237    public static final PackageManagerService main(Context context, Installer installer,
1238            boolean factoryTest, boolean onlyCore) {
1239        PackageManagerService m = new PackageManagerService(context, installer,
1240                factoryTest, onlyCore);
1241        ServiceManager.addService("package", m);
1242        return m;
1243    }
1244
1245    static String[] splitString(String str, char sep) {
1246        int count = 1;
1247        int i = 0;
1248        while ((i=str.indexOf(sep, i)) >= 0) {
1249            count++;
1250            i++;
1251        }
1252
1253        String[] res = new String[count];
1254        i=0;
1255        count = 0;
1256        int lastI=0;
1257        while ((i=str.indexOf(sep, i)) >= 0) {
1258            res[count] = str.substring(lastI, i);
1259            count++;
1260            i++;
1261            lastI = i;
1262        }
1263        res[count] = str.substring(lastI, str.length());
1264        return res;
1265    }
1266
1267    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1268        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1269                Context.DISPLAY_SERVICE);
1270        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1271    }
1272
1273    public PackageManagerService(Context context, Installer installer,
1274            boolean factoryTest, boolean onlyCore) {
1275        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1276                SystemClock.uptimeMillis());
1277
1278        if (mSdkVersion <= 0) {
1279            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1280        }
1281
1282        mContext = context;
1283        mFactoryTest = factoryTest;
1284        mOnlyCore = onlyCore;
1285        mMetrics = new DisplayMetrics();
1286        mSettings = new Settings(context);
1287        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1296                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1297        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1298                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1299
1300        String separateProcesses = SystemProperties.get("debug.separate_processes");
1301        if (separateProcesses != null && separateProcesses.length() > 0) {
1302            if ("*".equals(separateProcesses)) {
1303                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1304                mSeparateProcesses = null;
1305                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1306            } else {
1307                mDefParseFlags = 0;
1308                mSeparateProcesses = separateProcesses.split(",");
1309                Slog.w(TAG, "Running with debug.separate_processes: "
1310                        + separateProcesses);
1311            }
1312        } else {
1313            mDefParseFlags = 0;
1314            mSeparateProcesses = null;
1315        }
1316
1317        mInstaller = installer;
1318
1319        getDefaultDisplayMetrics(context, mMetrics);
1320
1321        SystemConfig systemConfig = SystemConfig.getInstance();
1322        mGlobalGids = systemConfig.getGlobalGids();
1323        mSystemPermissions = systemConfig.getSystemPermissions();
1324        mAvailableFeatures = systemConfig.getAvailableFeatures();
1325
1326        synchronized (mInstallLock) {
1327        // writer
1328        synchronized (mPackages) {
1329            mHandlerThread = new ServiceThread(TAG,
1330                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1331            mHandlerThread.start();
1332            mHandler = new PackageHandler(mHandlerThread.getLooper());
1333            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1334
1335            File dataDir = Environment.getDataDirectory();
1336            mAppDataDir = new File(dataDir, "data");
1337            mAppInstallDir = new File(dataDir, "app");
1338            mAppLib32InstallDir = new File(dataDir, "app-lib");
1339            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1340            mUserAppDataDir = new File(dataDir, "user");
1341            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1342
1343            sUserManager = new UserManagerService(context, this,
1344                    mInstallLock, mPackages);
1345
1346            // Propagate permission configuration in to package manager.
1347            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1348                    = systemConfig.getPermissions();
1349            for (int i=0; i<permConfig.size(); i++) {
1350                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1351                BasePermission bp = mSettings.mPermissions.get(perm.name);
1352                if (bp == null) {
1353                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1354                    mSettings.mPermissions.put(perm.name, bp);
1355                }
1356                if (perm.gids != null) {
1357                    bp.gids = appendInts(bp.gids, perm.gids);
1358                }
1359            }
1360
1361            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1362            for (int i=0; i<libConfig.size(); i++) {
1363                mSharedLibraries.put(libConfig.keyAt(i),
1364                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1365            }
1366
1367            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1368
1369            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1370                    mSdkVersion, mOnlyCore);
1371
1372            String customResolverActivity = Resources.getSystem().getString(
1373                    R.string.config_customResolverActivity);
1374            if (TextUtils.isEmpty(customResolverActivity)) {
1375                customResolverActivity = null;
1376            } else {
1377                mCustomResolverComponentName = ComponentName.unflattenFromString(
1378                        customResolverActivity);
1379            }
1380
1381            long startTime = SystemClock.uptimeMillis();
1382
1383            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1384                    startTime);
1385
1386            // Set flag to monitor and not change apk file paths when
1387            // scanning install directories.
1388            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1389
1390            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1391
1392            /**
1393             * Add everything in the in the boot class path to the
1394             * list of process files because dexopt will have been run
1395             * if necessary during zygote startup.
1396             */
1397            String bootClassPath = System.getProperty("java.boot.class.path");
1398            if (bootClassPath != null) {
1399                String[] paths = splitString(bootClassPath, ':');
1400                for (int i=0; i<paths.length; i++) {
1401                    alreadyDexOpted.add(paths[i]);
1402                }
1403            } else {
1404                Slog.w(TAG, "No BOOTCLASSPATH found!");
1405            }
1406
1407            boolean didDexOptLibraryOrTool = false;
1408
1409            final List<String> allInstructionSets = getAllInstructionSets();
1410            final String[] dexCodeInstructionSets =
1411                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1412
1413            /**
1414             * Ensure all external libraries have had dexopt run on them.
1415             */
1416            if (mSharedLibraries.size() > 0) {
1417                // NOTE: For now, we're compiling these system "shared libraries"
1418                // (and framework jars) into all available architectures. It's possible
1419                // to compile them only when we come across an app that uses them (there's
1420                // already logic for that in scanPackageLI) but that adds some complexity.
1421                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1422                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1423                        final String lib = libEntry.path;
1424                        if (lib == null) {
1425                            continue;
1426                        }
1427
1428                        try {
1429                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1430                                                                                 dexCodeInstructionSet,
1431                                                                                 false);
1432                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1433                                alreadyDexOpted.add(lib);
1434
1435                                // The list of "shared libraries" we have at this point is
1436                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1437                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1438                                } else {
1439                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1440                                }
1441                                didDexOptLibraryOrTool = true;
1442                            }
1443                        } catch (FileNotFoundException e) {
1444                            Slog.w(TAG, "Library not found: " + lib);
1445                        } catch (IOException e) {
1446                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1447                                    + e.getMessage());
1448                        }
1449                    }
1450                }
1451            }
1452
1453            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1454
1455            // Gross hack for now: we know this file doesn't contain any
1456            // code, so don't dexopt it to avoid the resulting log spew.
1457            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1458
1459            // Gross hack for now: we know this file is only part of
1460            // the boot class path for art, so don't dexopt it to
1461            // avoid the resulting log spew.
1462            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1463
1464            /**
1465             * And there are a number of commands implemented in Java, which
1466             * we currently need to do the dexopt on so that they can be
1467             * run from a non-root shell.
1468             */
1469            String[] frameworkFiles = frameworkDir.list();
1470            if (frameworkFiles != null) {
1471                // TODO: We could compile these only for the most preferred ABI. We should
1472                // first double check that the dex files for these commands are not referenced
1473                // by other system apps.
1474                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1475                    for (int i=0; i<frameworkFiles.length; i++) {
1476                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1477                        String path = libPath.getPath();
1478                        // Skip the file if we already did it.
1479                        if (alreadyDexOpted.contains(path)) {
1480                            continue;
1481                        }
1482                        // Skip the file if it is not a type we want to dexopt.
1483                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1484                            continue;
1485                        }
1486                        try {
1487                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1488                                                                                 dexCodeInstructionSet,
1489                                                                                 false);
1490                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1491                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1492                                didDexOptLibraryOrTool = true;
1493                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1494                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1495                                didDexOptLibraryOrTool = true;
1496                            }
1497                        } catch (FileNotFoundException e) {
1498                            Slog.w(TAG, "Jar not found: " + path);
1499                        } catch (IOException e) {
1500                            Slog.w(TAG, "Exception reading jar: " + path, e);
1501                        }
1502                    }
1503                }
1504            }
1505
1506            if (didDexOptLibraryOrTool) {
1507                // If we dexopted a library or tool, then something on the system has
1508                // changed. Consider this significant, and wipe away all other
1509                // existing dexopt files to ensure we don't leave any dangling around.
1510                //
1511                // TODO: This should be revisited because it isn't as good an indicator
1512                // as it used to be. It used to include the boot classpath but at some point
1513                // DexFile.isDexOptNeeded started returning false for the boot
1514                // class path files in all cases. It is very possible in a
1515                // small maintenance release update that the library and tool
1516                // jars may be unchanged but APK could be removed resulting in
1517                // unused dalvik-cache files.
1518                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1519                    mInstaller.pruneDexCache(dexCodeInstructionSet);
1520                }
1521
1522                // Additionally, delete all dex files from the root directory
1523                // since there shouldn't be any there anyway, unless we're upgrading
1524                // from an older OS version or a build that contained the "old" style
1525                // flat scheme.
1526                mInstaller.pruneDexCache(".");
1527            }
1528
1529            // Collect vendor overlay packages.
1530            // (Do this before scanning any apps.)
1531            // For security and version matching reason, only consider
1532            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1533            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1534            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1535                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1536
1537            // Find base frameworks (resource packages without code).
1538            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR
1540                    | PackageParser.PARSE_IS_PRIVILEGED,
1541                    scanMode | SCAN_NO_DEX, 0);
1542
1543            // Collected privileged system packages.
1544            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1545            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR
1547                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1548
1549            // Collect ordinary system packages.
1550            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1551            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1553
1554            // Collect all vendor packages.
1555            File vendorAppDir = new File("/vendor/app");
1556            try {
1557                vendorAppDir = vendorAppDir.getCanonicalFile();
1558            } catch (IOException e) {
1559                // failed to look up canonical path, continue with original one
1560            }
1561            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1562                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1563
1564            // Collect all OEM packages.
1565            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1566            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1567                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1568
1569            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1570            mInstaller.moveFiles();
1571
1572            // Prune any system packages that no longer exist.
1573            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1574            if (!mOnlyCore) {
1575                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1576                while (psit.hasNext()) {
1577                    PackageSetting ps = psit.next();
1578
1579                    /*
1580                     * If this is not a system app, it can't be a
1581                     * disable system app.
1582                     */
1583                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1584                        continue;
1585                    }
1586
1587                    /*
1588                     * If the package is scanned, it's not erased.
1589                     */
1590                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1591                    if (scannedPkg != null) {
1592                        /*
1593                         * If the system app is both scanned and in the
1594                         * disabled packages list, then it must have been
1595                         * added via OTA. Remove it from the currently
1596                         * scanned package so the previously user-installed
1597                         * application can be scanned.
1598                         */
1599                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1600                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1601                                    + "; removing system app");
1602                            removePackageLI(ps, true);
1603                        }
1604
1605                        continue;
1606                    }
1607
1608                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1609                        psit.remove();
1610                        String msg = "System package " + ps.name
1611                                + " no longer exists; wiping its data";
1612                        reportSettingsProblem(Log.WARN, msg);
1613                        removeDataDirsLI(ps.name);
1614                    } else {
1615                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1616                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1617                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1618                        }
1619                    }
1620                }
1621            }
1622
1623            //look for any incomplete package installations
1624            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1625            //clean up list
1626            for(int i = 0; i < deletePkgsList.size(); i++) {
1627                //clean up here
1628                cleanupInstallFailedPackage(deletePkgsList.get(i));
1629            }
1630            //delete tmp files
1631            deleteTempPackageFiles();
1632
1633            // Remove any shared userIDs that have no associated packages
1634            mSettings.pruneSharedUsersLPw();
1635
1636            if (!mOnlyCore) {
1637                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1638                        SystemClock.uptimeMillis());
1639                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1640
1641                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1642                        scanMode, 0);
1643
1644                /**
1645                 * Remove disable package settings for any updated system
1646                 * apps that were removed via an OTA. If they're not a
1647                 * previously-updated app, remove them completely.
1648                 * Otherwise, just revoke their system-level permissions.
1649                 */
1650                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1651                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1652                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1653
1654                    String msg;
1655                    if (deletedPkg == null) {
1656                        msg = "Updated system package " + deletedAppName
1657                                + " no longer exists; wiping its data";
1658                        removeDataDirsLI(deletedAppName);
1659                    } else {
1660                        msg = "Updated system app + " + deletedAppName
1661                                + " no longer present; removing system privileges for "
1662                                + deletedAppName;
1663
1664                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1665
1666                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1667                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1668                    }
1669                    reportSettingsProblem(Log.WARN, msg);
1670                }
1671            }
1672
1673            // Now that we know all of the shared libraries, update all clients to have
1674            // the correct library paths.
1675            updateAllSharedLibrariesLPw();
1676
1677            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1678                // NOTE: We ignore potential failures here during a system scan (like
1679                // the rest of the commands above) because there's precious little we
1680                // can do about it. A settings error is reported, though.
1681                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1682                        false /* force dexopt */, false /* defer dexopt */);
1683            }
1684
1685            // Now that we know all the packages we are keeping,
1686            // read and update their last usage times.
1687            mPackageUsage.readLP();
1688
1689            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1690                    SystemClock.uptimeMillis());
1691            Slog.i(TAG, "Time to scan packages: "
1692                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1693                    + " seconds");
1694
1695            // If the platform SDK has changed since the last time we booted,
1696            // we need to re-grant app permission to catch any new ones that
1697            // appear.  This is really a hack, and means that apps can in some
1698            // cases get permissions that the user didn't initially explicitly
1699            // allow...  it would be nice to have some better way to handle
1700            // this situation.
1701            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1702                    != mSdkVersion;
1703            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1704                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1705                    + "; regranting permissions for internal storage");
1706            mSettings.mInternalSdkPlatform = mSdkVersion;
1707
1708            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1709                    | (regrantPermissions
1710                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1711                            : 0));
1712
1713            // If this is the first boot, and it is a normal boot, then
1714            // we need to initialize the default preferred apps.
1715            if (!mRestoredSettings && !onlyCore) {
1716                mSettings.readDefaultPreferredAppsLPw(this, 0);
1717            }
1718
1719            // If this is first boot after an OTA, and a normal boot, then
1720            // we need to clear code cache directories.
1721            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1722                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1723                for (String pkgName : mSettings.mPackages.keySet()) {
1724                    deleteCodeCacheDirsLI(pkgName);
1725                }
1726                mSettings.mFingerprint = Build.FINGERPRINT;
1727            }
1728
1729            // All the changes are done during package scanning.
1730            mSettings.updateInternalDatabaseVersion();
1731
1732            // can downgrade to reader
1733            mSettings.writeLPr();
1734
1735            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1736                    SystemClock.uptimeMillis());
1737
1738
1739            mRequiredVerifierPackage = getRequiredVerifierLPr();
1740        } // synchronized (mPackages)
1741        } // synchronized (mInstallLock)
1742
1743        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1744
1745        // Now after opening every single application zip, make sure they
1746        // are all flushed.  Not really needed, but keeps things nice and
1747        // tidy.
1748        Runtime.getRuntime().gc();
1749    }
1750
1751    @Override
1752    public boolean isFirstBoot() {
1753        return !mRestoredSettings;
1754    }
1755
1756    @Override
1757    public boolean isOnlyCoreApps() {
1758        return mOnlyCore;
1759    }
1760
1761    private String getRequiredVerifierLPr() {
1762        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1763        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1764                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1765
1766        String requiredVerifier = null;
1767
1768        final int N = receivers.size();
1769        for (int i = 0; i < N; i++) {
1770            final ResolveInfo info = receivers.get(i);
1771
1772            if (info.activityInfo == null) {
1773                continue;
1774            }
1775
1776            final String packageName = info.activityInfo.packageName;
1777
1778            final PackageSetting ps = mSettings.mPackages.get(packageName);
1779            if (ps == null) {
1780                continue;
1781            }
1782
1783            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1784            if (!gp.grantedPermissions
1785                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1786                continue;
1787            }
1788
1789            if (requiredVerifier != null) {
1790                throw new RuntimeException("There can be only one required verifier");
1791            }
1792
1793            requiredVerifier = packageName;
1794        }
1795
1796        return requiredVerifier;
1797    }
1798
1799    @Override
1800    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1801            throws RemoteException {
1802        try {
1803            return super.onTransact(code, data, reply, flags);
1804        } catch (RuntimeException e) {
1805            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1806                Slog.wtf(TAG, "Package Manager Crash", e);
1807            }
1808            throw e;
1809        }
1810    }
1811
1812    void cleanupInstallFailedPackage(PackageSetting ps) {
1813        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1814        removeDataDirsLI(ps.name);
1815
1816        // TODO: try cleaning up codePath directory contents first, since it
1817        // might be a cluster
1818
1819        if (ps.codePath != null) {
1820            if (!ps.codePath.delete()) {
1821                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1822            }
1823        }
1824        if (ps.resourcePath != null) {
1825            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1826                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1827            }
1828        }
1829        mSettings.removePackageLPw(ps.name);
1830    }
1831
1832    static int[] appendInts(int[] cur, int[] add) {
1833        if (add == null) return cur;
1834        if (cur == null) return add;
1835        final int N = add.length;
1836        for (int i=0; i<N; i++) {
1837            cur = appendInt(cur, add[i]);
1838        }
1839        return cur;
1840    }
1841
1842    static int[] removeInts(int[] cur, int[] rem) {
1843        if (rem == null) return cur;
1844        if (cur == null) return cur;
1845        final int N = rem.length;
1846        for (int i=0; i<N; i++) {
1847            cur = removeInt(cur, rem[i]);
1848        }
1849        return cur;
1850    }
1851
1852    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1853        if (!sUserManager.exists(userId)) return null;
1854        final PackageSetting ps = (PackageSetting) p.mExtras;
1855        if (ps == null) {
1856            return null;
1857        }
1858        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1859        final PackageUserState state = ps.readUserState(userId);
1860        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1861                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1862                state, userId);
1863    }
1864
1865    @Override
1866    public boolean isPackageAvailable(String packageName, int userId) {
1867        if (!sUserManager.exists(userId)) return false;
1868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1869        synchronized (mPackages) {
1870            PackageParser.Package p = mPackages.get(packageName);
1871            if (p != null) {
1872                final PackageSetting ps = (PackageSetting) p.mExtras;
1873                if (ps != null) {
1874                    final PackageUserState state = ps.readUserState(userId);
1875                    if (state != null) {
1876                        return PackageParser.isAvailable(state);
1877                    }
1878                }
1879            }
1880        }
1881        return false;
1882    }
1883
1884    @Override
1885    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1886        if (!sUserManager.exists(userId)) return null;
1887        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1888        // reader
1889        synchronized (mPackages) {
1890            PackageParser.Package p = mPackages.get(packageName);
1891            if (DEBUG_PACKAGE_INFO)
1892                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1893            if (p != null) {
1894                return generatePackageInfo(p, flags, userId);
1895            }
1896            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1897                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1898            }
1899        }
1900        return null;
1901    }
1902
1903    @Override
1904    public String[] currentToCanonicalPackageNames(String[] names) {
1905        String[] out = new String[names.length];
1906        // reader
1907        synchronized (mPackages) {
1908            for (int i=names.length-1; i>=0; i--) {
1909                PackageSetting ps = mSettings.mPackages.get(names[i]);
1910                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1911            }
1912        }
1913        return out;
1914    }
1915
1916    @Override
1917    public String[] canonicalToCurrentPackageNames(String[] names) {
1918        String[] out = new String[names.length];
1919        // reader
1920        synchronized (mPackages) {
1921            for (int i=names.length-1; i>=0; i--) {
1922                String cur = mSettings.mRenamedPackages.get(names[i]);
1923                out[i] = cur != null ? cur : names[i];
1924            }
1925        }
1926        return out;
1927    }
1928
1929    @Override
1930    public int getPackageUid(String packageName, int userId) {
1931        if (!sUserManager.exists(userId)) return -1;
1932        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1933        // reader
1934        synchronized (mPackages) {
1935            PackageParser.Package p = mPackages.get(packageName);
1936            if(p != null) {
1937                return UserHandle.getUid(userId, p.applicationInfo.uid);
1938            }
1939            PackageSetting ps = mSettings.mPackages.get(packageName);
1940            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1941                return -1;
1942            }
1943            p = ps.pkg;
1944            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1945        }
1946    }
1947
1948    @Override
1949    public int[] getPackageGids(String packageName) {
1950        // reader
1951        synchronized (mPackages) {
1952            PackageParser.Package p = mPackages.get(packageName);
1953            if (DEBUG_PACKAGE_INFO)
1954                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1955            if (p != null) {
1956                final PackageSetting ps = (PackageSetting)p.mExtras;
1957                return ps.getGids();
1958            }
1959        }
1960        // stupid thing to indicate an error.
1961        return new int[0];
1962    }
1963
1964    static final PermissionInfo generatePermissionInfo(
1965            BasePermission bp, int flags) {
1966        if (bp.perm != null) {
1967            return PackageParser.generatePermissionInfo(bp.perm, flags);
1968        }
1969        PermissionInfo pi = new PermissionInfo();
1970        pi.name = bp.name;
1971        pi.packageName = bp.sourcePackage;
1972        pi.nonLocalizedLabel = bp.name;
1973        pi.protectionLevel = bp.protectionLevel;
1974        return pi;
1975    }
1976
1977    @Override
1978    public PermissionInfo getPermissionInfo(String name, int flags) {
1979        // reader
1980        synchronized (mPackages) {
1981            final BasePermission p = mSettings.mPermissions.get(name);
1982            if (p != null) {
1983                return generatePermissionInfo(p, flags);
1984            }
1985            return null;
1986        }
1987    }
1988
1989    @Override
1990    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1991        // reader
1992        synchronized (mPackages) {
1993            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1994            for (BasePermission p : mSettings.mPermissions.values()) {
1995                if (group == null) {
1996                    if (p.perm == null || p.perm.info.group == null) {
1997                        out.add(generatePermissionInfo(p, flags));
1998                    }
1999                } else {
2000                    if (p.perm != null && group.equals(p.perm.info.group)) {
2001                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2002                    }
2003                }
2004            }
2005
2006            if (out.size() > 0) {
2007                return out;
2008            }
2009            return mPermissionGroups.containsKey(group) ? out : null;
2010        }
2011    }
2012
2013    @Override
2014    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2015        // reader
2016        synchronized (mPackages) {
2017            return PackageParser.generatePermissionGroupInfo(
2018                    mPermissionGroups.get(name), flags);
2019        }
2020    }
2021
2022    @Override
2023    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2024        // reader
2025        synchronized (mPackages) {
2026            final int N = mPermissionGroups.size();
2027            ArrayList<PermissionGroupInfo> out
2028                    = new ArrayList<PermissionGroupInfo>(N);
2029            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2030                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2031            }
2032            return out;
2033        }
2034    }
2035
2036    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2037            int userId) {
2038        if (!sUserManager.exists(userId)) return null;
2039        PackageSetting ps = mSettings.mPackages.get(packageName);
2040        if (ps != null) {
2041            if (ps.pkg == null) {
2042                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2043                        flags, userId);
2044                if (pInfo != null) {
2045                    return pInfo.applicationInfo;
2046                }
2047                return null;
2048            }
2049            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2050                    ps.readUserState(userId), userId);
2051        }
2052        return null;
2053    }
2054
2055    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2056            int userId) {
2057        if (!sUserManager.exists(userId)) return null;
2058        PackageSetting ps = mSettings.mPackages.get(packageName);
2059        if (ps != null) {
2060            PackageParser.Package pkg = ps.pkg;
2061            if (pkg == null) {
2062                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2063                    return null;
2064                }
2065                // Only data remains, so we aren't worried about code paths
2066                pkg = new PackageParser.Package(packageName);
2067                pkg.applicationInfo.packageName = packageName;
2068                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2069                pkg.applicationInfo.dataDir =
2070                        getDataPathForPackage(packageName, 0).getPath();
2071                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2072                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2073            }
2074            return generatePackageInfo(pkg, flags, userId);
2075        }
2076        return null;
2077    }
2078
2079    @Override
2080    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2081        if (!sUserManager.exists(userId)) return null;
2082        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2083        // writer
2084        synchronized (mPackages) {
2085            PackageParser.Package p = mPackages.get(packageName);
2086            if (DEBUG_PACKAGE_INFO) Log.v(
2087                    TAG, "getApplicationInfo " + packageName
2088                    + ": " + p);
2089            if (p != null) {
2090                PackageSetting ps = mSettings.mPackages.get(packageName);
2091                if (ps == null) return null;
2092                // Note: isEnabledLP() does not apply here - always return info
2093                return PackageParser.generateApplicationInfo(
2094                        p, flags, ps.readUserState(userId), userId);
2095            }
2096            if ("android".equals(packageName)||"system".equals(packageName)) {
2097                return mAndroidApplication;
2098            }
2099            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2100                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2101            }
2102        }
2103        return null;
2104    }
2105
2106
2107    @Override
2108    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2109        mContext.enforceCallingOrSelfPermission(
2110                android.Manifest.permission.CLEAR_APP_CACHE, null);
2111        // Queue up an async operation since clearing cache may take a little while.
2112        mHandler.post(new Runnable() {
2113            public void run() {
2114                mHandler.removeCallbacks(this);
2115                int retCode = -1;
2116                synchronized (mInstallLock) {
2117                    retCode = mInstaller.freeCache(freeStorageSize);
2118                    if (retCode < 0) {
2119                        Slog.w(TAG, "Couldn't clear application caches");
2120                    }
2121                }
2122                if (observer != null) {
2123                    try {
2124                        observer.onRemoveCompleted(null, (retCode >= 0));
2125                    } catch (RemoteException e) {
2126                        Slog.w(TAG, "RemoveException when invoking call back");
2127                    }
2128                }
2129            }
2130        });
2131    }
2132
2133    @Override
2134    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2135        mContext.enforceCallingOrSelfPermission(
2136                android.Manifest.permission.CLEAR_APP_CACHE, null);
2137        // Queue up an async operation since clearing cache may take a little while.
2138        mHandler.post(new Runnable() {
2139            public void run() {
2140                mHandler.removeCallbacks(this);
2141                int retCode = -1;
2142                synchronized (mInstallLock) {
2143                    retCode = mInstaller.freeCache(freeStorageSize);
2144                    if (retCode < 0) {
2145                        Slog.w(TAG, "Couldn't clear application caches");
2146                    }
2147                }
2148                if(pi != null) {
2149                    try {
2150                        // Callback via pending intent
2151                        int code = (retCode >= 0) ? 1 : 0;
2152                        pi.sendIntent(null, code, null,
2153                                null, null);
2154                    } catch (SendIntentException e1) {
2155                        Slog.i(TAG, "Failed to send pending intent");
2156                    }
2157                }
2158            }
2159        });
2160    }
2161
2162    void freeStorage(long freeStorageSize) throws IOException {
2163        synchronized (mInstallLock) {
2164            if (mInstaller.freeCache(freeStorageSize) < 0) {
2165                throw new IOException("Failed to free enough space");
2166            }
2167        }
2168    }
2169
2170    @Override
2171    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2172        if (!sUserManager.exists(userId)) return null;
2173        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2174        synchronized (mPackages) {
2175            PackageParser.Activity a = mActivities.mActivities.get(component);
2176
2177            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2178            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2179                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2180                if (ps == null) return null;
2181                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2182                        userId);
2183            }
2184            if (mResolveComponentName.equals(component)) {
2185                return mResolveActivity;
2186            }
2187        }
2188        return null;
2189    }
2190
2191    @Override
2192    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2193            String resolvedType) {
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mActivities.mActivities.get(component);
2196            if (a == null) {
2197                return false;
2198            }
2199            for (int i=0; i<a.intents.size(); i++) {
2200                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2201                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2202                    return true;
2203                }
2204            }
2205            return false;
2206        }
2207    }
2208
2209    @Override
2210    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2211        if (!sUserManager.exists(userId)) return null;
2212        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2213        synchronized (mPackages) {
2214            PackageParser.Activity a = mReceivers.mActivities.get(component);
2215            if (DEBUG_PACKAGE_INFO) Log.v(
2216                TAG, "getReceiverInfo " + component + ": " + a);
2217            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2218                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2219                if (ps == null) return null;
2220                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2221                        userId);
2222            }
2223        }
2224        return null;
2225    }
2226
2227    @Override
2228    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2229        if (!sUserManager.exists(userId)) return null;
2230        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2231        synchronized (mPackages) {
2232            PackageParser.Service s = mServices.mServices.get(component);
2233            if (DEBUG_PACKAGE_INFO) Log.v(
2234                TAG, "getServiceInfo " + component + ": " + s);
2235            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2236                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2237                if (ps == null) return null;
2238                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2239                        userId);
2240            }
2241        }
2242        return null;
2243    }
2244
2245    @Override
2246    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2247        if (!sUserManager.exists(userId)) return null;
2248        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2249        synchronized (mPackages) {
2250            PackageParser.Provider p = mProviders.mProviders.get(component);
2251            if (DEBUG_PACKAGE_INFO) Log.v(
2252                TAG, "getProviderInfo " + component + ": " + p);
2253            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2254                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2255                if (ps == null) return null;
2256                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2257                        userId);
2258            }
2259        }
2260        return null;
2261    }
2262
2263    @Override
2264    public String[] getSystemSharedLibraryNames() {
2265        Set<String> libSet;
2266        synchronized (mPackages) {
2267            libSet = mSharedLibraries.keySet();
2268            int size = libSet.size();
2269            if (size > 0) {
2270                String[] libs = new String[size];
2271                libSet.toArray(libs);
2272                return libs;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public FeatureInfo[] getSystemAvailableFeatures() {
2280        Collection<FeatureInfo> featSet;
2281        synchronized (mPackages) {
2282            featSet = mAvailableFeatures.values();
2283            int size = featSet.size();
2284            if (size > 0) {
2285                FeatureInfo[] features = new FeatureInfo[size+1];
2286                featSet.toArray(features);
2287                FeatureInfo fi = new FeatureInfo();
2288                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2289                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2290                features[size] = fi;
2291                return features;
2292            }
2293        }
2294        return null;
2295    }
2296
2297    @Override
2298    public boolean hasSystemFeature(String name) {
2299        synchronized (mPackages) {
2300            return mAvailableFeatures.containsKey(name);
2301        }
2302    }
2303
2304    private void checkValidCaller(int uid, int userId) {
2305        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2306            return;
2307
2308        throw new SecurityException("Caller uid=" + uid
2309                + " is not privileged to communicate with user=" + userId);
2310    }
2311
2312    @Override
2313    public int checkPermission(String permName, String pkgName) {
2314        synchronized (mPackages) {
2315            PackageParser.Package p = mPackages.get(pkgName);
2316            if (p != null && p.mExtras != null) {
2317                PackageSetting ps = (PackageSetting)p.mExtras;
2318                if (ps.sharedUser != null) {
2319                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2320                        return PackageManager.PERMISSION_GRANTED;
2321                    }
2322                } else if (ps.grantedPermissions.contains(permName)) {
2323                    return PackageManager.PERMISSION_GRANTED;
2324                }
2325            }
2326        }
2327        return PackageManager.PERMISSION_DENIED;
2328    }
2329
2330    @Override
2331    public int checkUidPermission(String permName, int uid) {
2332        synchronized (mPackages) {
2333            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2334            if (obj != null) {
2335                GrantedPermissions gp = (GrantedPermissions)obj;
2336                if (gp.grantedPermissions.contains(permName)) {
2337                    return PackageManager.PERMISSION_GRANTED;
2338                }
2339            } else {
2340                HashSet<String> perms = mSystemPermissions.get(uid);
2341                if (perms != null && perms.contains(permName)) {
2342                    return PackageManager.PERMISSION_GRANTED;
2343                }
2344            }
2345        }
2346        return PackageManager.PERMISSION_DENIED;
2347    }
2348
2349    /**
2350     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2351     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2352     * @param message the message to log on security exception
2353     */
2354    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2355            String message) {
2356        if (userId < 0) {
2357            throw new IllegalArgumentException("Invalid userId " + userId);
2358        }
2359        if (userId == UserHandle.getUserId(callingUid)) return;
2360        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2361            if (requireFullPermission) {
2362                mContext.enforceCallingOrSelfPermission(
2363                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2364            } else {
2365                try {
2366                    mContext.enforceCallingOrSelfPermission(
2367                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2368                } catch (SecurityException se) {
2369                    mContext.enforceCallingOrSelfPermission(
2370                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2371                }
2372            }
2373        }
2374    }
2375
2376    private BasePermission findPermissionTreeLP(String permName) {
2377        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2378            if (permName.startsWith(bp.name) &&
2379                    permName.length() > bp.name.length() &&
2380                    permName.charAt(bp.name.length()) == '.') {
2381                return bp;
2382            }
2383        }
2384        return null;
2385    }
2386
2387    private BasePermission checkPermissionTreeLP(String permName) {
2388        if (permName != null) {
2389            BasePermission bp = findPermissionTreeLP(permName);
2390            if (bp != null) {
2391                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2392                    return bp;
2393                }
2394                throw new SecurityException("Calling uid "
2395                        + Binder.getCallingUid()
2396                        + " is not allowed to add to permission tree "
2397                        + bp.name + " owned by uid " + bp.uid);
2398            }
2399        }
2400        throw new SecurityException("No permission tree found for " + permName);
2401    }
2402
2403    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2404        if (s1 == null) {
2405            return s2 == null;
2406        }
2407        if (s2 == null) {
2408            return false;
2409        }
2410        if (s1.getClass() != s2.getClass()) {
2411            return false;
2412        }
2413        return s1.equals(s2);
2414    }
2415
2416    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2417        if (pi1.icon != pi2.icon) return false;
2418        if (pi1.logo != pi2.logo) return false;
2419        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2420        if (!compareStrings(pi1.name, pi2.name)) return false;
2421        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2422        // We'll take care of setting this one.
2423        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2424        // These are not currently stored in settings.
2425        //if (!compareStrings(pi1.group, pi2.group)) return false;
2426        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2427        //if (pi1.labelRes != pi2.labelRes) return false;
2428        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2429        return true;
2430    }
2431
2432    int permissionInfoFootprint(PermissionInfo info) {
2433        int size = info.name.length();
2434        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2435        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2436        return size;
2437    }
2438
2439    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2440        int size = 0;
2441        for (BasePermission perm : mSettings.mPermissions.values()) {
2442            if (perm.uid == tree.uid) {
2443                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2444            }
2445        }
2446        return size;
2447    }
2448
2449    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2450        // We calculate the max size of permissions defined by this uid and throw
2451        // if that plus the size of 'info' would exceed our stated maximum.
2452        if (tree.uid != Process.SYSTEM_UID) {
2453            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2454            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2455                throw new SecurityException("Permission tree size cap exceeded");
2456            }
2457        }
2458    }
2459
2460    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2461        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2462            throw new SecurityException("Label must be specified in permission");
2463        }
2464        BasePermission tree = checkPermissionTreeLP(info.name);
2465        BasePermission bp = mSettings.mPermissions.get(info.name);
2466        boolean added = bp == null;
2467        boolean changed = true;
2468        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2469        if (added) {
2470            enforcePermissionCapLocked(info, tree);
2471            bp = new BasePermission(info.name, tree.sourcePackage,
2472                    BasePermission.TYPE_DYNAMIC);
2473        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2474            throw new SecurityException(
2475                    "Not allowed to modify non-dynamic permission "
2476                    + info.name);
2477        } else {
2478            if (bp.protectionLevel == fixedLevel
2479                    && bp.perm.owner.equals(tree.perm.owner)
2480                    && bp.uid == tree.uid
2481                    && comparePermissionInfos(bp.perm.info, info)) {
2482                changed = false;
2483            }
2484        }
2485        bp.protectionLevel = fixedLevel;
2486        info = new PermissionInfo(info);
2487        info.protectionLevel = fixedLevel;
2488        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2489        bp.perm.info.packageName = tree.perm.info.packageName;
2490        bp.uid = tree.uid;
2491        if (added) {
2492            mSettings.mPermissions.put(info.name, bp);
2493        }
2494        if (changed) {
2495            if (!async) {
2496                mSettings.writeLPr();
2497            } else {
2498                scheduleWriteSettingsLocked();
2499            }
2500        }
2501        return added;
2502    }
2503
2504    @Override
2505    public boolean addPermission(PermissionInfo info) {
2506        synchronized (mPackages) {
2507            return addPermissionLocked(info, false);
2508        }
2509    }
2510
2511    @Override
2512    public boolean addPermissionAsync(PermissionInfo info) {
2513        synchronized (mPackages) {
2514            return addPermissionLocked(info, true);
2515        }
2516    }
2517
2518    @Override
2519    public void removePermission(String name) {
2520        synchronized (mPackages) {
2521            checkPermissionTreeLP(name);
2522            BasePermission bp = mSettings.mPermissions.get(name);
2523            if (bp != null) {
2524                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2525                    throw new SecurityException(
2526                            "Not allowed to modify non-dynamic permission "
2527                            + name);
2528                }
2529                mSettings.mPermissions.remove(name);
2530                mSettings.writeLPr();
2531            }
2532        }
2533    }
2534
2535    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2536        int index = pkg.requestedPermissions.indexOf(bp.name);
2537        if (index == -1) {
2538            throw new SecurityException("Package " + pkg.packageName
2539                    + " has not requested permission " + bp.name);
2540        }
2541        boolean isNormal =
2542                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2543                        == PermissionInfo.PROTECTION_NORMAL);
2544        boolean isDangerous =
2545                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2546                        == PermissionInfo.PROTECTION_DANGEROUS);
2547        boolean isDevelopment =
2548                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2549
2550        if (!isNormal && !isDangerous && !isDevelopment) {
2551            throw new SecurityException("Permission " + bp.name
2552                    + " is not a changeable permission type");
2553        }
2554
2555        if (isNormal || isDangerous) {
2556            if (pkg.requestedPermissionsRequired.get(index)) {
2557                throw new SecurityException("Can't change " + bp.name
2558                        + ". It is required by the application");
2559            }
2560        }
2561    }
2562
2563    @Override
2564    public void grantPermission(String packageName, String permissionName) {
2565        mContext.enforceCallingOrSelfPermission(
2566                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2567        synchronized (mPackages) {
2568            final PackageParser.Package pkg = mPackages.get(packageName);
2569            if (pkg == null) {
2570                throw new IllegalArgumentException("Unknown package: " + packageName);
2571            }
2572            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2573            if (bp == null) {
2574                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2575            }
2576
2577            checkGrantRevokePermissions(pkg, bp);
2578
2579            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2580            if (ps == null) {
2581                return;
2582            }
2583            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2584            if (gp.grantedPermissions.add(permissionName)) {
2585                if (ps.haveGids) {
2586                    gp.gids = appendInts(gp.gids, bp.gids);
2587                }
2588                mSettings.writeLPr();
2589            }
2590        }
2591    }
2592
2593    @Override
2594    public void revokePermission(String packageName, String permissionName) {
2595        int changedAppId = -1;
2596
2597        synchronized (mPackages) {
2598            final PackageParser.Package pkg = mPackages.get(packageName);
2599            if (pkg == null) {
2600                throw new IllegalArgumentException("Unknown package: " + packageName);
2601            }
2602            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2603                mContext.enforceCallingOrSelfPermission(
2604                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2605            }
2606            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2607            if (bp == null) {
2608                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2609            }
2610
2611            checkGrantRevokePermissions(pkg, bp);
2612
2613            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2614            if (ps == null) {
2615                return;
2616            }
2617            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2618            if (gp.grantedPermissions.remove(permissionName)) {
2619                gp.grantedPermissions.remove(permissionName);
2620                if (ps.haveGids) {
2621                    gp.gids = removeInts(gp.gids, bp.gids);
2622                }
2623                mSettings.writeLPr();
2624                changedAppId = ps.appId;
2625            }
2626        }
2627
2628        if (changedAppId >= 0) {
2629            // We changed the perm on someone, kill its processes.
2630            IActivityManager am = ActivityManagerNative.getDefault();
2631            if (am != null) {
2632                final int callingUserId = UserHandle.getCallingUserId();
2633                final long ident = Binder.clearCallingIdentity();
2634                try {
2635                    //XXX we should only revoke for the calling user's app permissions,
2636                    // but for now we impact all users.
2637                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2638                    //        "revoke " + permissionName);
2639                    int[] users = sUserManager.getUserIds();
2640                    for (int user : users) {
2641                        am.killUid(UserHandle.getUid(user, changedAppId),
2642                                "revoke " + permissionName);
2643                    }
2644                } catch (RemoteException e) {
2645                } finally {
2646                    Binder.restoreCallingIdentity(ident);
2647                }
2648            }
2649        }
2650    }
2651
2652    @Override
2653    public boolean isProtectedBroadcast(String actionName) {
2654        synchronized (mPackages) {
2655            return mProtectedBroadcasts.contains(actionName);
2656        }
2657    }
2658
2659    @Override
2660    public int checkSignatures(String pkg1, String pkg2) {
2661        synchronized (mPackages) {
2662            final PackageParser.Package p1 = mPackages.get(pkg1);
2663            final PackageParser.Package p2 = mPackages.get(pkg2);
2664            if (p1 == null || p1.mExtras == null
2665                    || p2 == null || p2.mExtras == null) {
2666                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2667            }
2668            return compareSignatures(p1.mSignatures, p2.mSignatures);
2669        }
2670    }
2671
2672    @Override
2673    public int checkUidSignatures(int uid1, int uid2) {
2674        // Map to base uids.
2675        uid1 = UserHandle.getAppId(uid1);
2676        uid2 = UserHandle.getAppId(uid2);
2677        // reader
2678        synchronized (mPackages) {
2679            Signature[] s1;
2680            Signature[] s2;
2681            Object obj = mSettings.getUserIdLPr(uid1);
2682            if (obj != null) {
2683                if (obj instanceof SharedUserSetting) {
2684                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2685                } else if (obj instanceof PackageSetting) {
2686                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2687                } else {
2688                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2689                }
2690            } else {
2691                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2692            }
2693            obj = mSettings.getUserIdLPr(uid2);
2694            if (obj != null) {
2695                if (obj instanceof SharedUserSetting) {
2696                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2697                } else if (obj instanceof PackageSetting) {
2698                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2699                } else {
2700                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2701                }
2702            } else {
2703                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2704            }
2705            return compareSignatures(s1, s2);
2706        }
2707    }
2708
2709    /**
2710     * Compares two sets of signatures. Returns:
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2715     * <br />
2716     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2717     * <br />
2718     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2719     * <br />
2720     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2721     */
2722    static int compareSignatures(Signature[] s1, Signature[] s2) {
2723        if (s1 == null) {
2724            return s2 == null
2725                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2726                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2727        }
2728
2729        if (s2 == null) {
2730            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2731        }
2732
2733        if (s1.length != s2.length) {
2734            return PackageManager.SIGNATURE_NO_MATCH;
2735        }
2736
2737        // Since both signature sets are of size 1, we can compare without HashSets.
2738        if (s1.length == 1) {
2739            return s1[0].equals(s2[0]) ?
2740                    PackageManager.SIGNATURE_MATCH :
2741                    PackageManager.SIGNATURE_NO_MATCH;
2742        }
2743
2744        HashSet<Signature> set1 = new HashSet<Signature>();
2745        for (Signature sig : s1) {
2746            set1.add(sig);
2747        }
2748        HashSet<Signature> set2 = new HashSet<Signature>();
2749        for (Signature sig : s2) {
2750            set2.add(sig);
2751        }
2752        // Make sure s2 contains all signatures in s1.
2753        if (set1.equals(set2)) {
2754            return PackageManager.SIGNATURE_MATCH;
2755        }
2756        return PackageManager.SIGNATURE_NO_MATCH;
2757    }
2758
2759    /**
2760     * If the database version for this type of package (internal storage or
2761     * external storage) is less than the version where package signatures
2762     * were updated, return true.
2763     */
2764    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2765        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2766                DatabaseVersion.SIGNATURE_END_ENTITY))
2767                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2768                        DatabaseVersion.SIGNATURE_END_ENTITY));
2769    }
2770
2771    /**
2772     * Used for backward compatibility to make sure any packages with
2773     * certificate chains get upgraded to the new style. {@code existingSigs}
2774     * will be in the old format (since they were stored on disk from before the
2775     * system upgrade) and {@code scannedSigs} will be in the newer format.
2776     */
2777    private int compareSignaturesCompat(PackageSignatures existingSigs,
2778            PackageParser.Package scannedPkg) {
2779        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2780            return PackageManager.SIGNATURE_NO_MATCH;
2781        }
2782
2783        HashSet<Signature> existingSet = new HashSet<Signature>();
2784        for (Signature sig : existingSigs.mSignatures) {
2785            existingSet.add(sig);
2786        }
2787        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2788        for (Signature sig : scannedPkg.mSignatures) {
2789            try {
2790                Signature[] chainSignatures = sig.getChainSignatures();
2791                for (Signature chainSig : chainSignatures) {
2792                    scannedCompatSet.add(chainSig);
2793                }
2794            } catch (CertificateEncodingException e) {
2795                scannedCompatSet.add(sig);
2796            }
2797        }
2798        /*
2799         * Make sure the expanded scanned set contains all signatures in the
2800         * existing one.
2801         */
2802        if (scannedCompatSet.equals(existingSet)) {
2803            // Migrate the old signatures to the new scheme.
2804            existingSigs.assignSignatures(scannedPkg.mSignatures);
2805            // The new KeySets will be re-added later in the scanning process.
2806            synchronized (mPackages) {
2807                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2808            }
2809            return PackageManager.SIGNATURE_MATCH;
2810        }
2811        return PackageManager.SIGNATURE_NO_MATCH;
2812    }
2813
2814    @Override
2815    public String[] getPackagesForUid(int uid) {
2816        uid = UserHandle.getAppId(uid);
2817        // reader
2818        synchronized (mPackages) {
2819            Object obj = mSettings.getUserIdLPr(uid);
2820            if (obj instanceof SharedUserSetting) {
2821                final SharedUserSetting sus = (SharedUserSetting) obj;
2822                final int N = sus.packages.size();
2823                final String[] res = new String[N];
2824                final Iterator<PackageSetting> it = sus.packages.iterator();
2825                int i = 0;
2826                while (it.hasNext()) {
2827                    res[i++] = it.next().name;
2828                }
2829                return res;
2830            } else if (obj instanceof PackageSetting) {
2831                final PackageSetting ps = (PackageSetting) obj;
2832                return new String[] { ps.name };
2833            }
2834        }
2835        return null;
2836    }
2837
2838    @Override
2839    public String getNameForUid(int uid) {
2840        // reader
2841        synchronized (mPackages) {
2842            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2843            if (obj instanceof SharedUserSetting) {
2844                final SharedUserSetting sus = (SharedUserSetting) obj;
2845                return sus.name + ":" + sus.userId;
2846            } else if (obj instanceof PackageSetting) {
2847                final PackageSetting ps = (PackageSetting) obj;
2848                return ps.name;
2849            }
2850        }
2851        return null;
2852    }
2853
2854    @Override
2855    public int getUidForSharedUser(String sharedUserName) {
2856        if(sharedUserName == null) {
2857            return -1;
2858        }
2859        // reader
2860        synchronized (mPackages) {
2861            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2862            if (suid == null) {
2863                return -1;
2864            }
2865            return suid.userId;
2866        }
2867    }
2868
2869    @Override
2870    public int getFlagsForUid(int uid) {
2871        synchronized (mPackages) {
2872            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2873            if (obj instanceof SharedUserSetting) {
2874                final SharedUserSetting sus = (SharedUserSetting) obj;
2875                return sus.pkgFlags;
2876            } else if (obj instanceof PackageSetting) {
2877                final PackageSetting ps = (PackageSetting) obj;
2878                return ps.pkgFlags;
2879            }
2880        }
2881        return 0;
2882    }
2883
2884    @Override
2885    public String[] getAppOpPermissionPackages(String permissionName) {
2886        synchronized (mPackages) {
2887            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2888            if (pkgs == null) {
2889                return null;
2890            }
2891            return pkgs.toArray(new String[pkgs.size()]);
2892        }
2893    }
2894
2895    @Override
2896    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2897            int flags, int userId) {
2898        if (!sUserManager.exists(userId)) return null;
2899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2900        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2901        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2902    }
2903
2904    @Override
2905    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2906            IntentFilter filter, int match, ComponentName activity) {
2907        final int userId = UserHandle.getCallingUserId();
2908        if (DEBUG_PREFERRED) {
2909            Log.v(TAG, "setLastChosenActivity intent=" + intent
2910                + " resolvedType=" + resolvedType
2911                + " flags=" + flags
2912                + " filter=" + filter
2913                + " match=" + match
2914                + " activity=" + activity);
2915            filter.dump(new PrintStreamPrinter(System.out), "    ");
2916        }
2917        intent.setComponent(null);
2918        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2919        // Find any earlier preferred or last chosen entries and nuke them
2920        findPreferredActivity(intent, resolvedType,
2921                flags, query, 0, false, true, false, userId);
2922        // Add the new activity as the last chosen for this filter
2923        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2924    }
2925
2926    @Override
2927    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2928        final int userId = UserHandle.getCallingUserId();
2929        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2930        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2931        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2932                false, false, false, userId);
2933    }
2934
2935    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2936            int flags, List<ResolveInfo> query, int userId) {
2937        if (query != null) {
2938            final int N = query.size();
2939            if (N == 1) {
2940                return query.get(0);
2941            } else if (N > 1) {
2942                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2943                // If there is more than one activity with the same priority,
2944                // then let the user decide between them.
2945                ResolveInfo r0 = query.get(0);
2946                ResolveInfo r1 = query.get(1);
2947                if (DEBUG_INTENT_MATCHING || debug) {
2948                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2949                            + r1.activityInfo.name + "=" + r1.priority);
2950                }
2951                // If the first activity has a higher priority, or a different
2952                // default, then it is always desireable to pick it.
2953                if (r0.priority != r1.priority
2954                        || r0.preferredOrder != r1.preferredOrder
2955                        || r0.isDefault != r1.isDefault) {
2956                    return query.get(0);
2957                }
2958                // If we have saved a preference for a preferred activity for
2959                // this Intent, use that.
2960                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2961                        flags, query, r0.priority, true, false, debug, userId);
2962                if (ri != null) {
2963                    return ri;
2964                }
2965                if (userId != 0) {
2966                    ri = new ResolveInfo(mResolveInfo);
2967                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2968                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2969                            ri.activityInfo.applicationInfo);
2970                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2971                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2972                    return ri;
2973                }
2974                return mResolveInfo;
2975            }
2976        }
2977        return null;
2978    }
2979
2980    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2981            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2982        final int N = query.size();
2983        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2984                .get(userId);
2985        // Get the list of persistent preferred activities that handle the intent
2986        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2987        List<PersistentPreferredActivity> pprefs = ppir != null
2988                ? ppir.queryIntent(intent, resolvedType,
2989                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2990                : null;
2991        if (pprefs != null && pprefs.size() > 0) {
2992            final int M = pprefs.size();
2993            for (int i=0; i<M; i++) {
2994                final PersistentPreferredActivity ppa = pprefs.get(i);
2995                if (DEBUG_PREFERRED || debug) {
2996                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2997                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2998                            + "\n  component=" + ppa.mComponent);
2999                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3000                }
3001                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3002                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3003                if (DEBUG_PREFERRED || debug) {
3004                    Slog.v(TAG, "Found persistent preferred activity:");
3005                    if (ai != null) {
3006                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3007                    } else {
3008                        Slog.v(TAG, "  null");
3009                    }
3010                }
3011                if (ai == null) {
3012                    // This previously registered persistent preferred activity
3013                    // component is no longer known. Ignore it and do NOT remove it.
3014                    continue;
3015                }
3016                for (int j=0; j<N; j++) {
3017                    final ResolveInfo ri = query.get(j);
3018                    if (!ri.activityInfo.applicationInfo.packageName
3019                            .equals(ai.applicationInfo.packageName)) {
3020                        continue;
3021                    }
3022                    if (!ri.activityInfo.name.equals(ai.name)) {
3023                        continue;
3024                    }
3025                    //  Found a persistent preference that can handle the intent.
3026                    if (DEBUG_PREFERRED || debug) {
3027                        Slog.v(TAG, "Returning persistent preferred activity: " +
3028                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3029                    }
3030                    return ri;
3031                }
3032            }
3033        }
3034        return null;
3035    }
3036
3037    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3038            List<ResolveInfo> query, int priority, boolean always,
3039            boolean removeMatches, boolean debug, int userId) {
3040        if (!sUserManager.exists(userId)) return null;
3041        // writer
3042        synchronized (mPackages) {
3043            if (intent.getSelector() != null) {
3044                intent = intent.getSelector();
3045            }
3046            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3047
3048            // Try to find a matching persistent preferred activity.
3049            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3050                    debug, userId);
3051
3052            // If a persistent preferred activity matched, use it.
3053            if (pri != null) {
3054                return pri;
3055            }
3056
3057            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3058            // Get the list of preferred activities that handle the intent
3059            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3060            List<PreferredActivity> prefs = pir != null
3061                    ? pir.queryIntent(intent, resolvedType,
3062                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3063                    : null;
3064            if (prefs != null && prefs.size() > 0) {
3065                // First figure out how good the original match set is.
3066                // We will only allow preferred activities that came
3067                // from the same match quality.
3068                int match = 0;
3069
3070                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3071
3072                final int N = query.size();
3073                for (int j=0; j<N; j++) {
3074                    final ResolveInfo ri = query.get(j);
3075                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3076                            + ": 0x" + Integer.toHexString(match));
3077                    if (ri.match > match) {
3078                        match = ri.match;
3079                    }
3080                }
3081
3082                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3083                        + Integer.toHexString(match));
3084
3085                match &= IntentFilter.MATCH_CATEGORY_MASK;
3086                final int M = prefs.size();
3087                for (int i=0; i<M; i++) {
3088                    final PreferredActivity pa = prefs.get(i);
3089                    if (DEBUG_PREFERRED || debug) {
3090                        Slog.v(TAG, "Checking PreferredActivity ds="
3091                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3092                                + "\n  component=" + pa.mPref.mComponent);
3093                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3094                    }
3095                    if (pa.mPref.mMatch != match) {
3096                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3097                                + Integer.toHexString(pa.mPref.mMatch));
3098                        continue;
3099                    }
3100                    // If it's not an "always" type preferred activity and that's what we're
3101                    // looking for, skip it.
3102                    if (always && !pa.mPref.mAlways) {
3103                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3104                        continue;
3105                    }
3106                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3107                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3108                    if (DEBUG_PREFERRED || debug) {
3109                        Slog.v(TAG, "Found preferred activity:");
3110                        if (ai != null) {
3111                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3112                        } else {
3113                            Slog.v(TAG, "  null");
3114                        }
3115                    }
3116                    if (ai == null) {
3117                        // This previously registered preferred activity
3118                        // component is no longer known.  Most likely an update
3119                        // to the app was installed and in the new version this
3120                        // component no longer exists.  Clean it up by removing
3121                        // it from the preferred activities list, and skip it.
3122                        Slog.w(TAG, "Removing dangling preferred activity: "
3123                                + pa.mPref.mComponent);
3124                        pir.removeFilter(pa);
3125                        continue;
3126                    }
3127                    for (int j=0; j<N; j++) {
3128                        final ResolveInfo ri = query.get(j);
3129                        if (!ri.activityInfo.applicationInfo.packageName
3130                                .equals(ai.applicationInfo.packageName)) {
3131                            continue;
3132                        }
3133                        if (!ri.activityInfo.name.equals(ai.name)) {
3134                            continue;
3135                        }
3136
3137                        if (removeMatches) {
3138                            pir.removeFilter(pa);
3139                            if (DEBUG_PREFERRED) {
3140                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3141                            }
3142                            break;
3143                        }
3144
3145                        // Okay we found a previously set preferred or last chosen app.
3146                        // If the result set is different from when this
3147                        // was created, we need to clear it and re-ask the
3148                        // user their preference, if we're looking for an "always" type entry.
3149                        if (always && !pa.mPref.sameSet(query, priority)) {
3150                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3151                                    + intent + " type " + resolvedType);
3152                            if (DEBUG_PREFERRED) {
3153                                Slog.v(TAG, "Removing preferred activity since set changed "
3154                                        + pa.mPref.mComponent);
3155                            }
3156                            pir.removeFilter(pa);
3157                            // Re-add the filter as a "last chosen" entry (!always)
3158                            PreferredActivity lastChosen = new PreferredActivity(
3159                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3160                            pir.addFilter(lastChosen);
3161                            mSettings.writePackageRestrictionsLPr(userId);
3162                            return null;
3163                        }
3164
3165                        // Yay! Either the set matched or we're looking for the last chosen
3166                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3167                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3168                        mSettings.writePackageRestrictionsLPr(userId);
3169                        return ri;
3170                    }
3171                }
3172            }
3173            mSettings.writePackageRestrictionsLPr(userId);
3174        }
3175        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3176        return null;
3177    }
3178
3179    /*
3180     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3181     */
3182    @Override
3183    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3184            int targetUserId) {
3185        mContext.enforceCallingOrSelfPermission(
3186                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3187        List<CrossProfileIntentFilter> matches =
3188                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3189        if (matches != null) {
3190            int size = matches.size();
3191            for (int i = 0; i < size; i++) {
3192                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3193            }
3194        }
3195
3196        ArrayList<String> packageNames = null;
3197        SparseArray<ArrayList<String>> fromSource =
3198                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3199        if (fromSource != null) {
3200            packageNames = fromSource.get(targetUserId);
3201        }
3202        if (packageNames != null && packageNames.contains(intent.getPackage())) {
3203            return true;
3204        }
3205        // We need the package name, so we try to resolve with the loosest flags possible
3206        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3207                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3208        int count = resolveInfos.size();
3209        for (int i = 0; i < count; i++) {
3210            ResolveInfo resolveInfo = resolveInfos.get(i);
3211            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3212                return true;
3213            }
3214        }
3215        return false;
3216    }
3217
3218    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3219            String resolvedType, int userId) {
3220        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3221        if (resolver != null) {
3222            return resolver.queryIntent(intent, resolvedType, false, userId);
3223        }
3224        return null;
3225    }
3226
3227    @Override
3228    public List<ResolveInfo> queryIntentActivities(Intent intent,
3229            String resolvedType, int flags, int userId) {
3230        if (!sUserManager.exists(userId)) return Collections.emptyList();
3231        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3232        ComponentName comp = intent.getComponent();
3233        if (comp == null) {
3234            if (intent.getSelector() != null) {
3235                intent = intent.getSelector();
3236                comp = intent.getComponent();
3237            }
3238        }
3239
3240        if (comp != null) {
3241            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3242            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3243            if (ai != null) {
3244                final ResolveInfo ri = new ResolveInfo();
3245                ri.activityInfo = ai;
3246                list.add(ri);
3247            }
3248            return list;
3249        }
3250
3251        // reader
3252        synchronized (mPackages) {
3253            final String pkgName = intent.getPackage();
3254            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3255            if (pkgName == null) {
3256                ResolveInfo resolveInfo = null;
3257                if (queryCrossProfile) {
3258                    // Check if the intent needs to be forwarded to another user for this package
3259                    ArrayList<ResolveInfo> crossProfileResult =
3260                            queryIntentActivitiesCrossProfilePackage(
3261                                    intent, resolvedType, flags, userId);
3262                    if (!crossProfileResult.isEmpty()) {
3263                        // Skip the current profile
3264                        return crossProfileResult;
3265                    }
3266                    List<CrossProfileIntentFilter> matchingFilters =
3267                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3268                    // Check for results that need to skip the current profile.
3269                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3270                            resolvedType, flags, userId);
3271                    if (resolveInfo != null) {
3272                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3273                        result.add(resolveInfo);
3274                        return result;
3275                    }
3276                    // Check for cross profile results.
3277                    resolveInfo = queryCrossProfileIntents(
3278                            matchingFilters, intent, resolvedType, flags, userId);
3279                }
3280                // Check for results in the current profile.
3281                List<ResolveInfo> result = mActivities.queryIntent(
3282                        intent, resolvedType, flags, userId);
3283                if (resolveInfo != null) {
3284                    result.add(resolveInfo);
3285                    Collections.sort(result, mResolvePrioritySorter);
3286                }
3287                return result;
3288            }
3289            final PackageParser.Package pkg = mPackages.get(pkgName);
3290            if (pkg != null) {
3291                if (queryCrossProfile) {
3292                    ArrayList<ResolveInfo> crossProfileResult =
3293                            queryIntentActivitiesCrossProfilePackage(
3294                                    intent, resolvedType, flags, userId, pkg, pkgName);
3295                    if (!crossProfileResult.isEmpty()) {
3296                        // Skip the current profile
3297                        return crossProfileResult;
3298                    }
3299                }
3300                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3301                        pkg.activities, userId);
3302            }
3303            return new ArrayList<ResolveInfo>();
3304        }
3305    }
3306
3307    private ResolveInfo querySkipCurrentProfileIntents(
3308            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3309            int flags, int sourceUserId) {
3310        if (matchingFilters != null) {
3311            int size = matchingFilters.size();
3312            for (int i = 0; i < size; i ++) {
3313                CrossProfileIntentFilter filter = matchingFilters.get(i);
3314                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3315                    // Checking if there are activities in the target user that can handle the
3316                    // intent.
3317                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3318                            flags, sourceUserId);
3319                    if (resolveInfo != null) {
3320                        return resolveInfo;
3321                    }
3322                }
3323            }
3324        }
3325        return null;
3326    }
3327
3328    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3329            Intent intent, String resolvedType, int flags, int userId) {
3330        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3331        SparseArray<ArrayList<String>> sourceForwardingInfo =
3332                mSettings.mCrossProfilePackageInfo.get(userId);
3333        if (sourceForwardingInfo != null) {
3334            int NI = sourceForwardingInfo.size();
3335            for (int i = 0; i < NI; i++) {
3336                int targetUserId = sourceForwardingInfo.keyAt(i);
3337                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3338                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3339                        intent, resolvedType, flags, targetUserId);
3340                int NJ = resolveInfos.size();
3341                for (int j = 0; j < NJ; j++) {
3342                    ResolveInfo resolveInfo = resolveInfos.get(j);
3343                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3344                        matchingResolveInfos.add(createForwardingResolveInfo(
3345                                resolveInfo.filter, userId, targetUserId));
3346                    }
3347                }
3348            }
3349        }
3350        return matchingResolveInfos;
3351    }
3352
3353    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3354            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3355            String packageName) {
3356        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3357        SparseArray<ArrayList<String>> sourceForwardingInfo =
3358                mSettings.mCrossProfilePackageInfo.get(userId);
3359        if (sourceForwardingInfo != null) {
3360            int NI = sourceForwardingInfo.size();
3361            for (int i = 0; i < NI; i++) {
3362                int targetUserId = sourceForwardingInfo.keyAt(i);
3363                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3364                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3365                            intent, resolvedType, flags, pkg.activities, targetUserId);
3366                    int NJ = resolveInfos.size();
3367                    for (int j = 0; j < NJ; j++) {
3368                        ResolveInfo resolveInfo = resolveInfos.get(j);
3369                        matchingResolveInfos.add(createForwardingResolveInfo(
3370                                resolveInfo.filter, userId, targetUserId));
3371                    }
3372                }
3373            }
3374        }
3375        return matchingResolveInfos;
3376    }
3377
3378    // Return matching ResolveInfo if any for skip current profile intent filters.
3379    private ResolveInfo queryCrossProfileIntents(
3380            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3381            int flags, int sourceUserId) {
3382        if (matchingFilters != null) {
3383            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3384            // match the same intent. For performance reasons, it is better not to
3385            // run queryIntent twice for the same userId
3386            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3387            int size = matchingFilters.size();
3388            for (int i = 0; i < size; i++) {
3389                CrossProfileIntentFilter filter = matchingFilters.get(i);
3390                int targetUserId = filter.getTargetUserId();
3391                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3392                        && !alreadyTriedUserIds.get(targetUserId)) {
3393                    // Checking if there are activities in the target user that can handle the
3394                    // intent.
3395                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3396                            flags, sourceUserId);
3397                    if (resolveInfo != null) return resolveInfo;
3398                    alreadyTriedUserIds.put(targetUserId, true);
3399                }
3400            }
3401        }
3402        return null;
3403    }
3404
3405    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3406            String resolvedType, int flags, int sourceUserId) {
3407        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3408                resolvedType, flags, filter.getTargetUserId());
3409        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3410            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3411        }
3412        return null;
3413    }
3414
3415    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3416            int sourceUserId, int targetUserId) {
3417        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3418        String className;
3419        if (targetUserId == UserHandle.USER_OWNER) {
3420            className = FORWARD_INTENT_TO_USER_OWNER;
3421        } else {
3422            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3423        }
3424        ComponentName forwardingActivityComponentName = new ComponentName(
3425                mAndroidApplication.packageName, className);
3426        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3427                sourceUserId);
3428        if (targetUserId == UserHandle.USER_OWNER) {
3429            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3430            forwardingResolveInfo.noResourceId = true;
3431        }
3432        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3433        forwardingResolveInfo.priority = 0;
3434        forwardingResolveInfo.preferredOrder = 0;
3435        forwardingResolveInfo.match = 0;
3436        forwardingResolveInfo.isDefault = true;
3437        forwardingResolveInfo.filter = filter;
3438        forwardingResolveInfo.targetUserId = targetUserId;
3439        return forwardingResolveInfo;
3440    }
3441
3442    @Override
3443    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3444            Intent[] specifics, String[] specificTypes, Intent intent,
3445            String resolvedType, int flags, int userId) {
3446        if (!sUserManager.exists(userId)) return Collections.emptyList();
3447        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3448                "query intent activity options");
3449        final String resultsAction = intent.getAction();
3450
3451        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3452                | PackageManager.GET_RESOLVED_FILTER, userId);
3453
3454        if (DEBUG_INTENT_MATCHING) {
3455            Log.v(TAG, "Query " + intent + ": " + results);
3456        }
3457
3458        int specificsPos = 0;
3459        int N;
3460
3461        // todo: note that the algorithm used here is O(N^2).  This
3462        // isn't a problem in our current environment, but if we start running
3463        // into situations where we have more than 5 or 10 matches then this
3464        // should probably be changed to something smarter...
3465
3466        // First we go through and resolve each of the specific items
3467        // that were supplied, taking care of removing any corresponding
3468        // duplicate items in the generic resolve list.
3469        if (specifics != null) {
3470            for (int i=0; i<specifics.length; i++) {
3471                final Intent sintent = specifics[i];
3472                if (sintent == null) {
3473                    continue;
3474                }
3475
3476                if (DEBUG_INTENT_MATCHING) {
3477                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3478                }
3479
3480                String action = sintent.getAction();
3481                if (resultsAction != null && resultsAction.equals(action)) {
3482                    // If this action was explicitly requested, then don't
3483                    // remove things that have it.
3484                    action = null;
3485                }
3486
3487                ResolveInfo ri = null;
3488                ActivityInfo ai = null;
3489
3490                ComponentName comp = sintent.getComponent();
3491                if (comp == null) {
3492                    ri = resolveIntent(
3493                        sintent,
3494                        specificTypes != null ? specificTypes[i] : null,
3495                            flags, userId);
3496                    if (ri == null) {
3497                        continue;
3498                    }
3499                    if (ri == mResolveInfo) {
3500                        // ACK!  Must do something better with this.
3501                    }
3502                    ai = ri.activityInfo;
3503                    comp = new ComponentName(ai.applicationInfo.packageName,
3504                            ai.name);
3505                } else {
3506                    ai = getActivityInfo(comp, flags, userId);
3507                    if (ai == null) {
3508                        continue;
3509                    }
3510                }
3511
3512                // Look for any generic query activities that are duplicates
3513                // of this specific one, and remove them from the results.
3514                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3515                N = results.size();
3516                int j;
3517                for (j=specificsPos; j<N; j++) {
3518                    ResolveInfo sri = results.get(j);
3519                    if ((sri.activityInfo.name.equals(comp.getClassName())
3520                            && sri.activityInfo.applicationInfo.packageName.equals(
3521                                    comp.getPackageName()))
3522                        || (action != null && sri.filter.matchAction(action))) {
3523                        results.remove(j);
3524                        if (DEBUG_INTENT_MATCHING) Log.v(
3525                            TAG, "Removing duplicate item from " + j
3526                            + " due to specific " + specificsPos);
3527                        if (ri == null) {
3528                            ri = sri;
3529                        }
3530                        j--;
3531                        N--;
3532                    }
3533                }
3534
3535                // Add this specific item to its proper place.
3536                if (ri == null) {
3537                    ri = new ResolveInfo();
3538                    ri.activityInfo = ai;
3539                }
3540                results.add(specificsPos, ri);
3541                ri.specificIndex = i;
3542                specificsPos++;
3543            }
3544        }
3545
3546        // Now we go through the remaining generic results and remove any
3547        // duplicate actions that are found here.
3548        N = results.size();
3549        for (int i=specificsPos; i<N-1; i++) {
3550            final ResolveInfo rii = results.get(i);
3551            if (rii.filter == null) {
3552                continue;
3553            }
3554
3555            // Iterate over all of the actions of this result's intent
3556            // filter...  typically this should be just one.
3557            final Iterator<String> it = rii.filter.actionsIterator();
3558            if (it == null) {
3559                continue;
3560            }
3561            while (it.hasNext()) {
3562                final String action = it.next();
3563                if (resultsAction != null && resultsAction.equals(action)) {
3564                    // If this action was explicitly requested, then don't
3565                    // remove things that have it.
3566                    continue;
3567                }
3568                for (int j=i+1; j<N; j++) {
3569                    final ResolveInfo rij = results.get(j);
3570                    if (rij.filter != null && rij.filter.hasAction(action)) {
3571                        results.remove(j);
3572                        if (DEBUG_INTENT_MATCHING) Log.v(
3573                            TAG, "Removing duplicate item from " + j
3574                            + " due to action " + action + " at " + i);
3575                        j--;
3576                        N--;
3577                    }
3578                }
3579            }
3580
3581            // If the caller didn't request filter information, drop it now
3582            // so we don't have to marshall/unmarshall it.
3583            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3584                rii.filter = null;
3585            }
3586        }
3587
3588        // Filter out the caller activity if so requested.
3589        if (caller != null) {
3590            N = results.size();
3591            for (int i=0; i<N; i++) {
3592                ActivityInfo ainfo = results.get(i).activityInfo;
3593                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3594                        && caller.getClassName().equals(ainfo.name)) {
3595                    results.remove(i);
3596                    break;
3597                }
3598            }
3599        }
3600
3601        // If the caller didn't request filter information,
3602        // drop them now so we don't have to
3603        // marshall/unmarshall it.
3604        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3605            N = results.size();
3606            for (int i=0; i<N; i++) {
3607                results.get(i).filter = null;
3608            }
3609        }
3610
3611        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3612        return results;
3613    }
3614
3615    @Override
3616    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3617            int userId) {
3618        if (!sUserManager.exists(userId)) return Collections.emptyList();
3619        ComponentName comp = intent.getComponent();
3620        if (comp == null) {
3621            if (intent.getSelector() != null) {
3622                intent = intent.getSelector();
3623                comp = intent.getComponent();
3624            }
3625        }
3626        if (comp != null) {
3627            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3628            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3629            if (ai != null) {
3630                ResolveInfo ri = new ResolveInfo();
3631                ri.activityInfo = ai;
3632                list.add(ri);
3633            }
3634            return list;
3635        }
3636
3637        // reader
3638        synchronized (mPackages) {
3639            String pkgName = intent.getPackage();
3640            if (pkgName == null) {
3641                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3642            }
3643            final PackageParser.Package pkg = mPackages.get(pkgName);
3644            if (pkg != null) {
3645                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3646                        userId);
3647            }
3648            return null;
3649        }
3650    }
3651
3652    @Override
3653    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3654        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3655        if (!sUserManager.exists(userId)) return null;
3656        if (query != null) {
3657            if (query.size() >= 1) {
3658                // If there is more than one service with the same priority,
3659                // just arbitrarily pick the first one.
3660                return query.get(0);
3661            }
3662        }
3663        return null;
3664    }
3665
3666    @Override
3667    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3668            int userId) {
3669        if (!sUserManager.exists(userId)) return Collections.emptyList();
3670        ComponentName comp = intent.getComponent();
3671        if (comp == null) {
3672            if (intent.getSelector() != null) {
3673                intent = intent.getSelector();
3674                comp = intent.getComponent();
3675            }
3676        }
3677        if (comp != null) {
3678            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3679            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3680            if (si != null) {
3681                final ResolveInfo ri = new ResolveInfo();
3682                ri.serviceInfo = si;
3683                list.add(ri);
3684            }
3685            return list;
3686        }
3687
3688        // reader
3689        synchronized (mPackages) {
3690            String pkgName = intent.getPackage();
3691            if (pkgName == null) {
3692                return mServices.queryIntent(intent, resolvedType, flags, userId);
3693            }
3694            final PackageParser.Package pkg = mPackages.get(pkgName);
3695            if (pkg != null) {
3696                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3697                        userId);
3698            }
3699            return null;
3700        }
3701    }
3702
3703    @Override
3704    public List<ResolveInfo> queryIntentContentProviders(
3705            Intent intent, String resolvedType, int flags, int userId) {
3706        if (!sUserManager.exists(userId)) return Collections.emptyList();
3707        ComponentName comp = intent.getComponent();
3708        if (comp == null) {
3709            if (intent.getSelector() != null) {
3710                intent = intent.getSelector();
3711                comp = intent.getComponent();
3712            }
3713        }
3714        if (comp != null) {
3715            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3716            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3717            if (pi != null) {
3718                final ResolveInfo ri = new ResolveInfo();
3719                ri.providerInfo = pi;
3720                list.add(ri);
3721            }
3722            return list;
3723        }
3724
3725        // reader
3726        synchronized (mPackages) {
3727            String pkgName = intent.getPackage();
3728            if (pkgName == null) {
3729                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3730            }
3731            final PackageParser.Package pkg = mPackages.get(pkgName);
3732            if (pkg != null) {
3733                return mProviders.queryIntentForPackage(
3734                        intent, resolvedType, flags, pkg.providers, userId);
3735            }
3736            return null;
3737        }
3738    }
3739
3740    @Override
3741    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3742        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3743
3744        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3745
3746        // writer
3747        synchronized (mPackages) {
3748            ArrayList<PackageInfo> list;
3749            if (listUninstalled) {
3750                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3751                for (PackageSetting ps : mSettings.mPackages.values()) {
3752                    PackageInfo pi;
3753                    if (ps.pkg != null) {
3754                        pi = generatePackageInfo(ps.pkg, flags, userId);
3755                    } else {
3756                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3757                    }
3758                    if (pi != null) {
3759                        list.add(pi);
3760                    }
3761                }
3762            } else {
3763                list = new ArrayList<PackageInfo>(mPackages.size());
3764                for (PackageParser.Package p : mPackages.values()) {
3765                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3766                    if (pi != null) {
3767                        list.add(pi);
3768                    }
3769                }
3770            }
3771
3772            return new ParceledListSlice<PackageInfo>(list);
3773        }
3774    }
3775
3776    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3777            String[] permissions, boolean[] tmp, int flags, int userId) {
3778        int numMatch = 0;
3779        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3780        for (int i=0; i<permissions.length; i++) {
3781            if (gp.grantedPermissions.contains(permissions[i])) {
3782                tmp[i] = true;
3783                numMatch++;
3784            } else {
3785                tmp[i] = false;
3786            }
3787        }
3788        if (numMatch == 0) {
3789            return;
3790        }
3791        PackageInfo pi;
3792        if (ps.pkg != null) {
3793            pi = generatePackageInfo(ps.pkg, flags, userId);
3794        } else {
3795            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3796        }
3797        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3798            if (numMatch == permissions.length) {
3799                pi.requestedPermissions = permissions;
3800            } else {
3801                pi.requestedPermissions = new String[numMatch];
3802                numMatch = 0;
3803                for (int i=0; i<permissions.length; i++) {
3804                    if (tmp[i]) {
3805                        pi.requestedPermissions[numMatch] = permissions[i];
3806                        numMatch++;
3807                    }
3808                }
3809            }
3810        }
3811        list.add(pi);
3812    }
3813
3814    @Override
3815    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3816            String[] permissions, int flags, int userId) {
3817        if (!sUserManager.exists(userId)) return null;
3818        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3819
3820        // writer
3821        synchronized (mPackages) {
3822            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3823            boolean[] tmpBools = new boolean[permissions.length];
3824            if (listUninstalled) {
3825                for (PackageSetting ps : mSettings.mPackages.values()) {
3826                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3827                }
3828            } else {
3829                for (PackageParser.Package pkg : mPackages.values()) {
3830                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3831                    if (ps != null) {
3832                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3833                                userId);
3834                    }
3835                }
3836            }
3837
3838            return new ParceledListSlice<PackageInfo>(list);
3839        }
3840    }
3841
3842    @Override
3843    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3844        if (!sUserManager.exists(userId)) return null;
3845        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3846
3847        // writer
3848        synchronized (mPackages) {
3849            ArrayList<ApplicationInfo> list;
3850            if (listUninstalled) {
3851                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3852                for (PackageSetting ps : mSettings.mPackages.values()) {
3853                    ApplicationInfo ai;
3854                    if (ps.pkg != null) {
3855                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3856                                ps.readUserState(userId), userId);
3857                    } else {
3858                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3859                    }
3860                    if (ai != null) {
3861                        list.add(ai);
3862                    }
3863                }
3864            } else {
3865                list = new ArrayList<ApplicationInfo>(mPackages.size());
3866                for (PackageParser.Package p : mPackages.values()) {
3867                    if (p.mExtras != null) {
3868                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3869                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3870                        if (ai != null) {
3871                            list.add(ai);
3872                        }
3873                    }
3874                }
3875            }
3876
3877            return new ParceledListSlice<ApplicationInfo>(list);
3878        }
3879    }
3880
3881    public List<ApplicationInfo> getPersistentApplications(int flags) {
3882        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3883
3884        // reader
3885        synchronized (mPackages) {
3886            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3887            final int userId = UserHandle.getCallingUserId();
3888            while (i.hasNext()) {
3889                final PackageParser.Package p = i.next();
3890                if (p.applicationInfo != null
3891                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3892                        && (!mSafeMode || isSystemApp(p))) {
3893                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3894                    if (ps != null) {
3895                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3896                                ps.readUserState(userId), userId);
3897                        if (ai != null) {
3898                            finalList.add(ai);
3899                        }
3900                    }
3901                }
3902            }
3903        }
3904
3905        return finalList;
3906    }
3907
3908    @Override
3909    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3910        if (!sUserManager.exists(userId)) return null;
3911        // reader
3912        synchronized (mPackages) {
3913            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3914            PackageSetting ps = provider != null
3915                    ? mSettings.mPackages.get(provider.owner.packageName)
3916                    : null;
3917            return ps != null
3918                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3919                    && (!mSafeMode || (provider.info.applicationInfo.flags
3920                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3921                    ? PackageParser.generateProviderInfo(provider, flags,
3922                            ps.readUserState(userId), userId)
3923                    : null;
3924        }
3925    }
3926
3927    /**
3928     * @deprecated
3929     */
3930    @Deprecated
3931    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3932        // reader
3933        synchronized (mPackages) {
3934            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3935                    .entrySet().iterator();
3936            final int userId = UserHandle.getCallingUserId();
3937            while (i.hasNext()) {
3938                Map.Entry<String, PackageParser.Provider> entry = i.next();
3939                PackageParser.Provider p = entry.getValue();
3940                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3941
3942                if (ps != null && p.syncable
3943                        && (!mSafeMode || (p.info.applicationInfo.flags
3944                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3945                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3946                            ps.readUserState(userId), userId);
3947                    if (info != null) {
3948                        outNames.add(entry.getKey());
3949                        outInfo.add(info);
3950                    }
3951                }
3952            }
3953        }
3954    }
3955
3956    @Override
3957    public List<ProviderInfo> queryContentProviders(String processName,
3958            int uid, int flags) {
3959        ArrayList<ProviderInfo> finalList = null;
3960        // reader
3961        synchronized (mPackages) {
3962            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3963            final int userId = processName != null ?
3964                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3965            while (i.hasNext()) {
3966                final PackageParser.Provider p = i.next();
3967                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3968                if (ps != null && p.info.authority != null
3969                        && (processName == null
3970                                || (p.info.processName.equals(processName)
3971                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3972                        && mSettings.isEnabledLPr(p.info, flags, userId)
3973                        && (!mSafeMode
3974                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3975                    if (finalList == null) {
3976                        finalList = new ArrayList<ProviderInfo>(3);
3977                    }
3978                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3979                            ps.readUserState(userId), userId);
3980                    if (info != null) {
3981                        finalList.add(info);
3982                    }
3983                }
3984            }
3985        }
3986
3987        if (finalList != null) {
3988            Collections.sort(finalList, mProviderInitOrderSorter);
3989        }
3990
3991        return finalList;
3992    }
3993
3994    @Override
3995    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3996            int flags) {
3997        // reader
3998        synchronized (mPackages) {
3999            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4000            return PackageParser.generateInstrumentationInfo(i, flags);
4001        }
4002    }
4003
4004    @Override
4005    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4006            int flags) {
4007        ArrayList<InstrumentationInfo> finalList =
4008            new ArrayList<InstrumentationInfo>();
4009
4010        // reader
4011        synchronized (mPackages) {
4012            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4013            while (i.hasNext()) {
4014                final PackageParser.Instrumentation p = i.next();
4015                if (targetPackage == null
4016                        || targetPackage.equals(p.info.targetPackage)) {
4017                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4018                            flags);
4019                    if (ii != null) {
4020                        finalList.add(ii);
4021                    }
4022                }
4023            }
4024        }
4025
4026        return finalList;
4027    }
4028
4029    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4030        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4031        if (overlays == null) {
4032            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4033            return;
4034        }
4035        for (PackageParser.Package opkg : overlays.values()) {
4036            // Not much to do if idmap fails: we already logged the error
4037            // and we certainly don't want to abort installation of pkg simply
4038            // because an overlay didn't fit properly. For these reasons,
4039            // ignore the return value of createIdmapForPackagePairLI.
4040            createIdmapForPackagePairLI(pkg, opkg);
4041        }
4042    }
4043
4044    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4045            PackageParser.Package opkg) {
4046        if (!opkg.mTrustedOverlay) {
4047            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4048                    opkg.baseCodePath + ": overlay not trusted");
4049            return false;
4050        }
4051        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4052        if (overlaySet == null) {
4053            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4054                    opkg.baseCodePath + " but target package has no known overlays");
4055            return false;
4056        }
4057        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4058        // TODO: generate idmap for split APKs
4059        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4060            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4061                    + opkg.baseCodePath);
4062            return false;
4063        }
4064        PackageParser.Package[] overlayArray =
4065            overlaySet.values().toArray(new PackageParser.Package[0]);
4066        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4067            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4068                return p1.mOverlayPriority - p2.mOverlayPriority;
4069            }
4070        };
4071        Arrays.sort(overlayArray, cmp);
4072
4073        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4074        int i = 0;
4075        for (PackageParser.Package p : overlayArray) {
4076            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4077        }
4078        return true;
4079    }
4080
4081    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4082        final File[] files = dir.listFiles();
4083        if (ArrayUtils.isEmpty(files)) {
4084            Log.d(TAG, "No files in app dir " + dir);
4085            return;
4086        }
4087
4088        if (DEBUG_PACKAGE_SCANNING) {
4089            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4090                    + " flags=0x" + Integer.toHexString(flags));
4091        }
4092
4093        for (File file : files) {
4094            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4095                    && !PackageInstallerService.isStageFile(file);
4096            if (!isPackage) {
4097                // Ignore entries which are not apk's
4098                continue;
4099            }
4100            try {
4101                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
4102            } catch (PackageManagerException e) {
4103                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4104
4105                // Don't mess around with apps in system partition.
4106                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4107                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4108                    // Delete the apk
4109                    Slog.w(TAG, "Cleaning up failed install of " + file);
4110                    file.delete();
4111                }
4112            }
4113        }
4114    }
4115
4116    private static File getSettingsProblemFile() {
4117        File dataDir = Environment.getDataDirectory();
4118        File systemDir = new File(dataDir, "system");
4119        File fname = new File(systemDir, "uiderrors.txt");
4120        return fname;
4121    }
4122
4123    static void reportSettingsProblem(int priority, String msg) {
4124        try {
4125            File fname = getSettingsProblemFile();
4126            FileOutputStream out = new FileOutputStream(fname, true);
4127            PrintWriter pw = new FastPrintWriter(out);
4128            SimpleDateFormat formatter = new SimpleDateFormat();
4129            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4130            pw.println(dateString + ": " + msg);
4131            pw.close();
4132            FileUtils.setPermissions(
4133                    fname.toString(),
4134                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4135                    -1, -1);
4136        } catch (java.io.IOException e) {
4137        }
4138        Slog.println(priority, TAG, msg);
4139    }
4140
4141    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4142            PackageParser.Package pkg, File srcFile, int parseFlags)
4143            throws PackageManagerException {
4144        if (ps != null
4145                && ps.codePath.equals(srcFile)
4146                && ps.timeStamp == srcFile.lastModified()
4147                && !isCompatSignatureUpdateNeeded(pkg)) {
4148            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4149            if (ps.signatures.mSignatures != null
4150                    && ps.signatures.mSignatures.length != 0
4151                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4152                // Optimization: reuse the existing cached certificates
4153                // if the package appears to be unchanged.
4154                pkg.mSignatures = ps.signatures.mSignatures;
4155                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4156                synchronized (mPackages) {
4157                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4158                }
4159                return;
4160            }
4161
4162            Slog.w(TAG, "PackageSetting for " + ps.name
4163                    + " is missing signatures.  Collecting certs again to recover them.");
4164        } else {
4165            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4166        }
4167
4168        try {
4169            pp.collectCertificates(pkg, parseFlags);
4170            pp.collectManifestDigest(pkg);
4171        } catch (PackageParserException e) {
4172            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4173                    + pkg.packageName + ": " + e.getMessage());
4174        }
4175    }
4176
4177    /*
4178     *  Scan a package and return the newly parsed package.
4179     *  Returns null in case of errors and the error code is stored in mLastScanError
4180     */
4181    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4182            long currentTime, UserHandle user) throws PackageManagerException {
4183        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4184        parseFlags |= mDefParseFlags;
4185        PackageParser pp = new PackageParser();
4186        pp.setSeparateProcesses(mSeparateProcesses);
4187        pp.setOnlyCoreApps(mOnlyCore);
4188        pp.setDisplayMetrics(mMetrics);
4189
4190        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4191            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4192        }
4193
4194        final PackageParser.Package pkg;
4195        try {
4196            pkg = pp.parsePackage(scanFile, parseFlags);
4197        } catch (PackageParserException e) {
4198            throw new PackageManagerException(e.error,
4199                    "Failed to scan " + scanFile + ": " + e.getMessage());
4200        }
4201
4202        PackageSetting ps = null;
4203        PackageSetting updatedPkg;
4204        // reader
4205        synchronized (mPackages) {
4206            // Look to see if we already know about this package.
4207            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4208            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4209                // This package has been renamed to its original name.  Let's
4210                // use that.
4211                ps = mSettings.peekPackageLPr(oldName);
4212            }
4213            // If there was no original package, see one for the real package name.
4214            if (ps == null) {
4215                ps = mSettings.peekPackageLPr(pkg.packageName);
4216            }
4217            // Check to see if this package could be hiding/updating a system
4218            // package.  Must look for it either under the original or real
4219            // package name depending on our state.
4220            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4221            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4222        }
4223        boolean updatedPkgBetter = false;
4224        // First check if this is a system package that may involve an update
4225        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4226            if (ps != null && !ps.codePath.equals(scanFile)) {
4227                // The path has changed from what was last scanned...  check the
4228                // version of the new path against what we have stored to determine
4229                // what to do.
4230                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4231                if (pkg.mVersionCode < ps.versionCode) {
4232                    // The system package has been updated and the code path does not match
4233                    // Ignore entry. Skip it.
4234                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4235                            + " ignored: updated version " + ps.versionCode
4236                            + " better than this " + pkg.mVersionCode);
4237                    if (!updatedPkg.codePath.equals(scanFile)) {
4238                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4239                                + ps.name + " changing from " + updatedPkg.codePathString
4240                                + " to " + scanFile);
4241                        updatedPkg.codePath = scanFile;
4242                        updatedPkg.codePathString = scanFile.toString();
4243                        // This is the point at which we know that the system-disk APK
4244                        // for this package has moved during a reboot (e.g. due to an OTA),
4245                        // so we need to reevaluate it for privilege policy.
4246                        if (locationIsPrivileged(scanFile)) {
4247                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4248                        }
4249                    }
4250                    updatedPkg.pkg = pkg;
4251                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4252                } else {
4253                    // The current app on the system partition is better than
4254                    // what we have updated to on the data partition; switch
4255                    // back to the system partition version.
4256                    // At this point, its safely assumed that package installation for
4257                    // apps in system partition will go through. If not there won't be a working
4258                    // version of the app
4259                    // writer
4260                    synchronized (mPackages) {
4261                        // Just remove the loaded entries from package lists.
4262                        mPackages.remove(ps.name);
4263                    }
4264                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4265                            + "reverting from " + ps.codePathString
4266                            + ": new version " + pkg.mVersionCode
4267                            + " better than installed " + ps.versionCode);
4268
4269                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4270                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4271                            getAppDexInstructionSets(ps), isMultiArch(ps));
4272                    synchronized (mInstallLock) {
4273                        args.cleanUpResourcesLI();
4274                    }
4275                    synchronized (mPackages) {
4276                        mSettings.enableSystemPackageLPw(ps.name);
4277                    }
4278                    updatedPkgBetter = true;
4279                }
4280            }
4281        }
4282
4283        if (updatedPkg != null) {
4284            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4285            // initially
4286            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4287
4288            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4289            // flag set initially
4290            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4291                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4292            }
4293        }
4294
4295        // Verify certificates against what was last scanned
4296        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4297
4298        /*
4299         * A new system app appeared, but we already had a non-system one of the
4300         * same name installed earlier.
4301         */
4302        boolean shouldHideSystemApp = false;
4303        if (updatedPkg == null && ps != null
4304                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4305            /*
4306             * Check to make sure the signatures match first. If they don't,
4307             * wipe the installed application and its data.
4308             */
4309            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4310                    != PackageManager.SIGNATURE_MATCH) {
4311                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4312                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4313                ps = null;
4314            } else {
4315                /*
4316                 * If the newly-added system app is an older version than the
4317                 * already installed version, hide it. It will be scanned later
4318                 * and re-added like an update.
4319                 */
4320                if (pkg.mVersionCode < ps.versionCode) {
4321                    shouldHideSystemApp = true;
4322                } else {
4323                    /*
4324                     * The newly found system app is a newer version that the
4325                     * one previously installed. Simply remove the
4326                     * already-installed application and replace it with our own
4327                     * while keeping the application data.
4328                     */
4329                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4330                            + ps.codePathString + ": new version " + pkg.mVersionCode
4331                            + " better than installed " + ps.versionCode);
4332                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4333                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4334                            getAppDexInstructionSets(ps), isMultiArch(ps));
4335                    synchronized (mInstallLock) {
4336                        args.cleanUpResourcesLI();
4337                    }
4338                }
4339            }
4340        }
4341
4342        // The apk is forward locked (not public) if its code and resources
4343        // are kept in different files. (except for app in either system or
4344        // vendor path).
4345        // TODO grab this value from PackageSettings
4346        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4347            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4348                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4349            }
4350        }
4351
4352        // TODO: extend to support forward-locked splits
4353        String resourcePath = null;
4354        String baseResourcePath = null;
4355        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4356            if (ps != null && ps.resourcePathString != null) {
4357                resourcePath = ps.resourcePathString;
4358                baseResourcePath = ps.resourcePathString;
4359            } else {
4360                // Should not happen at all. Just log an error.
4361                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4362            }
4363        } else {
4364            resourcePath = pkg.codePath;
4365            baseResourcePath = pkg.baseCodePath;
4366        }
4367
4368        // Set application objects path explicitly.
4369        pkg.applicationInfo.setCodePath(pkg.codePath);
4370        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4371        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4372        pkg.applicationInfo.setResourcePath(resourcePath);
4373        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4374        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4375
4376        // Note that we invoke the following method only if we are about to unpack an application
4377        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4378                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4379
4380        /*
4381         * If the system app should be overridden by a previously installed
4382         * data, hide the system app now and let the /data/app scan pick it up
4383         * again.
4384         */
4385        if (shouldHideSystemApp) {
4386            synchronized (mPackages) {
4387                /*
4388                 * We have to grant systems permissions before we hide, because
4389                 * grantPermissions will assume the package update is trying to
4390                 * expand its permissions.
4391                 */
4392                grantPermissionsLPw(pkg, true);
4393                mSettings.disableSystemPackageLPw(pkg.packageName);
4394            }
4395        }
4396
4397        return scannedPkg;
4398    }
4399
4400    private static String fixProcessName(String defProcessName,
4401            String processName, int uid) {
4402        if (processName == null) {
4403            return defProcessName;
4404        }
4405        return processName;
4406    }
4407
4408    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4409            throws PackageManagerException {
4410        if (pkgSetting.signatures.mSignatures != null) {
4411            // Already existing package. Make sure signatures match
4412            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4413                    == PackageManager.SIGNATURE_MATCH;
4414            if (!match) {
4415                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4416                        == PackageManager.SIGNATURE_MATCH;
4417            }
4418            if (!match) {
4419                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4420                        + pkg.packageName + " signatures do not match the "
4421                        + "previously installed version; ignoring!");
4422            }
4423        }
4424
4425        // Check for shared user signatures
4426        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4427            // Already existing package. Make sure signatures match
4428            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4429                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4430            if (!match) {
4431                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4432                        == PackageManager.SIGNATURE_MATCH;
4433            }
4434            if (!match) {
4435                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4436                        "Package " + pkg.packageName
4437                        + " has no signatures that match those in shared user "
4438                        + pkgSetting.sharedUser.name + "; ignoring!");
4439            }
4440        }
4441    }
4442
4443    /**
4444     * Enforces that only the system UID or root's UID can call a method exposed
4445     * via Binder.
4446     *
4447     * @param message used as message if SecurityException is thrown
4448     * @throws SecurityException if the caller is not system or root
4449     */
4450    private static final void enforceSystemOrRoot(String message) {
4451        final int uid = Binder.getCallingUid();
4452        if (uid != Process.SYSTEM_UID && uid != 0) {
4453            throw new SecurityException(message);
4454        }
4455    }
4456
4457    @Override
4458    public void performBootDexOpt() {
4459        enforceSystemOrRoot("Only the system can request dexopt be performed");
4460
4461        final HashSet<PackageParser.Package> pkgs;
4462        synchronized (mPackages) {
4463            pkgs = mDeferredDexOpt;
4464            mDeferredDexOpt = null;
4465        }
4466
4467        if (pkgs != null) {
4468            // Filter out packages that aren't recently used.
4469            //
4470            // The exception is first boot of a non-eng device, which
4471            // should do a full dexopt.
4472            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4473            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4474                // TODO: add a property to control this?
4475                long dexOptLRUThresholdInMinutes;
4476                if (eng) {
4477                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4478                } else {
4479                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4480                }
4481                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4482
4483                int total = pkgs.size();
4484                int skipped = 0;
4485                long now = System.currentTimeMillis();
4486                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4487                    PackageParser.Package pkg = i.next();
4488                    long then = pkg.mLastPackageUsageTimeInMills;
4489                    if (then + dexOptLRUThresholdInMills < now) {
4490                        if (DEBUG_DEXOPT) {
4491                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4492                                  ((then == 0) ? "never" : new Date(then)));
4493                        }
4494                        i.remove();
4495                        skipped++;
4496                    }
4497                }
4498                if (DEBUG_DEXOPT) {
4499                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4500                }
4501            }
4502
4503            int i = 0;
4504            for (PackageParser.Package pkg : pkgs) {
4505                i++;
4506                if (DEBUG_DEXOPT) {
4507                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4508                          + ": " + pkg.packageName);
4509                }
4510                if (!isFirstBoot()) {
4511                    try {
4512                        ActivityManagerNative.getDefault().showBootMessage(
4513                                mContext.getResources().getString(
4514                                        R.string.android_upgrading_apk,
4515                                        i, pkgs.size()), true);
4516                    } catch (RemoteException e) {
4517                    }
4518                }
4519                PackageParser.Package p = pkg;
4520                synchronized (mInstallLock) {
4521                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4522                            true /* include dependencies */);
4523                }
4524            }
4525        }
4526    }
4527
4528    @Override
4529    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4530        return performDexOpt(packageName, instructionSet, true);
4531    }
4532
4533    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4534        if (info.primaryCpuAbi == null) {
4535            return getPreferredInstructionSet();
4536        }
4537
4538        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4539    }
4540
4541    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4542        PackageParser.Package p;
4543        final String targetInstructionSet;
4544        synchronized (mPackages) {
4545            p = mPackages.get(packageName);
4546            if (p == null) {
4547                return false;
4548            }
4549            if (updateUsage) {
4550                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4551            }
4552            mPackageUsage.write(false);
4553
4554            targetInstructionSet = instructionSet != null ? instructionSet :
4555                    getPrimaryInstructionSet(p.applicationInfo);
4556            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4557                return false;
4558            }
4559        }
4560
4561        synchronized (mInstallLock) {
4562            final String[] instructionSets = new String[] { targetInstructionSet };
4563            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4564                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4565        }
4566    }
4567
4568    public HashSet<String> getPackagesThatNeedDexOpt() {
4569        HashSet<String> pkgs = null;
4570        synchronized (mPackages) {
4571            for (PackageParser.Package p : mPackages.values()) {
4572                if (DEBUG_DEXOPT) {
4573                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4574                }
4575                if (!p.mDexOptPerformed.isEmpty()) {
4576                    continue;
4577                }
4578                if (pkgs == null) {
4579                    pkgs = new HashSet<String>();
4580                }
4581                pkgs.add(p.packageName);
4582            }
4583        }
4584        return pkgs;
4585    }
4586
4587    public void shutdown() {
4588        mPackageUsage.write(true);
4589    }
4590
4591    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4592             boolean forceDex, boolean defer, HashSet<String> done) {
4593        for (int i=0; i<libs.size(); i++) {
4594            PackageParser.Package libPkg;
4595            String libName;
4596            synchronized (mPackages) {
4597                libName = libs.get(i);
4598                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4599                if (lib != null && lib.apk != null) {
4600                    libPkg = mPackages.get(lib.apk);
4601                } else {
4602                    libPkg = null;
4603                }
4604            }
4605            if (libPkg != null && !done.contains(libName)) {
4606                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4607            }
4608        }
4609    }
4610
4611    static final int DEX_OPT_SKIPPED = 0;
4612    static final int DEX_OPT_PERFORMED = 1;
4613    static final int DEX_OPT_DEFERRED = 2;
4614    static final int DEX_OPT_FAILED = -1;
4615
4616    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4617            boolean forceDex, boolean defer, HashSet<String> done) {
4618        final String[] instructionSets = targetInstructionSets != null ?
4619                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4620
4621        if (done != null) {
4622            done.add(pkg.packageName);
4623            if (pkg.usesLibraries != null) {
4624                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4625            }
4626            if (pkg.usesOptionalLibraries != null) {
4627                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4628            }
4629        }
4630
4631        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4632            return DEX_OPT_SKIPPED;
4633        }
4634
4635        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4636        boolean performedDexOpt = false;
4637        // There are three basic cases here:
4638        // 1.) we need to dexopt, either because we are forced or it is needed
4639        // 2.) we are defering a needed dexopt
4640        // 3.) we are skipping an unneeded dexopt
4641        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4642        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4643            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4644                continue;
4645            }
4646
4647            for (String path : paths) {
4648                try {
4649                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4650                    // patckage or the one we find does not match the image checksum (i.e. it was
4651                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4652                    // odex file and it matches the checksum of the image but not its base address,
4653                    // meaning we need to move it.
4654                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4655                            pkg.packageName, dexCodeInstructionSet, defer);
4656                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4657                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4658                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet);
4659                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4660                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4661                                pkg.packageName, dexCodeInstructionSet);
4662
4663                        if (ret < 0) {
4664                            // Don't bother running dexopt again if we failed, it will probably
4665                            // just result in an error again. Also, don't bother dexopting for other
4666                            // paths & ISAs.
4667                            return DEX_OPT_FAILED;
4668                        }
4669
4670                        performedDexOpt = true;
4671                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4672                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4673                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4674                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4675                                pkg.packageName, dexCodeInstructionSet);
4676
4677                        if (ret < 0) {
4678                            // Don't bother running patchoat again if we failed, it will probably
4679                            // just result in an error again. Also, don't bother dexopting for other
4680                            // paths & ISAs.
4681                            return DEX_OPT_FAILED;
4682                        }
4683
4684                        performedDexOpt = true;
4685                    }
4686
4687                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4688                    // paths and instruction sets. We'll deal with them all together when we process
4689                    // our list of deferred dexopts.
4690                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4691                        if (mDeferredDexOpt == null) {
4692                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4693                        }
4694                        mDeferredDexOpt.add(pkg);
4695                        return DEX_OPT_DEFERRED;
4696                    }
4697                } catch (FileNotFoundException e) {
4698                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4699                    return DEX_OPT_FAILED;
4700                } catch (IOException e) {
4701                    Slog.w(TAG, "IOException reading apk: " + path, e);
4702                    return DEX_OPT_FAILED;
4703                } catch (StaleDexCacheError e) {
4704                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4705                    return DEX_OPT_FAILED;
4706                } catch (Exception e) {
4707                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4708                    return DEX_OPT_FAILED;
4709                }
4710            }
4711
4712            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4713            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4714            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4715            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4716            // it.
4717            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4718        }
4719
4720        // If we've gotten here, we're sure that no error occurred and that we haven't
4721        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4722        // we've skipped all of them because they are up to date. In both cases this
4723        // package doesn't need dexopt any longer.
4724        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4725    }
4726
4727    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4728        if (info.primaryCpuAbi != null) {
4729            if (info.secondaryCpuAbi != null) {
4730                return new String[] {
4731                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4732                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4733            } else {
4734                return new String[] {
4735                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4736            }
4737        }
4738
4739        return new String[] { getPreferredInstructionSet() };
4740    }
4741
4742    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4743        if (ps.primaryCpuAbiString != null) {
4744            if (ps.secondaryCpuAbiString != null) {
4745                return new String[] {
4746                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4747                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4748            } else {
4749                return new String[] {
4750                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4751            }
4752        }
4753
4754        return new String[] { getPreferredInstructionSet() };
4755    }
4756
4757    private static String getPreferredInstructionSet() {
4758        if (sPreferredInstructionSet == null) {
4759            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4760        }
4761
4762        return sPreferredInstructionSet;
4763    }
4764
4765    private static List<String> getAllInstructionSets() {
4766        final String[] allAbis = Build.SUPPORTED_ABIS;
4767        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4768
4769        for (String abi : allAbis) {
4770            final String instructionSet = VMRuntime.getInstructionSet(abi);
4771            if (!allInstructionSets.contains(instructionSet)) {
4772                allInstructionSets.add(instructionSet);
4773            }
4774        }
4775
4776        return allInstructionSets;
4777    }
4778
4779    /**
4780     * Returns the instruction set that should be used to compile dex code. In the presence of
4781     * a native bridge this might be different than the one shared libraries use.
4782     */
4783    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4784        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4785        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4786    }
4787
4788    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4789        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4790        for (String instructionSet : instructionSets) {
4791            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4792        }
4793        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4794    }
4795
4796    @Override
4797    public void forceDexOpt(String packageName) {
4798        enforceSystemOrRoot("forceDexOpt");
4799
4800        PackageParser.Package pkg;
4801        synchronized (mPackages) {
4802            pkg = mPackages.get(packageName);
4803            if (pkg == null) {
4804                throw new IllegalArgumentException("Missing package: " + packageName);
4805            }
4806        }
4807
4808        synchronized (mInstallLock) {
4809            final String[] instructionSets = new String[] {
4810                    getPrimaryInstructionSet(pkg.applicationInfo) };
4811            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4812            if (res != DEX_OPT_PERFORMED) {
4813                throw new IllegalStateException("Failed to dexopt: " + res);
4814            }
4815        }
4816    }
4817
4818    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4819                                boolean forceDex, boolean defer, boolean inclDependencies) {
4820        HashSet<String> done;
4821        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4822            done = new HashSet<String>();
4823            done.add(pkg.packageName);
4824        } else {
4825            done = null;
4826        }
4827        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4828    }
4829
4830    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4831        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4832            Slog.w(TAG, "Unable to update from " + oldPkg.name
4833                    + " to " + newPkg.packageName
4834                    + ": old package not in system partition");
4835            return false;
4836        } else if (mPackages.get(oldPkg.name) != null) {
4837            Slog.w(TAG, "Unable to update from " + oldPkg.name
4838                    + " to " + newPkg.packageName
4839                    + ": old package still exists");
4840            return false;
4841        }
4842        return true;
4843    }
4844
4845    File getDataPathForUser(int userId) {
4846        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4847    }
4848
4849    private File getDataPathForPackage(String packageName, int userId) {
4850        /*
4851         * Until we fully support multiple users, return the directory we
4852         * previously would have. The PackageManagerTests will need to be
4853         * revised when this is changed back..
4854         */
4855        if (userId == 0) {
4856            return new File(mAppDataDir, packageName);
4857        } else {
4858            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4859                + File.separator + packageName);
4860        }
4861    }
4862
4863    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4864        int[] users = sUserManager.getUserIds();
4865        int res = mInstaller.install(packageName, uid, uid, seinfo);
4866        if (res < 0) {
4867            return res;
4868        }
4869        for (int user : users) {
4870            if (user != 0) {
4871                res = mInstaller.createUserData(packageName,
4872                        UserHandle.getUid(user, uid), user, seinfo);
4873                if (res < 0) {
4874                    return res;
4875                }
4876            }
4877        }
4878        return res;
4879    }
4880
4881    private int removeDataDirsLI(String packageName) {
4882        int[] users = sUserManager.getUserIds();
4883        int res = 0;
4884        for (int user : users) {
4885            int resInner = mInstaller.remove(packageName, user);
4886            if (resInner < 0) {
4887                res = resInner;
4888            }
4889        }
4890
4891        return res;
4892    }
4893
4894    private int deleteCodeCacheDirsLI(String packageName) {
4895        int[] users = sUserManager.getUserIds();
4896        int res = 0;
4897        for (int user : users) {
4898            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4899            if (resInner < 0) {
4900                res = resInner;
4901            }
4902        }
4903        return res;
4904    }
4905
4906    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4907            PackageParser.Package changingLib) {
4908        if (file.path != null) {
4909            usesLibraryFiles.add(file.path);
4910            return;
4911        }
4912        PackageParser.Package p = mPackages.get(file.apk);
4913        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4914            // If we are doing this while in the middle of updating a library apk,
4915            // then we need to make sure to use that new apk for determining the
4916            // dependencies here.  (We haven't yet finished committing the new apk
4917            // to the package manager state.)
4918            if (p == null || p.packageName.equals(changingLib.packageName)) {
4919                p = changingLib;
4920            }
4921        }
4922        if (p != null) {
4923            usesLibraryFiles.addAll(p.getAllCodePaths());
4924        }
4925    }
4926
4927    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4928            PackageParser.Package changingLib) throws PackageManagerException {
4929        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4930            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4931            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4932            for (int i=0; i<N; i++) {
4933                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4934                if (file == null) {
4935                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4936                            "Package " + pkg.packageName + " requires unavailable shared library "
4937                            + pkg.usesLibraries.get(i) + "; failing!");
4938                }
4939                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4940            }
4941            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4942            for (int i=0; i<N; i++) {
4943                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4944                if (file == null) {
4945                    Slog.w(TAG, "Package " + pkg.packageName
4946                            + " desires unavailable shared library "
4947                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4948                } else {
4949                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4950                }
4951            }
4952            N = usesLibraryFiles.size();
4953            if (N > 0) {
4954                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4955            } else {
4956                pkg.usesLibraryFiles = null;
4957            }
4958        }
4959    }
4960
4961    private static boolean hasString(List<String> list, List<String> which) {
4962        if (list == null) {
4963            return false;
4964        }
4965        for (int i=list.size()-1; i>=0; i--) {
4966            for (int j=which.size()-1; j>=0; j--) {
4967                if (which.get(j).equals(list.get(i))) {
4968                    return true;
4969                }
4970            }
4971        }
4972        return false;
4973    }
4974
4975    private void updateAllSharedLibrariesLPw() {
4976        for (PackageParser.Package pkg : mPackages.values()) {
4977            try {
4978                updateSharedLibrariesLPw(pkg, null);
4979            } catch (PackageManagerException e) {
4980                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4981            }
4982        }
4983    }
4984
4985    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4986            PackageParser.Package changingPkg) {
4987        ArrayList<PackageParser.Package> res = null;
4988        for (PackageParser.Package pkg : mPackages.values()) {
4989            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4990                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4991                if (res == null) {
4992                    res = new ArrayList<PackageParser.Package>();
4993                }
4994                res.add(pkg);
4995                try {
4996                    updateSharedLibrariesLPw(pkg, changingPkg);
4997                } catch (PackageManagerException e) {
4998                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4999                }
5000            }
5001        }
5002        return res;
5003    }
5004
5005    /**
5006     * Derive the value of the {@code cpuAbiOverride} based on the provided
5007     * value and an optional stored value from the package settings.
5008     */
5009    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5010        String cpuAbiOverride = null;
5011
5012        if (CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5013            cpuAbiOverride = null;
5014        } else if (abiOverride != null) {
5015            cpuAbiOverride = abiOverride;
5016        } else if (settings != null) {
5017            cpuAbiOverride = settings.cpuAbiOverrideString;
5018        }
5019
5020        return cpuAbiOverride;
5021    }
5022
5023    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5024            int scanMode, long currentTime, UserHandle user)
5025            throws PackageManagerException {
5026        final File scanFile = new File(pkg.codePath);
5027        if (pkg.applicationInfo.getCodePath() == null ||
5028                pkg.applicationInfo.getResourcePath() == null) {
5029            // Bail out. The resource and code paths haven't been set.
5030            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5031                    "Code and resource paths haven't been set correctly");
5032        }
5033
5034        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5035            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5036        }
5037
5038        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5039            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5040        }
5041
5042        if (mCustomResolverComponentName != null &&
5043                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5044            setUpCustomResolverActivity(pkg);
5045        }
5046
5047        if (pkg.packageName.equals("android")) {
5048            synchronized (mPackages) {
5049                if (mAndroidApplication != null) {
5050                    Slog.w(TAG, "*************************************************");
5051                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5052                    Slog.w(TAG, " file=" + scanFile);
5053                    Slog.w(TAG, "*************************************************");
5054                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5055                            "Core android package being redefined.  Skipping.");
5056                }
5057
5058                // Set up information for our fall-back user intent resolution activity.
5059                mPlatformPackage = pkg;
5060                pkg.mVersionCode = mSdkVersion;
5061                mAndroidApplication = pkg.applicationInfo;
5062
5063                if (!mResolverReplaced) {
5064                    mResolveActivity.applicationInfo = mAndroidApplication;
5065                    mResolveActivity.name = ResolverActivity.class.getName();
5066                    mResolveActivity.packageName = mAndroidApplication.packageName;
5067                    mResolveActivity.processName = "system:ui";
5068                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5069                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5070                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5071                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5072                    mResolveActivity.exported = true;
5073                    mResolveActivity.enabled = true;
5074                    mResolveInfo.activityInfo = mResolveActivity;
5075                    mResolveInfo.priority = 0;
5076                    mResolveInfo.preferredOrder = 0;
5077                    mResolveInfo.match = 0;
5078                    mResolveComponentName = new ComponentName(
5079                            mAndroidApplication.packageName, mResolveActivity.name);
5080                }
5081            }
5082        }
5083
5084        if (DEBUG_PACKAGE_SCANNING) {
5085            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5086                Log.d(TAG, "Scanning package " + pkg.packageName);
5087        }
5088
5089        if (mPackages.containsKey(pkg.packageName)
5090                || mSharedLibraries.containsKey(pkg.packageName)) {
5091            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5092                    "Application package " + pkg.packageName
5093                    + " already installed.  Skipping duplicate.");
5094        }
5095
5096        // Initialize package source and resource directories
5097        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5098        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5099
5100        SharedUserSetting suid = null;
5101        PackageSetting pkgSetting = null;
5102
5103        if (!isSystemApp(pkg)) {
5104            // Only system apps can use these features.
5105            pkg.mOriginalPackages = null;
5106            pkg.mRealPackage = null;
5107            pkg.mAdoptPermissions = null;
5108        }
5109
5110        // writer
5111        synchronized (mPackages) {
5112            if (pkg.mSharedUserId != null) {
5113                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5114                if (suid == null) {
5115                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5116                            "Creating application package " + pkg.packageName
5117                            + " for shared user failed");
5118                }
5119                if (DEBUG_PACKAGE_SCANNING) {
5120                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5121                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5122                                + "): packages=" + suid.packages);
5123                }
5124            }
5125
5126            // Check if we are renaming from an original package name.
5127            PackageSetting origPackage = null;
5128            String realName = null;
5129            if (pkg.mOriginalPackages != null) {
5130                // This package may need to be renamed to a previously
5131                // installed name.  Let's check on that...
5132                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5133                if (pkg.mOriginalPackages.contains(renamed)) {
5134                    // This package had originally been installed as the
5135                    // original name, and we have already taken care of
5136                    // transitioning to the new one.  Just update the new
5137                    // one to continue using the old name.
5138                    realName = pkg.mRealPackage;
5139                    if (!pkg.packageName.equals(renamed)) {
5140                        // Callers into this function may have already taken
5141                        // care of renaming the package; only do it here if
5142                        // it is not already done.
5143                        pkg.setPackageName(renamed);
5144                    }
5145
5146                } else {
5147                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5148                        if ((origPackage = mSettings.peekPackageLPr(
5149                                pkg.mOriginalPackages.get(i))) != null) {
5150                            // We do have the package already installed under its
5151                            // original name...  should we use it?
5152                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5153                                // New package is not compatible with original.
5154                                origPackage = null;
5155                                continue;
5156                            } else if (origPackage.sharedUser != null) {
5157                                // Make sure uid is compatible between packages.
5158                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5159                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5160                                            + " to " + pkg.packageName + ": old uid "
5161                                            + origPackage.sharedUser.name
5162                                            + " differs from " + pkg.mSharedUserId);
5163                                    origPackage = null;
5164                                    continue;
5165                                }
5166                            } else {
5167                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5168                                        + pkg.packageName + " to old name " + origPackage.name);
5169                            }
5170                            break;
5171                        }
5172                    }
5173                }
5174            }
5175
5176            if (mTransferedPackages.contains(pkg.packageName)) {
5177                Slog.w(TAG, "Package " + pkg.packageName
5178                        + " was transferred to another, but its .apk remains");
5179            }
5180
5181            // Just create the setting, don't add it yet. For already existing packages
5182            // the PkgSetting exists already and doesn't have to be created.
5183            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5184                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5185                    pkg.applicationInfo.primaryCpuAbi,
5186                    pkg.applicationInfo.secondaryCpuAbi,
5187                    pkg.applicationInfo.flags, user, false);
5188            if (pkgSetting == null) {
5189                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5190                        "Creating application package " + pkg.packageName + " failed");
5191            }
5192
5193            if (pkgSetting.origPackage != null) {
5194                // If we are first transitioning from an original package,
5195                // fix up the new package's name now.  We need to do this after
5196                // looking up the package under its new name, so getPackageLP
5197                // can take care of fiddling things correctly.
5198                pkg.setPackageName(origPackage.name);
5199
5200                // File a report about this.
5201                String msg = "New package " + pkgSetting.realName
5202                        + " renamed to replace old package " + pkgSetting.name;
5203                reportSettingsProblem(Log.WARN, msg);
5204
5205                // Make a note of it.
5206                mTransferedPackages.add(origPackage.name);
5207
5208                // No longer need to retain this.
5209                pkgSetting.origPackage = null;
5210            }
5211
5212            if (realName != null) {
5213                // Make a note of it.
5214                mTransferedPackages.add(pkg.packageName);
5215            }
5216
5217            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5218                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5219            }
5220
5221            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5222                // Check all shared libraries and map to their actual file path.
5223                // We only do this here for apps not on a system dir, because those
5224                // are the only ones that can fail an install due to this.  We
5225                // will take care of the system apps by updating all of their
5226                // library paths after the scan is done.
5227                updateSharedLibrariesLPw(pkg, null);
5228            }
5229
5230            if (mFoundPolicyFile) {
5231                SELinuxMMAC.assignSeinfoValue(pkg);
5232            }
5233
5234            pkg.applicationInfo.uid = pkgSetting.appId;
5235            pkg.mExtras = pkgSetting;
5236            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5237                try {
5238                    verifySignaturesLP(pkgSetting, pkg);
5239                } catch (PackageManagerException e) {
5240                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5241                        throw e;
5242                    }
5243                    // The signature has changed, but this package is in the system
5244                    // image...  let's recover!
5245                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5246                    // However...  if this package is part of a shared user, but it
5247                    // doesn't match the signature of the shared user, let's fail.
5248                    // What this means is that you can't change the signatures
5249                    // associated with an overall shared user, which doesn't seem all
5250                    // that unreasonable.
5251                    if (pkgSetting.sharedUser != null) {
5252                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5253                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5254                            throw new PackageManagerException(
5255                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5256                                            "Signature mismatch for shared user : "
5257                                            + pkgSetting.sharedUser);
5258                        }
5259                    }
5260                    // File a report about this.
5261                    String msg = "System package " + pkg.packageName
5262                        + " signature changed; retaining data.";
5263                    reportSettingsProblem(Log.WARN, msg);
5264                }
5265            } else {
5266                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5267                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5268                            + pkg.packageName + " upgrade keys do not match the "
5269                            + "previously installed version");
5270                } else {
5271                    // signatures may have changed as result of upgrade
5272                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5273                }
5274            }
5275            // Verify that this new package doesn't have any content providers
5276            // that conflict with existing packages.  Only do this if the
5277            // package isn't already installed, since we don't want to break
5278            // things that are installed.
5279            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5280                final int N = pkg.providers.size();
5281                int i;
5282                for (i=0; i<N; i++) {
5283                    PackageParser.Provider p = pkg.providers.get(i);
5284                    if (p.info.authority != null) {
5285                        String names[] = p.info.authority.split(";");
5286                        for (int j = 0; j < names.length; j++) {
5287                            if (mProvidersByAuthority.containsKey(names[j])) {
5288                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5289                                final String otherPackageName =
5290                                        ((other != null && other.getComponentName() != null) ?
5291                                                other.getComponentName().getPackageName() : "?");
5292                                throw new PackageManagerException(
5293                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5294                                                "Can't install because provider name " + names[j]
5295                                                + " (in package " + pkg.applicationInfo.packageName
5296                                                + ") is already used by " + otherPackageName);
5297                            }
5298                        }
5299                    }
5300                }
5301            }
5302
5303            if (pkg.mAdoptPermissions != null) {
5304                // This package wants to adopt ownership of permissions from
5305                // another package.
5306                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5307                    final String origName = pkg.mAdoptPermissions.get(i);
5308                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5309                    if (orig != null) {
5310                        if (verifyPackageUpdateLPr(orig, pkg)) {
5311                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5312                                    + pkg.packageName);
5313                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5314                        }
5315                    }
5316                }
5317            }
5318        }
5319
5320        final String pkgName = pkg.packageName;
5321
5322        final long scanFileTime = scanFile.lastModified();
5323        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5324        pkg.applicationInfo.processName = fixProcessName(
5325                pkg.applicationInfo.packageName,
5326                pkg.applicationInfo.processName,
5327                pkg.applicationInfo.uid);
5328
5329        File dataPath;
5330        if (mPlatformPackage == pkg) {
5331            // The system package is special.
5332            dataPath = new File (Environment.getDataDirectory(), "system");
5333            pkg.applicationInfo.dataDir = dataPath.getPath();
5334
5335        } else {
5336            // This is a normal package, need to make its data directory.
5337            dataPath = getDataPathForPackage(pkg.packageName, 0);
5338
5339            boolean uidError = false;
5340
5341            if (dataPath.exists()) {
5342                int currentUid = 0;
5343                try {
5344                    StructStat stat = Os.stat(dataPath.getPath());
5345                    currentUid = stat.st_uid;
5346                } catch (ErrnoException e) {
5347                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5348                }
5349
5350                // If we have mismatched owners for the data path, we have a problem.
5351                if (currentUid != pkg.applicationInfo.uid) {
5352                    boolean recovered = false;
5353                    if (currentUid == 0) {
5354                        // The directory somehow became owned by root.  Wow.
5355                        // This is probably because the system was stopped while
5356                        // installd was in the middle of messing with its libs
5357                        // directory.  Ask installd to fix that.
5358                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5359                                pkg.applicationInfo.uid);
5360                        if (ret >= 0) {
5361                            recovered = true;
5362                            String msg = "Package " + pkg.packageName
5363                                    + " unexpectedly changed to uid 0; recovered to " +
5364                                    + pkg.applicationInfo.uid;
5365                            reportSettingsProblem(Log.WARN, msg);
5366                        }
5367                    }
5368                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5369                            || (scanMode&SCAN_BOOTING) != 0)) {
5370                        // If this is a system app, we can at least delete its
5371                        // current data so the application will still work.
5372                        int ret = removeDataDirsLI(pkgName);
5373                        if (ret >= 0) {
5374                            // TODO: Kill the processes first
5375                            // Old data gone!
5376                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5377                                    ? "System package " : "Third party package ";
5378                            String msg = prefix + pkg.packageName
5379                                    + " has changed from uid: "
5380                                    + currentUid + " to "
5381                                    + pkg.applicationInfo.uid + "; old data erased";
5382                            reportSettingsProblem(Log.WARN, msg);
5383                            recovered = true;
5384
5385                            // And now re-install the app.
5386                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5387                                                   pkg.applicationInfo.seinfo);
5388                            if (ret == -1) {
5389                                // Ack should not happen!
5390                                msg = prefix + pkg.packageName
5391                                        + " could not have data directory re-created after delete.";
5392                                reportSettingsProblem(Log.WARN, msg);
5393                                throw new PackageManagerException(
5394                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5395                            }
5396                        }
5397                        if (!recovered) {
5398                            mHasSystemUidErrors = true;
5399                        }
5400                    } else if (!recovered) {
5401                        // If we allow this install to proceed, we will be broken.
5402                        // Abort, abort!
5403                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5404                                "scanPackageLI");
5405                    }
5406                    if (!recovered) {
5407                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5408                            + pkg.applicationInfo.uid + "/fs_"
5409                            + currentUid;
5410                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5411                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5412                        String msg = "Package " + pkg.packageName
5413                                + " has mismatched uid: "
5414                                + currentUid + " on disk, "
5415                                + pkg.applicationInfo.uid + " in settings";
5416                        // writer
5417                        synchronized (mPackages) {
5418                            mSettings.mReadMessages.append(msg);
5419                            mSettings.mReadMessages.append('\n');
5420                            uidError = true;
5421                            if (!pkgSetting.uidError) {
5422                                reportSettingsProblem(Log.ERROR, msg);
5423                            }
5424                        }
5425                    }
5426                }
5427                pkg.applicationInfo.dataDir = dataPath.getPath();
5428                if (mShouldRestoreconData) {
5429                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5430                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5431                                pkg.applicationInfo.uid);
5432                }
5433            } else {
5434                if (DEBUG_PACKAGE_SCANNING) {
5435                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5436                        Log.v(TAG, "Want this data dir: " + dataPath);
5437                }
5438                //invoke installer to do the actual installation
5439                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5440                                           pkg.applicationInfo.seinfo);
5441                if (ret < 0) {
5442                    // Error from installer
5443                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5444                            "Unable to create data dirs [errorCode=" + ret + "]");
5445                }
5446
5447                if (dataPath.exists()) {
5448                    pkg.applicationInfo.dataDir = dataPath.getPath();
5449                } else {
5450                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5451                    pkg.applicationInfo.dataDir = null;
5452                }
5453            }
5454
5455            pkgSetting.uidError = uidError;
5456        }
5457
5458        final String path = scanFile.getPath();
5459        final String codePath = pkg.applicationInfo.getCodePath();
5460        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5461        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5462            setBundledAppAbisAndRoots(pkg, pkgSetting);
5463
5464            // If we haven't found any native libraries for the app, check if it has
5465            // renderscript code. We'll need to force the app to 32 bit if it has
5466            // renderscript bitcode.
5467            if (pkg.applicationInfo.primaryCpuAbi == null
5468                    && pkg.applicationInfo.secondaryCpuAbi == null
5469                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5470                NativeLibraryHelper.Handle handle = null;
5471                try {
5472                    handle = NativeLibraryHelper.Handle.create(scanFile);
5473                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5474                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5475                    }
5476                } catch (IOException ioe) {
5477                    Slog.w(TAG, "Error scanning system app : " + ioe);
5478                } finally {
5479                    IoUtils.closeQuietly(handle);
5480                }
5481            }
5482
5483            setNativeLibraryPaths(pkg);
5484        } else {
5485            // TODO: We can probably be smarter about this stuff. For installed apps,
5486            // we can calculate this information at install time once and for all. For
5487            // system apps, we can probably assume that this information doesn't change
5488            // after the first boot scan. As things stand, we do lots of unnecessary work.
5489
5490            // Give ourselves some initial paths; we'll come back for another
5491            // pass once we've determined ABI below.
5492            setNativeLibraryPaths(pkg);
5493
5494            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5495            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5496            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5497
5498            NativeLibraryHelper.Handle handle = null;
5499            try {
5500                handle = NativeLibraryHelper.Handle.create(scanFile);
5501                // TODO(multiArch): This can be null for apps that didn't go through the
5502                // usual installation process. We can calculate it again, like we
5503                // do during install time.
5504                //
5505                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5506                // unnecessary.
5507                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5508
5509                // Null out the abis so that they can be recalculated.
5510                pkg.applicationInfo.primaryCpuAbi = null;
5511                pkg.applicationInfo.secondaryCpuAbi = null;
5512                if (isMultiArch(pkg.applicationInfo)) {
5513                    // Warn if we've set an abiOverride for multi-lib packages..
5514                    // By definition, we need to copy both 32 and 64 bit libraries for
5515                    // such packages.
5516                    if (pkg.cpuAbiOverride != null && !CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5517                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5518                    }
5519
5520                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5521                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5522                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5523                        if (isAsec) {
5524                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5525                        } else {
5526                            abi32 = copyNativeLibrariesForInternalApp(handle,
5527                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5528                        }
5529                    }
5530
5531                    maybeThrowExceptionForMultiArchCopy(
5532                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5533
5534                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5535                        if (isAsec) {
5536                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5537                        } else {
5538                            abi64 = copyNativeLibrariesForInternalApp(handle,
5539                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5540                        }
5541                    }
5542
5543                    maybeThrowExceptionForMultiArchCopy(
5544                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5545
5546                    if (abi64 >= 0) {
5547                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5548                    }
5549
5550                    if (abi32 >= 0) {
5551                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5552                        if (abi64 >= 0) {
5553                            pkg.applicationInfo.secondaryCpuAbi = abi;
5554                        } else {
5555                            pkg.applicationInfo.primaryCpuAbi = abi;
5556                        }
5557                    }
5558                } else {
5559                    String[] abiList = (cpuAbiOverride != null) ?
5560                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5561
5562                    // Enable gross and lame hacks for apps that are built with old
5563                    // SDK tools. We must scan their APKs for renderscript bitcode and
5564                    // not launch them if it's present. Don't bother checking on devices
5565                    // that don't have 64 bit support.
5566                    boolean needsRenderScriptOverride = false;
5567                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5568                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5569                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5570                        needsRenderScriptOverride = true;
5571                    }
5572
5573                    final int copyRet;
5574                    if (isAsec) {
5575                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5576                    } else {
5577                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5578                                useIsaSpecificSubdirs);
5579                    }
5580
5581                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5582                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5583                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5584                    }
5585
5586                    if (copyRet >= 0) {
5587                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5588                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5589                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5590                    } else if (needsRenderScriptOverride) {
5591                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5592                    }
5593                }
5594            } catch (IOException ioe) {
5595                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5596            } finally {
5597                IoUtils.closeQuietly(handle);
5598            }
5599
5600            // Now that we've calculated the ABIs and determined if it's an internal app,
5601            // we will go ahead and populate the nativeLibraryPath.
5602            setNativeLibraryPaths(pkg);
5603
5604            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5605            final int[] userIds = sUserManager.getUserIds();
5606            synchronized (mInstallLock) {
5607                // Create a native library symlink only if we have native libraries
5608                // and if the native libraries are 32 bit libraries. We do not provide
5609                // this symlink for 64 bit libraries.
5610                if (pkg.applicationInfo.primaryCpuAbi != null &&
5611                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5612                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5613                    for (int userId : userIds) {
5614                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5615                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5616                                    "Failed linking native library dir (user=" + userId + ")");
5617                        }
5618                    }
5619                }
5620            }
5621        }
5622
5623        // This is a special case for the "system" package, where the ABI is
5624        // dictated by the zygote configuration (and init.rc). We should keep track
5625        // of this ABI so that we can deal with "normal" applications that run under
5626        // the same UID correctly.
5627        if (mPlatformPackage == pkg) {
5628            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5629                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5630        }
5631
5632        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5633        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5634        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5635        // Copy the derived override back to the parsed package, so that we can
5636        // update the package settings accordingly.
5637        pkg.cpuAbiOverride = cpuAbiOverride;
5638
5639        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5640                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5641                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5642
5643        // Push the derived path down into PackageSettings so we know what to
5644        // clean up at uninstall time.
5645        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5646
5647        if (DEBUG_ABI_SELECTION) {
5648            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5649                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5650                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5651        }
5652
5653        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5654            // We don't do this here during boot because we can do it all
5655            // at once after scanning all existing packages.
5656            //
5657            // We also do this *before* we perform dexopt on this package, so that
5658            // we can avoid redundant dexopts, and also to make sure we've got the
5659            // code and package path correct.
5660            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5661                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5662        }
5663
5664        if ((scanMode&SCAN_NO_DEX) == 0) {
5665            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5666                    == DEX_OPT_FAILED) {
5667                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5668                    removeDataDirsLI(pkg.packageName);
5669                }
5670
5671                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5672            }
5673        }
5674
5675        if (mFactoryTest && pkg.requestedPermissions.contains(
5676                android.Manifest.permission.FACTORY_TEST)) {
5677            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5678        }
5679
5680        ArrayList<PackageParser.Package> clientLibPkgs = null;
5681
5682        // writer
5683        synchronized (mPackages) {
5684            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5685                // Only system apps can add new shared libraries.
5686                if (pkg.libraryNames != null) {
5687                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5688                        String name = pkg.libraryNames.get(i);
5689                        boolean allowed = false;
5690                        if (isUpdatedSystemApp(pkg)) {
5691                            // New library entries can only be added through the
5692                            // system image.  This is important to get rid of a lot
5693                            // of nasty edge cases: for example if we allowed a non-
5694                            // system update of the app to add a library, then uninstalling
5695                            // the update would make the library go away, and assumptions
5696                            // we made such as through app install filtering would now
5697                            // have allowed apps on the device which aren't compatible
5698                            // with it.  Better to just have the restriction here, be
5699                            // conservative, and create many fewer cases that can negatively
5700                            // impact the user experience.
5701                            final PackageSetting sysPs = mSettings
5702                                    .getDisabledSystemPkgLPr(pkg.packageName);
5703                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5704                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5705                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5706                                        allowed = true;
5707                                        allowed = true;
5708                                        break;
5709                                    }
5710                                }
5711                            }
5712                        } else {
5713                            allowed = true;
5714                        }
5715                        if (allowed) {
5716                            if (!mSharedLibraries.containsKey(name)) {
5717                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5718                            } else if (!name.equals(pkg.packageName)) {
5719                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5720                                        + name + " already exists; skipping");
5721                            }
5722                        } else {
5723                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5724                                    + name + " that is not declared on system image; skipping");
5725                        }
5726                    }
5727                    if ((scanMode&SCAN_BOOTING) == 0) {
5728                        // If we are not booting, we need to update any applications
5729                        // that are clients of our shared library.  If we are booting,
5730                        // this will all be done once the scan is complete.
5731                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5732                    }
5733                }
5734            }
5735        }
5736
5737        // We also need to dexopt any apps that are dependent on this library.  Note that
5738        // if these fail, we should abort the install since installing the library will
5739        // result in some apps being broken.
5740        if (clientLibPkgs != null) {
5741            if ((scanMode&SCAN_NO_DEX) == 0) {
5742                for (int i=0; i<clientLibPkgs.size(); i++) {
5743                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5744                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5745                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5746                            == DEX_OPT_FAILED) {
5747                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5748                            removeDataDirsLI(pkg.packageName);
5749                        }
5750
5751                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5752                                "scanPackageLI failed to dexopt clientLibPkgs");
5753                    }
5754                }
5755            }
5756        }
5757
5758        // Request the ActivityManager to kill the process(only for existing packages)
5759        // so that we do not end up in a confused state while the user is still using the older
5760        // version of the application while the new one gets installed.
5761        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5762            // If the package lives in an asec, tell everyone that the container is going
5763            // away so they can clean up any references to its resources (which would prevent
5764            // vold from being able to unmount the asec)
5765            if (isForwardLocked(pkg) || isExternal(pkg)) {
5766                if (DEBUG_INSTALL) {
5767                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5768                }
5769                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5770                final ArrayList<String> pkgList = new ArrayList<String>(1);
5771                pkgList.add(pkg.applicationInfo.packageName);
5772                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5773            }
5774
5775            // Post the request that it be killed now that the going-away broadcast is en route
5776            killApplication(pkg.applicationInfo.packageName,
5777                        pkg.applicationInfo.uid, "update pkg");
5778        }
5779
5780        // Also need to kill any apps that are dependent on the library.
5781        if (clientLibPkgs != null) {
5782            for (int i=0; i<clientLibPkgs.size(); i++) {
5783                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5784                killApplication(clientPkg.applicationInfo.packageName,
5785                        clientPkg.applicationInfo.uid, "update lib");
5786            }
5787        }
5788
5789        // writer
5790        synchronized (mPackages) {
5791            // We don't expect installation to fail beyond this point,
5792            if ((scanMode&SCAN_MONITOR) != 0) {
5793                mAppDirs.put(pkg.codePath, pkg);
5794            }
5795            // Add the new setting to mSettings
5796            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5797            // Add the new setting to mPackages
5798            mPackages.put(pkg.applicationInfo.packageName, pkg);
5799            // Make sure we don't accidentally delete its data.
5800            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5801            while (iter.hasNext()) {
5802                PackageCleanItem item = iter.next();
5803                if (pkgName.equals(item.packageName)) {
5804                    iter.remove();
5805                }
5806            }
5807
5808            // Take care of first install / last update times.
5809            if (currentTime != 0) {
5810                if (pkgSetting.firstInstallTime == 0) {
5811                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5812                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5813                    pkgSetting.lastUpdateTime = currentTime;
5814                }
5815            } else if (pkgSetting.firstInstallTime == 0) {
5816                // We need *something*.  Take time time stamp of the file.
5817                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5818            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5819                if (scanFileTime != pkgSetting.timeStamp) {
5820                    // A package on the system image has changed; consider this
5821                    // to be an update.
5822                    pkgSetting.lastUpdateTime = scanFileTime;
5823                }
5824            }
5825
5826            // Add the package's KeySets to the global KeySetManagerService
5827            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5828            try {
5829                // Old KeySetData no longer valid.
5830                ksms.removeAppKeySetDataLPw(pkg.packageName);
5831                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5832                if (pkg.mKeySetMapping != null) {
5833                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5834                            pkg.mKeySetMapping.entrySet()) {
5835                        if (entry.getValue() != null) {
5836                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5837                                                          entry.getValue(), entry.getKey());
5838                        }
5839                    }
5840                    if (pkg.mUpgradeKeySets != null) {
5841                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5842                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5843                        }
5844                    }
5845                }
5846            } catch (NullPointerException e) {
5847                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5848            } catch (IllegalArgumentException e) {
5849                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5850            }
5851
5852            int N = pkg.providers.size();
5853            StringBuilder r = null;
5854            int i;
5855            for (i=0; i<N; i++) {
5856                PackageParser.Provider p = pkg.providers.get(i);
5857                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5858                        p.info.processName, pkg.applicationInfo.uid);
5859                mProviders.addProvider(p);
5860                p.syncable = p.info.isSyncable;
5861                if (p.info.authority != null) {
5862                    String names[] = p.info.authority.split(";");
5863                    p.info.authority = null;
5864                    for (int j = 0; j < names.length; j++) {
5865                        if (j == 1 && p.syncable) {
5866                            // We only want the first authority for a provider to possibly be
5867                            // syncable, so if we already added this provider using a different
5868                            // authority clear the syncable flag. We copy the provider before
5869                            // changing it because the mProviders object contains a reference
5870                            // to a provider that we don't want to change.
5871                            // Only do this for the second authority since the resulting provider
5872                            // object can be the same for all future authorities for this provider.
5873                            p = new PackageParser.Provider(p);
5874                            p.syncable = false;
5875                        }
5876                        if (!mProvidersByAuthority.containsKey(names[j])) {
5877                            mProvidersByAuthority.put(names[j], p);
5878                            if (p.info.authority == null) {
5879                                p.info.authority = names[j];
5880                            } else {
5881                                p.info.authority = p.info.authority + ";" + names[j];
5882                            }
5883                            if (DEBUG_PACKAGE_SCANNING) {
5884                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5885                                    Log.d(TAG, "Registered content provider: " + names[j]
5886                                            + ", className = " + p.info.name + ", isSyncable = "
5887                                            + p.info.isSyncable);
5888                            }
5889                        } else {
5890                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5891                            Slog.w(TAG, "Skipping provider name " + names[j] +
5892                                    " (in package " + pkg.applicationInfo.packageName +
5893                                    "): name already used by "
5894                                    + ((other != null && other.getComponentName() != null)
5895                                            ? other.getComponentName().getPackageName() : "?"));
5896                        }
5897                    }
5898                }
5899                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5900                    if (r == null) {
5901                        r = new StringBuilder(256);
5902                    } else {
5903                        r.append(' ');
5904                    }
5905                    r.append(p.info.name);
5906                }
5907            }
5908            if (r != null) {
5909                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5910            }
5911
5912            N = pkg.services.size();
5913            r = null;
5914            for (i=0; i<N; i++) {
5915                PackageParser.Service s = pkg.services.get(i);
5916                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5917                        s.info.processName, pkg.applicationInfo.uid);
5918                mServices.addService(s);
5919                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5920                    if (r == null) {
5921                        r = new StringBuilder(256);
5922                    } else {
5923                        r.append(' ');
5924                    }
5925                    r.append(s.info.name);
5926                }
5927            }
5928            if (r != null) {
5929                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5930            }
5931
5932            N = pkg.receivers.size();
5933            r = null;
5934            for (i=0; i<N; i++) {
5935                PackageParser.Activity a = pkg.receivers.get(i);
5936                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5937                        a.info.processName, pkg.applicationInfo.uid);
5938                mReceivers.addActivity(a, "receiver");
5939                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5940                    if (r == null) {
5941                        r = new StringBuilder(256);
5942                    } else {
5943                        r.append(' ');
5944                    }
5945                    r.append(a.info.name);
5946                }
5947            }
5948            if (r != null) {
5949                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5950            }
5951
5952            N = pkg.activities.size();
5953            r = null;
5954            for (i=0; i<N; i++) {
5955                PackageParser.Activity a = pkg.activities.get(i);
5956                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5957                        a.info.processName, pkg.applicationInfo.uid);
5958                mActivities.addActivity(a, "activity");
5959                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5960                    if (r == null) {
5961                        r = new StringBuilder(256);
5962                    } else {
5963                        r.append(' ');
5964                    }
5965                    r.append(a.info.name);
5966                }
5967            }
5968            if (r != null) {
5969                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5970            }
5971
5972            N = pkg.permissionGroups.size();
5973            r = null;
5974            for (i=0; i<N; i++) {
5975                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5976                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5977                if (cur == null) {
5978                    mPermissionGroups.put(pg.info.name, pg);
5979                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5980                        if (r == null) {
5981                            r = new StringBuilder(256);
5982                        } else {
5983                            r.append(' ');
5984                        }
5985                        r.append(pg.info.name);
5986                    }
5987                } else {
5988                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5989                            + pg.info.packageName + " ignored: original from "
5990                            + cur.info.packageName);
5991                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5992                        if (r == null) {
5993                            r = new StringBuilder(256);
5994                        } else {
5995                            r.append(' ');
5996                        }
5997                        r.append("DUP:");
5998                        r.append(pg.info.name);
5999                    }
6000                }
6001            }
6002            if (r != null) {
6003                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6004            }
6005
6006            N = pkg.permissions.size();
6007            r = null;
6008            for (i=0; i<N; i++) {
6009                PackageParser.Permission p = pkg.permissions.get(i);
6010                HashMap<String, BasePermission> permissionMap =
6011                        p.tree ? mSettings.mPermissionTrees
6012                        : mSettings.mPermissions;
6013                p.group = mPermissionGroups.get(p.info.group);
6014                if (p.info.group == null || p.group != null) {
6015                    BasePermission bp = permissionMap.get(p.info.name);
6016                    if (bp == null) {
6017                        bp = new BasePermission(p.info.name, p.info.packageName,
6018                                BasePermission.TYPE_NORMAL);
6019                        permissionMap.put(p.info.name, bp);
6020                    }
6021                    if (bp.perm == null) {
6022                        if (bp.sourcePackage != null
6023                                && !bp.sourcePackage.equals(p.info.packageName)) {
6024                            // If this is a permission that was formerly defined by a non-system
6025                            // app, but is now defined by a system app (following an upgrade),
6026                            // discard the previous declaration and consider the system's to be
6027                            // canonical.
6028                            if (isSystemApp(p.owner)) {
6029                                String msg = "New decl " + p.owner + " of permission  "
6030                                        + p.info.name + " is system";
6031                                reportSettingsProblem(Log.WARN, msg);
6032                                bp.sourcePackage = null;
6033                            }
6034                        }
6035                        if (bp.sourcePackage == null
6036                                || bp.sourcePackage.equals(p.info.packageName)) {
6037                            BasePermission tree = findPermissionTreeLP(p.info.name);
6038                            if (tree == null
6039                                    || tree.sourcePackage.equals(p.info.packageName)) {
6040                                bp.packageSetting = pkgSetting;
6041                                bp.perm = p;
6042                                bp.uid = pkg.applicationInfo.uid;
6043                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6044                                    if (r == null) {
6045                                        r = new StringBuilder(256);
6046                                    } else {
6047                                        r.append(' ');
6048                                    }
6049                                    r.append(p.info.name);
6050                                }
6051                            } else {
6052                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6053                                        + p.info.packageName + " ignored: base tree "
6054                                        + tree.name + " is from package "
6055                                        + tree.sourcePackage);
6056                            }
6057                        } else {
6058                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6059                                    + p.info.packageName + " ignored: original from "
6060                                    + bp.sourcePackage);
6061                        }
6062                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6063                        if (r == null) {
6064                            r = new StringBuilder(256);
6065                        } else {
6066                            r.append(' ');
6067                        }
6068                        r.append("DUP:");
6069                        r.append(p.info.name);
6070                    }
6071                    if (bp.perm == p) {
6072                        bp.protectionLevel = p.info.protectionLevel;
6073                    }
6074                } else {
6075                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6076                            + p.info.packageName + " ignored: no group "
6077                            + p.group);
6078                }
6079            }
6080            if (r != null) {
6081                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6082            }
6083
6084            N = pkg.instrumentation.size();
6085            r = null;
6086            for (i=0; i<N; i++) {
6087                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6088                a.info.packageName = pkg.applicationInfo.packageName;
6089                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6090                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6091                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6092                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6093                a.info.dataDir = pkg.applicationInfo.dataDir;
6094
6095                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6096                // need other information about the application, like the ABI and what not ?
6097                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6098                mInstrumentation.put(a.getComponentName(), a);
6099                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6100                    if (r == null) {
6101                        r = new StringBuilder(256);
6102                    } else {
6103                        r.append(' ');
6104                    }
6105                    r.append(a.info.name);
6106                }
6107            }
6108            if (r != null) {
6109                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6110            }
6111
6112            if (pkg.protectedBroadcasts != null) {
6113                N = pkg.protectedBroadcasts.size();
6114                for (i=0; i<N; i++) {
6115                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6116                }
6117            }
6118
6119            pkgSetting.setTimeStamp(scanFileTime);
6120
6121            // Create idmap files for pairs of (packages, overlay packages).
6122            // Note: "android", ie framework-res.apk, is handled by native layers.
6123            if (pkg.mOverlayTarget != null) {
6124                // This is an overlay package.
6125                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6126                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6127                        mOverlays.put(pkg.mOverlayTarget,
6128                                new HashMap<String, PackageParser.Package>());
6129                    }
6130                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6131                    map.put(pkg.packageName, pkg);
6132                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6133                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6134                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6135                                "scanPackageLI failed to createIdmap");
6136                    }
6137                }
6138            } else if (mOverlays.containsKey(pkg.packageName) &&
6139                    !pkg.packageName.equals("android")) {
6140                // This is a regular package, with one or more known overlay packages.
6141                createIdmapsForPackageLI(pkg);
6142            }
6143        }
6144
6145        return pkg;
6146    }
6147
6148    /**
6149     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6150     * i.e, so that all packages can be run inside a single process if required.
6151     *
6152     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6153     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6154     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6155     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6156     * updating a package that belongs to a shared user.
6157     *
6158     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6159     * adds unnecessary complexity.
6160     */
6161    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6162            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6163        String requiredInstructionSet = null;
6164        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6165            requiredInstructionSet = VMRuntime.getInstructionSet(
6166                     scannedPackage.applicationInfo.primaryCpuAbi);
6167        }
6168
6169        PackageSetting requirer = null;
6170        for (PackageSetting ps : packagesForUser) {
6171            // If packagesForUser contains scannedPackage, we skip it. This will happen
6172            // when scannedPackage is an update of an existing package. Without this check,
6173            // we will never be able to change the ABI of any package belonging to a shared
6174            // user, even if it's compatible with other packages.
6175            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6176                if (ps.primaryCpuAbiString == null) {
6177                    continue;
6178                }
6179
6180                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6181                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6182                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6183                    // this but there's not much we can do.
6184                    String errorMessage = "Instruction set mismatch, "
6185                            + ((requirer == null) ? "[caller]" : requirer)
6186                            + " requires " + requiredInstructionSet + " whereas " + ps
6187                            + " requires " + instructionSet;
6188                    Slog.w(TAG, errorMessage);
6189                }
6190
6191                if (requiredInstructionSet == null) {
6192                    requiredInstructionSet = instructionSet;
6193                    requirer = ps;
6194                }
6195            }
6196        }
6197
6198        if (requiredInstructionSet != null) {
6199            String adjustedAbi;
6200            if (requirer != null) {
6201                // requirer != null implies that either scannedPackage was null or that scannedPackage
6202                // did not require an ABI, in which case we have to adjust scannedPackage to match
6203                // the ABI of the set (which is the same as requirer's ABI)
6204                adjustedAbi = requirer.primaryCpuAbiString;
6205                if (scannedPackage != null) {
6206                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6207                }
6208            } else {
6209                // requirer == null implies that we're updating all ABIs in the set to
6210                // match scannedPackage.
6211                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6212            }
6213
6214            for (PackageSetting ps : packagesForUser) {
6215                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6216                    if (ps.primaryCpuAbiString != null) {
6217                        continue;
6218                    }
6219
6220                    ps.primaryCpuAbiString = adjustedAbi;
6221                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6222                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6223                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6224
6225                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6226                                deferDexOpt, true) == DEX_OPT_FAILED) {
6227                            ps.primaryCpuAbiString = null;
6228                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6229                            return;
6230                        } else {
6231                            mInstaller.rmdex(ps.codePathString,
6232                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6233                        }
6234                    }
6235                }
6236            }
6237        }
6238    }
6239
6240    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6241        synchronized (mPackages) {
6242            mResolverReplaced = true;
6243            // Set up information for custom user intent resolution activity.
6244            mResolveActivity.applicationInfo = pkg.applicationInfo;
6245            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6246            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6247            mResolveActivity.processName = null;
6248            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6249            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6250                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6251            mResolveActivity.theme = 0;
6252            mResolveActivity.exported = true;
6253            mResolveActivity.enabled = true;
6254            mResolveInfo.activityInfo = mResolveActivity;
6255            mResolveInfo.priority = 0;
6256            mResolveInfo.preferredOrder = 0;
6257            mResolveInfo.match = 0;
6258            mResolveComponentName = mCustomResolverComponentName;
6259            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6260                    mResolveComponentName);
6261        }
6262    }
6263
6264    private static String calculateBundledApkRoot(final String codePathString) {
6265        final File codePath = new File(codePathString);
6266        final File codeRoot;
6267        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6268            codeRoot = Environment.getRootDirectory();
6269        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6270            codeRoot = Environment.getOemDirectory();
6271        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6272            codeRoot = Environment.getVendorDirectory();
6273        } else {
6274            // Unrecognized code path; take its top real segment as the apk root:
6275            // e.g. /something/app/blah.apk => /something
6276            try {
6277                File f = codePath.getCanonicalFile();
6278                File parent = f.getParentFile();    // non-null because codePath is a file
6279                File tmp;
6280                while ((tmp = parent.getParentFile()) != null) {
6281                    f = parent;
6282                    parent = tmp;
6283                }
6284                codeRoot = f;
6285                Slog.w(TAG, "Unrecognized code path "
6286                        + codePath + " - using " + codeRoot);
6287            } catch (IOException e) {
6288                // Can't canonicalize the code path -- shenanigans?
6289                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6290                return Environment.getRootDirectory().getPath();
6291            }
6292        }
6293        return codeRoot.getPath();
6294    }
6295
6296    /**
6297     * Derive and set the location of native libraries for the given package,
6298     * which varies depending on where and how the package was installed.
6299     */
6300    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6301        final ApplicationInfo info = pkg.applicationInfo;
6302        final String codePath = pkg.codePath;
6303        final File codeFile = new File(codePath);
6304        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6305        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6306
6307        info.nativeLibraryRootDir = null;
6308        info.nativeLibraryRootRequiresIsa = false;
6309        info.nativeLibraryDir = null;
6310        info.secondaryNativeLibraryDir = null;
6311
6312        if (isApkFile(codeFile)) {
6313            // Monolithic install
6314            if (bundledApp) {
6315                // If "/system/lib64/apkname" exists, assume that is the per-package
6316                // native library directory to use; otherwise use "/system/lib/apkname".
6317                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6318                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6319                        getPrimaryInstructionSet(info));
6320
6321                // This is a bundled system app so choose the path based on the ABI.
6322                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6323                // is just the default path.
6324                final String apkName = deriveCodePathName(codePath);
6325                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6326                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6327                        apkName).getAbsolutePath();
6328
6329                if (info.secondaryCpuAbi != null) {
6330                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6331                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6332                            secondaryLibDir, apkName).getAbsolutePath();
6333                }
6334            } else if (asecApp) {
6335                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6336                        .getAbsolutePath();
6337            } else {
6338                final String apkName = deriveCodePathName(codePath);
6339                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6340                        .getAbsolutePath();
6341            }
6342
6343            info.nativeLibraryRootRequiresIsa = false;
6344            info.nativeLibraryDir = info.nativeLibraryRootDir;
6345        } else {
6346            // Cluster install
6347            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6348            info.nativeLibraryRootRequiresIsa = true;
6349
6350            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6351                    getPrimaryInstructionSet(info)).getAbsolutePath();
6352
6353            if (info.secondaryCpuAbi != null) {
6354                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6355                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6356            }
6357        }
6358    }
6359
6360    /**
6361     * Calculate the abis and roots for a bundled app. These can uniquely
6362     * be determined from the contents of the system partition, i.e whether
6363     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6364     * of this information, and instead assume that the system was built
6365     * sensibly.
6366     */
6367    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6368                                           PackageSetting pkgSetting) {
6369        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6370
6371        // If "/system/lib64/apkname" exists, assume that is the per-package
6372        // native library directory to use; otherwise use "/system/lib/apkname".
6373        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6374        setBundledAppAbi(pkg, apkRoot, apkName);
6375        // pkgSetting might be null during rescan following uninstall of updates
6376        // to a bundled app, so accommodate that possibility.  The settings in
6377        // that case will be established later from the parsed package.
6378        //
6379        // If the settings aren't null, sync them up with what we've just derived.
6380        // note that apkRoot isn't stored in the package settings.
6381        if (pkgSetting != null) {
6382            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6383            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6384        }
6385    }
6386
6387    /**
6388     * Deduces the ABI of a bundled app and sets the relevant fields on the
6389     * parsed pkg object.
6390     *
6391     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6392     *        under which system libraries are installed.
6393     * @param apkName the name of the installed package.
6394     */
6395    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6396        final File codeFile = new File(pkg.codePath);
6397
6398        final boolean has64BitLibs;
6399        final boolean has32BitLibs;
6400        if (isApkFile(codeFile)) {
6401            // Monolithic install
6402            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6403            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6404        } else {
6405            // Cluster install
6406            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6407            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6408                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6409                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6410                has64BitLibs = (new File(rootDir, isa)).exists();
6411            } else {
6412                has64BitLibs = false;
6413            }
6414            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6415                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6416                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6417                has32BitLibs = (new File(rootDir, isa)).exists();
6418            } else {
6419                has32BitLibs = false;
6420            }
6421        }
6422
6423        if (has64BitLibs && !has32BitLibs) {
6424            // The package has 64 bit libs, but not 32 bit libs. Its primary
6425            // ABI should be 64 bit. We can safely assume here that the bundled
6426            // native libraries correspond to the most preferred ABI in the list.
6427
6428            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6429            pkg.applicationInfo.secondaryCpuAbi = null;
6430        } else if (has32BitLibs && !has64BitLibs) {
6431            // The package has 32 bit libs but not 64 bit libs. Its primary
6432            // ABI should be 32 bit.
6433
6434            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6435            pkg.applicationInfo.secondaryCpuAbi = null;
6436        } else if (has32BitLibs && has64BitLibs) {
6437            // The application has both 64 and 32 bit bundled libraries. We check
6438            // here that the app declares multiArch support, and warn if it doesn't.
6439            //
6440            // We will be lenient here and record both ABIs. The primary will be the
6441            // ABI that's higher on the list, i.e, a device that's configured to prefer
6442            // 64 bit apps will see a 64 bit primary ABI,
6443
6444            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6445                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6446            }
6447
6448            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6449                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6450                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6451            } else {
6452                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6453                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6454            }
6455        } else {
6456            pkg.applicationInfo.primaryCpuAbi = null;
6457            pkg.applicationInfo.secondaryCpuAbi = null;
6458        }
6459    }
6460
6461    private static void createNativeLibrarySubdir(File path) throws IOException {
6462        if (!path.isDirectory()) {
6463            path.delete();
6464
6465            if (!path.mkdir()) {
6466                throw new IOException("Cannot create " + path.getPath());
6467            }
6468
6469            try {
6470                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6471            } catch (ErrnoException e) {
6472                throw new IOException("Cannot chmod native library directory "
6473                        + path.getPath(), e);
6474            }
6475        } else if (!SELinux.restorecon(path)) {
6476            throw new IOException("Cannot set SELinux context for " + path.getPath());
6477        }
6478    }
6479
6480    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6481            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6482        createNativeLibrarySubdir(nativeLibraryRoot);
6483
6484        /*
6485         * If this is an internal application or our nativeLibraryPath points to
6486         * the app-lib directory, unpack the libraries if necessary.
6487         */
6488        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6489        if (abi >= 0) {
6490            /*
6491             * If we have a matching instruction set, construct a subdir under the native
6492             * library root that corresponds to this instruction set.
6493             */
6494            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6495            final File subDir;
6496            if (useIsaSubdir) {
6497                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6498                createNativeLibrarySubdir(isaSubdir);
6499                subDir = isaSubdir;
6500            } else {
6501                subDir = nativeLibraryRoot;
6502            }
6503
6504            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6505            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6506                return copyRet;
6507            }
6508        }
6509
6510        return abi;
6511    }
6512
6513    private void killApplication(String pkgName, int appId, String reason) {
6514        // Request the ActivityManager to kill the process(only for existing packages)
6515        // so that we do not end up in a confused state while the user is still using the older
6516        // version of the application while the new one gets installed.
6517        IActivityManager am = ActivityManagerNative.getDefault();
6518        if (am != null) {
6519            try {
6520                am.killApplicationWithAppId(pkgName, appId, reason);
6521            } catch (RemoteException e) {
6522            }
6523        }
6524    }
6525
6526    void removePackageLI(PackageSetting ps, boolean chatty) {
6527        if (DEBUG_INSTALL) {
6528            if (chatty)
6529                Log.d(TAG, "Removing package " + ps.name);
6530        }
6531
6532        // writer
6533        synchronized (mPackages) {
6534            mPackages.remove(ps.name);
6535            if (ps.codePathString != null) {
6536                mAppDirs.remove(ps.codePathString);
6537            }
6538
6539            final PackageParser.Package pkg = ps.pkg;
6540            if (pkg != null) {
6541                cleanPackageDataStructuresLILPw(pkg, chatty);
6542            }
6543        }
6544    }
6545
6546    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6547        if (DEBUG_INSTALL) {
6548            if (chatty)
6549                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6550        }
6551
6552        // writer
6553        synchronized (mPackages) {
6554            mPackages.remove(pkg.applicationInfo.packageName);
6555            if (pkg.codePath != null) {
6556                mAppDirs.remove(pkg.codePath);
6557            }
6558            cleanPackageDataStructuresLILPw(pkg, chatty);
6559        }
6560    }
6561
6562    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6563        int N = pkg.providers.size();
6564        StringBuilder r = null;
6565        int i;
6566        for (i=0; i<N; i++) {
6567            PackageParser.Provider p = pkg.providers.get(i);
6568            mProviders.removeProvider(p);
6569            if (p.info.authority == null) {
6570
6571                /* There was another ContentProvider with this authority when
6572                 * this app was installed so this authority is null,
6573                 * Ignore it as we don't have to unregister the provider.
6574                 */
6575                continue;
6576            }
6577            String names[] = p.info.authority.split(";");
6578            for (int j = 0; j < names.length; j++) {
6579                if (mProvidersByAuthority.get(names[j]) == p) {
6580                    mProvidersByAuthority.remove(names[j]);
6581                    if (DEBUG_REMOVE) {
6582                        if (chatty)
6583                            Log.d(TAG, "Unregistered content provider: " + names[j]
6584                                    + ", className = " + p.info.name + ", isSyncable = "
6585                                    + p.info.isSyncable);
6586                    }
6587                }
6588            }
6589            if (DEBUG_REMOVE && chatty) {
6590                if (r == null) {
6591                    r = new StringBuilder(256);
6592                } else {
6593                    r.append(' ');
6594                }
6595                r.append(p.info.name);
6596            }
6597        }
6598        if (r != null) {
6599            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6600        }
6601
6602        N = pkg.services.size();
6603        r = null;
6604        for (i=0; i<N; i++) {
6605            PackageParser.Service s = pkg.services.get(i);
6606            mServices.removeService(s);
6607            if (chatty) {
6608                if (r == null) {
6609                    r = new StringBuilder(256);
6610                } else {
6611                    r.append(' ');
6612                }
6613                r.append(s.info.name);
6614            }
6615        }
6616        if (r != null) {
6617            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6618        }
6619
6620        N = pkg.receivers.size();
6621        r = null;
6622        for (i=0; i<N; i++) {
6623            PackageParser.Activity a = pkg.receivers.get(i);
6624            mReceivers.removeActivity(a, "receiver");
6625            if (DEBUG_REMOVE && chatty) {
6626                if (r == null) {
6627                    r = new StringBuilder(256);
6628                } else {
6629                    r.append(' ');
6630                }
6631                r.append(a.info.name);
6632            }
6633        }
6634        if (r != null) {
6635            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6636        }
6637
6638        N = pkg.activities.size();
6639        r = null;
6640        for (i=0; i<N; i++) {
6641            PackageParser.Activity a = pkg.activities.get(i);
6642            mActivities.removeActivity(a, "activity");
6643            if (DEBUG_REMOVE && chatty) {
6644                if (r == null) {
6645                    r = new StringBuilder(256);
6646                } else {
6647                    r.append(' ');
6648                }
6649                r.append(a.info.name);
6650            }
6651        }
6652        if (r != null) {
6653            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6654        }
6655
6656        N = pkg.permissions.size();
6657        r = null;
6658        for (i=0; i<N; i++) {
6659            PackageParser.Permission p = pkg.permissions.get(i);
6660            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6661            if (bp == null) {
6662                bp = mSettings.mPermissionTrees.get(p.info.name);
6663            }
6664            if (bp != null && bp.perm == p) {
6665                bp.perm = null;
6666                if (DEBUG_REMOVE && chatty) {
6667                    if (r == null) {
6668                        r = new StringBuilder(256);
6669                    } else {
6670                        r.append(' ');
6671                    }
6672                    r.append(p.info.name);
6673                }
6674            }
6675            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6676                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6677                if (appOpPerms != null) {
6678                    appOpPerms.remove(pkg.packageName);
6679                }
6680            }
6681        }
6682        if (r != null) {
6683            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6684        }
6685
6686        N = pkg.requestedPermissions.size();
6687        r = null;
6688        for (i=0; i<N; i++) {
6689            String perm = pkg.requestedPermissions.get(i);
6690            BasePermission bp = mSettings.mPermissions.get(perm);
6691            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6692                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6693                if (appOpPerms != null) {
6694                    appOpPerms.remove(pkg.packageName);
6695                    if (appOpPerms.isEmpty()) {
6696                        mAppOpPermissionPackages.remove(perm);
6697                    }
6698                }
6699            }
6700        }
6701        if (r != null) {
6702            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6703        }
6704
6705        N = pkg.instrumentation.size();
6706        r = null;
6707        for (i=0; i<N; i++) {
6708            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6709            mInstrumentation.remove(a.getComponentName());
6710            if (DEBUG_REMOVE && chatty) {
6711                if (r == null) {
6712                    r = new StringBuilder(256);
6713                } else {
6714                    r.append(' ');
6715                }
6716                r.append(a.info.name);
6717            }
6718        }
6719        if (r != null) {
6720            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6721        }
6722
6723        r = null;
6724        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6725            // Only system apps can hold shared libraries.
6726            if (pkg.libraryNames != null) {
6727                for (i=0; i<pkg.libraryNames.size(); i++) {
6728                    String name = pkg.libraryNames.get(i);
6729                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6730                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6731                        mSharedLibraries.remove(name);
6732                        if (DEBUG_REMOVE && chatty) {
6733                            if (r == null) {
6734                                r = new StringBuilder(256);
6735                            } else {
6736                                r.append(' ');
6737                            }
6738                            r.append(name);
6739                        }
6740                    }
6741                }
6742            }
6743        }
6744        if (r != null) {
6745            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6746        }
6747    }
6748
6749    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6750        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6751            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6752                return true;
6753            }
6754        }
6755        return false;
6756    }
6757
6758    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6759    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6760    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6761
6762    private void updatePermissionsLPw(String changingPkg,
6763            PackageParser.Package pkgInfo, int flags) {
6764        // Make sure there are no dangling permission trees.
6765        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6766        while (it.hasNext()) {
6767            final BasePermission bp = it.next();
6768            if (bp.packageSetting == null) {
6769                // We may not yet have parsed the package, so just see if
6770                // we still know about its settings.
6771                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6772            }
6773            if (bp.packageSetting == null) {
6774                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6775                        + " from package " + bp.sourcePackage);
6776                it.remove();
6777            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6778                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6779                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6780                            + " from package " + bp.sourcePackage);
6781                    flags |= UPDATE_PERMISSIONS_ALL;
6782                    it.remove();
6783                }
6784            }
6785        }
6786
6787        // Make sure all dynamic permissions have been assigned to a package,
6788        // and make sure there are no dangling permissions.
6789        it = mSettings.mPermissions.values().iterator();
6790        while (it.hasNext()) {
6791            final BasePermission bp = it.next();
6792            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6793                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6794                        + bp.name + " pkg=" + bp.sourcePackage
6795                        + " info=" + bp.pendingInfo);
6796                if (bp.packageSetting == null && bp.pendingInfo != null) {
6797                    final BasePermission tree = findPermissionTreeLP(bp.name);
6798                    if (tree != null && tree.perm != null) {
6799                        bp.packageSetting = tree.packageSetting;
6800                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6801                                new PermissionInfo(bp.pendingInfo));
6802                        bp.perm.info.packageName = tree.perm.info.packageName;
6803                        bp.perm.info.name = bp.name;
6804                        bp.uid = tree.uid;
6805                    }
6806                }
6807            }
6808            if (bp.packageSetting == null) {
6809                // We may not yet have parsed the package, so just see if
6810                // we still know about its settings.
6811                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6812            }
6813            if (bp.packageSetting == null) {
6814                Slog.w(TAG, "Removing dangling permission: " + bp.name
6815                        + " from package " + bp.sourcePackage);
6816                it.remove();
6817            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6818                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6819                    Slog.i(TAG, "Removing old permission: " + bp.name
6820                            + " from package " + bp.sourcePackage);
6821                    flags |= UPDATE_PERMISSIONS_ALL;
6822                    it.remove();
6823                }
6824            }
6825        }
6826
6827        // Now update the permissions for all packages, in particular
6828        // replace the granted permissions of the system packages.
6829        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6830            for (PackageParser.Package pkg : mPackages.values()) {
6831                if (pkg != pkgInfo) {
6832                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6833                }
6834            }
6835        }
6836
6837        if (pkgInfo != null) {
6838            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6839        }
6840    }
6841
6842    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6843        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6844        if (ps == null) {
6845            return;
6846        }
6847        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6848        HashSet<String> origPermissions = gp.grantedPermissions;
6849        boolean changedPermission = false;
6850
6851        if (replace) {
6852            ps.permissionsFixed = false;
6853            if (gp == ps) {
6854                origPermissions = new HashSet<String>(gp.grantedPermissions);
6855                gp.grantedPermissions.clear();
6856                gp.gids = mGlobalGids;
6857            }
6858        }
6859
6860        if (gp.gids == null) {
6861            gp.gids = mGlobalGids;
6862        }
6863
6864        final int N = pkg.requestedPermissions.size();
6865        for (int i=0; i<N; i++) {
6866            final String name = pkg.requestedPermissions.get(i);
6867            final boolean required = pkg.requestedPermissionsRequired.get(i);
6868            final BasePermission bp = mSettings.mPermissions.get(name);
6869            if (DEBUG_INSTALL) {
6870                if (gp != ps) {
6871                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6872                }
6873            }
6874
6875            if (bp == null || bp.packageSetting == null) {
6876                Slog.w(TAG, "Unknown permission " + name
6877                        + " in package " + pkg.packageName);
6878                continue;
6879            }
6880
6881            final String perm = bp.name;
6882            boolean allowed;
6883            boolean allowedSig = false;
6884            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6885                // Keep track of app op permissions.
6886                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6887                if (pkgs == null) {
6888                    pkgs = new ArraySet<>();
6889                    mAppOpPermissionPackages.put(bp.name, pkgs);
6890                }
6891                pkgs.add(pkg.packageName);
6892            }
6893            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6894            if (level == PermissionInfo.PROTECTION_NORMAL
6895                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6896                // We grant a normal or dangerous permission if any of the following
6897                // are true:
6898                // 1) The permission is required
6899                // 2) The permission is optional, but was granted in the past
6900                // 3) The permission is optional, but was requested by an
6901                //    app in /system (not /data)
6902                //
6903                // Otherwise, reject the permission.
6904                allowed = (required || origPermissions.contains(perm)
6905                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6906            } else if (bp.packageSetting == null) {
6907                // This permission is invalid; skip it.
6908                allowed = false;
6909            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6910                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6911                if (allowed) {
6912                    allowedSig = true;
6913                }
6914            } else {
6915                allowed = false;
6916            }
6917            if (DEBUG_INSTALL) {
6918                if (gp != ps) {
6919                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6920                }
6921            }
6922            if (allowed) {
6923                if (!isSystemApp(ps) && ps.permissionsFixed) {
6924                    // If this is an existing, non-system package, then
6925                    // we can't add any new permissions to it.
6926                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6927                        // Except...  if this is a permission that was added
6928                        // to the platform (note: need to only do this when
6929                        // updating the platform).
6930                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6931                    }
6932                }
6933                if (allowed) {
6934                    if (!gp.grantedPermissions.contains(perm)) {
6935                        changedPermission = true;
6936                        gp.grantedPermissions.add(perm);
6937                        gp.gids = appendInts(gp.gids, bp.gids);
6938                    } else if (!ps.haveGids) {
6939                        gp.gids = appendInts(gp.gids, bp.gids);
6940                    }
6941                } else {
6942                    Slog.w(TAG, "Not granting permission " + perm
6943                            + " to package " + pkg.packageName
6944                            + " because it was previously installed without");
6945                }
6946            } else {
6947                if (gp.grantedPermissions.remove(perm)) {
6948                    changedPermission = true;
6949                    gp.gids = removeInts(gp.gids, bp.gids);
6950                    Slog.i(TAG, "Un-granting permission " + perm
6951                            + " from package " + pkg.packageName
6952                            + " (protectionLevel=" + bp.protectionLevel
6953                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6954                            + ")");
6955                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6956                    // Don't print warning for app op permissions, since it is fine for them
6957                    // not to be granted, there is a UI for the user to decide.
6958                    Slog.w(TAG, "Not granting permission " + perm
6959                            + " to package " + pkg.packageName
6960                            + " (protectionLevel=" + bp.protectionLevel
6961                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6962                            + ")");
6963                }
6964            }
6965        }
6966
6967        if ((changedPermission || replace) && !ps.permissionsFixed &&
6968                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6969            // This is the first that we have heard about this package, so the
6970            // permissions we have now selected are fixed until explicitly
6971            // changed.
6972            ps.permissionsFixed = true;
6973        }
6974        ps.haveGids = true;
6975    }
6976
6977    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6978        boolean allowed = false;
6979        final int NP = PackageParser.NEW_PERMISSIONS.length;
6980        for (int ip=0; ip<NP; ip++) {
6981            final PackageParser.NewPermissionInfo npi
6982                    = PackageParser.NEW_PERMISSIONS[ip];
6983            if (npi.name.equals(perm)
6984                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6985                allowed = true;
6986                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6987                        + pkg.packageName);
6988                break;
6989            }
6990        }
6991        return allowed;
6992    }
6993
6994    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6995                                          BasePermission bp, HashSet<String> origPermissions) {
6996        boolean allowed;
6997        allowed = (compareSignatures(
6998                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6999                        == PackageManager.SIGNATURE_MATCH)
7000                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7001                        == PackageManager.SIGNATURE_MATCH);
7002        if (!allowed && (bp.protectionLevel
7003                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7004            if (isSystemApp(pkg)) {
7005                // For updated system applications, a system permission
7006                // is granted only if it had been defined by the original application.
7007                if (isUpdatedSystemApp(pkg)) {
7008                    final PackageSetting sysPs = mSettings
7009                            .getDisabledSystemPkgLPr(pkg.packageName);
7010                    final GrantedPermissions origGp = sysPs.sharedUser != null
7011                            ? sysPs.sharedUser : sysPs;
7012
7013                    if (origGp.grantedPermissions.contains(perm)) {
7014                        // If the original was granted this permission, we take
7015                        // that grant decision as read and propagate it to the
7016                        // update.
7017                        allowed = true;
7018                    } else {
7019                        // The system apk may have been updated with an older
7020                        // version of the one on the data partition, but which
7021                        // granted a new system permission that it didn't have
7022                        // before.  In this case we do want to allow the app to
7023                        // now get the new permission if the ancestral apk is
7024                        // privileged to get it.
7025                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7026                            for (int j=0;
7027                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7028                                if (perm.equals(
7029                                        sysPs.pkg.requestedPermissions.get(j))) {
7030                                    allowed = true;
7031                                    break;
7032                                }
7033                            }
7034                        }
7035                    }
7036                } else {
7037                    allowed = isPrivilegedApp(pkg);
7038                }
7039            }
7040        }
7041        if (!allowed && (bp.protectionLevel
7042                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7043            // For development permissions, a development permission
7044            // is granted only if it was already granted.
7045            allowed = origPermissions.contains(perm);
7046        }
7047        return allowed;
7048    }
7049
7050    final class ActivityIntentResolver
7051            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7052        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7053                boolean defaultOnly, int userId) {
7054            if (!sUserManager.exists(userId)) return null;
7055            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7056            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7057        }
7058
7059        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7060                int userId) {
7061            if (!sUserManager.exists(userId)) return null;
7062            mFlags = flags;
7063            return super.queryIntent(intent, resolvedType,
7064                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7065        }
7066
7067        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7068                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7069            if (!sUserManager.exists(userId)) return null;
7070            if (packageActivities == null) {
7071                return null;
7072            }
7073            mFlags = flags;
7074            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7075            final int N = packageActivities.size();
7076            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7077                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7078
7079            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7080            for (int i = 0; i < N; ++i) {
7081                intentFilters = packageActivities.get(i).intents;
7082                if (intentFilters != null && intentFilters.size() > 0) {
7083                    PackageParser.ActivityIntentInfo[] array =
7084                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7085                    intentFilters.toArray(array);
7086                    listCut.add(array);
7087                }
7088            }
7089            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7090        }
7091
7092        public final void addActivity(PackageParser.Activity a, String type) {
7093            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7094            mActivities.put(a.getComponentName(), a);
7095            if (DEBUG_SHOW_INFO)
7096                Log.v(
7097                TAG, "  " + type + " " +
7098                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7099            if (DEBUG_SHOW_INFO)
7100                Log.v(TAG, "    Class=" + a.info.name);
7101            final int NI = a.intents.size();
7102            for (int j=0; j<NI; j++) {
7103                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7104                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7105                    intent.setPriority(0);
7106                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7107                            + a.className + " with priority > 0, forcing to 0");
7108                }
7109                if (DEBUG_SHOW_INFO) {
7110                    Log.v(TAG, "    IntentFilter:");
7111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7112                }
7113                if (!intent.debugCheck()) {
7114                    Log.w(TAG, "==> For Activity " + a.info.name);
7115                }
7116                addFilter(intent);
7117            }
7118        }
7119
7120        public final void removeActivity(PackageParser.Activity a, String type) {
7121            mActivities.remove(a.getComponentName());
7122            if (DEBUG_SHOW_INFO) {
7123                Log.v(TAG, "  " + type + " "
7124                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7125                                : a.info.name) + ":");
7126                Log.v(TAG, "    Class=" + a.info.name);
7127            }
7128            final int NI = a.intents.size();
7129            for (int j=0; j<NI; j++) {
7130                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7131                if (DEBUG_SHOW_INFO) {
7132                    Log.v(TAG, "    IntentFilter:");
7133                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7134                }
7135                removeFilter(intent);
7136            }
7137        }
7138
7139        @Override
7140        protected boolean allowFilterResult(
7141                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7142            ActivityInfo filterAi = filter.activity.info;
7143            for (int i=dest.size()-1; i>=0; i--) {
7144                ActivityInfo destAi = dest.get(i).activityInfo;
7145                if (destAi.name == filterAi.name
7146                        && destAi.packageName == filterAi.packageName) {
7147                    return false;
7148                }
7149            }
7150            return true;
7151        }
7152
7153        @Override
7154        protected ActivityIntentInfo[] newArray(int size) {
7155            return new ActivityIntentInfo[size];
7156        }
7157
7158        @Override
7159        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7160            if (!sUserManager.exists(userId)) return true;
7161            PackageParser.Package p = filter.activity.owner;
7162            if (p != null) {
7163                PackageSetting ps = (PackageSetting)p.mExtras;
7164                if (ps != null) {
7165                    // System apps are never considered stopped for purposes of
7166                    // filtering, because there may be no way for the user to
7167                    // actually re-launch them.
7168                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7169                            && ps.getStopped(userId);
7170                }
7171            }
7172            return false;
7173        }
7174
7175        @Override
7176        protected boolean isPackageForFilter(String packageName,
7177                PackageParser.ActivityIntentInfo info) {
7178            return packageName.equals(info.activity.owner.packageName);
7179        }
7180
7181        @Override
7182        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7183                int match, int userId) {
7184            if (!sUserManager.exists(userId)) return null;
7185            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7186                return null;
7187            }
7188            final PackageParser.Activity activity = info.activity;
7189            if (mSafeMode && (activity.info.applicationInfo.flags
7190                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7191                return null;
7192            }
7193            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7194            if (ps == null) {
7195                return null;
7196            }
7197            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7198                    ps.readUserState(userId), userId);
7199            if (ai == null) {
7200                return null;
7201            }
7202            final ResolveInfo res = new ResolveInfo();
7203            res.activityInfo = ai;
7204            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7205                res.filter = info;
7206            }
7207            res.priority = info.getPriority();
7208            res.preferredOrder = activity.owner.mPreferredOrder;
7209            //System.out.println("Result: " + res.activityInfo.className +
7210            //                   " = " + res.priority);
7211            res.match = match;
7212            res.isDefault = info.hasDefault;
7213            res.labelRes = info.labelRes;
7214            res.nonLocalizedLabel = info.nonLocalizedLabel;
7215            if (userNeedsBadging(userId)) {
7216                res.noResourceId = true;
7217            } else {
7218                res.icon = info.icon;
7219            }
7220            res.system = isSystemApp(res.activityInfo.applicationInfo);
7221            return res;
7222        }
7223
7224        @Override
7225        protected void sortResults(List<ResolveInfo> results) {
7226            Collections.sort(results, mResolvePrioritySorter);
7227        }
7228
7229        @Override
7230        protected void dumpFilter(PrintWriter out, String prefix,
7231                PackageParser.ActivityIntentInfo filter) {
7232            out.print(prefix); out.print(
7233                    Integer.toHexString(System.identityHashCode(filter.activity)));
7234                    out.print(' ');
7235                    filter.activity.printComponentShortName(out);
7236                    out.print(" filter ");
7237                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7238        }
7239
7240//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7241//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7242//            final List<ResolveInfo> retList = Lists.newArrayList();
7243//            while (i.hasNext()) {
7244//                final ResolveInfo resolveInfo = i.next();
7245//                if (isEnabledLP(resolveInfo.activityInfo)) {
7246//                    retList.add(resolveInfo);
7247//                }
7248//            }
7249//            return retList;
7250//        }
7251
7252        // Keys are String (activity class name), values are Activity.
7253        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7254                = new HashMap<ComponentName, PackageParser.Activity>();
7255        private int mFlags;
7256    }
7257
7258    private final class ServiceIntentResolver
7259            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7260        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7261                boolean defaultOnly, int userId) {
7262            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7263            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7264        }
7265
7266        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7267                int userId) {
7268            if (!sUserManager.exists(userId)) return null;
7269            mFlags = flags;
7270            return super.queryIntent(intent, resolvedType,
7271                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7272        }
7273
7274        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7275                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7276            if (!sUserManager.exists(userId)) return null;
7277            if (packageServices == null) {
7278                return null;
7279            }
7280            mFlags = flags;
7281            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7282            final int N = packageServices.size();
7283            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7284                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7285
7286            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7287            for (int i = 0; i < N; ++i) {
7288                intentFilters = packageServices.get(i).intents;
7289                if (intentFilters != null && intentFilters.size() > 0) {
7290                    PackageParser.ServiceIntentInfo[] array =
7291                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7292                    intentFilters.toArray(array);
7293                    listCut.add(array);
7294                }
7295            }
7296            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7297        }
7298
7299        public final void addService(PackageParser.Service s) {
7300            mServices.put(s.getComponentName(), s);
7301            if (DEBUG_SHOW_INFO) {
7302                Log.v(TAG, "  "
7303                        + (s.info.nonLocalizedLabel != null
7304                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7305                Log.v(TAG, "    Class=" + s.info.name);
7306            }
7307            final int NI = s.intents.size();
7308            int j;
7309            for (j=0; j<NI; j++) {
7310                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7311                if (DEBUG_SHOW_INFO) {
7312                    Log.v(TAG, "    IntentFilter:");
7313                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7314                }
7315                if (!intent.debugCheck()) {
7316                    Log.w(TAG, "==> For Service " + s.info.name);
7317                }
7318                addFilter(intent);
7319            }
7320        }
7321
7322        public final void removeService(PackageParser.Service s) {
7323            mServices.remove(s.getComponentName());
7324            if (DEBUG_SHOW_INFO) {
7325                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7326                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7327                Log.v(TAG, "    Class=" + s.info.name);
7328            }
7329            final int NI = s.intents.size();
7330            int j;
7331            for (j=0; j<NI; j++) {
7332                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7333                if (DEBUG_SHOW_INFO) {
7334                    Log.v(TAG, "    IntentFilter:");
7335                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7336                }
7337                removeFilter(intent);
7338            }
7339        }
7340
7341        @Override
7342        protected boolean allowFilterResult(
7343                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7344            ServiceInfo filterSi = filter.service.info;
7345            for (int i=dest.size()-1; i>=0; i--) {
7346                ServiceInfo destAi = dest.get(i).serviceInfo;
7347                if (destAi.name == filterSi.name
7348                        && destAi.packageName == filterSi.packageName) {
7349                    return false;
7350                }
7351            }
7352            return true;
7353        }
7354
7355        @Override
7356        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7357            return new PackageParser.ServiceIntentInfo[size];
7358        }
7359
7360        @Override
7361        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7362            if (!sUserManager.exists(userId)) return true;
7363            PackageParser.Package p = filter.service.owner;
7364            if (p != null) {
7365                PackageSetting ps = (PackageSetting)p.mExtras;
7366                if (ps != null) {
7367                    // System apps are never considered stopped for purposes of
7368                    // filtering, because there may be no way for the user to
7369                    // actually re-launch them.
7370                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7371                            && ps.getStopped(userId);
7372                }
7373            }
7374            return false;
7375        }
7376
7377        @Override
7378        protected boolean isPackageForFilter(String packageName,
7379                PackageParser.ServiceIntentInfo info) {
7380            return packageName.equals(info.service.owner.packageName);
7381        }
7382
7383        @Override
7384        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7385                int match, int userId) {
7386            if (!sUserManager.exists(userId)) return null;
7387            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7388            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7389                return null;
7390            }
7391            final PackageParser.Service service = info.service;
7392            if (mSafeMode && (service.info.applicationInfo.flags
7393                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7394                return null;
7395            }
7396            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7397            if (ps == null) {
7398                return null;
7399            }
7400            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7401                    ps.readUserState(userId), userId);
7402            if (si == null) {
7403                return null;
7404            }
7405            final ResolveInfo res = new ResolveInfo();
7406            res.serviceInfo = si;
7407            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7408                res.filter = filter;
7409            }
7410            res.priority = info.getPriority();
7411            res.preferredOrder = service.owner.mPreferredOrder;
7412            //System.out.println("Result: " + res.activityInfo.className +
7413            //                   " = " + res.priority);
7414            res.match = match;
7415            res.isDefault = info.hasDefault;
7416            res.labelRes = info.labelRes;
7417            res.nonLocalizedLabel = info.nonLocalizedLabel;
7418            res.icon = info.icon;
7419            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7420            return res;
7421        }
7422
7423        @Override
7424        protected void sortResults(List<ResolveInfo> results) {
7425            Collections.sort(results, mResolvePrioritySorter);
7426        }
7427
7428        @Override
7429        protected void dumpFilter(PrintWriter out, String prefix,
7430                PackageParser.ServiceIntentInfo filter) {
7431            out.print(prefix); out.print(
7432                    Integer.toHexString(System.identityHashCode(filter.service)));
7433                    out.print(' ');
7434                    filter.service.printComponentShortName(out);
7435                    out.print(" filter ");
7436                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7437        }
7438
7439//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7440//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7441//            final List<ResolveInfo> retList = Lists.newArrayList();
7442//            while (i.hasNext()) {
7443//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7444//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7445//                    retList.add(resolveInfo);
7446//                }
7447//            }
7448//            return retList;
7449//        }
7450
7451        // Keys are String (activity class name), values are Activity.
7452        private final HashMap<ComponentName, PackageParser.Service> mServices
7453                = new HashMap<ComponentName, PackageParser.Service>();
7454        private int mFlags;
7455    };
7456
7457    private final class ProviderIntentResolver
7458            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7459        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7460                boolean defaultOnly, int userId) {
7461            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7462            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7463        }
7464
7465        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7466                int userId) {
7467            if (!sUserManager.exists(userId))
7468                return null;
7469            mFlags = flags;
7470            return super.queryIntent(intent, resolvedType,
7471                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7472        }
7473
7474        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7475                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7476            if (!sUserManager.exists(userId))
7477                return null;
7478            if (packageProviders == null) {
7479                return null;
7480            }
7481            mFlags = flags;
7482            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7483            final int N = packageProviders.size();
7484            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7485                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7486
7487            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7488            for (int i = 0; i < N; ++i) {
7489                intentFilters = packageProviders.get(i).intents;
7490                if (intentFilters != null && intentFilters.size() > 0) {
7491                    PackageParser.ProviderIntentInfo[] array =
7492                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7493                    intentFilters.toArray(array);
7494                    listCut.add(array);
7495                }
7496            }
7497            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7498        }
7499
7500        public final void addProvider(PackageParser.Provider p) {
7501            if (mProviders.containsKey(p.getComponentName())) {
7502                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7503                return;
7504            }
7505
7506            mProviders.put(p.getComponentName(), p);
7507            if (DEBUG_SHOW_INFO) {
7508                Log.v(TAG, "  "
7509                        + (p.info.nonLocalizedLabel != null
7510                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7511                Log.v(TAG, "    Class=" + p.info.name);
7512            }
7513            final int NI = p.intents.size();
7514            int j;
7515            for (j = 0; j < NI; j++) {
7516                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7517                if (DEBUG_SHOW_INFO) {
7518                    Log.v(TAG, "    IntentFilter:");
7519                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7520                }
7521                if (!intent.debugCheck()) {
7522                    Log.w(TAG, "==> For Provider " + p.info.name);
7523                }
7524                addFilter(intent);
7525            }
7526        }
7527
7528        public final void removeProvider(PackageParser.Provider p) {
7529            mProviders.remove(p.getComponentName());
7530            if (DEBUG_SHOW_INFO) {
7531                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7532                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7533                Log.v(TAG, "    Class=" + p.info.name);
7534            }
7535            final int NI = p.intents.size();
7536            int j;
7537            for (j = 0; j < NI; j++) {
7538                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7539                if (DEBUG_SHOW_INFO) {
7540                    Log.v(TAG, "    IntentFilter:");
7541                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7542                }
7543                removeFilter(intent);
7544            }
7545        }
7546
7547        @Override
7548        protected boolean allowFilterResult(
7549                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7550            ProviderInfo filterPi = filter.provider.info;
7551            for (int i = dest.size() - 1; i >= 0; i--) {
7552                ProviderInfo destPi = dest.get(i).providerInfo;
7553                if (destPi.name == filterPi.name
7554                        && destPi.packageName == filterPi.packageName) {
7555                    return false;
7556                }
7557            }
7558            return true;
7559        }
7560
7561        @Override
7562        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7563            return new PackageParser.ProviderIntentInfo[size];
7564        }
7565
7566        @Override
7567        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7568            if (!sUserManager.exists(userId))
7569                return true;
7570            PackageParser.Package p = filter.provider.owner;
7571            if (p != null) {
7572                PackageSetting ps = (PackageSetting) p.mExtras;
7573                if (ps != null) {
7574                    // System apps are never considered stopped for purposes of
7575                    // filtering, because there may be no way for the user to
7576                    // actually re-launch them.
7577                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7578                            && ps.getStopped(userId);
7579                }
7580            }
7581            return false;
7582        }
7583
7584        @Override
7585        protected boolean isPackageForFilter(String packageName,
7586                PackageParser.ProviderIntentInfo info) {
7587            return packageName.equals(info.provider.owner.packageName);
7588        }
7589
7590        @Override
7591        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7592                int match, int userId) {
7593            if (!sUserManager.exists(userId))
7594                return null;
7595            final PackageParser.ProviderIntentInfo info = filter;
7596            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7597                return null;
7598            }
7599            final PackageParser.Provider provider = info.provider;
7600            if (mSafeMode && (provider.info.applicationInfo.flags
7601                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7602                return null;
7603            }
7604            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7605            if (ps == null) {
7606                return null;
7607            }
7608            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7609                    ps.readUserState(userId), userId);
7610            if (pi == null) {
7611                return null;
7612            }
7613            final ResolveInfo res = new ResolveInfo();
7614            res.providerInfo = pi;
7615            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7616                res.filter = filter;
7617            }
7618            res.priority = info.getPriority();
7619            res.preferredOrder = provider.owner.mPreferredOrder;
7620            res.match = match;
7621            res.isDefault = info.hasDefault;
7622            res.labelRes = info.labelRes;
7623            res.nonLocalizedLabel = info.nonLocalizedLabel;
7624            res.icon = info.icon;
7625            res.system = isSystemApp(res.providerInfo.applicationInfo);
7626            return res;
7627        }
7628
7629        @Override
7630        protected void sortResults(List<ResolveInfo> results) {
7631            Collections.sort(results, mResolvePrioritySorter);
7632        }
7633
7634        @Override
7635        protected void dumpFilter(PrintWriter out, String prefix,
7636                PackageParser.ProviderIntentInfo filter) {
7637            out.print(prefix);
7638            out.print(
7639                    Integer.toHexString(System.identityHashCode(filter.provider)));
7640            out.print(' ');
7641            filter.provider.printComponentShortName(out);
7642            out.print(" filter ");
7643            out.println(Integer.toHexString(System.identityHashCode(filter)));
7644        }
7645
7646        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7647                = new HashMap<ComponentName, PackageParser.Provider>();
7648        private int mFlags;
7649    };
7650
7651    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7652            new Comparator<ResolveInfo>() {
7653        public int compare(ResolveInfo r1, ResolveInfo r2) {
7654            int v1 = r1.priority;
7655            int v2 = r2.priority;
7656            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7657            if (v1 != v2) {
7658                return (v1 > v2) ? -1 : 1;
7659            }
7660            v1 = r1.preferredOrder;
7661            v2 = r2.preferredOrder;
7662            if (v1 != v2) {
7663                return (v1 > v2) ? -1 : 1;
7664            }
7665            if (r1.isDefault != r2.isDefault) {
7666                return r1.isDefault ? -1 : 1;
7667            }
7668            v1 = r1.match;
7669            v2 = r2.match;
7670            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7671            if (v1 != v2) {
7672                return (v1 > v2) ? -1 : 1;
7673            }
7674            if (r1.system != r2.system) {
7675                return r1.system ? -1 : 1;
7676            }
7677            return 0;
7678        }
7679    };
7680
7681    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7682            new Comparator<ProviderInfo>() {
7683        public int compare(ProviderInfo p1, ProviderInfo p2) {
7684            final int v1 = p1.initOrder;
7685            final int v2 = p2.initOrder;
7686            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7687        }
7688    };
7689
7690    static final void sendPackageBroadcast(String action, String pkg,
7691            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7692            int[] userIds) {
7693        IActivityManager am = ActivityManagerNative.getDefault();
7694        if (am != null) {
7695            try {
7696                if (userIds == null) {
7697                    userIds = am.getRunningUserIds();
7698                }
7699                for (int id : userIds) {
7700                    final Intent intent = new Intent(action,
7701                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7702                    if (extras != null) {
7703                        intent.putExtras(extras);
7704                    }
7705                    if (targetPkg != null) {
7706                        intent.setPackage(targetPkg);
7707                    }
7708                    // Modify the UID when posting to other users
7709                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7710                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7711                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7712                        intent.putExtra(Intent.EXTRA_UID, uid);
7713                    }
7714                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7715                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7716                    if (DEBUG_BROADCASTS) {
7717                        RuntimeException here = new RuntimeException("here");
7718                        here.fillInStackTrace();
7719                        Slog.d(TAG, "Sending to user " + id + ": "
7720                                + intent.toShortString(false, true, false, false)
7721                                + " " + intent.getExtras(), here);
7722                    }
7723                    am.broadcastIntent(null, intent, null, finishedReceiver,
7724                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7725                            finishedReceiver != null, false, id);
7726                }
7727            } catch (RemoteException ex) {
7728            }
7729        }
7730    }
7731
7732    /**
7733     * Check if the external storage media is available. This is true if there
7734     * is a mounted external storage medium or if the external storage is
7735     * emulated.
7736     */
7737    private boolean isExternalMediaAvailable() {
7738        return mMediaMounted || Environment.isExternalStorageEmulated();
7739    }
7740
7741    @Override
7742    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7743        // writer
7744        synchronized (mPackages) {
7745            if (!isExternalMediaAvailable()) {
7746                // If the external storage is no longer mounted at this point,
7747                // the caller may not have been able to delete all of this
7748                // packages files and can not delete any more.  Bail.
7749                return null;
7750            }
7751            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7752            if (lastPackage != null) {
7753                pkgs.remove(lastPackage);
7754            }
7755            if (pkgs.size() > 0) {
7756                return pkgs.get(0);
7757            }
7758        }
7759        return null;
7760    }
7761
7762    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7763        if (false) {
7764            RuntimeException here = new RuntimeException("here");
7765            here.fillInStackTrace();
7766            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7767                    + " andCode=" + andCode, here);
7768        }
7769        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7770                userId, andCode ? 1 : 0, packageName));
7771    }
7772
7773    void startCleaningPackages() {
7774        // reader
7775        synchronized (mPackages) {
7776            if (!isExternalMediaAvailable()) {
7777                return;
7778            }
7779            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7780                return;
7781            }
7782        }
7783        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7784        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7785        IActivityManager am = ActivityManagerNative.getDefault();
7786        if (am != null) {
7787            try {
7788                am.startService(null, intent, null, UserHandle.USER_OWNER);
7789            } catch (RemoteException e) {
7790            }
7791        }
7792    }
7793
7794    @Override
7795    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7796            String installerPackageName, VerificationParams verificationParams,
7797            String packageAbiOverride) {
7798        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7799                null);
7800
7801        final File originFile = new File(originPath);
7802        final int uid = Binder.getCallingUid();
7803        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7804            try {
7805                if (observer != null) {
7806                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7807                }
7808            } catch (RemoteException re) {
7809            }
7810            return;
7811        }
7812
7813        UserHandle user;
7814        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7815            user = UserHandle.ALL;
7816        } else {
7817            user = new UserHandle(UserHandle.getUserId(uid));
7818        }
7819
7820        final int filteredFlags;
7821        if (uid == Process.SHELL_UID || uid == 0) {
7822            if (DEBUG_INSTALL) {
7823                Slog.v(TAG, "Install from ADB");
7824            }
7825            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7826        } else {
7827            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7828        }
7829
7830        verificationParams.setInstallerUid(uid);
7831
7832        final Message msg = mHandler.obtainMessage(INIT_COPY);
7833        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7834                installerPackageName, verificationParams, user, packageAbiOverride);
7835        mHandler.sendMessage(msg);
7836    }
7837
7838    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7839            InstallSessionParams params, String installerPackageName, int installerUid,
7840            UserHandle user) {
7841        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7842                params.referrerUri, installerUid, null);
7843
7844        final Message msg = mHandler.obtainMessage(INIT_COPY);
7845        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7846                installerPackageName, verifParams, user, params.abiOverride);
7847        mHandler.sendMessage(msg);
7848    }
7849
7850    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7851        Bundle extras = new Bundle(1);
7852        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7853
7854        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7855                packageName, extras, null, null, new int[] {userId});
7856        try {
7857            IActivityManager am = ActivityManagerNative.getDefault();
7858            final boolean isSystem =
7859                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7860            if (isSystem && am.isUserRunning(userId, false)) {
7861                // The just-installed/enabled app is bundled on the system, so presumed
7862                // to be able to run automatically without needing an explicit launch.
7863                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7864                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7865                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7866                        .setPackage(packageName);
7867                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7868                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7869            }
7870        } catch (RemoteException e) {
7871            // shouldn't happen
7872            Slog.w(TAG, "Unable to bootstrap installed package", e);
7873        }
7874    }
7875
7876    @Override
7877    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7878            int userId) {
7879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7880        PackageSetting pkgSetting;
7881        final int uid = Binder.getCallingUid();
7882        if (UserHandle.getUserId(uid) != userId) {
7883            mContext.enforceCallingOrSelfPermission(
7884                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7885                    "setApplicationHiddenSetting for user " + userId);
7886        }
7887
7888        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7889            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7890            return false;
7891        }
7892
7893        long callingId = Binder.clearCallingIdentity();
7894        try {
7895            boolean sendAdded = false;
7896            boolean sendRemoved = false;
7897            // writer
7898            synchronized (mPackages) {
7899                pkgSetting = mSettings.mPackages.get(packageName);
7900                if (pkgSetting == null) {
7901                    return false;
7902                }
7903                if (pkgSetting.getHidden(userId) != hidden) {
7904                    pkgSetting.setHidden(hidden, userId);
7905                    mSettings.writePackageRestrictionsLPr(userId);
7906                    if (hidden) {
7907                        sendRemoved = true;
7908                    } else {
7909                        sendAdded = true;
7910                    }
7911                }
7912            }
7913            if (sendAdded) {
7914                sendPackageAddedForUser(packageName, pkgSetting, userId);
7915                return true;
7916            }
7917            if (sendRemoved) {
7918                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7919                        "hiding pkg");
7920                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7921            }
7922        } finally {
7923            Binder.restoreCallingIdentity(callingId);
7924        }
7925        return false;
7926    }
7927
7928    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7929            int userId) {
7930        final PackageRemovedInfo info = new PackageRemovedInfo();
7931        info.removedPackage = packageName;
7932        info.removedUsers = new int[] {userId};
7933        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7934        info.sendBroadcast(false, false, false);
7935    }
7936
7937    /**
7938     * Returns true if application is not found or there was an error. Otherwise it returns
7939     * the hidden state of the package for the given user.
7940     */
7941    @Override
7942    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7943        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7944        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7945                "getApplicationHidden for user " + userId);
7946        PackageSetting pkgSetting;
7947        long callingId = Binder.clearCallingIdentity();
7948        try {
7949            // writer
7950            synchronized (mPackages) {
7951                pkgSetting = mSettings.mPackages.get(packageName);
7952                if (pkgSetting == null) {
7953                    return true;
7954                }
7955                return pkgSetting.getHidden(userId);
7956            }
7957        } finally {
7958            Binder.restoreCallingIdentity(callingId);
7959        }
7960    }
7961
7962    /**
7963     * @hide
7964     */
7965    @Override
7966    public int installExistingPackageAsUser(String packageName, int userId) {
7967        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7968                null);
7969        PackageSetting pkgSetting;
7970        final int uid = Binder.getCallingUid();
7971        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7972        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7973            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7974        }
7975
7976        long callingId = Binder.clearCallingIdentity();
7977        try {
7978            boolean sendAdded = false;
7979            Bundle extras = new Bundle(1);
7980
7981            // writer
7982            synchronized (mPackages) {
7983                pkgSetting = mSettings.mPackages.get(packageName);
7984                if (pkgSetting == null) {
7985                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7986                }
7987                if (!pkgSetting.getInstalled(userId)) {
7988                    pkgSetting.setInstalled(true, userId);
7989                    pkgSetting.setHidden(false, userId);
7990                    mSettings.writePackageRestrictionsLPr(userId);
7991                    sendAdded = true;
7992                }
7993            }
7994
7995            if (sendAdded) {
7996                sendPackageAddedForUser(packageName, pkgSetting, userId);
7997            }
7998        } finally {
7999            Binder.restoreCallingIdentity(callingId);
8000        }
8001
8002        return PackageManager.INSTALL_SUCCEEDED;
8003    }
8004
8005    boolean isUserRestricted(int userId, String restrictionKey) {
8006        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8007        if (restrictions.getBoolean(restrictionKey, false)) {
8008            Log.w(TAG, "User is restricted: " + restrictionKey);
8009            return true;
8010        }
8011        return false;
8012    }
8013
8014    @Override
8015    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8016        mContext.enforceCallingOrSelfPermission(
8017                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8018                "Only package verification agents can verify applications");
8019
8020        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8021        final PackageVerificationResponse response = new PackageVerificationResponse(
8022                verificationCode, Binder.getCallingUid());
8023        msg.arg1 = id;
8024        msg.obj = response;
8025        mHandler.sendMessage(msg);
8026    }
8027
8028    @Override
8029    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8030            long millisecondsToDelay) {
8031        mContext.enforceCallingOrSelfPermission(
8032                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8033                "Only package verification agents can extend verification timeouts");
8034
8035        final PackageVerificationState state = mPendingVerification.get(id);
8036        final PackageVerificationResponse response = new PackageVerificationResponse(
8037                verificationCodeAtTimeout, Binder.getCallingUid());
8038
8039        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8040            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8041        }
8042        if (millisecondsToDelay < 0) {
8043            millisecondsToDelay = 0;
8044        }
8045        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8046                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8047            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8048        }
8049
8050        if ((state != null) && !state.timeoutExtended()) {
8051            state.extendTimeout();
8052
8053            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8054            msg.arg1 = id;
8055            msg.obj = response;
8056            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8057        }
8058    }
8059
8060    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8061            int verificationCode, UserHandle user) {
8062        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8063        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8064        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8065        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8066        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8067
8068        mContext.sendBroadcastAsUser(intent, user,
8069                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8070    }
8071
8072    private ComponentName matchComponentForVerifier(String packageName,
8073            List<ResolveInfo> receivers) {
8074        ActivityInfo targetReceiver = null;
8075
8076        final int NR = receivers.size();
8077        for (int i = 0; i < NR; i++) {
8078            final ResolveInfo info = receivers.get(i);
8079            if (info.activityInfo == null) {
8080                continue;
8081            }
8082
8083            if (packageName.equals(info.activityInfo.packageName)) {
8084                targetReceiver = info.activityInfo;
8085                break;
8086            }
8087        }
8088
8089        if (targetReceiver == null) {
8090            return null;
8091        }
8092
8093        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8094    }
8095
8096    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8097            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8098        if (pkgInfo.verifiers.length == 0) {
8099            return null;
8100        }
8101
8102        final int N = pkgInfo.verifiers.length;
8103        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8104        for (int i = 0; i < N; i++) {
8105            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8106
8107            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8108                    receivers);
8109            if (comp == null) {
8110                continue;
8111            }
8112
8113            final int verifierUid = getUidForVerifier(verifierInfo);
8114            if (verifierUid == -1) {
8115                continue;
8116            }
8117
8118            if (DEBUG_VERIFY) {
8119                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8120                        + " with the correct signature");
8121            }
8122            sufficientVerifiers.add(comp);
8123            verificationState.addSufficientVerifier(verifierUid);
8124        }
8125
8126        return sufficientVerifiers;
8127    }
8128
8129    private int getUidForVerifier(VerifierInfo verifierInfo) {
8130        synchronized (mPackages) {
8131            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8132            if (pkg == null) {
8133                return -1;
8134            } else if (pkg.mSignatures.length != 1) {
8135                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8136                        + " has more than one signature; ignoring");
8137                return -1;
8138            }
8139
8140            /*
8141             * If the public key of the package's signature does not match
8142             * our expected public key, then this is a different package and
8143             * we should skip.
8144             */
8145
8146            final byte[] expectedPublicKey;
8147            try {
8148                final Signature verifierSig = pkg.mSignatures[0];
8149                final PublicKey publicKey = verifierSig.getPublicKey();
8150                expectedPublicKey = publicKey.getEncoded();
8151            } catch (CertificateException e) {
8152                return -1;
8153            }
8154
8155            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8156
8157            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8158                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8159                        + " does not have the expected public key; ignoring");
8160                return -1;
8161            }
8162
8163            return pkg.applicationInfo.uid;
8164        }
8165    }
8166
8167    @Override
8168    public void finishPackageInstall(int token) {
8169        enforceSystemOrRoot("Only the system is allowed to finish installs");
8170
8171        if (DEBUG_INSTALL) {
8172            Slog.v(TAG, "BM finishing package install for " + token);
8173        }
8174
8175        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8176        mHandler.sendMessage(msg);
8177    }
8178
8179    /**
8180     * Get the verification agent timeout.
8181     *
8182     * @return verification timeout in milliseconds
8183     */
8184    private long getVerificationTimeout() {
8185        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8186                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8187                DEFAULT_VERIFICATION_TIMEOUT);
8188    }
8189
8190    /**
8191     * Get the default verification agent response code.
8192     *
8193     * @return default verification response code
8194     */
8195    private int getDefaultVerificationResponse() {
8196        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8197                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8198                DEFAULT_VERIFICATION_RESPONSE);
8199    }
8200
8201    /**
8202     * Check whether or not package verification has been enabled.
8203     *
8204     * @return true if verification should be performed
8205     */
8206    private boolean isVerificationEnabled(int userId, int flags) {
8207        if (!DEFAULT_VERIFY_ENABLE) {
8208            return false;
8209        }
8210
8211        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8212
8213        // Check if installing from ADB
8214        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8215            // Do not run verification in a test harness environment
8216            if (ActivityManager.isRunningInTestHarness()) {
8217                return false;
8218            }
8219            if (ensureVerifyAppsEnabled) {
8220                return true;
8221            }
8222            // Check if the developer does not want package verification for ADB installs
8223            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8224                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8225                return false;
8226            }
8227        }
8228
8229        if (ensureVerifyAppsEnabled) {
8230            return true;
8231        }
8232
8233        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8234                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8235    }
8236
8237    /**
8238     * Get the "allow unknown sources" setting.
8239     *
8240     * @return the current "allow unknown sources" setting
8241     */
8242    private int getUnknownSourcesSettings() {
8243        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8244                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8245                -1);
8246    }
8247
8248    @Override
8249    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8250        final int uid = Binder.getCallingUid();
8251        // writer
8252        synchronized (mPackages) {
8253            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8254            if (targetPackageSetting == null) {
8255                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8256            }
8257
8258            PackageSetting installerPackageSetting;
8259            if (installerPackageName != null) {
8260                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8261                if (installerPackageSetting == null) {
8262                    throw new IllegalArgumentException("Unknown installer package: "
8263                            + installerPackageName);
8264                }
8265            } else {
8266                installerPackageSetting = null;
8267            }
8268
8269            Signature[] callerSignature;
8270            Object obj = mSettings.getUserIdLPr(uid);
8271            if (obj != null) {
8272                if (obj instanceof SharedUserSetting) {
8273                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8274                } else if (obj instanceof PackageSetting) {
8275                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8276                } else {
8277                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8278                }
8279            } else {
8280                throw new SecurityException("Unknown calling uid " + uid);
8281            }
8282
8283            // Verify: can't set installerPackageName to a package that is
8284            // not signed with the same cert as the caller.
8285            if (installerPackageSetting != null) {
8286                if (compareSignatures(callerSignature,
8287                        installerPackageSetting.signatures.mSignatures)
8288                        != PackageManager.SIGNATURE_MATCH) {
8289                    throw new SecurityException(
8290                            "Caller does not have same cert as new installer package "
8291                            + installerPackageName);
8292                }
8293            }
8294
8295            // Verify: if target already has an installer package, it must
8296            // be signed with the same cert as the caller.
8297            if (targetPackageSetting.installerPackageName != null) {
8298                PackageSetting setting = mSettings.mPackages.get(
8299                        targetPackageSetting.installerPackageName);
8300                // If the currently set package isn't valid, then it's always
8301                // okay to change it.
8302                if (setting != null) {
8303                    if (compareSignatures(callerSignature,
8304                            setting.signatures.mSignatures)
8305                            != PackageManager.SIGNATURE_MATCH) {
8306                        throw new SecurityException(
8307                                "Caller does not have same cert as old installer package "
8308                                + targetPackageSetting.installerPackageName);
8309                    }
8310                }
8311            }
8312
8313            // Okay!
8314            targetPackageSetting.installerPackageName = installerPackageName;
8315            scheduleWriteSettingsLocked();
8316        }
8317    }
8318
8319    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8320        // Queue up an async operation since the package installation may take a little while.
8321        mHandler.post(new Runnable() {
8322            public void run() {
8323                mHandler.removeCallbacks(this);
8324                 // Result object to be returned
8325                PackageInstalledInfo res = new PackageInstalledInfo();
8326                res.returnCode = currentStatus;
8327                res.uid = -1;
8328                res.pkg = null;
8329                res.removedInfo = new PackageRemovedInfo();
8330                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8331                    args.doPreInstall(res.returnCode);
8332                    synchronized (mInstallLock) {
8333                        installPackageLI(args, true, res);
8334                    }
8335                    args.doPostInstall(res.returnCode, res.uid);
8336                }
8337
8338                // A restore should be performed at this point if (a) the install
8339                // succeeded, (b) the operation is not an update, and (c) the new
8340                // package has not opted out of backup participation.
8341                final boolean update = res.removedInfo.removedPackage != null;
8342                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8343                boolean doRestore = !update
8344                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8345
8346                // Set up the post-install work request bookkeeping.  This will be used
8347                // and cleaned up by the post-install event handling regardless of whether
8348                // there's a restore pass performed.  Token values are >= 1.
8349                int token;
8350                if (mNextInstallToken < 0) mNextInstallToken = 1;
8351                token = mNextInstallToken++;
8352
8353                PostInstallData data = new PostInstallData(args, res);
8354                mRunningInstalls.put(token, data);
8355                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8356
8357                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8358                    // Pass responsibility to the Backup Manager.  It will perform a
8359                    // restore if appropriate, then pass responsibility back to the
8360                    // Package Manager to run the post-install observer callbacks
8361                    // and broadcasts.
8362                    IBackupManager bm = IBackupManager.Stub.asInterface(
8363                            ServiceManager.getService(Context.BACKUP_SERVICE));
8364                    if (bm != null) {
8365                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8366                                + " to BM for possible restore");
8367                        try {
8368                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8369                        } catch (RemoteException e) {
8370                            // can't happen; the backup manager is local
8371                        } catch (Exception e) {
8372                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8373                            doRestore = false;
8374                        }
8375                    } else {
8376                        Slog.e(TAG, "Backup Manager not found!");
8377                        doRestore = false;
8378                    }
8379                }
8380
8381                if (!doRestore) {
8382                    // No restore possible, or the Backup Manager was mysteriously not
8383                    // available -- just fire the post-install work request directly.
8384                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8385                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8386                    mHandler.sendMessage(msg);
8387                }
8388            }
8389        });
8390    }
8391
8392    private abstract class HandlerParams {
8393        private static final int MAX_RETRIES = 4;
8394
8395        /**
8396         * Number of times startCopy() has been attempted and had a non-fatal
8397         * error.
8398         */
8399        private int mRetries = 0;
8400
8401        /** User handle for the user requesting the information or installation. */
8402        private final UserHandle mUser;
8403
8404        HandlerParams(UserHandle user) {
8405            mUser = user;
8406        }
8407
8408        UserHandle getUser() {
8409            return mUser;
8410        }
8411
8412        final boolean startCopy() {
8413            boolean res;
8414            try {
8415                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8416
8417                if (++mRetries > MAX_RETRIES) {
8418                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8419                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8420                    handleServiceError();
8421                    return false;
8422                } else {
8423                    handleStartCopy();
8424                    res = true;
8425                }
8426            } catch (RemoteException e) {
8427                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8428                mHandler.sendEmptyMessage(MCS_RECONNECT);
8429                res = false;
8430            }
8431            handleReturnCode();
8432            return res;
8433        }
8434
8435        final void serviceError() {
8436            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8437            handleServiceError();
8438            handleReturnCode();
8439        }
8440
8441        abstract void handleStartCopy() throws RemoteException;
8442        abstract void handleServiceError();
8443        abstract void handleReturnCode();
8444    }
8445
8446    class MeasureParams extends HandlerParams {
8447        private final PackageStats mStats;
8448        private boolean mSuccess;
8449
8450        private final IPackageStatsObserver mObserver;
8451
8452        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8453            super(new UserHandle(stats.userHandle));
8454            mObserver = observer;
8455            mStats = stats;
8456        }
8457
8458        @Override
8459        public String toString() {
8460            return "MeasureParams{"
8461                + Integer.toHexString(System.identityHashCode(this))
8462                + " " + mStats.packageName + "}";
8463        }
8464
8465        @Override
8466        void handleStartCopy() throws RemoteException {
8467            synchronized (mInstallLock) {
8468                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8469            }
8470
8471            if (mSuccess) {
8472                final boolean mounted;
8473                if (Environment.isExternalStorageEmulated()) {
8474                    mounted = true;
8475                } else {
8476                    final String status = Environment.getExternalStorageState();
8477                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8478                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8479                }
8480
8481                if (mounted) {
8482                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8483
8484                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8485                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8486
8487                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8488                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8489
8490                    // Always subtract cache size, since it's a subdirectory
8491                    mStats.externalDataSize -= mStats.externalCacheSize;
8492
8493                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8494                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8495
8496                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8497                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8498                }
8499            }
8500        }
8501
8502        @Override
8503        void handleReturnCode() {
8504            if (mObserver != null) {
8505                try {
8506                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8507                } catch (RemoteException e) {
8508                    Slog.i(TAG, "Observer no longer exists.");
8509                }
8510            }
8511        }
8512
8513        @Override
8514        void handleServiceError() {
8515            Slog.e(TAG, "Could not measure application " + mStats.packageName
8516                            + " external storage");
8517        }
8518    }
8519
8520    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8521            throws RemoteException {
8522        long result = 0;
8523        for (File path : paths) {
8524            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8525        }
8526        return result;
8527    }
8528
8529    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8530        for (File path : paths) {
8531            try {
8532                mcs.clearDirectory(path.getAbsolutePath());
8533            } catch (RemoteException e) {
8534            }
8535        }
8536    }
8537
8538    class InstallParams extends HandlerParams {
8539        /**
8540         * Location where install is coming from, before it has been
8541         * copied/renamed into place. This could be a single monolithic APK
8542         * file, or a cluster directory. This location may be untrusted.
8543         */
8544        final File originFile;
8545
8546        /**
8547         * Flag indicating that {@link #originFile} has already been staged,
8548         * meaning downstream users don't need to defensively copy the contents.
8549         */
8550        boolean originStaged;
8551
8552        final IPackageInstallObserver2 observer;
8553        int flags;
8554        final String installerPackageName;
8555        final VerificationParams verificationParams;
8556        private InstallArgs mArgs;
8557        private int mRet;
8558        final String packageAbiOverride;
8559        boolean multiArch;
8560
8561        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8562                int flags, String installerPackageName, VerificationParams verificationParams,
8563                UserHandle user, String packageAbiOverride) {
8564            super(user);
8565            this.originFile = Preconditions.checkNotNull(originFile);
8566            this.originStaged = originStaged;
8567            this.observer = observer;
8568            this.flags = flags;
8569            this.installerPackageName = installerPackageName;
8570            this.verificationParams = verificationParams;
8571            this.packageAbiOverride = packageAbiOverride;
8572        }
8573
8574        @Override
8575        public String toString() {
8576            return "InstallParams{"
8577                + Integer.toHexString(System.identityHashCode(this))
8578                + " " + originFile + "}";
8579        }
8580
8581        public ManifestDigest getManifestDigest() {
8582            if (verificationParams == null) {
8583                return null;
8584            }
8585            return verificationParams.getManifestDigest();
8586        }
8587
8588        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8589            String packageName = pkgLite.packageName;
8590            int installLocation = pkgLite.installLocation;
8591            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8592            // reader
8593            synchronized (mPackages) {
8594                PackageParser.Package pkg = mPackages.get(packageName);
8595                if (pkg != null) {
8596                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8597                        // Check for downgrading.
8598                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8599                            if (pkgLite.versionCode < pkg.mVersionCode) {
8600                                Slog.w(TAG, "Can't install update of " + packageName
8601                                        + " update version " + pkgLite.versionCode
8602                                        + " is older than installed version "
8603                                        + pkg.mVersionCode);
8604                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8605                            }
8606                        }
8607                        // Check for updated system application.
8608                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8609                            if (onSd) {
8610                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8611                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8612                            }
8613                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8614                        } else {
8615                            if (onSd) {
8616                                // Install flag overrides everything.
8617                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8618                            }
8619                            // If current upgrade specifies particular preference
8620                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8621                                // Application explicitly specified internal.
8622                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8623                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8624                                // App explictly prefers external. Let policy decide
8625                            } else {
8626                                // Prefer previous location
8627                                if (isExternal(pkg)) {
8628                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8629                                }
8630                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8631                            }
8632                        }
8633                    } else {
8634                        // Invalid install. Return error code
8635                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8636                    }
8637                }
8638            }
8639            // All the special cases have been taken care of.
8640            // Return result based on recommended install location.
8641            if (onSd) {
8642                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8643            }
8644            return pkgLite.recommendedInstallLocation;
8645        }
8646
8647        private long getMemoryLowThreshold() {
8648            final DeviceStorageMonitorInternal
8649                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8650            if (dsm == null) {
8651                return 0L;
8652            }
8653            return dsm.getMemoryLowThreshold();
8654        }
8655
8656        /*
8657         * Invoke remote method to get package information and install
8658         * location values. Override install location based on default
8659         * policy if needed and then create install arguments based
8660         * on the install location.
8661         */
8662        public void handleStartCopy() throws RemoteException {
8663            int ret = PackageManager.INSTALL_SUCCEEDED;
8664            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8665            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8666            PackageInfoLite pkgLite = null;
8667
8668            if (onInt && onSd) {
8669                // Check if both bits are set.
8670                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8671                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8672            } else {
8673                final long lowThreshold = getMemoryLowThreshold();
8674                if (lowThreshold == 0L) {
8675                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8676                }
8677
8678                // Remote call to find out default install location
8679                final String originPath = originFile.getAbsolutePath();
8680                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8681                        packageAbiOverride);
8682                // Keep track of whether this package is a multiArch package until
8683                // we perform a full scan of it. We need to do this because we might
8684                // end up extracting the package shared libraries before we perform
8685                // a full scan.
8686                multiArch = pkgLite.multiArch;
8687
8688                /*
8689                 * If we have too little free space, try to free cache
8690                 * before giving up.
8691                 */
8692                if (pkgLite.recommendedInstallLocation
8693                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8694                    final long size = mContainerService.calculateInstalledSize(
8695                            originPath, isForwardLocked(), packageAbiOverride);
8696                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8697                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8698                                lowThreshold, packageAbiOverride);
8699                    }
8700                    /*
8701                     * The cache free must have deleted the file we
8702                     * downloaded to install.
8703                     *
8704                     * TODO: fix the "freeCache" call to not delete
8705                     *       the file we care about.
8706                     */
8707                    if (pkgLite.recommendedInstallLocation
8708                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8709                        pkgLite.recommendedInstallLocation
8710                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8711                    }
8712                }
8713            }
8714
8715            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8716                int loc = pkgLite.recommendedInstallLocation;
8717                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8718                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8719                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8720                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8721                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8722                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8723                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8724                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8725                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8726                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8727                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8728                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8729                } else {
8730                    // Override with defaults if needed.
8731                    loc = installLocationPolicy(pkgLite, flags);
8732                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8733                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8734                    } else if (!onSd && !onInt) {
8735                        // Override install location with flags
8736                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8737                            // Set the flag to install on external media.
8738                            flags |= PackageManager.INSTALL_EXTERNAL;
8739                            flags &= ~PackageManager.INSTALL_INTERNAL;
8740                        } else {
8741                            // Make sure the flag for installing on external
8742                            // media is unset
8743                            flags |= PackageManager.INSTALL_INTERNAL;
8744                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8745                        }
8746                    }
8747                }
8748            }
8749
8750            final InstallArgs args = createInstallArgs(this);
8751            mArgs = args;
8752
8753            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8754                 /*
8755                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8756                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8757                 */
8758                int userIdentifier = getUser().getIdentifier();
8759                if (userIdentifier == UserHandle.USER_ALL
8760                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8761                    userIdentifier = UserHandle.USER_OWNER;
8762                }
8763
8764                /*
8765                 * Determine if we have any installed package verifiers. If we
8766                 * do, then we'll defer to them to verify the packages.
8767                 */
8768                final int requiredUid = mRequiredVerifierPackage == null ? -1
8769                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8770                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8771                    // TODO: send verifier the install session instead of uri
8772                    final Intent verification = new Intent(
8773                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8774                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8775                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8776
8777                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8778                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8779                            0 /* TODO: Which userId? */);
8780
8781                    if (DEBUG_VERIFY) {
8782                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8783                                + verification.toString() + " with " + pkgLite.verifiers.length
8784                                + " optional verifiers");
8785                    }
8786
8787                    final int verificationId = mPendingVerificationToken++;
8788
8789                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8790
8791                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8792                            installerPackageName);
8793
8794                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8795
8796                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8797                            pkgLite.packageName);
8798
8799                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8800                            pkgLite.versionCode);
8801
8802                    if (verificationParams != null) {
8803                        if (verificationParams.getVerificationURI() != null) {
8804                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8805                                 verificationParams.getVerificationURI());
8806                        }
8807                        if (verificationParams.getOriginatingURI() != null) {
8808                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8809                                  verificationParams.getOriginatingURI());
8810                        }
8811                        if (verificationParams.getReferrer() != null) {
8812                            verification.putExtra(Intent.EXTRA_REFERRER,
8813                                  verificationParams.getReferrer());
8814                        }
8815                        if (verificationParams.getOriginatingUid() >= 0) {
8816                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8817                                  verificationParams.getOriginatingUid());
8818                        }
8819                        if (verificationParams.getInstallerUid() >= 0) {
8820                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8821                                  verificationParams.getInstallerUid());
8822                        }
8823                    }
8824
8825                    final PackageVerificationState verificationState = new PackageVerificationState(
8826                            requiredUid, args);
8827
8828                    mPendingVerification.append(verificationId, verificationState);
8829
8830                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8831                            receivers, verificationState);
8832
8833                    /*
8834                     * If any sufficient verifiers were listed in the package
8835                     * manifest, attempt to ask them.
8836                     */
8837                    if (sufficientVerifiers != null) {
8838                        final int N = sufficientVerifiers.size();
8839                        if (N == 0) {
8840                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8841                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8842                        } else {
8843                            for (int i = 0; i < N; i++) {
8844                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8845
8846                                final Intent sufficientIntent = new Intent(verification);
8847                                sufficientIntent.setComponent(verifierComponent);
8848
8849                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8850                            }
8851                        }
8852                    }
8853
8854                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8855                            mRequiredVerifierPackage, receivers);
8856                    if (ret == PackageManager.INSTALL_SUCCEEDED
8857                            && mRequiredVerifierPackage != null) {
8858                        /*
8859                         * Send the intent to the required verification agent,
8860                         * but only start the verification timeout after the
8861                         * target BroadcastReceivers have run.
8862                         */
8863                        verification.setComponent(requiredVerifierComponent);
8864                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8865                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8866                                new BroadcastReceiver() {
8867                                    @Override
8868                                    public void onReceive(Context context, Intent intent) {
8869                                        final Message msg = mHandler
8870                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8871                                        msg.arg1 = verificationId;
8872                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8873                                    }
8874                                }, null, 0, null, null);
8875
8876                        /*
8877                         * We don't want the copy to proceed until verification
8878                         * succeeds, so null out this field.
8879                         */
8880                        mArgs = null;
8881                    }
8882                } else {
8883                    /*
8884                     * No package verification is enabled, so immediately start
8885                     * the remote call to initiate copy using temporary file.
8886                     */
8887                    ret = args.copyApk(mContainerService, true);
8888                }
8889            }
8890
8891            mRet = ret;
8892        }
8893
8894        @Override
8895        void handleReturnCode() {
8896            // If mArgs is null, then MCS couldn't be reached. When it
8897            // reconnects, it will try again to install. At that point, this
8898            // will succeed.
8899            if (mArgs != null) {
8900                processPendingInstall(mArgs, mRet);
8901            }
8902        }
8903
8904        @Override
8905        void handleServiceError() {
8906            mArgs = createInstallArgs(this);
8907            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8908        }
8909
8910        public boolean isForwardLocked() {
8911            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8912        }
8913    }
8914
8915    /*
8916     * Utility class used in movePackage api.
8917     * srcArgs and targetArgs are not set for invalid flags and make
8918     * sure to do null checks when invoking methods on them.
8919     * We probably want to return ErrorPrams for both failed installs
8920     * and moves.
8921     */
8922    class MoveParams extends HandlerParams {
8923        final IPackageMoveObserver observer;
8924        final int flags;
8925        final String packageName;
8926        final InstallArgs srcArgs;
8927        final InstallArgs targetArgs;
8928        int uid;
8929        int mRet;
8930
8931        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8932                String packageName, String[] instructionSets, int uid, UserHandle user,
8933                boolean isMultiArch) {
8934            super(user);
8935            this.srcArgs = srcArgs;
8936            this.observer = observer;
8937            this.flags = flags;
8938            this.packageName = packageName;
8939            this.uid = uid;
8940            if (srcArgs != null) {
8941                final String codePath = srcArgs.getCodePath();
8942                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8943                        instructionSets, isMultiArch);
8944            } else {
8945                targetArgs = null;
8946            }
8947        }
8948
8949        @Override
8950        public String toString() {
8951            return "MoveParams{"
8952                + Integer.toHexString(System.identityHashCode(this))
8953                + " " + packageName + "}";
8954        }
8955
8956        public void handleStartCopy() throws RemoteException {
8957            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8958            // Check for storage space on target medium
8959            if (!targetArgs.checkFreeStorage(mContainerService)) {
8960                Log.w(TAG, "Insufficient storage to install");
8961                return;
8962            }
8963
8964            mRet = srcArgs.doPreCopy();
8965            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8966                return;
8967            }
8968
8969            mRet = targetArgs.copyApk(mContainerService, false);
8970            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8971                srcArgs.doPostCopy(uid);
8972                return;
8973            }
8974
8975            mRet = srcArgs.doPostCopy(uid);
8976            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8977                return;
8978            }
8979
8980            mRet = targetArgs.doPreInstall(mRet);
8981            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8982                return;
8983            }
8984
8985            if (DEBUG_SD_INSTALL) {
8986                StringBuilder builder = new StringBuilder();
8987                if (srcArgs != null) {
8988                    builder.append("src: ");
8989                    builder.append(srcArgs.getCodePath());
8990                }
8991                if (targetArgs != null) {
8992                    builder.append(" target : ");
8993                    builder.append(targetArgs.getCodePath());
8994                }
8995                Log.i(TAG, builder.toString());
8996            }
8997        }
8998
8999        @Override
9000        void handleReturnCode() {
9001            targetArgs.doPostInstall(mRet, uid);
9002            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9003            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
9004                currentStatus = PackageManager.MOVE_SUCCEEDED;
9005            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
9006                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9007            }
9008            processPendingMove(this, currentStatus);
9009        }
9010
9011        @Override
9012        void handleServiceError() {
9013            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9014        }
9015    }
9016
9017    /**
9018     * Used during creation of InstallArgs
9019     *
9020     * @param flags package installation flags
9021     * @return true if should be installed on external storage
9022     */
9023    private static boolean installOnSd(int flags) {
9024        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9025            return false;
9026        }
9027        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9028            return true;
9029        }
9030        return false;
9031    }
9032
9033    /**
9034     * Used during creation of InstallArgs
9035     *
9036     * @param flags package installation flags
9037     * @return true if should be installed as forward locked
9038     */
9039    private static boolean installForwardLocked(int flags) {
9040        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9041    }
9042
9043    private InstallArgs createInstallArgs(InstallParams params) {
9044        // TODO: extend to support incoming zero-copy locations
9045
9046        if (installOnSd(params.flags) || params.isForwardLocked()) {
9047            return new AsecInstallArgs(params);
9048        } else {
9049            return new FileInstallArgs(params);
9050        }
9051    }
9052
9053    /**
9054     * Create args that describe an existing installed package. Typically used
9055     * when cleaning up old installs, or used as a move source.
9056     */
9057    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9058            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9059            boolean isMultiArch) {
9060        final boolean isInAsec;
9061        if (installOnSd(flags)) {
9062            /* Apps on SD card are always in ASEC containers. */
9063            isInAsec = true;
9064        } else if (installForwardLocked(flags)
9065                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9066            /*
9067             * Forward-locked apps are only in ASEC containers if they're the
9068             * new style
9069             */
9070            isInAsec = true;
9071        } else {
9072            isInAsec = false;
9073        }
9074
9075        if (isInAsec) {
9076            return new AsecInstallArgs(codePath, instructionSets,
9077                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9078        } else {
9079            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9080                    instructionSets, isMultiArch);
9081        }
9082    }
9083
9084    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9085            String[] instructionSets, boolean isMultiArch) {
9086        final File codeFile = new File(codePath);
9087        if (installOnSd(flags) || installForwardLocked(flags)) {
9088            String cid = getNextCodePath(codePath, pkgName, "/"
9089                    + AsecInstallArgs.RES_FILE_NAME);
9090            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9091                    installForwardLocked(flags), isMultiArch);
9092        } else {
9093            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9094        }
9095    }
9096
9097    static abstract class InstallArgs {
9098        /** @see InstallParams#originFile */
9099        final File originFile;
9100        /** @see InstallParams#originStaged */
9101        final boolean originStaged;
9102
9103        // TODO: define inherit location
9104
9105        final IPackageInstallObserver2 observer;
9106        // Always refers to PackageManager flags only
9107        final int flags;
9108        final String installerPackageName;
9109        final ManifestDigest manifestDigest;
9110        final UserHandle user;
9111        final String abiOverride;
9112        final boolean multiArch;
9113
9114        // The list of instruction sets supported by this app. This is currently
9115        // only used during the rmdex() phase to clean up resources. We can get rid of this
9116        // if we move dex files under the common app path.
9117        /* nullable */ String[] instructionSets;
9118
9119        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9120                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9121                    UserHandle user, String[] instructionSets,
9122                    String abiOverride, boolean multiArch) {
9123            this.originFile = originFile;
9124            this.originStaged = originStaged;
9125            this.flags = flags;
9126            this.observer = observer;
9127            this.installerPackageName = installerPackageName;
9128            this.manifestDigest = manifestDigest;
9129            this.user = user;
9130            this.instructionSets = instructionSets;
9131            this.abiOverride = abiOverride;
9132            this.multiArch = multiArch;
9133        }
9134
9135        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9136        abstract int doPreInstall(int status);
9137
9138        /**
9139         * Rename package into final resting place. All paths on the given
9140         * scanned package should be updated to reflect the rename.
9141         */
9142        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9143        abstract int doPostInstall(int status, int uid);
9144
9145        /** @see PackageSettingBase#codePathString */
9146        abstract String getCodePath();
9147        /** @see PackageSettingBase#resourcePathString */
9148        abstract String getResourcePath();
9149        abstract String getLegacyNativeLibraryPath();
9150
9151        // Need installer lock especially for dex file removal.
9152        abstract void cleanUpResourcesLI();
9153        abstract boolean doPostDeleteLI(boolean delete);
9154        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9155
9156        /**
9157         * Called before the source arguments are copied. This is used mostly
9158         * for MoveParams when it needs to read the source file to put it in the
9159         * destination.
9160         */
9161        int doPreCopy() {
9162            return PackageManager.INSTALL_SUCCEEDED;
9163        }
9164
9165        /**
9166         * Called after the source arguments are copied. This is used mostly for
9167         * MoveParams when it needs to read the source file to put it in the
9168         * destination.
9169         *
9170         * @return
9171         */
9172        int doPostCopy(int uid) {
9173            return PackageManager.INSTALL_SUCCEEDED;
9174        }
9175
9176        protected boolean isFwdLocked() {
9177            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9178        }
9179
9180        UserHandle getUser() {
9181            return user;
9182        }
9183    }
9184
9185    /**
9186     * Logic to handle installation of non-ASEC applications, including copying
9187     * and renaming logic.
9188     */
9189    class FileInstallArgs extends InstallArgs {
9190        private File codeFile;
9191        private File resourceFile;
9192        private File legacyNativeLibraryPath;
9193
9194        // Example topology:
9195        // /data/app/com.example/base.apk
9196        // /data/app/com.example/split_foo.apk
9197        // /data/app/com.example/lib/arm/libfoo.so
9198        // /data/app/com.example/lib/arm64/libfoo.so
9199        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9200
9201        /** New install */
9202        FileInstallArgs(InstallParams params) {
9203            super(params.originFile, params.originStaged, params.observer, params.flags,
9204                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9205                    null /* instruction sets */, params.packageAbiOverride,
9206                    params.multiArch);
9207            if (isFwdLocked()) {
9208                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9209            }
9210        }
9211
9212        /** Existing install */
9213        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9214                String[] instructionSets, boolean isMultiArch) {
9215            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9216            this.codeFile = (codePath != null) ? new File(codePath) : null;
9217            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9218            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9219                    new File(legacyNativeLibraryPath) : null;
9220        }
9221
9222        /** New install from existing */
9223        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9224            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9225                    isMultiArch);
9226        }
9227
9228        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9229            final long lowThreshold;
9230
9231            final DeviceStorageMonitorInternal
9232                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9233            if (dsm == null) {
9234                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9235                lowThreshold = 0L;
9236            } else {
9237                if (dsm.isMemoryLow()) {
9238                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9239                    return false;
9240                }
9241
9242                lowThreshold = dsm.getMemoryLowThreshold();
9243            }
9244
9245            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9246                    lowThreshold);
9247        }
9248
9249        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9250            int ret = PackageManager.INSTALL_SUCCEEDED;
9251
9252            if (originStaged) {
9253                Slog.d(TAG, originFile + " already staged; skipping copy");
9254                codeFile = originFile;
9255                resourceFile = originFile;
9256            } else {
9257                try {
9258                    final File tempDir = mInstallerService.allocateSessionDir();
9259                    codeFile = tempDir;
9260                    resourceFile = tempDir;
9261                } catch (IOException e) {
9262                    Slog.w(TAG, "Failed to create copy file: " + e);
9263                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9264                }
9265
9266                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9267                    @Override
9268                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9269                        if (!FileUtils.isValidExtFilename(name)) {
9270                            throw new IllegalArgumentException("Invalid filename: " + name);
9271                        }
9272                        try {
9273                            final File file = new File(codeFile, name);
9274                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9275                                    O_RDWR | O_CREAT, 0644);
9276                            Os.chmod(file.getAbsolutePath(), 0644);
9277                            return new ParcelFileDescriptor(fd);
9278                        } catch (ErrnoException e) {
9279                            throw new RemoteException("Failed to open: " + e.getMessage());
9280                        }
9281                    }
9282                };
9283
9284                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9285                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9286                    Slog.e(TAG, "Failed to copy package");
9287                    return ret;
9288                }
9289            }
9290
9291            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9292            NativeLibraryHelper.Handle handle = null;
9293            try {
9294                handle = NativeLibraryHelper.Handle.create(codeFile);
9295                if (multiArch) {
9296                    // Warn if we've set an abiOverride for multi-lib packages..
9297                    // By definition, we need to copy both 32 and 64 bit libraries for
9298                    // such packages.
9299                    if (abiOverride != null &&  !CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9300                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9301                    }
9302
9303                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9304                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9305                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9306                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9307                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9308                    }
9309
9310                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9311                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9312                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9313                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9314                    }
9315                } else {
9316                    final String cpuAbiOverride = deriveAbiOverride(this.abiOverride, null /* package setting */);
9317                    String[] abiList = (cpuAbiOverride != null) ?
9318                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9319
9320                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9321                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9322                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9323                    }
9324
9325                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9326                            true /* use isa specific subdirs */);
9327                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9328                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9329                        return copyRet;
9330                    }
9331                }
9332            } catch (IOException e) {
9333                Slog.e(TAG, "Copying native libraries failed", e);
9334                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9335            } catch (PackageManagerException pme) {
9336                Slog.e(TAG, "Copying native libraries failed", pme);
9337                ret = pme.error;
9338            } finally {
9339                IoUtils.closeQuietly(handle);
9340            }
9341
9342            return ret;
9343        }
9344
9345        int doPreInstall(int status) {
9346            if (status != PackageManager.INSTALL_SUCCEEDED) {
9347                cleanUp();
9348            }
9349            return status;
9350        }
9351
9352        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9353            if (status != PackageManager.INSTALL_SUCCEEDED) {
9354                cleanUp();
9355                return false;
9356            } else {
9357                final File beforeCodeFile = codeFile;
9358                final File afterCodeFile = getNextCodePath(pkg.packageName);
9359
9360                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9361                try {
9362                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9363                } catch (ErrnoException e) {
9364                    Slog.d(TAG, "Failed to rename", e);
9365                    return false;
9366                }
9367
9368                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9369                    Slog.d(TAG, "Failed to restorecon");
9370                    return false;
9371                }
9372
9373                // Reflect the rename internally
9374                codeFile = afterCodeFile;
9375                resourceFile = afterCodeFile;
9376
9377                // Reflect the rename in scanned details
9378                pkg.codePath = afterCodeFile.getAbsolutePath();
9379                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9380                        pkg.baseCodePath);
9381                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9382                        pkg.splitCodePaths);
9383
9384                // Reflect the rename in app info
9385                pkg.applicationInfo.setCodePath(pkg.codePath);
9386                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9387                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9388                pkg.applicationInfo.setResourcePath(pkg.codePath);
9389                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9390                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9391
9392                return true;
9393            }
9394        }
9395
9396        int doPostInstall(int status, int uid) {
9397            if (status != PackageManager.INSTALL_SUCCEEDED) {
9398                cleanUp();
9399            }
9400            return status;
9401        }
9402
9403        @Override
9404        String getCodePath() {
9405            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9406        }
9407
9408        @Override
9409        String getResourcePath() {
9410            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9411        }
9412
9413        @Override
9414        String getLegacyNativeLibraryPath() {
9415            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9416        }
9417
9418        private boolean cleanUp() {
9419            if (codeFile == null || !codeFile.exists()) {
9420                return false;
9421            }
9422
9423            if (codeFile.isDirectory()) {
9424                FileUtils.deleteContents(codeFile);
9425            }
9426            codeFile.delete();
9427
9428            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9429                resourceFile.delete();
9430            }
9431
9432            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9433                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9434                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9435                }
9436                legacyNativeLibraryPath.delete();
9437            }
9438
9439            return true;
9440        }
9441
9442        void cleanUpResourcesLI() {
9443            // Try enumerating all code paths before deleting
9444            List<String> allCodePaths = Collections.EMPTY_LIST;
9445            if (codeFile != null && codeFile.exists()) {
9446                try {
9447                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9448                    allCodePaths = pkg.getAllCodePaths();
9449                } catch (PackageParserException e) {
9450                    // Ignored; we tried our best
9451                }
9452            }
9453
9454            cleanUp();
9455
9456            if (!allCodePaths.isEmpty()) {
9457                if (instructionSets == null) {
9458                    throw new IllegalStateException("instructionSet == null");
9459                }
9460                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9461                for (String codePath : allCodePaths) {
9462                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9463                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9464                        if (retCode < 0) {
9465                            Slog.w(TAG, "Couldn't remove dex file for package: "
9466                                    + " at location " + codePath + ", retcode=" + retCode);
9467                            // we don't consider this to be a failure of the core package deletion
9468                        }
9469                    }
9470                }
9471            }
9472        }
9473
9474        boolean doPostDeleteLI(boolean delete) {
9475            // XXX err, shouldn't we respect the delete flag?
9476            cleanUpResourcesLI();
9477            return true;
9478        }
9479    }
9480
9481    private boolean isAsecExternal(String cid) {
9482        final String asecPath = PackageHelper.getSdFilesystem(cid);
9483        return !asecPath.startsWith(mAsecInternalPath);
9484    }
9485
9486    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9487            PackageManagerException {
9488        if (copyRet < 0) {
9489            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9490                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9491                throw new PackageManagerException(copyRet, message);
9492            }
9493        }
9494    }
9495
9496    /**
9497     * Extract the MountService "container ID" from the full code path of an
9498     * .apk.
9499     */
9500    static String cidFromCodePath(String fullCodePath) {
9501        int eidx = fullCodePath.lastIndexOf("/");
9502        String subStr1 = fullCodePath.substring(0, eidx);
9503        int sidx = subStr1.lastIndexOf("/");
9504        return subStr1.substring(sidx+1, eidx);
9505    }
9506
9507    /**
9508     * Logic to handle installation of ASEC applications, including copying and
9509     * renaming logic.
9510     */
9511    class AsecInstallArgs extends InstallArgs {
9512        // TODO: teach about handling cluster directories
9513
9514        static final String RES_FILE_NAME = "pkg.apk";
9515        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9516
9517        String cid;
9518        String packagePath;
9519        String resourcePath;
9520        String legacyNativeLibraryDir;
9521
9522        /** New install */
9523        AsecInstallArgs(InstallParams params) {
9524            super(params.originFile, params.originStaged, params.observer, params.flags,
9525                    params.installerPackageName, params.getManifestDigest(),
9526                    params.getUser(), null /* instruction sets */,
9527                    params.packageAbiOverride, params.multiArch);
9528        }
9529
9530        /** Existing install */
9531        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9532                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9533            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9534                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9535                    instructionSets, null, isMultiArch);
9536            // Extract cid from fullCodePath
9537            int eidx = fullCodePath.lastIndexOf("/");
9538            String subStr1 = fullCodePath.substring(0, eidx);
9539            int sidx = subStr1.lastIndexOf("/");
9540            cid = subStr1.substring(sidx+1, eidx);
9541            setCachePath(subStr1);
9542        }
9543
9544        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9545                        boolean isMultiArch) {
9546            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9547                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9548                    instructionSets, null, isMultiArch);
9549            this.cid = cid;
9550            setCachePath(PackageHelper.getSdDir(cid));
9551        }
9552
9553        /** New install from existing */
9554        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9555                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9556            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9557                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9558                    instructionSets, null, isMultiArch);
9559            this.cid = cid;
9560        }
9561
9562        void createCopyFile() {
9563            cid = getTempContainerId();
9564        }
9565
9566        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9567            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9568                    abiOverride);
9569        }
9570
9571        private final boolean isExternal() {
9572            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9573        }
9574
9575        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9576            if (temp) {
9577                createCopyFile();
9578            } else {
9579                /*
9580                 * Pre-emptively destroy the container since it's destroyed if
9581                 * copying fails due to it existing anyway.
9582                 */
9583                PackageHelper.destroySdDir(cid);
9584            }
9585
9586            final String newCachePath = imcs.copyPackageToContainer(
9587                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9588                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9589
9590            if (newCachePath != null) {
9591                setCachePath(newCachePath);
9592                return PackageManager.INSTALL_SUCCEEDED;
9593            } else {
9594                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9595            }
9596        }
9597
9598        @Override
9599        String getCodePath() {
9600            return packagePath;
9601        }
9602
9603        @Override
9604        String getResourcePath() {
9605            return resourcePath;
9606        }
9607
9608        @Override
9609        String getLegacyNativeLibraryPath() {
9610            return legacyNativeLibraryDir;
9611        }
9612
9613        int doPreInstall(int status) {
9614            if (status != PackageManager.INSTALL_SUCCEEDED) {
9615                // Destroy container
9616                PackageHelper.destroySdDir(cid);
9617            } else {
9618                boolean mounted = PackageHelper.isContainerMounted(cid);
9619                if (!mounted) {
9620                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9621                            Process.SYSTEM_UID);
9622                    if (newCachePath != null) {
9623                        setCachePath(newCachePath);
9624                    } else {
9625                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9626                    }
9627                }
9628            }
9629            return status;
9630        }
9631
9632        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9633            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9634            String newCachePath = null;
9635            if (PackageHelper.isContainerMounted(cid)) {
9636                // Unmount the container
9637                if (!PackageHelper.unMountSdDir(cid)) {
9638                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9639                    return false;
9640                }
9641            }
9642            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9643                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9644                        " which might be stale. Will try to clean up.");
9645                // Clean up the stale container and proceed to recreate.
9646                if (!PackageHelper.destroySdDir(newCacheId)) {
9647                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9648                    return false;
9649                }
9650                // Successfully cleaned up stale container. Try to rename again.
9651                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9652                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9653                            + " inspite of cleaning it up.");
9654                    return false;
9655                }
9656            }
9657            if (!PackageHelper.isContainerMounted(newCacheId)) {
9658                Slog.w(TAG, "Mounting container " + newCacheId);
9659                newCachePath = PackageHelper.mountSdDir(newCacheId,
9660                        getEncryptKey(), Process.SYSTEM_UID);
9661            } else {
9662                newCachePath = PackageHelper.getSdDir(newCacheId);
9663            }
9664            if (newCachePath == null) {
9665                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9666                return false;
9667            }
9668            Log.i(TAG, "Succesfully renamed " + cid +
9669                    " to " + newCacheId +
9670                    " at new path: " + newCachePath);
9671            cid = newCacheId;
9672            setCachePath(newCachePath);
9673
9674            // TODO: extend to support split APKs
9675            pkg.codePath = getCodePath();
9676            pkg.baseCodePath = getCodePath();
9677            pkg.splitCodePaths = null;
9678
9679            pkg.applicationInfo.setCodePath(getCodePath());
9680            pkg.applicationInfo.setBaseCodePath(getCodePath());
9681            pkg.applicationInfo.setSplitCodePaths(null);
9682            pkg.applicationInfo.setResourcePath(getResourcePath());
9683            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9684            pkg.applicationInfo.setSplitResourcePaths(null);
9685
9686            return true;
9687        }
9688
9689        private void setCachePath(String newCachePath) {
9690            File cachePath = new File(newCachePath);
9691            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9692            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9693
9694            if (isFwdLocked()) {
9695                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9696            } else {
9697                resourcePath = packagePath;
9698            }
9699        }
9700
9701        int doPostInstall(int status, int uid) {
9702            if (status != PackageManager.INSTALL_SUCCEEDED) {
9703                cleanUp();
9704            } else {
9705                final int groupOwner;
9706                final String protectedFile;
9707                if (isFwdLocked()) {
9708                    groupOwner = UserHandle.getSharedAppGid(uid);
9709                    protectedFile = RES_FILE_NAME;
9710                } else {
9711                    groupOwner = -1;
9712                    protectedFile = null;
9713                }
9714
9715                if (uid < Process.FIRST_APPLICATION_UID
9716                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9717                    Slog.e(TAG, "Failed to finalize " + cid);
9718                    PackageHelper.destroySdDir(cid);
9719                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9720                }
9721
9722                boolean mounted = PackageHelper.isContainerMounted(cid);
9723                if (!mounted) {
9724                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9725                }
9726            }
9727            return status;
9728        }
9729
9730        private void cleanUp() {
9731            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9732
9733            // Destroy secure container
9734            PackageHelper.destroySdDir(cid);
9735        }
9736
9737        void cleanUpResourcesLI() {
9738            String sourceFile = getCodePath();
9739            // Remove dex file
9740            if (instructionSets == null) {
9741                throw new IllegalStateException("instructionSet == null");
9742            }
9743            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9744            for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9745                int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet);
9746                if (retCode < 0) {
9747                    Slog.w(TAG, "Couldn't remove dex file for package: "
9748                            + " at location "
9749                            + sourceFile.toString() + ", retcode=" + retCode);
9750                    // we don't consider this to be a failure of the core package deletion
9751                }
9752            }
9753            cleanUp();
9754        }
9755
9756        boolean matchContainer(String app) {
9757            if (cid.startsWith(app)) {
9758                return true;
9759            }
9760            return false;
9761        }
9762
9763        String getPackageName() {
9764            return getAsecPackageName(cid);
9765        }
9766
9767        boolean doPostDeleteLI(boolean delete) {
9768            boolean ret = false;
9769            boolean mounted = PackageHelper.isContainerMounted(cid);
9770            if (mounted) {
9771                // Unmount first
9772                ret = PackageHelper.unMountSdDir(cid);
9773            }
9774            if (ret && delete) {
9775                cleanUpResourcesLI();
9776            }
9777            return ret;
9778        }
9779
9780        @Override
9781        int doPreCopy() {
9782            if (isFwdLocked()) {
9783                if (!PackageHelper.fixSdPermissions(cid,
9784                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9785                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9786                }
9787            }
9788
9789            return PackageManager.INSTALL_SUCCEEDED;
9790        }
9791
9792        @Override
9793        int doPostCopy(int uid) {
9794            if (isFwdLocked()) {
9795                if (uid < Process.FIRST_APPLICATION_UID
9796                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9797                                RES_FILE_NAME)) {
9798                    Slog.e(TAG, "Failed to finalize " + cid);
9799                    PackageHelper.destroySdDir(cid);
9800                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9801                }
9802            }
9803
9804            return PackageManager.INSTALL_SUCCEEDED;
9805        }
9806    }
9807
9808    static String getAsecPackageName(String packageCid) {
9809        int idx = packageCid.lastIndexOf("-");
9810        if (idx == -1) {
9811            return packageCid;
9812        }
9813        return packageCid.substring(0, idx);
9814    }
9815
9816    // Utility method used to create code paths based on package name and available index.
9817    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9818        String idxStr = "";
9819        int idx = 1;
9820        // Fall back to default value of idx=1 if prefix is not
9821        // part of oldCodePath
9822        if (oldCodePath != null) {
9823            String subStr = oldCodePath;
9824            // Drop the suffix right away
9825            if (suffix != null && subStr.endsWith(suffix)) {
9826                subStr = subStr.substring(0, subStr.length() - suffix.length());
9827            }
9828            // If oldCodePath already contains prefix find out the
9829            // ending index to either increment or decrement.
9830            int sidx = subStr.lastIndexOf(prefix);
9831            if (sidx != -1) {
9832                subStr = subStr.substring(sidx + prefix.length());
9833                if (subStr != null) {
9834                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9835                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9836                    }
9837                    try {
9838                        idx = Integer.parseInt(subStr);
9839                        if (idx <= 1) {
9840                            idx++;
9841                        } else {
9842                            idx--;
9843                        }
9844                    } catch(NumberFormatException e) {
9845                    }
9846                }
9847            }
9848        }
9849        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9850        return prefix + idxStr;
9851    }
9852
9853    private File getNextCodePath(String packageName) {
9854        int suffix = 1;
9855        File result;
9856        do {
9857            result = new File(mAppInstallDir, packageName + "-" + suffix);
9858            suffix++;
9859        } while (result.exists());
9860        return result;
9861    }
9862
9863    // Utility method used to ignore ADD/REMOVE events
9864    // by directory observer.
9865    private static boolean ignoreCodePath(String fullPathStr) {
9866        String apkName = deriveCodePathName(fullPathStr);
9867        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9868        if (idx != -1 && ((idx+1) < apkName.length())) {
9869            // Make sure the package ends with a numeral
9870            String version = apkName.substring(idx+1);
9871            try {
9872                Integer.parseInt(version);
9873                return true;
9874            } catch (NumberFormatException e) {}
9875        }
9876        return false;
9877    }
9878
9879    // Utility method that returns the relative package path with respect
9880    // to the installation directory. Like say for /data/data/com.test-1.apk
9881    // string com.test-1 is returned.
9882    static String deriveCodePathName(String codePath) {
9883        if (codePath == null) {
9884            return null;
9885        }
9886        final File codeFile = new File(codePath);
9887        final String name = codeFile.getName();
9888        if (codeFile.isDirectory()) {
9889            return name;
9890        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9891            final int lastDot = name.lastIndexOf('.');
9892            return name.substring(0, lastDot);
9893        } else {
9894            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9895            return null;
9896        }
9897    }
9898
9899    class PackageInstalledInfo {
9900        String name;
9901        int uid;
9902        // The set of users that originally had this package installed.
9903        int[] origUsers;
9904        // The set of users that now have this package installed.
9905        int[] newUsers;
9906        PackageParser.Package pkg;
9907        int returnCode;
9908        String returnMsg;
9909        PackageRemovedInfo removedInfo;
9910
9911        public void setError(int code, String msg) {
9912            returnCode = code;
9913            returnMsg = msg;
9914            Slog.w(TAG, msg);
9915        }
9916
9917        public void setError(String msg, PackageParserException e) {
9918            returnCode = e.error;
9919            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9920            Slog.w(TAG, msg, e);
9921        }
9922
9923        public void setError(String msg, PackageManagerException e) {
9924            returnCode = e.error;
9925            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9926            Slog.w(TAG, msg, e);
9927        }
9928
9929        // In some error cases we want to convey more info back to the observer
9930        String origPackage;
9931        String origPermission;
9932    }
9933
9934    /*
9935     * Install a non-existing package.
9936     */
9937    private void installNewPackageLI(PackageParser.Package pkg,
9938            int parseFlags, int scanMode, UserHandle user,
9939            String installerPackageName, PackageInstalledInfo res) {
9940        // Remember this for later, in case we need to rollback this install
9941        String pkgName = pkg.packageName;
9942
9943        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9944        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9945        synchronized(mPackages) {
9946            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9947                // A package with the same name is already installed, though
9948                // it has been renamed to an older name.  The package we
9949                // are trying to install should be installed as an update to
9950                // the existing one, but that has not been requested, so bail.
9951                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9952                        + " without first uninstalling package running as "
9953                        + mSettings.mRenamedPackages.get(pkgName));
9954                return;
9955            }
9956            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9957                // Don't allow installation over an existing package with the same name.
9958                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9959                        + " without first uninstalling.");
9960                return;
9961            }
9962        }
9963
9964        try {
9965            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9966                    System.currentTimeMillis(), user);
9967
9968            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9969            // delete the partially installed application. the data directory will have to be
9970            // restored if it was already existing
9971            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9972                // remove package from internal structures.  Note that we want deletePackageX to
9973                // delete the package data and cache directories that it created in
9974                // scanPackageLocked, unless those directories existed before we even tried to
9975                // install.
9976                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9977                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9978                                res.removedInfo, true);
9979            }
9980
9981        } catch (PackageManagerException e) {
9982            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9983        }
9984    }
9985
9986    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9987        // Upgrade keysets are being used.  Determine if new package has a superset of the
9988        // required keys.
9989        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9990        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9991        for (int i = 0; i < upgradeKeySets.length; i++) {
9992            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9993            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9994                return true;
9995            }
9996        }
9997        return false;
9998    }
9999
10000    private void replacePackageLI(PackageParser.Package pkg,
10001            int parseFlags, int scanMode, UserHandle user,
10002            String installerPackageName, PackageInstalledInfo res) {
10003        PackageParser.Package oldPackage;
10004        String pkgName = pkg.packageName;
10005        int[] allUsers;
10006        boolean[] perUserInstalled;
10007
10008        // First find the old package info and check signatures
10009        synchronized(mPackages) {
10010            oldPackage = mPackages.get(pkgName);
10011            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10012            PackageSetting ps = mSettings.mPackages.get(pkgName);
10013            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10014                // default to original signature matching
10015                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10016                    != PackageManager.SIGNATURE_MATCH) {
10017                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10018                            "New package has a different signature: " + pkgName);
10019                    return;
10020                }
10021            } else {
10022                if(!checkUpgradeKeySetLP(ps, pkg)) {
10023                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10024                            "New package not signed by keys specified by upgrade-keysets: "
10025                            + pkgName);
10026                    return;
10027                }
10028            }
10029
10030            // In case of rollback, remember per-user/profile install state
10031            allUsers = sUserManager.getUserIds();
10032            perUserInstalled = new boolean[allUsers.length];
10033            for (int i = 0; i < allUsers.length; i++) {
10034                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10035            }
10036        }
10037
10038        boolean sysPkg = (isSystemApp(oldPackage));
10039        if (sysPkg) {
10040            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10041                    user, allUsers, perUserInstalled, installerPackageName, res);
10042        } else {
10043            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10044                    user, allUsers, perUserInstalled, installerPackageName, res);
10045        }
10046    }
10047
10048    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10049            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10050            int[] allUsers, boolean[] perUserInstalled,
10051            String installerPackageName, PackageInstalledInfo res) {
10052        String pkgName = deletedPackage.packageName;
10053        boolean deletedPkg = true;
10054        boolean updatedSettings = false;
10055
10056        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10057                + deletedPackage);
10058        long origUpdateTime;
10059        if (pkg.mExtras != null) {
10060            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10061        } else {
10062            origUpdateTime = 0;
10063        }
10064
10065        // First delete the existing package while retaining the data directory
10066        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10067                res.removedInfo, true)) {
10068            // If the existing package wasn't successfully deleted
10069            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10070            deletedPkg = false;
10071        } else {
10072            // Successfully deleted the old package. Now proceed with re-installation
10073            deleteCodeCacheDirsLI(pkgName);
10074            try {
10075                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10076                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10077                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10078                updatedSettings = true;
10079            } catch (PackageManagerException e) {
10080                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10081            }
10082        }
10083
10084        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10085            // remove package from internal structures.  Note that we want deletePackageX to
10086            // delete the package data and cache directories that it created in
10087            // scanPackageLocked, unless those directories existed before we even tried to
10088            // install.
10089            if(updatedSettings) {
10090                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10091                deletePackageLI(
10092                        pkgName, null, true, allUsers, perUserInstalled,
10093                        PackageManager.DELETE_KEEP_DATA,
10094                                res.removedInfo, true);
10095            }
10096            // Since we failed to install the new package we need to restore the old
10097            // package that we deleted.
10098            if (deletedPkg) {
10099                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10100                File restoreFile = new File(deletedPackage.codePath);
10101                // Parse old package
10102                boolean oldOnSd = isExternal(deletedPackage);
10103                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10104                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10105                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10106                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10107                        | SCAN_UPDATE_TIME;
10108                try {
10109                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null);
10110                } catch (PackageManagerException e) {
10111                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10112                            + e.getMessage());
10113                    return;
10114                }
10115                // Restore of old package succeeded. Update permissions.
10116                // writer
10117                synchronized (mPackages) {
10118                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10119                            UPDATE_PERMISSIONS_ALL);
10120                    // can downgrade to reader
10121                    mSettings.writeLPr();
10122                }
10123                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10124            }
10125        }
10126    }
10127
10128    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10129            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10130            int[] allUsers, boolean[] perUserInstalled,
10131            String installerPackageName, PackageInstalledInfo res) {
10132        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10133                + ", old=" + deletedPackage);
10134        boolean updatedSettings = false;
10135        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10136                PackageParser.PARSE_IS_SYSTEM;
10137        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10138            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10139        }
10140        String packageName = deletedPackage.packageName;
10141        if (packageName == null) {
10142            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10143                    "Attempt to delete null packageName.");
10144            return;
10145        }
10146        PackageParser.Package oldPkg;
10147        PackageSetting oldPkgSetting;
10148        // reader
10149        synchronized (mPackages) {
10150            oldPkg = mPackages.get(packageName);
10151            oldPkgSetting = mSettings.mPackages.get(packageName);
10152            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10153                    (oldPkgSetting == null)) {
10154                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10155                        "Couldn't find package:" + packageName + " information");
10156                return;
10157            }
10158        }
10159
10160        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10161
10162        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10163        res.removedInfo.removedPackage = packageName;
10164        // Remove existing system package
10165        removePackageLI(oldPkgSetting, true);
10166        // writer
10167        synchronized (mPackages) {
10168            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10169                // We didn't need to disable the .apk as a current system package,
10170                // which means we are replacing another update that is already
10171                // installed.  We need to make sure to delete the older one's .apk.
10172                res.removedInfo.args = createInstallArgsForExisting(0,
10173                        deletedPackage.applicationInfo.getCodePath(),
10174                        deletedPackage.applicationInfo.getResourcePath(),
10175                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10176                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10177                        isMultiArch(deletedPackage.applicationInfo));
10178            } else {
10179                res.removedInfo.args = null;
10180            }
10181        }
10182
10183        // Successfully disabled the old package. Now proceed with re-installation
10184        deleteCodeCacheDirsLI(packageName);
10185
10186        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10187        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10188
10189        PackageParser.Package newPackage = null;
10190        try {
10191            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
10192            if (newPackage.mExtras != null) {
10193                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10194                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10195                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10196
10197                // is the update attempting to change shared user? that isn't going to work...
10198                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10199                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10200                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10201                            + " to " + newPkgSetting.sharedUser);
10202                    updatedSettings = true;
10203                }
10204            }
10205
10206            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10207                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10208                updatedSettings = true;
10209            }
10210
10211        } catch (PackageManagerException e) {
10212            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10213        }
10214
10215        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10216            // Re installation failed. Restore old information
10217            // Remove new pkg information
10218            if (newPackage != null) {
10219                removeInstalledPackageLI(newPackage, true);
10220            }
10221            // Add back the old system package
10222            try {
10223                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
10224            } catch (PackageManagerException e) {
10225                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10226            }
10227            // Restore the old system information in Settings
10228            synchronized(mPackages) {
10229                if (updatedSettings) {
10230                    mSettings.enableSystemPackageLPw(packageName);
10231                    mSettings.setInstallerPackageName(packageName,
10232                            oldPkgSetting.installerPackageName);
10233                }
10234                mSettings.writeLPr();
10235            }
10236        }
10237    }
10238
10239    // Utility method used to move dex files during install.
10240    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10241        // TODO: extend to move split APK dex files
10242        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10243            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10244            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10245            for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10246                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10247                        dexCodeInstructionSet);
10248                if (retCode != 0) {
10249                /*
10250                 * Programs may be lazily run through dexopt, so the
10251                 * source may not exist. However, something seems to
10252                 * have gone wrong, so note that dexopt needs to be
10253                 * run again and remove the source file. In addition,
10254                 * remove the target to make sure there isn't a stale
10255                 * file from a previous version of the package.
10256                 */
10257                    newPackage.mDexOptPerformed.clear();
10258                    mInstaller.rmdex(oldCodePath, dexCodeInstructionSet);
10259                    mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet);
10260                }
10261            }
10262        }
10263        return PackageManager.INSTALL_SUCCEEDED;
10264    }
10265
10266    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10267            int[] allUsers, boolean[] perUserInstalled,
10268            PackageInstalledInfo res) {
10269        String pkgName = newPackage.packageName;
10270        synchronized (mPackages) {
10271            //write settings. the installStatus will be incomplete at this stage.
10272            //note that the new package setting would have already been
10273            //added to mPackages. It hasn't been persisted yet.
10274            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10275            mSettings.writeLPr();
10276        }
10277
10278        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10279
10280        synchronized (mPackages) {
10281            updatePermissionsLPw(newPackage.packageName, newPackage,
10282                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10283                            ? UPDATE_PERMISSIONS_ALL : 0));
10284            // For system-bundled packages, we assume that installing an upgraded version
10285            // of the package implies that the user actually wants to run that new code,
10286            // so we enable the package.
10287            if (isSystemApp(newPackage)) {
10288                // NB: implicit assumption that system package upgrades apply to all users
10289                if (DEBUG_INSTALL) {
10290                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10291                }
10292                PackageSetting ps = mSettings.mPackages.get(pkgName);
10293                if (ps != null) {
10294                    if (res.origUsers != null) {
10295                        for (int userHandle : res.origUsers) {
10296                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10297                                    userHandle, installerPackageName);
10298                        }
10299                    }
10300                    // Also convey the prior install/uninstall state
10301                    if (allUsers != null && perUserInstalled != null) {
10302                        for (int i = 0; i < allUsers.length; i++) {
10303                            if (DEBUG_INSTALL) {
10304                                Slog.d(TAG, "    user " + allUsers[i]
10305                                        + " => " + perUserInstalled[i]);
10306                            }
10307                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10308                        }
10309                        // these install state changes will be persisted in the
10310                        // upcoming call to mSettings.writeLPr().
10311                    }
10312                }
10313            }
10314            res.name = pkgName;
10315            res.uid = newPackage.applicationInfo.uid;
10316            res.pkg = newPackage;
10317            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10318            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10319            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10320            //to update install status
10321            mSettings.writeLPr();
10322        }
10323    }
10324
10325    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10326        int pFlags = args.flags;
10327        String installerPackageName = args.installerPackageName;
10328        File tmpPackageFile = new File(args.getCodePath());
10329        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10330        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10331        boolean replace = false;
10332        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10333                | (newInstall ? SCAN_NEW_INSTALL : 0);
10334        // Result object to be returned
10335        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10336
10337        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10338        // Retrieve PackageSettings and parse package
10339        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10340                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10341                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10342        PackageParser pp = new PackageParser();
10343        pp.setSeparateProcesses(mSeparateProcesses);
10344        pp.setDisplayMetrics(mMetrics);
10345
10346        final PackageParser.Package pkg;
10347        try {
10348            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10349        } catch (PackageParserException e) {
10350            res.setError("Failed parse during installPackageLI", e);
10351            return;
10352        }
10353
10354        // Mark that we have an install time CPU ABI override.
10355        pkg.cpuAbiOverride = args.abiOverride;
10356
10357        String pkgName = res.name = pkg.packageName;
10358        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10359            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10360                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10361                return;
10362            }
10363        }
10364
10365        try {
10366            pp.collectCertificates(pkg, parseFlags);
10367            pp.collectManifestDigest(pkg);
10368        } catch (PackageParserException e) {
10369            res.setError("Failed collect during installPackageLI", e);
10370            return;
10371        }
10372
10373        /* If the installer passed in a manifest digest, compare it now. */
10374        if (args.manifestDigest != null) {
10375            if (DEBUG_INSTALL) {
10376                final String parsedManifest = pkg.manifestDigest == null ? "null"
10377                        : pkg.manifestDigest.toString();
10378                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10379                        + parsedManifest);
10380            }
10381
10382            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10383                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10384                return;
10385            }
10386        } else if (DEBUG_INSTALL) {
10387            final String parsedManifest = pkg.manifestDigest == null
10388                    ? "null" : pkg.manifestDigest.toString();
10389            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10390        }
10391
10392        // Get rid of all references to package scan path via parser.
10393        pp = null;
10394        String oldCodePath = null;
10395        boolean systemApp = false;
10396        synchronized (mPackages) {
10397            // Check whether the newly-scanned package wants to define an already-defined perm
10398            int N = pkg.permissions.size();
10399            for (int i = N-1; i >= 0; i--) {
10400                PackageParser.Permission perm = pkg.permissions.get(i);
10401                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10402                if (bp != null) {
10403                    // If the defining package is signed with our cert, it's okay.  This
10404                    // also includes the "updating the same package" case, of course.
10405                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10406                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10407                        // If the owning package is the system itself, we log but allow
10408                        // install to proceed; we fail the install on all other permission
10409                        // redefinitions.
10410                        if (!bp.sourcePackage.equals("android")) {
10411                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10412                                    + pkg.packageName + " attempting to redeclare permission "
10413                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10414                            res.origPermission = perm.info.name;
10415                            res.origPackage = bp.sourcePackage;
10416                            return;
10417                        } else {
10418                            Slog.w(TAG, "Package " + pkg.packageName
10419                                    + " attempting to redeclare system permission "
10420                                    + perm.info.name + "; ignoring new declaration");
10421                            pkg.permissions.remove(i);
10422                        }
10423                    }
10424                }
10425            }
10426
10427            // Check if installing already existing package
10428            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10429                String oldName = mSettings.mRenamedPackages.get(pkgName);
10430                if (pkg.mOriginalPackages != null
10431                        && pkg.mOriginalPackages.contains(oldName)
10432                        && mPackages.containsKey(oldName)) {
10433                    // This package is derived from an original package,
10434                    // and this device has been updating from that original
10435                    // name.  We must continue using the original name, so
10436                    // rename the new package here.
10437                    pkg.setPackageName(oldName);
10438                    pkgName = pkg.packageName;
10439                    replace = true;
10440                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10441                            + oldName + " pkgName=" + pkgName);
10442                } else if (mPackages.containsKey(pkgName)) {
10443                    // This package, under its official name, already exists
10444                    // on the device; we should replace it.
10445                    replace = true;
10446                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10447                }
10448            }
10449            PackageSetting ps = mSettings.mPackages.get(pkgName);
10450            if (ps != null) {
10451                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10452                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10453                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10454                    systemApp = (ps.pkg.applicationInfo.flags &
10455                            ApplicationInfo.FLAG_SYSTEM) != 0;
10456                }
10457                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10458            }
10459        }
10460
10461        if (systemApp && onSd) {
10462            // Disable updates to system apps on sdcard
10463            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10464                    "Cannot install updates to system apps on sdcard");
10465            return;
10466        }
10467
10468        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10469            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10470            return;
10471        }
10472
10473        if (replace) {
10474            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10475                    installerPackageName, res);
10476        } else {
10477            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10478                    installerPackageName, res);
10479        }
10480        synchronized (mPackages) {
10481            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10482            if (ps != null) {
10483                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10484            }
10485        }
10486    }
10487
10488    private static boolean isForwardLocked(PackageParser.Package pkg) {
10489        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10490    }
10491
10492    private static boolean isForwardLocked(ApplicationInfo info) {
10493        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10494    }
10495
10496    private boolean isForwardLocked(PackageSetting ps) {
10497        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10498    }
10499
10500    private static boolean isMultiArch(PackageSetting ps) {
10501        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10502    }
10503
10504    private static boolean isMultiArch(ApplicationInfo info) {
10505        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10506    }
10507
10508    private static boolean isExternal(PackageParser.Package pkg) {
10509        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10510    }
10511
10512    private static boolean isExternal(PackageSetting ps) {
10513        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10514    }
10515
10516    private static boolean isExternal(ApplicationInfo info) {
10517        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10518    }
10519
10520    private static boolean isSystemApp(PackageParser.Package pkg) {
10521        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10522    }
10523
10524    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10525        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10526    }
10527
10528    private static boolean isSystemApp(ApplicationInfo info) {
10529        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10530    }
10531
10532    private static boolean isSystemApp(PackageSetting ps) {
10533        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10534    }
10535
10536    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10537        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10538    }
10539
10540    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10541        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10542    }
10543
10544    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10545        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10546    }
10547
10548    private int packageFlagsToInstallFlags(PackageSetting ps) {
10549        int installFlags = 0;
10550        if (isExternal(ps)) {
10551            installFlags |= PackageManager.INSTALL_EXTERNAL;
10552        }
10553        if (isForwardLocked(ps)) {
10554            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10555        }
10556        return installFlags;
10557    }
10558
10559    private void deleteTempPackageFiles() {
10560        final FilenameFilter filter = new FilenameFilter() {
10561            public boolean accept(File dir, String name) {
10562                return name.startsWith("vmdl") && name.endsWith(".tmp");
10563            }
10564        };
10565        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10566            file.delete();
10567        }
10568    }
10569
10570    @Override
10571    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10572            int flags) {
10573        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10574                flags);
10575    }
10576
10577    @Override
10578    public void deletePackage(final String packageName,
10579            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10580        mContext.enforceCallingOrSelfPermission(
10581                android.Manifest.permission.DELETE_PACKAGES, null);
10582        final int uid = Binder.getCallingUid();
10583        if (UserHandle.getUserId(uid) != userId) {
10584            mContext.enforceCallingPermission(
10585                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10586                    "deletePackage for user " + userId);
10587        }
10588        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10589            try {
10590                observer.onPackageDeleted(packageName,
10591                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10592            } catch (RemoteException re) {
10593            }
10594            return;
10595        }
10596
10597        boolean uninstallBlocked = false;
10598        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10599            int[] users = sUserManager.getUserIds();
10600            for (int i = 0; i < users.length; ++i) {
10601                if (getBlockUninstallForUser(packageName, users[i])) {
10602                    uninstallBlocked = true;
10603                    break;
10604                }
10605            }
10606        } else {
10607            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10608        }
10609        if (uninstallBlocked) {
10610            try {
10611                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10612                        null);
10613            } catch (RemoteException re) {
10614            }
10615            return;
10616        }
10617
10618        if (DEBUG_REMOVE) {
10619            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10620        }
10621        // Queue up an async operation since the package deletion may take a little while.
10622        mHandler.post(new Runnable() {
10623            public void run() {
10624                mHandler.removeCallbacks(this);
10625                final int returnCode = deletePackageX(packageName, userId, flags);
10626                if (observer != null) {
10627                    try {
10628                        observer.onPackageDeleted(packageName, returnCode, null);
10629                    } catch (RemoteException e) {
10630                        Log.i(TAG, "Observer no longer exists.");
10631                    } //end catch
10632                } //end if
10633            } //end run
10634        });
10635    }
10636
10637    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10638        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10639                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10640        try {
10641            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10642                    || dpm.isDeviceOwner(packageName))) {
10643                return true;
10644            }
10645        } catch (RemoteException e) {
10646        }
10647        return false;
10648    }
10649
10650    /**
10651     *  This method is an internal method that could be get invoked either
10652     *  to delete an installed package or to clean up a failed installation.
10653     *  After deleting an installed package, a broadcast is sent to notify any
10654     *  listeners that the package has been installed. For cleaning up a failed
10655     *  installation, the broadcast is not necessary since the package's
10656     *  installation wouldn't have sent the initial broadcast either
10657     *  The key steps in deleting a package are
10658     *  deleting the package information in internal structures like mPackages,
10659     *  deleting the packages base directories through installd
10660     *  updating mSettings to reflect current status
10661     *  persisting settings for later use
10662     *  sending a broadcast if necessary
10663     */
10664    private int deletePackageX(String packageName, int userId, int flags) {
10665        final PackageRemovedInfo info = new PackageRemovedInfo();
10666        final boolean res;
10667
10668        if (isPackageDeviceAdmin(packageName, userId)) {
10669            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10670            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10671        }
10672
10673        boolean removedForAllUsers = false;
10674        boolean systemUpdate = false;
10675
10676        // for the uninstall-updates case and restricted profiles, remember the per-
10677        // userhandle installed state
10678        int[] allUsers;
10679        boolean[] perUserInstalled;
10680        synchronized (mPackages) {
10681            PackageSetting ps = mSettings.mPackages.get(packageName);
10682            allUsers = sUserManager.getUserIds();
10683            perUserInstalled = new boolean[allUsers.length];
10684            for (int i = 0; i < allUsers.length; i++) {
10685                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10686            }
10687        }
10688
10689        synchronized (mInstallLock) {
10690            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10691            res = deletePackageLI(packageName,
10692                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10693                            ? UserHandle.ALL : new UserHandle(userId),
10694                    true, allUsers, perUserInstalled,
10695                    flags | REMOVE_CHATTY, info, true);
10696            systemUpdate = info.isRemovedPackageSystemUpdate;
10697            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10698                removedForAllUsers = true;
10699            }
10700            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10701                    + " removedForAllUsers=" + removedForAllUsers);
10702        }
10703
10704        if (res) {
10705            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10706
10707            // If the removed package was a system update, the old system package
10708            // was re-enabled; we need to broadcast this information
10709            if (systemUpdate) {
10710                Bundle extras = new Bundle(1);
10711                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10712                        ? info.removedAppId : info.uid);
10713                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10714
10715                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10716                        extras, null, null, null);
10717                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10718                        extras, null, null, null);
10719                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10720                        null, packageName, null, null);
10721            }
10722        }
10723        // Force a gc here.
10724        Runtime.getRuntime().gc();
10725        // Delete the resources here after sending the broadcast to let
10726        // other processes clean up before deleting resources.
10727        if (info.args != null) {
10728            synchronized (mInstallLock) {
10729                info.args.doPostDeleteLI(true);
10730            }
10731        }
10732
10733        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10734    }
10735
10736    static class PackageRemovedInfo {
10737        String removedPackage;
10738        int uid = -1;
10739        int removedAppId = -1;
10740        int[] removedUsers = null;
10741        boolean isRemovedPackageSystemUpdate = false;
10742        // Clean up resources deleted packages.
10743        InstallArgs args = null;
10744
10745        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10746            Bundle extras = new Bundle(1);
10747            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10748            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10749            if (replacing) {
10750                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10751            }
10752            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10753            if (removedPackage != null) {
10754                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10755                        extras, null, null, removedUsers);
10756                if (fullRemove && !replacing) {
10757                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10758                            extras, null, null, removedUsers);
10759                }
10760            }
10761            if (removedAppId >= 0) {
10762                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10763                        removedUsers);
10764            }
10765        }
10766    }
10767
10768    /*
10769     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10770     * flag is not set, the data directory is removed as well.
10771     * make sure this flag is set for partially installed apps. If not its meaningless to
10772     * delete a partially installed application.
10773     */
10774    private void removePackageDataLI(PackageSetting ps,
10775            int[] allUserHandles, boolean[] perUserInstalled,
10776            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10777        String packageName = ps.name;
10778        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10779        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10780        // Retrieve object to delete permissions for shared user later on
10781        final PackageSetting deletedPs;
10782        // reader
10783        synchronized (mPackages) {
10784            deletedPs = mSettings.mPackages.get(packageName);
10785            if (outInfo != null) {
10786                outInfo.removedPackage = packageName;
10787                outInfo.removedUsers = deletedPs != null
10788                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10789                        : null;
10790            }
10791        }
10792        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10793            removeDataDirsLI(packageName);
10794            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10795        }
10796        // writer
10797        synchronized (mPackages) {
10798            if (deletedPs != null) {
10799                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10800                    if (outInfo != null) {
10801                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10802                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10803                    }
10804                    if (deletedPs != null) {
10805                        updatePermissionsLPw(deletedPs.name, null, 0);
10806                        if (deletedPs.sharedUser != null) {
10807                            // remove permissions associated with package
10808                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10809                        }
10810                    }
10811                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10812                }
10813                // make sure to preserve per-user disabled state if this removal was just
10814                // a downgrade of a system app to the factory package
10815                if (allUserHandles != null && perUserInstalled != null) {
10816                    if (DEBUG_REMOVE) {
10817                        Slog.d(TAG, "Propagating install state across downgrade");
10818                    }
10819                    for (int i = 0; i < allUserHandles.length; i++) {
10820                        if (DEBUG_REMOVE) {
10821                            Slog.d(TAG, "    user " + allUserHandles[i]
10822                                    + " => " + perUserInstalled[i]);
10823                        }
10824                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10825                    }
10826                }
10827            }
10828            // can downgrade to reader
10829            if (writeSettings) {
10830                // Save settings now
10831                mSettings.writeLPr();
10832            }
10833        }
10834        if (outInfo != null) {
10835            // A user ID was deleted here. Go through all users and remove it
10836            // from KeyStore.
10837            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10838        }
10839    }
10840
10841    static boolean locationIsPrivileged(File path) {
10842        try {
10843            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10844                    .getCanonicalPath();
10845            return path.getCanonicalPath().startsWith(privilegedAppDir);
10846        } catch (IOException e) {
10847            Slog.e(TAG, "Unable to access code path " + path);
10848        }
10849        return false;
10850    }
10851
10852    /*
10853     * Tries to delete system package.
10854     */
10855    private boolean deleteSystemPackageLI(PackageSetting newPs,
10856            int[] allUserHandles, boolean[] perUserInstalled,
10857            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10858        final boolean applyUserRestrictions
10859                = (allUserHandles != null) && (perUserInstalled != null);
10860        PackageSetting disabledPs = null;
10861        // Confirm if the system package has been updated
10862        // An updated system app can be deleted. This will also have to restore
10863        // the system pkg from system partition
10864        // reader
10865        synchronized (mPackages) {
10866            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10867        }
10868        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10869                + " disabledPs=" + disabledPs);
10870        if (disabledPs == null) {
10871            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10872            return false;
10873        } else if (DEBUG_REMOVE) {
10874            Slog.d(TAG, "Deleting system pkg from data partition");
10875        }
10876        if (DEBUG_REMOVE) {
10877            if (applyUserRestrictions) {
10878                Slog.d(TAG, "Remembering install states:");
10879                for (int i = 0; i < allUserHandles.length; i++) {
10880                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10881                }
10882            }
10883        }
10884        // Delete the updated package
10885        outInfo.isRemovedPackageSystemUpdate = true;
10886        if (disabledPs.versionCode < newPs.versionCode) {
10887            // Delete data for downgrades
10888            flags &= ~PackageManager.DELETE_KEEP_DATA;
10889        } else {
10890            // Preserve data by setting flag
10891            flags |= PackageManager.DELETE_KEEP_DATA;
10892        }
10893        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10894                allUserHandles, perUserInstalled, outInfo, writeSettings);
10895        if (!ret) {
10896            return false;
10897        }
10898        // writer
10899        synchronized (mPackages) {
10900            // Reinstate the old system package
10901            mSettings.enableSystemPackageLPw(newPs.name);
10902            // Remove any native libraries from the upgraded package.
10903            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10904        }
10905        // Install the system package
10906        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10907        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10908        if (locationIsPrivileged(disabledPs.codePath)) {
10909            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10910        }
10911
10912        final PackageParser.Package newPkg;
10913        try {
10914            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10915        } catch (PackageManagerException e) {
10916            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10917            return false;
10918        }
10919
10920        // writer
10921        synchronized (mPackages) {
10922            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10923            updatePermissionsLPw(newPkg.packageName, newPkg,
10924                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10925            if (applyUserRestrictions) {
10926                if (DEBUG_REMOVE) {
10927                    Slog.d(TAG, "Propagating install state across reinstall");
10928                }
10929                for (int i = 0; i < allUserHandles.length; i++) {
10930                    if (DEBUG_REMOVE) {
10931                        Slog.d(TAG, "    user " + allUserHandles[i]
10932                                + " => " + perUserInstalled[i]);
10933                    }
10934                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10935                }
10936                // Regardless of writeSettings we need to ensure that this restriction
10937                // state propagation is persisted
10938                mSettings.writeAllUsersPackageRestrictionsLPr();
10939            }
10940            // can downgrade to reader here
10941            if (writeSettings) {
10942                mSettings.writeLPr();
10943            }
10944        }
10945        return true;
10946    }
10947
10948    private boolean deleteInstalledPackageLI(PackageSetting ps,
10949            boolean deleteCodeAndResources, int flags,
10950            int[] allUserHandles, boolean[] perUserInstalled,
10951            PackageRemovedInfo outInfo, boolean writeSettings) {
10952        if (outInfo != null) {
10953            outInfo.uid = ps.appId;
10954        }
10955
10956        // Delete package data from internal structures and also remove data if flag is set
10957        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10958
10959        // Delete application code and resources
10960        if (deleteCodeAndResources && (outInfo != null)) {
10961            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10962                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10963                    getAppDexInstructionSets(ps), isMultiArch(ps));
10964        }
10965        return true;
10966    }
10967
10968    @Override
10969    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10970            int userId) {
10971        mContext.enforceCallingOrSelfPermission(
10972                android.Manifest.permission.DELETE_PACKAGES, null);
10973        synchronized (mPackages) {
10974            PackageSetting ps = mSettings.mPackages.get(packageName);
10975            if (ps == null) {
10976                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10977                return false;
10978            }
10979            if (!ps.getInstalled(userId)) {
10980                // Can't block uninstall for an app that is not installed or enabled.
10981                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10982                return false;
10983            }
10984            ps.setBlockUninstall(blockUninstall, userId);
10985            mSettings.writePackageRestrictionsLPr(userId);
10986        }
10987        return true;
10988    }
10989
10990    @Override
10991    public boolean getBlockUninstallForUser(String packageName, int userId) {
10992        synchronized (mPackages) {
10993            PackageSetting ps = mSettings.mPackages.get(packageName);
10994            if (ps == null) {
10995                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10996                return false;
10997            }
10998            return ps.getBlockUninstall(userId);
10999        }
11000    }
11001
11002    /*
11003     * This method handles package deletion in general
11004     */
11005    private boolean deletePackageLI(String packageName, UserHandle user,
11006            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11007            int flags, PackageRemovedInfo outInfo,
11008            boolean writeSettings) {
11009        if (packageName == null) {
11010            Slog.w(TAG, "Attempt to delete null packageName.");
11011            return false;
11012        }
11013        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11014        PackageSetting ps;
11015        boolean dataOnly = false;
11016        int removeUser = -1;
11017        int appId = -1;
11018        synchronized (mPackages) {
11019            ps = mSettings.mPackages.get(packageName);
11020            if (ps == null) {
11021                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11022                return false;
11023            }
11024            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11025                    && user.getIdentifier() != UserHandle.USER_ALL) {
11026                // The caller is asking that the package only be deleted for a single
11027                // user.  To do this, we just mark its uninstalled state and delete
11028                // its data.  If this is a system app, we only allow this to happen if
11029                // they have set the special DELETE_SYSTEM_APP which requests different
11030                // semantics than normal for uninstalling system apps.
11031                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11032                ps.setUserState(user.getIdentifier(),
11033                        COMPONENT_ENABLED_STATE_DEFAULT,
11034                        false, //installed
11035                        true,  //stopped
11036                        true,  //notLaunched
11037                        false, //hidden
11038                        null, null, null,
11039                        false // blockUninstall
11040                        );
11041                if (!isSystemApp(ps)) {
11042                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11043                        // Other user still have this package installed, so all
11044                        // we need to do is clear this user's data and save that
11045                        // it is uninstalled.
11046                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11047                        removeUser = user.getIdentifier();
11048                        appId = ps.appId;
11049                        mSettings.writePackageRestrictionsLPr(removeUser);
11050                    } else {
11051                        // We need to set it back to 'installed' so the uninstall
11052                        // broadcasts will be sent correctly.
11053                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11054                        ps.setInstalled(true, user.getIdentifier());
11055                    }
11056                } else {
11057                    // This is a system app, so we assume that the
11058                    // other users still have this package installed, so all
11059                    // we need to do is clear this user's data and save that
11060                    // it is uninstalled.
11061                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11062                    removeUser = user.getIdentifier();
11063                    appId = ps.appId;
11064                    mSettings.writePackageRestrictionsLPr(removeUser);
11065                }
11066            }
11067        }
11068
11069        if (removeUser >= 0) {
11070            // From above, we determined that we are deleting this only
11071            // for a single user.  Continue the work here.
11072            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11073            if (outInfo != null) {
11074                outInfo.removedPackage = packageName;
11075                outInfo.removedAppId = appId;
11076                outInfo.removedUsers = new int[] {removeUser};
11077            }
11078            mInstaller.clearUserData(packageName, removeUser);
11079            removeKeystoreDataIfNeeded(removeUser, appId);
11080            schedulePackageCleaning(packageName, removeUser, false);
11081            return true;
11082        }
11083
11084        if (dataOnly) {
11085            // Delete application data first
11086            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11087            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11088            return true;
11089        }
11090
11091        boolean ret = false;
11092        if (isSystemApp(ps)) {
11093            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11094            // When an updated system application is deleted we delete the existing resources as well and
11095            // fall back to existing code in system partition
11096            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11097                    flags, outInfo, writeSettings);
11098        } else {
11099            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11100            // Kill application pre-emptively especially for apps on sd.
11101            killApplication(packageName, ps.appId, "uninstall pkg");
11102            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11103                    allUserHandles, perUserInstalled,
11104                    outInfo, writeSettings);
11105        }
11106
11107        return ret;
11108    }
11109
11110    private final class ClearStorageConnection implements ServiceConnection {
11111        IMediaContainerService mContainerService;
11112
11113        @Override
11114        public void onServiceConnected(ComponentName name, IBinder service) {
11115            synchronized (this) {
11116                mContainerService = IMediaContainerService.Stub.asInterface(service);
11117                notifyAll();
11118            }
11119        }
11120
11121        @Override
11122        public void onServiceDisconnected(ComponentName name) {
11123        }
11124    }
11125
11126    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11127        final boolean mounted;
11128        if (Environment.isExternalStorageEmulated()) {
11129            mounted = true;
11130        } else {
11131            final String status = Environment.getExternalStorageState();
11132
11133            mounted = status.equals(Environment.MEDIA_MOUNTED)
11134                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11135        }
11136
11137        if (!mounted) {
11138            return;
11139        }
11140
11141        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11142        int[] users;
11143        if (userId == UserHandle.USER_ALL) {
11144            users = sUserManager.getUserIds();
11145        } else {
11146            users = new int[] { userId };
11147        }
11148        final ClearStorageConnection conn = new ClearStorageConnection();
11149        if (mContext.bindServiceAsUser(
11150                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11151            try {
11152                for (int curUser : users) {
11153                    long timeout = SystemClock.uptimeMillis() + 5000;
11154                    synchronized (conn) {
11155                        long now = SystemClock.uptimeMillis();
11156                        while (conn.mContainerService == null && now < timeout) {
11157                            try {
11158                                conn.wait(timeout - now);
11159                            } catch (InterruptedException e) {
11160                            }
11161                        }
11162                    }
11163                    if (conn.mContainerService == null) {
11164                        return;
11165                    }
11166
11167                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11168                    clearDirectory(conn.mContainerService,
11169                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11170                    if (allData) {
11171                        clearDirectory(conn.mContainerService,
11172                                userEnv.buildExternalStorageAppDataDirs(packageName));
11173                        clearDirectory(conn.mContainerService,
11174                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11175                    }
11176                }
11177            } finally {
11178                mContext.unbindService(conn);
11179            }
11180        }
11181    }
11182
11183    @Override
11184    public void clearApplicationUserData(final String packageName,
11185            final IPackageDataObserver observer, final int userId) {
11186        mContext.enforceCallingOrSelfPermission(
11187                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11188        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11189        // Queue up an async operation since the package deletion may take a little while.
11190        mHandler.post(new Runnable() {
11191            public void run() {
11192                mHandler.removeCallbacks(this);
11193                final boolean succeeded;
11194                synchronized (mInstallLock) {
11195                    succeeded = clearApplicationUserDataLI(packageName, userId);
11196                }
11197                clearExternalStorageDataSync(packageName, userId, true);
11198                if (succeeded) {
11199                    // invoke DeviceStorageMonitor's update method to clear any notifications
11200                    DeviceStorageMonitorInternal
11201                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11202                    if (dsm != null) {
11203                        dsm.checkMemory();
11204                    }
11205                }
11206                if(observer != null) {
11207                    try {
11208                        observer.onRemoveCompleted(packageName, succeeded);
11209                    } catch (RemoteException e) {
11210                        Log.i(TAG, "Observer no longer exists.");
11211                    }
11212                } //end if observer
11213            } //end run
11214        });
11215    }
11216
11217    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11218        if (packageName == null) {
11219            Slog.w(TAG, "Attempt to delete null packageName.");
11220            return false;
11221        }
11222        PackageParser.Package p;
11223        boolean dataOnly = false;
11224        final int appId;
11225        synchronized (mPackages) {
11226            p = mPackages.get(packageName);
11227            if (p == null) {
11228                dataOnly = true;
11229                PackageSetting ps = mSettings.mPackages.get(packageName);
11230                if ((ps == null) || (ps.pkg == null)) {
11231                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11232                    return false;
11233                }
11234                p = ps.pkg;
11235            }
11236            if (!dataOnly) {
11237                // need to check this only for fully installed applications
11238                if (p == null) {
11239                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11240                    return false;
11241                }
11242                final ApplicationInfo applicationInfo = p.applicationInfo;
11243                if (applicationInfo == null) {
11244                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11245                    return false;
11246                }
11247            }
11248            if (p != null && p.applicationInfo != null) {
11249                appId = p.applicationInfo.uid;
11250            } else {
11251                appId = -1;
11252            }
11253        }
11254        int retCode = mInstaller.clearUserData(packageName, userId);
11255        if (retCode < 0) {
11256            Slog.w(TAG, "Couldn't remove cache files for package: "
11257                    + packageName);
11258            return false;
11259        }
11260        removeKeystoreDataIfNeeded(userId, appId);
11261        return true;
11262    }
11263
11264    /**
11265     * Remove entries from the keystore daemon. Will only remove it if the
11266     * {@code appId} is valid.
11267     */
11268    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11269        if (appId < 0) {
11270            return;
11271        }
11272
11273        final KeyStore keyStore = KeyStore.getInstance();
11274        if (keyStore != null) {
11275            if (userId == UserHandle.USER_ALL) {
11276                for (final int individual : sUserManager.getUserIds()) {
11277                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11278                }
11279            } else {
11280                keyStore.clearUid(UserHandle.getUid(userId, appId));
11281            }
11282        } else {
11283            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11284        }
11285    }
11286
11287    @Override
11288    public void deleteApplicationCacheFiles(final String packageName,
11289            final IPackageDataObserver observer) {
11290        mContext.enforceCallingOrSelfPermission(
11291                android.Manifest.permission.DELETE_CACHE_FILES, null);
11292        // Queue up an async operation since the package deletion may take a little while.
11293        final int userId = UserHandle.getCallingUserId();
11294        mHandler.post(new Runnable() {
11295            public void run() {
11296                mHandler.removeCallbacks(this);
11297                final boolean succeded;
11298                synchronized (mInstallLock) {
11299                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11300                }
11301                clearExternalStorageDataSync(packageName, userId, false);
11302                if(observer != null) {
11303                    try {
11304                        observer.onRemoveCompleted(packageName, succeded);
11305                    } catch (RemoteException e) {
11306                        Log.i(TAG, "Observer no longer exists.");
11307                    }
11308                } //end if observer
11309            } //end run
11310        });
11311    }
11312
11313    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11314        if (packageName == null) {
11315            Slog.w(TAG, "Attempt to delete null packageName.");
11316            return false;
11317        }
11318        PackageParser.Package p;
11319        synchronized (mPackages) {
11320            p = mPackages.get(packageName);
11321        }
11322        if (p == null) {
11323            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11324            return false;
11325        }
11326        final ApplicationInfo applicationInfo = p.applicationInfo;
11327        if (applicationInfo == null) {
11328            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11329            return false;
11330        }
11331        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11332        if (retCode < 0) {
11333            Slog.w(TAG, "Couldn't remove cache files for package: "
11334                       + packageName + " u" + userId);
11335            return false;
11336        }
11337        return true;
11338    }
11339
11340    @Override
11341    public void getPackageSizeInfo(final String packageName, int userHandle,
11342            final IPackageStatsObserver observer) {
11343        mContext.enforceCallingOrSelfPermission(
11344                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11345        if (packageName == null) {
11346            throw new IllegalArgumentException("Attempt to get size of null packageName");
11347        }
11348
11349        PackageStats stats = new PackageStats(packageName, userHandle);
11350
11351        /*
11352         * Queue up an async operation since the package measurement may take a
11353         * little while.
11354         */
11355        Message msg = mHandler.obtainMessage(INIT_COPY);
11356        msg.obj = new MeasureParams(stats, observer);
11357        mHandler.sendMessage(msg);
11358    }
11359
11360    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11361            PackageStats pStats) {
11362        if (packageName == null) {
11363            Slog.w(TAG, "Attempt to get size of null packageName.");
11364            return false;
11365        }
11366        PackageParser.Package p;
11367        boolean dataOnly = false;
11368        String libDirRoot = null;
11369        String asecPath = null;
11370        PackageSetting ps = null;
11371        synchronized (mPackages) {
11372            p = mPackages.get(packageName);
11373            ps = mSettings.mPackages.get(packageName);
11374            if(p == null) {
11375                dataOnly = true;
11376                if((ps == null) || (ps.pkg == null)) {
11377                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11378                    return false;
11379                }
11380                p = ps.pkg;
11381            }
11382            if (ps != null) {
11383                libDirRoot = ps.legacyNativeLibraryPathString;
11384            }
11385            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11386                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11387                if (secureContainerId != null) {
11388                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11389                }
11390            }
11391        }
11392        String publicSrcDir = null;
11393        if(!dataOnly) {
11394            final ApplicationInfo applicationInfo = p.applicationInfo;
11395            if (applicationInfo == null) {
11396                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11397                return false;
11398            }
11399            if (isForwardLocked(p)) {
11400                publicSrcDir = applicationInfo.getBaseResourcePath();
11401            }
11402        }
11403        // TODO: extend to measure size of split APKs
11404        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11405        // not just the first level.
11406        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11407        // just the primary.
11408        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11409        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11410                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11411        if (res < 0) {
11412            return false;
11413        }
11414
11415        // Fix-up for forward-locked applications in ASEC containers.
11416        if (!isExternal(p)) {
11417            pStats.codeSize += pStats.externalCodeSize;
11418            pStats.externalCodeSize = 0L;
11419        }
11420
11421        return true;
11422    }
11423
11424
11425    @Override
11426    public void addPackageToPreferred(String packageName) {
11427        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11428    }
11429
11430    @Override
11431    public void removePackageFromPreferred(String packageName) {
11432        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11433    }
11434
11435    @Override
11436    public List<PackageInfo> getPreferredPackages(int flags) {
11437        return new ArrayList<PackageInfo>();
11438    }
11439
11440    private int getUidTargetSdkVersionLockedLPr(int uid) {
11441        Object obj = mSettings.getUserIdLPr(uid);
11442        if (obj instanceof SharedUserSetting) {
11443            final SharedUserSetting sus = (SharedUserSetting) obj;
11444            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11445            final Iterator<PackageSetting> it = sus.packages.iterator();
11446            while (it.hasNext()) {
11447                final PackageSetting ps = it.next();
11448                if (ps.pkg != null) {
11449                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11450                    if (v < vers) vers = v;
11451                }
11452            }
11453            return vers;
11454        } else if (obj instanceof PackageSetting) {
11455            final PackageSetting ps = (PackageSetting) obj;
11456            if (ps.pkg != null) {
11457                return ps.pkg.applicationInfo.targetSdkVersion;
11458            }
11459        }
11460        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11461    }
11462
11463    @Override
11464    public void addPreferredActivity(IntentFilter filter, int match,
11465            ComponentName[] set, ComponentName activity, int userId) {
11466        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11467    }
11468
11469    private void addPreferredActivityInternal(IntentFilter filter, int match,
11470            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11471        // writer
11472        int callingUid = Binder.getCallingUid();
11473        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11474        if (filter.countActions() == 0) {
11475            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11476            return;
11477        }
11478        synchronized (mPackages) {
11479            if (mContext.checkCallingOrSelfPermission(
11480                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11481                    != PackageManager.PERMISSION_GRANTED) {
11482                if (getUidTargetSdkVersionLockedLPr(callingUid)
11483                        < Build.VERSION_CODES.FROYO) {
11484                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11485                            + callingUid);
11486                    return;
11487                }
11488                mContext.enforceCallingOrSelfPermission(
11489                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11490            }
11491
11492            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11493            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11494            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11495                    new PreferredActivity(filter, match, set, activity, always));
11496            mSettings.writePackageRestrictionsLPr(userId);
11497        }
11498    }
11499
11500    @Override
11501    public void replacePreferredActivity(IntentFilter filter, int match,
11502            ComponentName[] set, ComponentName activity, int userId) {
11503        if (filter.countActions() != 1) {
11504            throw new IllegalArgumentException(
11505                    "replacePreferredActivity expects filter to have only 1 action.");
11506        }
11507        if (filter.countDataAuthorities() != 0
11508                || filter.countDataPaths() != 0
11509                || filter.countDataSchemes() > 1
11510                || filter.countDataTypes() != 0) {
11511            throw new IllegalArgumentException(
11512                    "replacePreferredActivity expects filter to have no data authorities, " +
11513                    "paths, or types; and at most one scheme.");
11514        }
11515
11516        final int callingUid = Binder.getCallingUid();
11517        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11518        final int callingUserId = UserHandle.getUserId(callingUid);
11519        synchronized (mPackages) {
11520            if (mContext.checkCallingOrSelfPermission(
11521                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11522                    != PackageManager.PERMISSION_GRANTED) {
11523                if (getUidTargetSdkVersionLockedLPr(callingUid)
11524                        < Build.VERSION_CODES.FROYO) {
11525                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11526                            + Binder.getCallingUid());
11527                    return;
11528                }
11529                mContext.enforceCallingOrSelfPermission(
11530                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11531            }
11532
11533            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11534            if (pir != null) {
11535                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11536                if (filter.countDataSchemes() == 1) {
11537                    Uri.Builder builder = new Uri.Builder();
11538                    builder.scheme(filter.getDataScheme(0));
11539                    intent.setData(builder.build());
11540                }
11541                List<PreferredActivity> matches = pir.queryIntent(
11542                        intent, null, true, callingUserId);
11543                if (DEBUG_PREFERRED) {
11544                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11545                }
11546                for (int i = 0; i < matches.size(); i++) {
11547                    PreferredActivity pa = matches.get(i);
11548                    if (DEBUG_PREFERRED) {
11549                        Slog.i(TAG, "Removing preferred activity "
11550                                + pa.mPref.mComponent + ":");
11551                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11552                    }
11553                    pir.removeFilter(pa);
11554                }
11555            }
11556            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11557        }
11558    }
11559
11560    @Override
11561    public void clearPackagePreferredActivities(String packageName) {
11562        final int uid = Binder.getCallingUid();
11563        // writer
11564        synchronized (mPackages) {
11565            PackageParser.Package pkg = mPackages.get(packageName);
11566            if (pkg == null || pkg.applicationInfo.uid != uid) {
11567                if (mContext.checkCallingOrSelfPermission(
11568                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11569                        != PackageManager.PERMISSION_GRANTED) {
11570                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11571                            < Build.VERSION_CODES.FROYO) {
11572                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11573                                + Binder.getCallingUid());
11574                        return;
11575                    }
11576                    mContext.enforceCallingOrSelfPermission(
11577                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11578                }
11579            }
11580
11581            int user = UserHandle.getCallingUserId();
11582            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11583                mSettings.writePackageRestrictionsLPr(user);
11584                scheduleWriteSettingsLocked();
11585            }
11586        }
11587    }
11588
11589    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11590    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11591        ArrayList<PreferredActivity> removed = null;
11592        boolean changed = false;
11593        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11594            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11595            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11596            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11597                continue;
11598            }
11599            Iterator<PreferredActivity> it = pir.filterIterator();
11600            while (it.hasNext()) {
11601                PreferredActivity pa = it.next();
11602                // Mark entry for removal only if it matches the package name
11603                // and the entry is of type "always".
11604                if (packageName == null ||
11605                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11606                                && pa.mPref.mAlways)) {
11607                    if (removed == null) {
11608                        removed = new ArrayList<PreferredActivity>();
11609                    }
11610                    removed.add(pa);
11611                }
11612            }
11613            if (removed != null) {
11614                for (int j=0; j<removed.size(); j++) {
11615                    PreferredActivity pa = removed.get(j);
11616                    pir.removeFilter(pa);
11617                }
11618                changed = true;
11619            }
11620        }
11621        return changed;
11622    }
11623
11624    @Override
11625    public void resetPreferredActivities(int userId) {
11626        mContext.enforceCallingOrSelfPermission(
11627                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11628        // writer
11629        synchronized (mPackages) {
11630            int user = UserHandle.getCallingUserId();
11631            clearPackagePreferredActivitiesLPw(null, user);
11632            mSettings.readDefaultPreferredAppsLPw(this, user);
11633            mSettings.writePackageRestrictionsLPr(user);
11634            scheduleWriteSettingsLocked();
11635        }
11636    }
11637
11638    @Override
11639    public int getPreferredActivities(List<IntentFilter> outFilters,
11640            List<ComponentName> outActivities, String packageName) {
11641
11642        int num = 0;
11643        final int userId = UserHandle.getCallingUserId();
11644        // reader
11645        synchronized (mPackages) {
11646            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11647            if (pir != null) {
11648                final Iterator<PreferredActivity> it = pir.filterIterator();
11649                while (it.hasNext()) {
11650                    final PreferredActivity pa = it.next();
11651                    if (packageName == null
11652                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11653                                    && pa.mPref.mAlways)) {
11654                        if (outFilters != null) {
11655                            outFilters.add(new IntentFilter(pa));
11656                        }
11657                        if (outActivities != null) {
11658                            outActivities.add(pa.mPref.mComponent);
11659                        }
11660                    }
11661                }
11662            }
11663        }
11664
11665        return num;
11666    }
11667
11668    @Override
11669    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11670            int userId) {
11671        int callingUid = Binder.getCallingUid();
11672        if (callingUid != Process.SYSTEM_UID) {
11673            throw new SecurityException(
11674                    "addPersistentPreferredActivity can only be run by the system");
11675        }
11676        if (filter.countActions() == 0) {
11677            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11678            return;
11679        }
11680        synchronized (mPackages) {
11681            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11682                    " :");
11683            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11684            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11685                    new PersistentPreferredActivity(filter, activity));
11686            mSettings.writePackageRestrictionsLPr(userId);
11687        }
11688    }
11689
11690    @Override
11691    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11692        int callingUid = Binder.getCallingUid();
11693        if (callingUid != Process.SYSTEM_UID) {
11694            throw new SecurityException(
11695                    "clearPackagePersistentPreferredActivities can only be run by the system");
11696        }
11697        ArrayList<PersistentPreferredActivity> removed = null;
11698        boolean changed = false;
11699        synchronized (mPackages) {
11700            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11701                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11702                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11703                        .valueAt(i);
11704                if (userId != thisUserId) {
11705                    continue;
11706                }
11707                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11708                while (it.hasNext()) {
11709                    PersistentPreferredActivity ppa = it.next();
11710                    // Mark entry for removal only if it matches the package name.
11711                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11712                        if (removed == null) {
11713                            removed = new ArrayList<PersistentPreferredActivity>();
11714                        }
11715                        removed.add(ppa);
11716                    }
11717                }
11718                if (removed != null) {
11719                    for (int j=0; j<removed.size(); j++) {
11720                        PersistentPreferredActivity ppa = removed.get(j);
11721                        ppir.removeFilter(ppa);
11722                    }
11723                    changed = true;
11724                }
11725            }
11726
11727            if (changed) {
11728                mSettings.writePackageRestrictionsLPr(userId);
11729            }
11730        }
11731    }
11732
11733    @Override
11734    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11735            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11736        mContext.enforceCallingOrSelfPermission(
11737                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11738        int callingUid = Binder.getCallingUid();
11739        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11740        if (intentFilter.countActions() == 0) {
11741            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11742            return;
11743        }
11744        synchronized (mPackages) {
11745            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11746                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11747            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11748            mSettings.writePackageRestrictionsLPr(sourceUserId);
11749        }
11750    }
11751
11752    @Override
11753    public void addCrossProfileIntentsForPackage(String packageName,
11754            int sourceUserId, int targetUserId) {
11755        mContext.enforceCallingOrSelfPermission(
11756                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11757        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11758        mSettings.writePackageRestrictionsLPr(sourceUserId);
11759    }
11760
11761    @Override
11762    public void removeCrossProfileIntentsForPackage(String packageName,
11763            int sourceUserId, int targetUserId) {
11764        mContext.enforceCallingOrSelfPermission(
11765                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11766        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11767        mSettings.writePackageRestrictionsLPr(sourceUserId);
11768    }
11769
11770    @Override
11771    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11772            int ownerUserId) {
11773        mContext.enforceCallingOrSelfPermission(
11774                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11775        int callingUid = Binder.getCallingUid();
11776        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11777        int callingUserId = UserHandle.getUserId(callingUid);
11778        synchronized (mPackages) {
11779            CrossProfileIntentResolver resolver =
11780                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11781            HashSet<CrossProfileIntentFilter> set =
11782                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11783            for (CrossProfileIntentFilter filter : set) {
11784                if (filter.getOwnerPackage().equals(ownerPackage)
11785                        && filter.getOwnerUserId() == callingUserId) {
11786                    resolver.removeFilter(filter);
11787                }
11788            }
11789            mSettings.writePackageRestrictionsLPr(sourceUserId);
11790        }
11791    }
11792
11793    // Enforcing that callingUid is owning pkg on userId
11794    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11795        // The system owns everything.
11796        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11797            return;
11798        }
11799        int callingUserId = UserHandle.getUserId(callingUid);
11800        if (callingUserId != userId) {
11801            throw new SecurityException("calling uid " + callingUid
11802                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11803                    + callingUserId);
11804        }
11805        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11806        if (pi == null) {
11807            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11808                    + callingUserId);
11809        }
11810        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11811            throw new SecurityException("Calling uid " + callingUid
11812                    + " does not own package " + pkg);
11813        }
11814    }
11815
11816    @Override
11817    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11818        Intent intent = new Intent(Intent.ACTION_MAIN);
11819        intent.addCategory(Intent.CATEGORY_HOME);
11820
11821        final int callingUserId = UserHandle.getCallingUserId();
11822        List<ResolveInfo> list = queryIntentActivities(intent, null,
11823                PackageManager.GET_META_DATA, callingUserId);
11824        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11825                true, false, false, callingUserId);
11826
11827        allHomeCandidates.clear();
11828        if (list != null) {
11829            for (ResolveInfo ri : list) {
11830                allHomeCandidates.add(ri);
11831            }
11832        }
11833        return (preferred == null || preferred.activityInfo == null)
11834                ? null
11835                : new ComponentName(preferred.activityInfo.packageName,
11836                        preferred.activityInfo.name);
11837    }
11838
11839    /**
11840     * Check if calling UID is the current home app. This handles both the case
11841     * where the user has selected a specific home app, and where there is only
11842     * one home app.
11843     */
11844    public boolean checkCallerIsHomeApp() {
11845        final Intent intent = new Intent(Intent.ACTION_MAIN);
11846        intent.addCategory(Intent.CATEGORY_HOME);
11847
11848        final int callingUid = Binder.getCallingUid();
11849        final int callingUserId = UserHandle.getCallingUserId();
11850        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11851        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11852                false, false, callingUserId);
11853
11854        if (preferredHome != null) {
11855            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11856                return true;
11857            }
11858        } else {
11859            for (ResolveInfo info : allHomes) {
11860                if (callingUid == info.activityInfo.applicationInfo.uid) {
11861                    return true;
11862                }
11863            }
11864        }
11865
11866        return false;
11867    }
11868
11869    /**
11870     * Enforce that calling UID is the current home app. This handles both the
11871     * case where the user has selected a specific home app, and where there is
11872     * only one home app.
11873     */
11874    public void enforceCallerIsHomeApp() {
11875        if (!checkCallerIsHomeApp()) {
11876            throw new SecurityException("Caller is not currently selected home app");
11877        }
11878    }
11879
11880    @Override
11881    public void setApplicationEnabledSetting(String appPackageName,
11882            int newState, int flags, int userId, String callingPackage) {
11883        if (!sUserManager.exists(userId)) return;
11884        if (callingPackage == null) {
11885            callingPackage = Integer.toString(Binder.getCallingUid());
11886        }
11887        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11888    }
11889
11890    @Override
11891    public void setComponentEnabledSetting(ComponentName componentName,
11892            int newState, int flags, int userId) {
11893        if (!sUserManager.exists(userId)) return;
11894        setEnabledSetting(componentName.getPackageName(),
11895                componentName.getClassName(), newState, flags, userId, null);
11896    }
11897
11898    private void setEnabledSetting(final String packageName, String className, int newState,
11899            final int flags, int userId, String callingPackage) {
11900        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11901              || newState == COMPONENT_ENABLED_STATE_ENABLED
11902              || newState == COMPONENT_ENABLED_STATE_DISABLED
11903              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11904              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11905            throw new IllegalArgumentException("Invalid new component state: "
11906                    + newState);
11907        }
11908        PackageSetting pkgSetting;
11909        final int uid = Binder.getCallingUid();
11910        final int permission = mContext.checkCallingOrSelfPermission(
11911                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11912        enforceCrossUserPermission(uid, userId, false, "set enabled");
11913        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11914        boolean sendNow = false;
11915        boolean isApp = (className == null);
11916        String componentName = isApp ? packageName : className;
11917        int packageUid = -1;
11918        ArrayList<String> components;
11919
11920        // writer
11921        synchronized (mPackages) {
11922            pkgSetting = mSettings.mPackages.get(packageName);
11923            if (pkgSetting == null) {
11924                if (className == null) {
11925                    throw new IllegalArgumentException(
11926                            "Unknown package: " + packageName);
11927                }
11928                throw new IllegalArgumentException(
11929                        "Unknown component: " + packageName
11930                        + "/" + className);
11931            }
11932            // Allow root and verify that userId is not being specified by a different user
11933            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11934                throw new SecurityException(
11935                        "Permission Denial: attempt to change component state from pid="
11936                        + Binder.getCallingPid()
11937                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11938            }
11939            if (className == null) {
11940                // We're dealing with an application/package level state change
11941                if (pkgSetting.getEnabled(userId) == newState) {
11942                    // Nothing to do
11943                    return;
11944                }
11945                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11946                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11947                    // Don't care about who enables an app.
11948                    callingPackage = null;
11949                }
11950                pkgSetting.setEnabled(newState, userId, callingPackage);
11951                // pkgSetting.pkg.mSetEnabled = newState;
11952            } else {
11953                // We're dealing with a component level state change
11954                // First, verify that this is a valid class name.
11955                PackageParser.Package pkg = pkgSetting.pkg;
11956                if (pkg == null || !pkg.hasComponentClassName(className)) {
11957                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11958                        throw new IllegalArgumentException("Component class " + className
11959                                + " does not exist in " + packageName);
11960                    } else {
11961                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11962                                + className + " does not exist in " + packageName);
11963                    }
11964                }
11965                switch (newState) {
11966                case COMPONENT_ENABLED_STATE_ENABLED:
11967                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11968                        return;
11969                    }
11970                    break;
11971                case COMPONENT_ENABLED_STATE_DISABLED:
11972                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11973                        return;
11974                    }
11975                    break;
11976                case COMPONENT_ENABLED_STATE_DEFAULT:
11977                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11978                        return;
11979                    }
11980                    break;
11981                default:
11982                    Slog.e(TAG, "Invalid new component state: " + newState);
11983                    return;
11984                }
11985            }
11986            mSettings.writePackageRestrictionsLPr(userId);
11987            components = mPendingBroadcasts.get(userId, packageName);
11988            final boolean newPackage = components == null;
11989            if (newPackage) {
11990                components = new ArrayList<String>();
11991            }
11992            if (!components.contains(componentName)) {
11993                components.add(componentName);
11994            }
11995            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11996                sendNow = true;
11997                // Purge entry from pending broadcast list if another one exists already
11998                // since we are sending one right away.
11999                mPendingBroadcasts.remove(userId, packageName);
12000            } else {
12001                if (newPackage) {
12002                    mPendingBroadcasts.put(userId, packageName, components);
12003                }
12004                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12005                    // Schedule a message
12006                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12007                }
12008            }
12009        }
12010
12011        long callingId = Binder.clearCallingIdentity();
12012        try {
12013            if (sendNow) {
12014                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12015                sendPackageChangedBroadcast(packageName,
12016                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12017            }
12018        } finally {
12019            Binder.restoreCallingIdentity(callingId);
12020        }
12021    }
12022
12023    private void sendPackageChangedBroadcast(String packageName,
12024            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12025        if (DEBUG_INSTALL)
12026            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12027                    + componentNames);
12028        Bundle extras = new Bundle(4);
12029        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12030        String nameList[] = new String[componentNames.size()];
12031        componentNames.toArray(nameList);
12032        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12033        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12034        extras.putInt(Intent.EXTRA_UID, packageUid);
12035        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12036                new int[] {UserHandle.getUserId(packageUid)});
12037    }
12038
12039    @Override
12040    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12041        if (!sUserManager.exists(userId)) return;
12042        final int uid = Binder.getCallingUid();
12043        final int permission = mContext.checkCallingOrSelfPermission(
12044                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12045        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12046        enforceCrossUserPermission(uid, userId, true, "stop package");
12047        // writer
12048        synchronized (mPackages) {
12049            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12050                    uid, userId)) {
12051                scheduleWritePackageRestrictionsLocked(userId);
12052            }
12053        }
12054    }
12055
12056    @Override
12057    public String getInstallerPackageName(String packageName) {
12058        // reader
12059        synchronized (mPackages) {
12060            return mSettings.getInstallerPackageNameLPr(packageName);
12061        }
12062    }
12063
12064    @Override
12065    public int getApplicationEnabledSetting(String packageName, int userId) {
12066        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12067        int uid = Binder.getCallingUid();
12068        enforceCrossUserPermission(uid, userId, false, "get enabled");
12069        // reader
12070        synchronized (mPackages) {
12071            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12072        }
12073    }
12074
12075    @Override
12076    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12077        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12078        int uid = Binder.getCallingUid();
12079        enforceCrossUserPermission(uid, userId, false, "get component enabled");
12080        // reader
12081        synchronized (mPackages) {
12082            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12083        }
12084    }
12085
12086    @Override
12087    public void enterSafeMode() {
12088        enforceSystemOrRoot("Only the system can request entering safe mode");
12089
12090        if (!mSystemReady) {
12091            mSafeMode = true;
12092        }
12093    }
12094
12095    @Override
12096    public void systemReady() {
12097        mSystemReady = true;
12098
12099        // Read the compatibilty setting when the system is ready.
12100        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12101                mContext.getContentResolver(),
12102                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12103        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12104        if (DEBUG_SETTINGS) {
12105            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12106        }
12107
12108        synchronized (mPackages) {
12109            // Verify that all of the preferred activity components actually
12110            // exist.  It is possible for applications to be updated and at
12111            // that point remove a previously declared activity component that
12112            // had been set as a preferred activity.  We try to clean this up
12113            // the next time we encounter that preferred activity, but it is
12114            // possible for the user flow to never be able to return to that
12115            // situation so here we do a sanity check to make sure we haven't
12116            // left any junk around.
12117            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12118            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12119                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12120                removed.clear();
12121                for (PreferredActivity pa : pir.filterSet()) {
12122                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12123                        removed.add(pa);
12124                    }
12125                }
12126                if (removed.size() > 0) {
12127                    for (int r=0; r<removed.size(); r++) {
12128                        PreferredActivity pa = removed.get(r);
12129                        Slog.w(TAG, "Removing dangling preferred activity: "
12130                                + pa.mPref.mComponent);
12131                        pir.removeFilter(pa);
12132                    }
12133                    mSettings.writePackageRestrictionsLPr(
12134                            mSettings.mPreferredActivities.keyAt(i));
12135                }
12136            }
12137        }
12138        sUserManager.systemReady();
12139    }
12140
12141    @Override
12142    public boolean isSafeMode() {
12143        return mSafeMode;
12144    }
12145
12146    @Override
12147    public boolean hasSystemUidErrors() {
12148        return mHasSystemUidErrors;
12149    }
12150
12151    static String arrayToString(int[] array) {
12152        StringBuffer buf = new StringBuffer(128);
12153        buf.append('[');
12154        if (array != null) {
12155            for (int i=0; i<array.length; i++) {
12156                if (i > 0) buf.append(", ");
12157                buf.append(array[i]);
12158            }
12159        }
12160        buf.append(']');
12161        return buf.toString();
12162    }
12163
12164    static class DumpState {
12165        public static final int DUMP_LIBS = 1 << 0;
12166        public static final int DUMP_FEATURES = 1 << 1;
12167        public static final int DUMP_RESOLVERS = 1 << 2;
12168        public static final int DUMP_PERMISSIONS = 1 << 3;
12169        public static final int DUMP_PACKAGES = 1 << 4;
12170        public static final int DUMP_SHARED_USERS = 1 << 5;
12171        public static final int DUMP_MESSAGES = 1 << 6;
12172        public static final int DUMP_PROVIDERS = 1 << 7;
12173        public static final int DUMP_VERIFIERS = 1 << 8;
12174        public static final int DUMP_PREFERRED = 1 << 9;
12175        public static final int DUMP_PREFERRED_XML = 1 << 10;
12176        public static final int DUMP_KEYSETS = 1 << 11;
12177        public static final int DUMP_VERSION = 1 << 12;
12178        public static final int DUMP_INSTALLS = 1 << 13;
12179
12180        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12181
12182        private int mTypes;
12183
12184        private int mOptions;
12185
12186        private boolean mTitlePrinted;
12187
12188        private SharedUserSetting mSharedUser;
12189
12190        public boolean isDumping(int type) {
12191            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12192                return true;
12193            }
12194
12195            return (mTypes & type) != 0;
12196        }
12197
12198        public void setDump(int type) {
12199            mTypes |= type;
12200        }
12201
12202        public boolean isOptionEnabled(int option) {
12203            return (mOptions & option) != 0;
12204        }
12205
12206        public void setOptionEnabled(int option) {
12207            mOptions |= option;
12208        }
12209
12210        public boolean onTitlePrinted() {
12211            final boolean printed = mTitlePrinted;
12212            mTitlePrinted = true;
12213            return printed;
12214        }
12215
12216        public boolean getTitlePrinted() {
12217            return mTitlePrinted;
12218        }
12219
12220        public void setTitlePrinted(boolean enabled) {
12221            mTitlePrinted = enabled;
12222        }
12223
12224        public SharedUserSetting getSharedUser() {
12225            return mSharedUser;
12226        }
12227
12228        public void setSharedUser(SharedUserSetting user) {
12229            mSharedUser = user;
12230        }
12231    }
12232
12233    @Override
12234    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12235        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12236                != PackageManager.PERMISSION_GRANTED) {
12237            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12238                    + Binder.getCallingPid()
12239                    + ", uid=" + Binder.getCallingUid()
12240                    + " without permission "
12241                    + android.Manifest.permission.DUMP);
12242            return;
12243        }
12244
12245        DumpState dumpState = new DumpState();
12246        boolean fullPreferred = false;
12247        boolean checkin = false;
12248
12249        String packageName = null;
12250
12251        int opti = 0;
12252        while (opti < args.length) {
12253            String opt = args[opti];
12254            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12255                break;
12256            }
12257            opti++;
12258            if ("-a".equals(opt)) {
12259                // Right now we only know how to print all.
12260            } else if ("-h".equals(opt)) {
12261                pw.println("Package manager dump options:");
12262                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12263                pw.println("    --checkin: dump for a checkin");
12264                pw.println("    -f: print details of intent filters");
12265                pw.println("    -h: print this help");
12266                pw.println("  cmd may be one of:");
12267                pw.println("    l[ibraries]: list known shared libraries");
12268                pw.println("    f[ibraries]: list device features");
12269                pw.println("    k[eysets]: print known keysets");
12270                pw.println("    r[esolvers]: dump intent resolvers");
12271                pw.println("    perm[issions]: dump permissions");
12272                pw.println("    pref[erred]: print preferred package settings");
12273                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12274                pw.println("    prov[iders]: dump content providers");
12275                pw.println("    p[ackages]: dump installed packages");
12276                pw.println("    s[hared-users]: dump shared user IDs");
12277                pw.println("    m[essages]: print collected runtime messages");
12278                pw.println("    v[erifiers]: print package verifier info");
12279                pw.println("    version: print database version info");
12280                pw.println("    write: write current settings now");
12281                pw.println("    <package.name>: info about given package");
12282                pw.println("    installs: details about install sessions");
12283                return;
12284            } else if ("--checkin".equals(opt)) {
12285                checkin = true;
12286            } else if ("-f".equals(opt)) {
12287                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12288            } else {
12289                pw.println("Unknown argument: " + opt + "; use -h for help");
12290            }
12291        }
12292
12293        // Is the caller requesting to dump a particular piece of data?
12294        if (opti < args.length) {
12295            String cmd = args[opti];
12296            opti++;
12297            // Is this a package name?
12298            if ("android".equals(cmd) || cmd.contains(".")) {
12299                packageName = cmd;
12300                // When dumping a single package, we always dump all of its
12301                // filter information since the amount of data will be reasonable.
12302                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12303            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12304                dumpState.setDump(DumpState.DUMP_LIBS);
12305            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12306                dumpState.setDump(DumpState.DUMP_FEATURES);
12307            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12308                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12309            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12310                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12311            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12312                dumpState.setDump(DumpState.DUMP_PREFERRED);
12313            } else if ("preferred-xml".equals(cmd)) {
12314                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12315                if (opti < args.length && "--full".equals(args[opti])) {
12316                    fullPreferred = true;
12317                    opti++;
12318                }
12319            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12320                dumpState.setDump(DumpState.DUMP_PACKAGES);
12321            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12322                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12323            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12324                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12325            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12326                dumpState.setDump(DumpState.DUMP_MESSAGES);
12327            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12328                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12329            } else if ("version".equals(cmd)) {
12330                dumpState.setDump(DumpState.DUMP_VERSION);
12331            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12332                dumpState.setDump(DumpState.DUMP_KEYSETS);
12333            } else if ("write".equals(cmd)) {
12334                synchronized (mPackages) {
12335                    mSettings.writeLPr();
12336                    pw.println("Settings written.");
12337                    return;
12338                }
12339            } else if ("installs".equals(cmd)) {
12340                dumpState.setDump(DumpState.DUMP_INSTALLS);
12341            }
12342        }
12343
12344        if (checkin) {
12345            pw.println("vers,1");
12346        }
12347
12348        // reader
12349        synchronized (mPackages) {
12350            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12351                if (!checkin) {
12352                    if (dumpState.onTitlePrinted())
12353                        pw.println();
12354                    pw.println("Database versions:");
12355                    pw.print("  SDK Version:");
12356                    pw.print(" internal=");
12357                    pw.print(mSettings.mInternalSdkPlatform);
12358                    pw.print(" external=");
12359                    pw.println(mSettings.mExternalSdkPlatform);
12360                    pw.print("  DB Version:");
12361                    pw.print(" internal=");
12362                    pw.print(mSettings.mInternalDatabaseVersion);
12363                    pw.print(" external=");
12364                    pw.println(mSettings.mExternalDatabaseVersion);
12365                }
12366            }
12367
12368            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12369                if (!checkin) {
12370                    if (dumpState.onTitlePrinted())
12371                        pw.println();
12372                    pw.println("Verifiers:");
12373                    pw.print("  Required: ");
12374                    pw.print(mRequiredVerifierPackage);
12375                    pw.print(" (uid=");
12376                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12377                    pw.println(")");
12378                } else if (mRequiredVerifierPackage != null) {
12379                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12380                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12381                }
12382            }
12383
12384            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12385                boolean printedHeader = false;
12386                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12387                while (it.hasNext()) {
12388                    String name = it.next();
12389                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12390                    if (!checkin) {
12391                        if (!printedHeader) {
12392                            if (dumpState.onTitlePrinted())
12393                                pw.println();
12394                            pw.println("Libraries:");
12395                            printedHeader = true;
12396                        }
12397                        pw.print("  ");
12398                    } else {
12399                        pw.print("lib,");
12400                    }
12401                    pw.print(name);
12402                    if (!checkin) {
12403                        pw.print(" -> ");
12404                    }
12405                    if (ent.path != null) {
12406                        if (!checkin) {
12407                            pw.print("(jar) ");
12408                            pw.print(ent.path);
12409                        } else {
12410                            pw.print(",jar,");
12411                            pw.print(ent.path);
12412                        }
12413                    } else {
12414                        if (!checkin) {
12415                            pw.print("(apk) ");
12416                            pw.print(ent.apk);
12417                        } else {
12418                            pw.print(",apk,");
12419                            pw.print(ent.apk);
12420                        }
12421                    }
12422                    pw.println();
12423                }
12424            }
12425
12426            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12427                if (dumpState.onTitlePrinted())
12428                    pw.println();
12429                if (!checkin) {
12430                    pw.println("Features:");
12431                }
12432                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12433                while (it.hasNext()) {
12434                    String name = it.next();
12435                    if (!checkin) {
12436                        pw.print("  ");
12437                    } else {
12438                        pw.print("feat,");
12439                    }
12440                    pw.println(name);
12441                }
12442            }
12443
12444            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12445                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12446                        : "Activity Resolver Table:", "  ", packageName,
12447                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12448                    dumpState.setTitlePrinted(true);
12449                }
12450                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12451                        : "Receiver Resolver Table:", "  ", packageName,
12452                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12453                    dumpState.setTitlePrinted(true);
12454                }
12455                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12456                        : "Service Resolver Table:", "  ", packageName,
12457                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12458                    dumpState.setTitlePrinted(true);
12459                }
12460                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12461                        : "Provider Resolver Table:", "  ", packageName,
12462                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12463                    dumpState.setTitlePrinted(true);
12464                }
12465            }
12466
12467            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12468                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12469                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12470                    int user = mSettings.mPreferredActivities.keyAt(i);
12471                    if (pir.dump(pw,
12472                            dumpState.getTitlePrinted()
12473                                ? "\nPreferred Activities User " + user + ":"
12474                                : "Preferred Activities User " + user + ":", "  ",
12475                            packageName, true)) {
12476                        dumpState.setTitlePrinted(true);
12477                    }
12478                }
12479            }
12480
12481            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12482                pw.flush();
12483                FileOutputStream fout = new FileOutputStream(fd);
12484                BufferedOutputStream str = new BufferedOutputStream(fout);
12485                XmlSerializer serializer = new FastXmlSerializer();
12486                try {
12487                    serializer.setOutput(str, "utf-8");
12488                    serializer.startDocument(null, true);
12489                    serializer.setFeature(
12490                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12491                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12492                    serializer.endDocument();
12493                    serializer.flush();
12494                } catch (IllegalArgumentException e) {
12495                    pw.println("Failed writing: " + e);
12496                } catch (IllegalStateException e) {
12497                    pw.println("Failed writing: " + e);
12498                } catch (IOException e) {
12499                    pw.println("Failed writing: " + e);
12500                }
12501            }
12502
12503            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12504                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12505                if (packageName == null) {
12506                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12507                        if (iperm == 0) {
12508                            if (dumpState.onTitlePrinted())
12509                                pw.println();
12510                            pw.println("AppOp Permissions:");
12511                        }
12512                        pw.print("  AppOp Permission ");
12513                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12514                        pw.println(":");
12515                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12516                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12517                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12518                        }
12519                    }
12520                }
12521            }
12522
12523            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12524                boolean printedSomething = false;
12525                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12526                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12527                        continue;
12528                    }
12529                    if (!printedSomething) {
12530                        if (dumpState.onTitlePrinted())
12531                            pw.println();
12532                        pw.println("Registered ContentProviders:");
12533                        printedSomething = true;
12534                    }
12535                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12536                    pw.print("    "); pw.println(p.toString());
12537                }
12538                printedSomething = false;
12539                for (Map.Entry<String, PackageParser.Provider> entry :
12540                        mProvidersByAuthority.entrySet()) {
12541                    PackageParser.Provider p = entry.getValue();
12542                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12543                        continue;
12544                    }
12545                    if (!printedSomething) {
12546                        if (dumpState.onTitlePrinted())
12547                            pw.println();
12548                        pw.println("ContentProvider Authorities:");
12549                        printedSomething = true;
12550                    }
12551                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12552                    pw.print("    "); pw.println(p.toString());
12553                    if (p.info != null && p.info.applicationInfo != null) {
12554                        final String appInfo = p.info.applicationInfo.toString();
12555                        pw.print("      applicationInfo="); pw.println(appInfo);
12556                    }
12557                }
12558            }
12559
12560            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12561                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12562            }
12563
12564            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12565                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12566            }
12567
12568            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12569                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12570            }
12571
12572            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12573                if (dumpState.onTitlePrinted()) pw.println();
12574                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12575            }
12576
12577            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12578                if (dumpState.onTitlePrinted()) pw.println();
12579                mSettings.dumpReadMessagesLPr(pw, dumpState);
12580
12581                pw.println();
12582                pw.println("Package warning messages:");
12583                final File fname = getSettingsProblemFile();
12584                FileInputStream in = null;
12585                try {
12586                    in = new FileInputStream(fname);
12587                    final int avail = in.available();
12588                    final byte[] data = new byte[avail];
12589                    in.read(data);
12590                    pw.print(new String(data));
12591                } catch (FileNotFoundException e) {
12592                } catch (IOException e) {
12593                } finally {
12594                    if (in != null) {
12595                        try {
12596                            in.close();
12597                        } catch (IOException e) {
12598                        }
12599                    }
12600                }
12601            }
12602        }
12603    }
12604
12605    // ------- apps on sdcard specific code -------
12606    static final boolean DEBUG_SD_INSTALL = false;
12607
12608    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12609
12610    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12611
12612    private boolean mMediaMounted = false;
12613
12614    private String getEncryptKey() {
12615        try {
12616            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12617                    SD_ENCRYPTION_KEYSTORE_NAME);
12618            if (sdEncKey == null) {
12619                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12620                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12621                if (sdEncKey == null) {
12622                    Slog.e(TAG, "Failed to create encryption keys");
12623                    return null;
12624                }
12625            }
12626            return sdEncKey;
12627        } catch (NoSuchAlgorithmException nsae) {
12628            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12629            return null;
12630        } catch (IOException ioe) {
12631            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12632            return null;
12633        }
12634
12635    }
12636
12637    /* package */static String getTempContainerId() {
12638        int tmpIdx = 1;
12639        String list[] = PackageHelper.getSecureContainerList();
12640        if (list != null) {
12641            for (final String name : list) {
12642                // Ignore null and non-temporary container entries
12643                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12644                    continue;
12645                }
12646
12647                String subStr = name.substring(mTempContainerPrefix.length());
12648                try {
12649                    int cid = Integer.parseInt(subStr);
12650                    if (cid >= tmpIdx) {
12651                        tmpIdx = cid + 1;
12652                    }
12653                } catch (NumberFormatException e) {
12654                }
12655            }
12656        }
12657        return mTempContainerPrefix + tmpIdx;
12658    }
12659
12660    /*
12661     * Update media status on PackageManager.
12662     */
12663    @Override
12664    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12665        int callingUid = Binder.getCallingUid();
12666        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12667            throw new SecurityException("Media status can only be updated by the system");
12668        }
12669        // reader; this apparently protects mMediaMounted, but should probably
12670        // be a different lock in that case.
12671        synchronized (mPackages) {
12672            Log.i(TAG, "Updating external media status from "
12673                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12674                    + (mediaStatus ? "mounted" : "unmounted"));
12675            if (DEBUG_SD_INSTALL)
12676                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12677                        + ", mMediaMounted=" + mMediaMounted);
12678            if (mediaStatus == mMediaMounted) {
12679                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12680                        : 0, -1);
12681                mHandler.sendMessage(msg);
12682                return;
12683            }
12684            mMediaMounted = mediaStatus;
12685        }
12686        // Queue up an async operation since the package installation may take a
12687        // little while.
12688        mHandler.post(new Runnable() {
12689            public void run() {
12690                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12691            }
12692        });
12693    }
12694
12695    /**
12696     * Called by MountService when the initial ASECs to scan are available.
12697     * Should block until all the ASEC containers are finished being scanned.
12698     */
12699    public void scanAvailableAsecs() {
12700        updateExternalMediaStatusInner(true, false, false);
12701        if (mShouldRestoreconData) {
12702            SELinuxMMAC.setRestoreconDone();
12703            mShouldRestoreconData = false;
12704        }
12705    }
12706
12707    /*
12708     * Collect information of applications on external media, map them against
12709     * existing containers and update information based on current mount status.
12710     * Please note that we always have to report status if reportStatus has been
12711     * set to true especially when unloading packages.
12712     */
12713    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12714            boolean externalStorage) {
12715        // Collection of uids
12716        int uidArr[] = null;
12717        // Collection of stale containers
12718        HashSet<String> removeCids = new HashSet<String>();
12719        // Collection of packages on external media with valid containers.
12720        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12721        // Get list of secure containers.
12722        final String list[] = PackageHelper.getSecureContainerList();
12723        if (list == null || list.length == 0) {
12724            Log.i(TAG, "No secure containers on sdcard");
12725        } else {
12726            // Process list of secure containers and categorize them
12727            // as active or stale based on their package internal state.
12728            int uidList[] = new int[list.length];
12729            int num = 0;
12730            // reader
12731            synchronized (mPackages) {
12732                for (String cid : list) {
12733                    if (DEBUG_SD_INSTALL)
12734                        Log.i(TAG, "Processing container " + cid);
12735                    String pkgName = getAsecPackageName(cid);
12736                    if (pkgName == null) {
12737                        if (DEBUG_SD_INSTALL)
12738                            Log.i(TAG, "Container : " + cid + " stale");
12739                        removeCids.add(cid);
12740                        continue;
12741                    }
12742                    if (DEBUG_SD_INSTALL)
12743                        Log.i(TAG, "Looking for pkg : " + pkgName);
12744
12745                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12746                    if (ps == null) {
12747                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12748                        removeCids.add(cid);
12749                        continue;
12750                    }
12751
12752                    /*
12753                     * Skip packages that are not external if we're unmounting
12754                     * external storage.
12755                     */
12756                    if (externalStorage && !isMounted && !isExternal(ps)) {
12757                        continue;
12758                    }
12759
12760                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12761                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12762                    // The package status is changed only if the code path
12763                    // matches between settings and the container id.
12764                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12765                        if (DEBUG_SD_INSTALL) {
12766                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12767                                    + " at code path: " + ps.codePathString);
12768                        }
12769
12770                        // We do have a valid package installed on sdcard
12771                        processCids.put(args, ps.codePathString);
12772                        final int uid = ps.appId;
12773                        if (uid != -1) {
12774                            uidList[num++] = uid;
12775                        }
12776                    } else {
12777                        Log.i(TAG, "Deleting stale container for " + cid);
12778                        removeCids.add(cid);
12779                    }
12780                }
12781            }
12782
12783            if (num > 0) {
12784                // Sort uid list
12785                Arrays.sort(uidList, 0, num);
12786                // Throw away duplicates
12787                uidArr = new int[num];
12788                uidArr[0] = uidList[0];
12789                int di = 0;
12790                for (int i = 1; i < num; i++) {
12791                    if (uidList[i - 1] != uidList[i]) {
12792                        uidArr[di++] = uidList[i];
12793                    }
12794                }
12795            }
12796        }
12797        // Process packages with valid entries.
12798        if (isMounted) {
12799            if (DEBUG_SD_INSTALL)
12800                Log.i(TAG, "Loading packages");
12801            loadMediaPackages(processCids, uidArr, removeCids);
12802            startCleaningPackages();
12803        } else {
12804            if (DEBUG_SD_INSTALL)
12805                Log.i(TAG, "Unloading packages");
12806            unloadMediaPackages(processCids, uidArr, reportStatus);
12807        }
12808    }
12809
12810   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12811           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12812        int size = pkgList.size();
12813        if (size > 0) {
12814            // Send broadcasts here
12815            Bundle extras = new Bundle();
12816            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12817                    .toArray(new String[size]));
12818            if (uidArr != null) {
12819                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12820            }
12821            if (replacing) {
12822                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12823            }
12824            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12825                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12826            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12827        }
12828    }
12829
12830   /*
12831     * Look at potentially valid container ids from processCids If package
12832     * information doesn't match the one on record or package scanning fails,
12833     * the cid is added to list of removeCids. We currently don't delete stale
12834     * containers.
12835     */
12836   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12837            HashSet<String> removeCids) {
12838        ArrayList<String> pkgList = new ArrayList<String>();
12839        Set<AsecInstallArgs> keys = processCids.keySet();
12840        boolean doGc = false;
12841        for (AsecInstallArgs args : keys) {
12842            String codePath = processCids.get(args);
12843            if (DEBUG_SD_INSTALL)
12844                Log.i(TAG, "Loading container : " + args.cid);
12845            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12846            try {
12847                // Make sure there are no container errors first.
12848                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12849                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12850                            + " when installing from sdcard");
12851                    continue;
12852                }
12853                // Check code path here.
12854                if (codePath == null || !codePath.equals(args.getCodePath())) {
12855                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12856                            + " does not match one in settings " + codePath);
12857                    continue;
12858                }
12859                // Parse package
12860                int parseFlags = mDefParseFlags;
12861                if (args.isExternal()) {
12862                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12863                }
12864                if (args.isFwdLocked()) {
12865                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12866                }
12867
12868                doGc = true;
12869                synchronized (mInstallLock) {
12870                    PackageParser.Package pkg = null;
12871                    try {
12872                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12873                    } catch (PackageManagerException e) {
12874                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12875                    }
12876                    // Scan the package
12877                    if (pkg != null) {
12878                        /*
12879                         * TODO why is the lock being held? doPostInstall is
12880                         * called in other places without the lock. This needs
12881                         * to be straightened out.
12882                         */
12883                        // writer
12884                        synchronized (mPackages) {
12885                            retCode = PackageManager.INSTALL_SUCCEEDED;
12886                            pkgList.add(pkg.packageName);
12887                            // Post process args
12888                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12889                                    pkg.applicationInfo.uid);
12890                        }
12891                    } else {
12892                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12893                    }
12894                }
12895
12896            } finally {
12897                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12898                    // Don't destroy container here. Wait till gc clears things
12899                    // up.
12900                    removeCids.add(args.cid);
12901                }
12902            }
12903        }
12904        // writer
12905        synchronized (mPackages) {
12906            // If the platform SDK has changed since the last time we booted,
12907            // we need to re-grant app permission to catch any new ones that
12908            // appear. This is really a hack, and means that apps can in some
12909            // cases get permissions that the user didn't initially explicitly
12910            // allow... it would be nice to have some better way to handle
12911            // this situation.
12912            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12913            if (regrantPermissions)
12914                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12915                        + mSdkVersion + "; regranting permissions for external storage");
12916            mSettings.mExternalSdkPlatform = mSdkVersion;
12917
12918            // Make sure group IDs have been assigned, and any permission
12919            // changes in other apps are accounted for
12920            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12921                    | (regrantPermissions
12922                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12923                            : 0));
12924
12925            mSettings.updateExternalDatabaseVersion();
12926
12927            // can downgrade to reader
12928            // Persist settings
12929            mSettings.writeLPr();
12930        }
12931        // Send a broadcast to let everyone know we are done processing
12932        if (pkgList.size() > 0) {
12933            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12934        }
12935        // Force gc to avoid any stale parser references that we might have.
12936        if (doGc) {
12937            Runtime.getRuntime().gc();
12938        }
12939        // List stale containers and destroy stale temporary containers.
12940        if (removeCids != null) {
12941            for (String cid : removeCids) {
12942                if (cid.startsWith(mTempContainerPrefix)) {
12943                    Log.i(TAG, "Destroying stale temporary container " + cid);
12944                    PackageHelper.destroySdDir(cid);
12945                } else {
12946                    Log.w(TAG, "Container " + cid + " is stale");
12947               }
12948           }
12949        }
12950    }
12951
12952   /*
12953     * Utility method to unload a list of specified containers
12954     */
12955    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12956        // Just unmount all valid containers.
12957        for (AsecInstallArgs arg : cidArgs) {
12958            synchronized (mInstallLock) {
12959                arg.doPostDeleteLI(false);
12960           }
12961       }
12962   }
12963
12964    /*
12965     * Unload packages mounted on external media. This involves deleting package
12966     * data from internal structures, sending broadcasts about diabled packages,
12967     * gc'ing to free up references, unmounting all secure containers
12968     * corresponding to packages on external media, and posting a
12969     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12970     * that we always have to post this message if status has been requested no
12971     * matter what.
12972     */
12973    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12974            final boolean reportStatus) {
12975        if (DEBUG_SD_INSTALL)
12976            Log.i(TAG, "unloading media packages");
12977        ArrayList<String> pkgList = new ArrayList<String>();
12978        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12979        final Set<AsecInstallArgs> keys = processCids.keySet();
12980        for (AsecInstallArgs args : keys) {
12981            String pkgName = args.getPackageName();
12982            if (DEBUG_SD_INSTALL)
12983                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12984            // Delete package internally
12985            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12986            synchronized (mInstallLock) {
12987                boolean res = deletePackageLI(pkgName, null, false, null, null,
12988                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12989                if (res) {
12990                    pkgList.add(pkgName);
12991                } else {
12992                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12993                    failedList.add(args);
12994                }
12995            }
12996        }
12997
12998        // reader
12999        synchronized (mPackages) {
13000            // We didn't update the settings after removing each package;
13001            // write them now for all packages.
13002            mSettings.writeLPr();
13003        }
13004
13005        // We have to absolutely send UPDATED_MEDIA_STATUS only
13006        // after confirming that all the receivers processed the ordered
13007        // broadcast when packages get disabled, force a gc to clean things up.
13008        // and unload all the containers.
13009        if (pkgList.size() > 0) {
13010            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13011                    new IIntentReceiver.Stub() {
13012                public void performReceive(Intent intent, int resultCode, String data,
13013                        Bundle extras, boolean ordered, boolean sticky,
13014                        int sendingUser) throws RemoteException {
13015                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13016                            reportStatus ? 1 : 0, 1, keys);
13017                    mHandler.sendMessage(msg);
13018                }
13019            });
13020        } else {
13021            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13022                    keys);
13023            mHandler.sendMessage(msg);
13024        }
13025    }
13026
13027    /** Binder call */
13028    @Override
13029    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13030            final int flags) {
13031        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13032        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13033        int returnCode = PackageManager.MOVE_SUCCEEDED;
13034        int currFlags = 0;
13035        int newFlags = 0;
13036        // reader
13037        synchronized (mPackages) {
13038            PackageParser.Package pkg = mPackages.get(packageName);
13039            if (pkg == null) {
13040                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13041            } else {
13042                // Disable moving fwd locked apps and system packages
13043                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13044                    Slog.w(TAG, "Cannot move system application");
13045                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13046                } else if (pkg.mOperationPending) {
13047                    Slog.w(TAG, "Attempt to move package which has pending operations");
13048                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13049                } else {
13050                    // Find install location first
13051                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13052                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13053                        Slog.w(TAG, "Ambigous flags specified for move location.");
13054                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13055                    } else {
13056                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
13057                                : PackageManager.INSTALL_INTERNAL;
13058                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
13059                                : PackageManager.INSTALL_INTERNAL;
13060
13061                        if (newFlags == currFlags) {
13062                            Slog.w(TAG, "No move required. Trying to move to same location");
13063                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13064                        } else {
13065                            if (isForwardLocked(pkg)) {
13066                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13067                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13068                            }
13069                        }
13070                    }
13071                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13072                        pkg.mOperationPending = true;
13073                    }
13074                }
13075            }
13076
13077            /*
13078             * TODO this next block probably shouldn't be inside the lock. We
13079             * can't guarantee these won't change after this is fired off
13080             * anyway.
13081             */
13082            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13083                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
13084                        returnCode);
13085            } else {
13086                Message msg = mHandler.obtainMessage(INIT_COPY);
13087                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
13088                final boolean multiArch = isMultiArch(pkg.applicationInfo);
13089                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
13090                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
13091                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
13092                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
13093                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
13094                msg.obj = mp;
13095                mHandler.sendMessage(msg);
13096            }
13097        }
13098    }
13099
13100    private void processPendingMove(final MoveParams mp, final int currentStatus) {
13101        // Queue up an async operation since the package deletion may take a
13102        // little while.
13103        mHandler.post(new Runnable() {
13104            public void run() {
13105                // TODO fix this; this does nothing.
13106                mHandler.removeCallbacks(this);
13107                int returnCode = currentStatus;
13108                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13109                    int uidArr[] = null;
13110                    ArrayList<String> pkgList = null;
13111                    synchronized (mPackages) {
13112                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13113                        if (pkg == null) {
13114                            Slog.w(TAG, " Package " + mp.packageName
13115                                    + " doesn't exist. Aborting move");
13116                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13117                        } else if (!mp.srcArgs.getCodePath().equals(
13118                                pkg.applicationInfo.getCodePath())) {
13119                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13120                                    + mp.srcArgs.getCodePath() + " to "
13121                                    + pkg.applicationInfo.getCodePath()
13122                                    + " Aborting move and returning error");
13123                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13124                        } else {
13125                            uidArr = new int[] {
13126                                pkg.applicationInfo.uid
13127                            };
13128                            pkgList = new ArrayList<String>();
13129                            pkgList.add(mp.packageName);
13130                        }
13131                    }
13132                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13133                        // Send resources unavailable broadcast
13134                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13135                        // Update package code and resource paths
13136                        synchronized (mInstallLock) {
13137                            synchronized (mPackages) {
13138                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13139                                // Recheck for package again.
13140                                if (pkg == null) {
13141                                    Slog.w(TAG, " Package " + mp.packageName
13142                                            + " doesn't exist. Aborting move");
13143                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13144                                } else if (!mp.srcArgs.getCodePath().equals(
13145                                        pkg.applicationInfo.getCodePath())) {
13146                                    Slog.w(TAG, "Package " + mp.packageName
13147                                            + " code path changed from " + mp.srcArgs.getCodePath()
13148                                            + " to " + pkg.applicationInfo.getCodePath()
13149                                            + " Aborting move and returning error");
13150                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13151                                } else {
13152                                    final String oldCodePath = pkg.codePath;
13153                                    final String newCodePath = mp.targetArgs.getCodePath();
13154                                    final String newResPath = mp.targetArgs.getResourcePath();
13155                                    // TODO: This assumes the new style of installation.
13156                                    // should we look at legacyNativeLibraryPath ?
13157                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13158                                    final File newNativeDir = new File(newNativeRoot);
13159
13160                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13161                                        // TODO(multiArch): Fix this so that it looks at the existing
13162                                        // recorded CPU abis from the package. There's no need for a separate
13163                                        // round of ABI scanning here.
13164                                        NativeLibraryHelper.Handle handle = null;
13165                                        try {
13166                                            handle = NativeLibraryHelper.Handle.create(
13167                                                    new File(newCodePath));
13168                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13169                                                    handle, Build.SUPPORTED_ABIS);
13170                                            if (abi >= 0) {
13171                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13172                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13173                                            }
13174                                        } catch (IOException ioe) {
13175                                            Slog.w(TAG, "Unable to extract native libs for package :"
13176                                                    + mp.packageName, ioe);
13177                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13178                                        } finally {
13179                                            IoUtils.closeQuietly(handle);
13180                                        }
13181                                    }
13182
13183                                    final int[] users = sUserManager.getUserIds();
13184                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13185                                        for (int user : users) {
13186                                            // TODO(multiArch): Fix this so that it links to the
13187                                            // correct directory. We're currently pointing to root. but we
13188                                            // must point to the arch specific subdirectory (if applicable).
13189                                            //
13190                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13191                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13192                                                    newNativeRoot, user) < 0) {
13193                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13194                                            }
13195                                        }
13196                                    }
13197
13198                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13199                                        pkg.codePath = newCodePath;
13200                                        pkg.baseCodePath = newCodePath;
13201                                        // Move dex files around
13202                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13203                                            // Moving of dex files failed. Set
13204                                            // error code and abort move.
13205                                            pkg.codePath = oldCodePath;
13206                                            pkg.baseCodePath = oldCodePath;
13207                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13208                                        }
13209                                    }
13210
13211                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13212                                        pkg.applicationInfo.setCodePath(newCodePath);
13213                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13214                                        pkg.applicationInfo.setSplitCodePaths(null);
13215                                        pkg.applicationInfo.setResourcePath(newResPath);
13216                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13217                                        pkg.applicationInfo.setSplitResourcePaths(null);
13218
13219                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13220                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13221                                        ps.codePathString = ps.codePath.getPath();
13222                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13223                                        ps.resourcePathString = ps.resourcePath.getPath();
13224
13225                                        // Note that we don't have to recalculate the primary and secondary
13226                                        // CPU ABIs because they must already have been calculated during the
13227                                        // initial install of the app.
13228                                        ps.legacyNativeLibraryPathString = null;
13229
13230                                        // Set the application info flag
13231                                        // correctly.
13232                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13233                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13234                                        } else {
13235                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13236                                        }
13237                                        ps.setFlags(pkg.applicationInfo.flags);
13238                                        mAppDirs.remove(oldCodePath);
13239                                        mAppDirs.put(newCodePath, pkg);
13240                                        // Persist settings
13241                                        mSettings.writeLPr();
13242                                    }
13243                                }
13244                            }
13245                        }
13246                        // Send resources available broadcast
13247                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13248                    }
13249                }
13250                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13251                    // Clean up failed installation
13252                    if (mp.targetArgs != null) {
13253                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13254                                -1);
13255                    }
13256                } else {
13257                    // Force a gc to clear things up.
13258                    Runtime.getRuntime().gc();
13259                    // Delete older code
13260                    synchronized (mInstallLock) {
13261                        mp.srcArgs.doPostDeleteLI(true);
13262                    }
13263                }
13264
13265                // Allow more operations on this file if we didn't fail because
13266                // an operation was already pending for this package.
13267                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13268                    synchronized (mPackages) {
13269                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13270                        if (pkg != null) {
13271                            pkg.mOperationPending = false;
13272                       }
13273                   }
13274                }
13275
13276                IPackageMoveObserver observer = mp.observer;
13277                if (observer != null) {
13278                    try {
13279                        observer.packageMoved(mp.packageName, returnCode);
13280                    } catch (RemoteException e) {
13281                        Log.i(TAG, "Observer no longer exists.");
13282                    }
13283                }
13284            }
13285        });
13286    }
13287
13288    @Override
13289    public boolean setInstallLocation(int loc) {
13290        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13291                null);
13292        if (getInstallLocation() == loc) {
13293            return true;
13294        }
13295        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13296                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13297            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13298                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13299            return true;
13300        }
13301        return false;
13302   }
13303
13304    @Override
13305    public int getInstallLocation() {
13306        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13307                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13308                PackageHelper.APP_INSTALL_AUTO);
13309    }
13310
13311    /** Called by UserManagerService */
13312    void cleanUpUserLILPw(int userHandle) {
13313        mDirtyUsers.remove(userHandle);
13314        mSettings.removeUserLPw(userHandle);
13315        mPendingBroadcasts.remove(userHandle);
13316        if (mInstaller != null) {
13317            // Technically, we shouldn't be doing this with the package lock
13318            // held.  However, this is very rare, and there is already so much
13319            // other disk I/O going on, that we'll let it slide for now.
13320            mInstaller.removeUserDataDirs(userHandle);
13321        }
13322        mUserNeedsBadging.delete(userHandle);
13323    }
13324
13325    /** Called by UserManagerService */
13326    void createNewUserLILPw(int userHandle, File path) {
13327        if (mInstaller != null) {
13328            mInstaller.createUserConfig(userHandle);
13329            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13330        }
13331    }
13332
13333    @Override
13334    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13335        mContext.enforceCallingOrSelfPermission(
13336                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13337                "Only package verification agents can read the verifier device identity");
13338
13339        synchronized (mPackages) {
13340            return mSettings.getVerifierDeviceIdentityLPw();
13341        }
13342    }
13343
13344    @Override
13345    public void setPermissionEnforced(String permission, boolean enforced) {
13346        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13347        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13348            synchronized (mPackages) {
13349                if (mSettings.mReadExternalStorageEnforced == null
13350                        || mSettings.mReadExternalStorageEnforced != enforced) {
13351                    mSettings.mReadExternalStorageEnforced = enforced;
13352                    mSettings.writeLPr();
13353                }
13354            }
13355            // kill any non-foreground processes so we restart them and
13356            // grant/revoke the GID.
13357            final IActivityManager am = ActivityManagerNative.getDefault();
13358            if (am != null) {
13359                final long token = Binder.clearCallingIdentity();
13360                try {
13361                    am.killProcessesBelowForeground("setPermissionEnforcement");
13362                } catch (RemoteException e) {
13363                } finally {
13364                    Binder.restoreCallingIdentity(token);
13365                }
13366            }
13367        } else {
13368            throw new IllegalArgumentException("No selective enforcement for " + permission);
13369        }
13370    }
13371
13372    @Override
13373    @Deprecated
13374    public boolean isPermissionEnforced(String permission) {
13375        return true;
13376    }
13377
13378    @Override
13379    public boolean isStorageLow() {
13380        final long token = Binder.clearCallingIdentity();
13381        try {
13382            final DeviceStorageMonitorInternal
13383                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13384            if (dsm != null) {
13385                return dsm.isMemoryLow();
13386            } else {
13387                return false;
13388            }
13389        } finally {
13390            Binder.restoreCallingIdentity(token);
13391        }
13392    }
13393
13394    @Override
13395    public IPackageInstaller getPackageInstaller() {
13396        return mInstallerService;
13397    }
13398
13399    private boolean userNeedsBadging(int userId) {
13400        int index = mUserNeedsBadging.indexOfKey(userId);
13401        if (index < 0) {
13402            final UserInfo userInfo;
13403            final long token = Binder.clearCallingIdentity();
13404            try {
13405                userInfo = sUserManager.getUserInfo(userId);
13406            } finally {
13407                Binder.restoreCallingIdentity(token);
13408            }
13409            final boolean b;
13410            if (userInfo != null && userInfo.isManagedProfile()) {
13411                b = true;
13412            } else {
13413                b = false;
13414            }
13415            mUserNeedsBadging.put(userId, b);
13416            return b;
13417        }
13418        return mUserNeedsBadging.valueAt(index);
13419    }
13420
13421    @Override
13422    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13423        if (packageName == null || alias == null) {
13424            return null;
13425        }
13426        synchronized(mPackages) {
13427            final PackageParser.Package pkg = mPackages.get(packageName);
13428            if (pkg == null) {
13429                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13430                throw new IllegalArgumentException("Unknown package: " + packageName);
13431            }
13432            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13433                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13434                throw new SecurityException("May not access KeySets defined by"
13435                        + " aliases in other applications.");
13436            }
13437            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13438            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13439        }
13440    }
13441
13442    @Override
13443    public KeySetHandle getSigningKeySet(String packageName) {
13444        if (packageName == null) {
13445            return null;
13446        }
13447        synchronized(mPackages) {
13448            final PackageParser.Package pkg = mPackages.get(packageName);
13449            if (pkg == null) {
13450                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13451                throw new IllegalArgumentException("Unknown package: " + packageName);
13452            }
13453            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13454                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13455                throw new SecurityException("May not access signing KeySet of other apps.");
13456            }
13457            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13458            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13459        }
13460    }
13461
13462    @Override
13463    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13464        if (packageName == null || ks == null) {
13465            return false;
13466        }
13467        synchronized(mPackages) {
13468            final PackageParser.Package pkg = mPackages.get(packageName);
13469            if (pkg == null) {
13470                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13471                throw new IllegalArgumentException("Unknown package: " + packageName);
13472            }
13473            if (ks instanceof KeySetHandle) {
13474                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13475                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13476            }
13477            return false;
13478        }
13479    }
13480
13481    @Override
13482    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13483        if (packageName == null || ks == null) {
13484            return false;
13485        }
13486        synchronized(mPackages) {
13487            final PackageParser.Package pkg = mPackages.get(packageName);
13488            if (pkg == null) {
13489                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13490                throw new IllegalArgumentException("Unknown package: " + packageName);
13491            }
13492            if (ks instanceof KeySetHandle) {
13493                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13494                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13495            }
13496            return false;
13497        }
13498    }
13499}
13500