PackageManagerService.java revision a0907436c01fd8c545a6b5c7b28bc3bc9db59270
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.InstrumentationInfo;
111import android.content.pm.ManifestDigest;
112import android.content.pm.PackageCleanItem;
113import android.content.pm.PackageInfo;
114import android.content.pm.PackageInfoLite;
115import android.content.pm.PackageInstaller;
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                }
3286                return result;
3287            }
3288            final PackageParser.Package pkg = mPackages.get(pkgName);
3289            if (pkg != null) {
3290                if (queryCrossProfile) {
3291                    ArrayList<ResolveInfo> crossProfileResult =
3292                            queryIntentActivitiesCrossProfilePackage(
3293                                    intent, resolvedType, flags, userId, pkg, pkgName);
3294                    if (!crossProfileResult.isEmpty()) {
3295                        // Skip the current profile
3296                        return crossProfileResult;
3297                    }
3298                }
3299                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3300                        pkg.activities, userId);
3301            }
3302            return new ArrayList<ResolveInfo>();
3303        }
3304    }
3305
3306    private ResolveInfo querySkipCurrentProfileIntents(
3307            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3308            int flags, int sourceUserId) {
3309        if (matchingFilters != null) {
3310            int size = matchingFilters.size();
3311            for (int i = 0; i < size; i ++) {
3312                CrossProfileIntentFilter filter = matchingFilters.get(i);
3313                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3314                    // Checking if there are activities in the target user that can handle the
3315                    // intent.
3316                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3317                            flags, sourceUserId);
3318                    if (resolveInfo != null) {
3319                        return resolveInfo;
3320                    }
3321                }
3322            }
3323        }
3324        return null;
3325    }
3326
3327    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3328            Intent intent, String resolvedType, int flags, int userId) {
3329        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3330        SparseArray<ArrayList<String>> sourceForwardingInfo =
3331                mSettings.mCrossProfilePackageInfo.get(userId);
3332        if (sourceForwardingInfo != null) {
3333            int NI = sourceForwardingInfo.size();
3334            for (int i = 0; i < NI; i++) {
3335                int targetUserId = sourceForwardingInfo.keyAt(i);
3336                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3337                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3338                        intent, resolvedType, flags, targetUserId);
3339                int NJ = resolveInfos.size();
3340                for (int j = 0; j < NJ; j++) {
3341                    ResolveInfo resolveInfo = resolveInfos.get(j);
3342                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3343                        matchingResolveInfos.add(createForwardingResolveInfo(
3344                                resolveInfo.filter, userId, targetUserId));
3345                    }
3346                }
3347            }
3348        }
3349        return matchingResolveInfos;
3350    }
3351
3352    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3353            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3354            String packageName) {
3355        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3356        SparseArray<ArrayList<String>> sourceForwardingInfo =
3357                mSettings.mCrossProfilePackageInfo.get(userId);
3358        if (sourceForwardingInfo != null) {
3359            int NI = sourceForwardingInfo.size();
3360            for (int i = 0; i < NI; i++) {
3361                int targetUserId = sourceForwardingInfo.keyAt(i);
3362                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3363                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3364                            intent, resolvedType, flags, pkg.activities, targetUserId);
3365                    int NJ = resolveInfos.size();
3366                    for (int j = 0; j < NJ; j++) {
3367                        ResolveInfo resolveInfo = resolveInfos.get(j);
3368                        matchingResolveInfos.add(createForwardingResolveInfo(
3369                                resolveInfo.filter, userId, targetUserId));
3370                    }
3371                }
3372            }
3373        }
3374        return matchingResolveInfos;
3375    }
3376
3377    // Return matching ResolveInfo if any for skip current profile intent filters.
3378    private ResolveInfo queryCrossProfileIntents(
3379            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3380            int flags, int sourceUserId) {
3381        if (matchingFilters != null) {
3382            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3383            // match the same intent. For performance reasons, it is better not to
3384            // run queryIntent twice for the same userId
3385            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3386            int size = matchingFilters.size();
3387            for (int i = 0; i < size; i++) {
3388                CrossProfileIntentFilter filter = matchingFilters.get(i);
3389                int targetUserId = filter.getTargetUserId();
3390                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3391                        && !alreadyTriedUserIds.get(targetUserId)) {
3392                    // Checking if there are activities in the target user that can handle the
3393                    // intent.
3394                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3395                            flags, sourceUserId);
3396                    if (resolveInfo != null) return resolveInfo;
3397                    alreadyTriedUserIds.put(targetUserId, true);
3398                }
3399            }
3400        }
3401        return null;
3402    }
3403
3404    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3405            String resolvedType, int flags, int sourceUserId) {
3406        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3407                resolvedType, flags, filter.getTargetUserId());
3408        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3409            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3410        }
3411        return null;
3412    }
3413
3414    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3415            int sourceUserId, int targetUserId) {
3416        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3417        String className;
3418        if (targetUserId == UserHandle.USER_OWNER) {
3419            className = FORWARD_INTENT_TO_USER_OWNER;
3420        } else {
3421            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3422        }
3423        ComponentName forwardingActivityComponentName = new ComponentName(
3424                mAndroidApplication.packageName, className);
3425        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3426                sourceUserId);
3427        if (targetUserId == UserHandle.USER_OWNER) {
3428            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3429            forwardingResolveInfo.noResourceId = true;
3430        }
3431        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3432        forwardingResolveInfo.priority = 0;
3433        forwardingResolveInfo.preferredOrder = 0;
3434        forwardingResolveInfo.match = 0;
3435        forwardingResolveInfo.isDefault = true;
3436        forwardingResolveInfo.filter = filter;
3437        forwardingResolveInfo.targetUserId = targetUserId;
3438        return forwardingResolveInfo;
3439    }
3440
3441    @Override
3442    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3443            Intent[] specifics, String[] specificTypes, Intent intent,
3444            String resolvedType, int flags, int userId) {
3445        if (!sUserManager.exists(userId)) return Collections.emptyList();
3446        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3447                "query intent activity options");
3448        final String resultsAction = intent.getAction();
3449
3450        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3451                | PackageManager.GET_RESOLVED_FILTER, userId);
3452
3453        if (DEBUG_INTENT_MATCHING) {
3454            Log.v(TAG, "Query " + intent + ": " + results);
3455        }
3456
3457        int specificsPos = 0;
3458        int N;
3459
3460        // todo: note that the algorithm used here is O(N^2).  This
3461        // isn't a problem in our current environment, but if we start running
3462        // into situations where we have more than 5 or 10 matches then this
3463        // should probably be changed to something smarter...
3464
3465        // First we go through and resolve each of the specific items
3466        // that were supplied, taking care of removing any corresponding
3467        // duplicate items in the generic resolve list.
3468        if (specifics != null) {
3469            for (int i=0; i<specifics.length; i++) {
3470                final Intent sintent = specifics[i];
3471                if (sintent == null) {
3472                    continue;
3473                }
3474
3475                if (DEBUG_INTENT_MATCHING) {
3476                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3477                }
3478
3479                String action = sintent.getAction();
3480                if (resultsAction != null && resultsAction.equals(action)) {
3481                    // If this action was explicitly requested, then don't
3482                    // remove things that have it.
3483                    action = null;
3484                }
3485
3486                ResolveInfo ri = null;
3487                ActivityInfo ai = null;
3488
3489                ComponentName comp = sintent.getComponent();
3490                if (comp == null) {
3491                    ri = resolveIntent(
3492                        sintent,
3493                        specificTypes != null ? specificTypes[i] : null,
3494                            flags, userId);
3495                    if (ri == null) {
3496                        continue;
3497                    }
3498                    if (ri == mResolveInfo) {
3499                        // ACK!  Must do something better with this.
3500                    }
3501                    ai = ri.activityInfo;
3502                    comp = new ComponentName(ai.applicationInfo.packageName,
3503                            ai.name);
3504                } else {
3505                    ai = getActivityInfo(comp, flags, userId);
3506                    if (ai == null) {
3507                        continue;
3508                    }
3509                }
3510
3511                // Look for any generic query activities that are duplicates
3512                // of this specific one, and remove them from the results.
3513                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3514                N = results.size();
3515                int j;
3516                for (j=specificsPos; j<N; j++) {
3517                    ResolveInfo sri = results.get(j);
3518                    if ((sri.activityInfo.name.equals(comp.getClassName())
3519                            && sri.activityInfo.applicationInfo.packageName.equals(
3520                                    comp.getPackageName()))
3521                        || (action != null && sri.filter.matchAction(action))) {
3522                        results.remove(j);
3523                        if (DEBUG_INTENT_MATCHING) Log.v(
3524                            TAG, "Removing duplicate item from " + j
3525                            + " due to specific " + specificsPos);
3526                        if (ri == null) {
3527                            ri = sri;
3528                        }
3529                        j--;
3530                        N--;
3531                    }
3532                }
3533
3534                // Add this specific item to its proper place.
3535                if (ri == null) {
3536                    ri = new ResolveInfo();
3537                    ri.activityInfo = ai;
3538                }
3539                results.add(specificsPos, ri);
3540                ri.specificIndex = i;
3541                specificsPos++;
3542            }
3543        }
3544
3545        // Now we go through the remaining generic results and remove any
3546        // duplicate actions that are found here.
3547        N = results.size();
3548        for (int i=specificsPos; i<N-1; i++) {
3549            final ResolveInfo rii = results.get(i);
3550            if (rii.filter == null) {
3551                continue;
3552            }
3553
3554            // Iterate over all of the actions of this result's intent
3555            // filter...  typically this should be just one.
3556            final Iterator<String> it = rii.filter.actionsIterator();
3557            if (it == null) {
3558                continue;
3559            }
3560            while (it.hasNext()) {
3561                final String action = it.next();
3562                if (resultsAction != null && resultsAction.equals(action)) {
3563                    // If this action was explicitly requested, then don't
3564                    // remove things that have it.
3565                    continue;
3566                }
3567                for (int j=i+1; j<N; j++) {
3568                    final ResolveInfo rij = results.get(j);
3569                    if (rij.filter != null && rij.filter.hasAction(action)) {
3570                        results.remove(j);
3571                        if (DEBUG_INTENT_MATCHING) Log.v(
3572                            TAG, "Removing duplicate item from " + j
3573                            + " due to action " + action + " at " + i);
3574                        j--;
3575                        N--;
3576                    }
3577                }
3578            }
3579
3580            // If the caller didn't request filter information, drop it now
3581            // so we don't have to marshall/unmarshall it.
3582            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3583                rii.filter = null;
3584            }
3585        }
3586
3587        // Filter out the caller activity if so requested.
3588        if (caller != null) {
3589            N = results.size();
3590            for (int i=0; i<N; i++) {
3591                ActivityInfo ainfo = results.get(i).activityInfo;
3592                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3593                        && caller.getClassName().equals(ainfo.name)) {
3594                    results.remove(i);
3595                    break;
3596                }
3597            }
3598        }
3599
3600        // If the caller didn't request filter information,
3601        // drop them now so we don't have to
3602        // marshall/unmarshall it.
3603        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3604            N = results.size();
3605            for (int i=0; i<N; i++) {
3606                results.get(i).filter = null;
3607            }
3608        }
3609
3610        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3611        return results;
3612    }
3613
3614    @Override
3615    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3616            int userId) {
3617        if (!sUserManager.exists(userId)) return Collections.emptyList();
3618        ComponentName comp = intent.getComponent();
3619        if (comp == null) {
3620            if (intent.getSelector() != null) {
3621                intent = intent.getSelector();
3622                comp = intent.getComponent();
3623            }
3624        }
3625        if (comp != null) {
3626            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3627            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3628            if (ai != null) {
3629                ResolveInfo ri = new ResolveInfo();
3630                ri.activityInfo = ai;
3631                list.add(ri);
3632            }
3633            return list;
3634        }
3635
3636        // reader
3637        synchronized (mPackages) {
3638            String pkgName = intent.getPackage();
3639            if (pkgName == null) {
3640                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3641            }
3642            final PackageParser.Package pkg = mPackages.get(pkgName);
3643            if (pkg != null) {
3644                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3645                        userId);
3646            }
3647            return null;
3648        }
3649    }
3650
3651    @Override
3652    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3653        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3654        if (!sUserManager.exists(userId)) return null;
3655        if (query != null) {
3656            if (query.size() >= 1) {
3657                // If there is more than one service with the same priority,
3658                // just arbitrarily pick the first one.
3659                return query.get(0);
3660            }
3661        }
3662        return null;
3663    }
3664
3665    @Override
3666    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3667            int userId) {
3668        if (!sUserManager.exists(userId)) return Collections.emptyList();
3669        ComponentName comp = intent.getComponent();
3670        if (comp == null) {
3671            if (intent.getSelector() != null) {
3672                intent = intent.getSelector();
3673                comp = intent.getComponent();
3674            }
3675        }
3676        if (comp != null) {
3677            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3678            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3679            if (si != null) {
3680                final ResolveInfo ri = new ResolveInfo();
3681                ri.serviceInfo = si;
3682                list.add(ri);
3683            }
3684            return list;
3685        }
3686
3687        // reader
3688        synchronized (mPackages) {
3689            String pkgName = intent.getPackage();
3690            if (pkgName == null) {
3691                return mServices.queryIntent(intent, resolvedType, flags, userId);
3692            }
3693            final PackageParser.Package pkg = mPackages.get(pkgName);
3694            if (pkg != null) {
3695                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3696                        userId);
3697            }
3698            return null;
3699        }
3700    }
3701
3702    @Override
3703    public List<ResolveInfo> queryIntentContentProviders(
3704            Intent intent, String resolvedType, int flags, int userId) {
3705        if (!sUserManager.exists(userId)) return Collections.emptyList();
3706        ComponentName comp = intent.getComponent();
3707        if (comp == null) {
3708            if (intent.getSelector() != null) {
3709                intent = intent.getSelector();
3710                comp = intent.getComponent();
3711            }
3712        }
3713        if (comp != null) {
3714            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3715            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3716            if (pi != null) {
3717                final ResolveInfo ri = new ResolveInfo();
3718                ri.providerInfo = pi;
3719                list.add(ri);
3720            }
3721            return list;
3722        }
3723
3724        // reader
3725        synchronized (mPackages) {
3726            String pkgName = intent.getPackage();
3727            if (pkgName == null) {
3728                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3729            }
3730            final PackageParser.Package pkg = mPackages.get(pkgName);
3731            if (pkg != null) {
3732                return mProviders.queryIntentForPackage(
3733                        intent, resolvedType, flags, pkg.providers, userId);
3734            }
3735            return null;
3736        }
3737    }
3738
3739    @Override
3740    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3741        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3742
3743        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3744
3745        // writer
3746        synchronized (mPackages) {
3747            ArrayList<PackageInfo> list;
3748            if (listUninstalled) {
3749                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3750                for (PackageSetting ps : mSettings.mPackages.values()) {
3751                    PackageInfo pi;
3752                    if (ps.pkg != null) {
3753                        pi = generatePackageInfo(ps.pkg, flags, userId);
3754                    } else {
3755                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3756                    }
3757                    if (pi != null) {
3758                        list.add(pi);
3759                    }
3760                }
3761            } else {
3762                list = new ArrayList<PackageInfo>(mPackages.size());
3763                for (PackageParser.Package p : mPackages.values()) {
3764                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3765                    if (pi != null) {
3766                        list.add(pi);
3767                    }
3768                }
3769            }
3770
3771            return new ParceledListSlice<PackageInfo>(list);
3772        }
3773    }
3774
3775    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3776            String[] permissions, boolean[] tmp, int flags, int userId) {
3777        int numMatch = 0;
3778        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3779        for (int i=0; i<permissions.length; i++) {
3780            if (gp.grantedPermissions.contains(permissions[i])) {
3781                tmp[i] = true;
3782                numMatch++;
3783            } else {
3784                tmp[i] = false;
3785            }
3786        }
3787        if (numMatch == 0) {
3788            return;
3789        }
3790        PackageInfo pi;
3791        if (ps.pkg != null) {
3792            pi = generatePackageInfo(ps.pkg, flags, userId);
3793        } else {
3794            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3795        }
3796        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3797            if (numMatch == permissions.length) {
3798                pi.requestedPermissions = permissions;
3799            } else {
3800                pi.requestedPermissions = new String[numMatch];
3801                numMatch = 0;
3802                for (int i=0; i<permissions.length; i++) {
3803                    if (tmp[i]) {
3804                        pi.requestedPermissions[numMatch] = permissions[i];
3805                        numMatch++;
3806                    }
3807                }
3808            }
3809        }
3810        list.add(pi);
3811    }
3812
3813    @Override
3814    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3815            String[] permissions, int flags, int userId) {
3816        if (!sUserManager.exists(userId)) return null;
3817        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3818
3819        // writer
3820        synchronized (mPackages) {
3821            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3822            boolean[] tmpBools = new boolean[permissions.length];
3823            if (listUninstalled) {
3824                for (PackageSetting ps : mSettings.mPackages.values()) {
3825                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3826                }
3827            } else {
3828                for (PackageParser.Package pkg : mPackages.values()) {
3829                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3830                    if (ps != null) {
3831                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3832                                userId);
3833                    }
3834                }
3835            }
3836
3837            return new ParceledListSlice<PackageInfo>(list);
3838        }
3839    }
3840
3841    @Override
3842    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3843        if (!sUserManager.exists(userId)) return null;
3844        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3845
3846        // writer
3847        synchronized (mPackages) {
3848            ArrayList<ApplicationInfo> list;
3849            if (listUninstalled) {
3850                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3851                for (PackageSetting ps : mSettings.mPackages.values()) {
3852                    ApplicationInfo ai;
3853                    if (ps.pkg != null) {
3854                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3855                                ps.readUserState(userId), userId);
3856                    } else {
3857                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3858                    }
3859                    if (ai != null) {
3860                        list.add(ai);
3861                    }
3862                }
3863            } else {
3864                list = new ArrayList<ApplicationInfo>(mPackages.size());
3865                for (PackageParser.Package p : mPackages.values()) {
3866                    if (p.mExtras != null) {
3867                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3868                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3869                        if (ai != null) {
3870                            list.add(ai);
3871                        }
3872                    }
3873                }
3874            }
3875
3876            return new ParceledListSlice<ApplicationInfo>(list);
3877        }
3878    }
3879
3880    public List<ApplicationInfo> getPersistentApplications(int flags) {
3881        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3882
3883        // reader
3884        synchronized (mPackages) {
3885            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3886            final int userId = UserHandle.getCallingUserId();
3887            while (i.hasNext()) {
3888                final PackageParser.Package p = i.next();
3889                if (p.applicationInfo != null
3890                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3891                        && (!mSafeMode || isSystemApp(p))) {
3892                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3893                    if (ps != null) {
3894                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3895                                ps.readUserState(userId), userId);
3896                        if (ai != null) {
3897                            finalList.add(ai);
3898                        }
3899                    }
3900                }
3901            }
3902        }
3903
3904        return finalList;
3905    }
3906
3907    @Override
3908    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3909        if (!sUserManager.exists(userId)) return null;
3910        // reader
3911        synchronized (mPackages) {
3912            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3913            PackageSetting ps = provider != null
3914                    ? mSettings.mPackages.get(provider.owner.packageName)
3915                    : null;
3916            return ps != null
3917                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3918                    && (!mSafeMode || (provider.info.applicationInfo.flags
3919                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3920                    ? PackageParser.generateProviderInfo(provider, flags,
3921                            ps.readUserState(userId), userId)
3922                    : null;
3923        }
3924    }
3925
3926    /**
3927     * @deprecated
3928     */
3929    @Deprecated
3930    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3931        // reader
3932        synchronized (mPackages) {
3933            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3934                    .entrySet().iterator();
3935            final int userId = UserHandle.getCallingUserId();
3936            while (i.hasNext()) {
3937                Map.Entry<String, PackageParser.Provider> entry = i.next();
3938                PackageParser.Provider p = entry.getValue();
3939                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3940
3941                if (ps != null && p.syncable
3942                        && (!mSafeMode || (p.info.applicationInfo.flags
3943                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3944                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3945                            ps.readUserState(userId), userId);
3946                    if (info != null) {
3947                        outNames.add(entry.getKey());
3948                        outInfo.add(info);
3949                    }
3950                }
3951            }
3952        }
3953    }
3954
3955    @Override
3956    public List<ProviderInfo> queryContentProviders(String processName,
3957            int uid, int flags) {
3958        ArrayList<ProviderInfo> finalList = null;
3959        // reader
3960        synchronized (mPackages) {
3961            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3962            final int userId = processName != null ?
3963                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3964            while (i.hasNext()) {
3965                final PackageParser.Provider p = i.next();
3966                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3967                if (ps != null && p.info.authority != null
3968                        && (processName == null
3969                                || (p.info.processName.equals(processName)
3970                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3971                        && mSettings.isEnabledLPr(p.info, flags, userId)
3972                        && (!mSafeMode
3973                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3974                    if (finalList == null) {
3975                        finalList = new ArrayList<ProviderInfo>(3);
3976                    }
3977                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3978                            ps.readUserState(userId), userId);
3979                    if (info != null) {
3980                        finalList.add(info);
3981                    }
3982                }
3983            }
3984        }
3985
3986        if (finalList != null) {
3987            Collections.sort(finalList, mProviderInitOrderSorter);
3988        }
3989
3990        return finalList;
3991    }
3992
3993    @Override
3994    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3995            int flags) {
3996        // reader
3997        synchronized (mPackages) {
3998            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3999            return PackageParser.generateInstrumentationInfo(i, flags);
4000        }
4001    }
4002
4003    @Override
4004    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4005            int flags) {
4006        ArrayList<InstrumentationInfo> finalList =
4007            new ArrayList<InstrumentationInfo>();
4008
4009        // reader
4010        synchronized (mPackages) {
4011            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4012            while (i.hasNext()) {
4013                final PackageParser.Instrumentation p = i.next();
4014                if (targetPackage == null
4015                        || targetPackage.equals(p.info.targetPackage)) {
4016                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4017                            flags);
4018                    if (ii != null) {
4019                        finalList.add(ii);
4020                    }
4021                }
4022            }
4023        }
4024
4025        return finalList;
4026    }
4027
4028    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4029        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4030        if (overlays == null) {
4031            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4032            return;
4033        }
4034        for (PackageParser.Package opkg : overlays.values()) {
4035            // Not much to do if idmap fails: we already logged the error
4036            // and we certainly don't want to abort installation of pkg simply
4037            // because an overlay didn't fit properly. For these reasons,
4038            // ignore the return value of createIdmapForPackagePairLI.
4039            createIdmapForPackagePairLI(pkg, opkg);
4040        }
4041    }
4042
4043    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4044            PackageParser.Package opkg) {
4045        if (!opkg.mTrustedOverlay) {
4046            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4047                    opkg.baseCodePath + ": overlay not trusted");
4048            return false;
4049        }
4050        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4051        if (overlaySet == null) {
4052            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4053                    opkg.baseCodePath + " but target package has no known overlays");
4054            return false;
4055        }
4056        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4057        // TODO: generate idmap for split APKs
4058        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4059            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4060                    + opkg.baseCodePath);
4061            return false;
4062        }
4063        PackageParser.Package[] overlayArray =
4064            overlaySet.values().toArray(new PackageParser.Package[0]);
4065        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4066            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4067                return p1.mOverlayPriority - p2.mOverlayPriority;
4068            }
4069        };
4070        Arrays.sort(overlayArray, cmp);
4071
4072        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4073        int i = 0;
4074        for (PackageParser.Package p : overlayArray) {
4075            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4076        }
4077        return true;
4078    }
4079
4080    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4081        final File[] files = dir.listFiles();
4082        if (ArrayUtils.isEmpty(files)) {
4083            Log.d(TAG, "No files in app dir " + dir);
4084            return;
4085        }
4086
4087        if (DEBUG_PACKAGE_SCANNING) {
4088            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4089                    + " flags=0x" + Integer.toHexString(flags));
4090        }
4091
4092        for (File file : files) {
4093            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4094                    && !PackageInstallerService.isStageFile(file);
4095            if (!isPackage) {
4096                // Ignore entries which are not apk's
4097                continue;
4098            }
4099            try {
4100                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
4101            } catch (PackageManagerException e) {
4102                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4103
4104                // Don't mess around with apps in system partition.
4105                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4106                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4107                    // Delete the apk
4108                    Slog.w(TAG, "Cleaning up failed install of " + file);
4109                    file.delete();
4110                }
4111            }
4112        }
4113    }
4114
4115    private static File getSettingsProblemFile() {
4116        File dataDir = Environment.getDataDirectory();
4117        File systemDir = new File(dataDir, "system");
4118        File fname = new File(systemDir, "uiderrors.txt");
4119        return fname;
4120    }
4121
4122    static void reportSettingsProblem(int priority, String msg) {
4123        try {
4124            File fname = getSettingsProblemFile();
4125            FileOutputStream out = new FileOutputStream(fname, true);
4126            PrintWriter pw = new FastPrintWriter(out);
4127            SimpleDateFormat formatter = new SimpleDateFormat();
4128            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4129            pw.println(dateString + ": " + msg);
4130            pw.close();
4131            FileUtils.setPermissions(
4132                    fname.toString(),
4133                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4134                    -1, -1);
4135        } catch (java.io.IOException e) {
4136        }
4137        Slog.println(priority, TAG, msg);
4138    }
4139
4140    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4141            PackageParser.Package pkg, File srcFile, int parseFlags)
4142            throws PackageManagerException {
4143        if (ps != null
4144                && ps.codePath.equals(srcFile)
4145                && ps.timeStamp == srcFile.lastModified()
4146                && !isCompatSignatureUpdateNeeded(pkg)) {
4147            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4148            if (ps.signatures.mSignatures != null
4149                    && ps.signatures.mSignatures.length != 0
4150                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4151                // Optimization: reuse the existing cached certificates
4152                // if the package appears to be unchanged.
4153                pkg.mSignatures = ps.signatures.mSignatures;
4154                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4155                synchronized (mPackages) {
4156                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4157                }
4158                return;
4159            }
4160
4161            Slog.w(TAG, "PackageSetting for " + ps.name
4162                    + " is missing signatures.  Collecting certs again to recover them.");
4163        } else {
4164            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4165        }
4166
4167        try {
4168            pp.collectCertificates(pkg, parseFlags);
4169            pp.collectManifestDigest(pkg);
4170        } catch (PackageParserException e) {
4171            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4172                    + pkg.packageName + ": " + e.getMessage());
4173        }
4174    }
4175
4176    /*
4177     *  Scan a package and return the newly parsed package.
4178     *  Returns null in case of errors and the error code is stored in mLastScanError
4179     */
4180    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4181            long currentTime, UserHandle user) throws PackageManagerException {
4182        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4183        parseFlags |= mDefParseFlags;
4184        PackageParser pp = new PackageParser();
4185        pp.setSeparateProcesses(mSeparateProcesses);
4186        pp.setOnlyCoreApps(mOnlyCore);
4187        pp.setDisplayMetrics(mMetrics);
4188
4189        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4190            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4191        }
4192
4193        final PackageParser.Package pkg;
4194        try {
4195            pkg = pp.parsePackage(scanFile, parseFlags);
4196        } catch (PackageParserException e) {
4197            throw new PackageManagerException(e.error,
4198                    "Failed to scan " + scanFile + ": " + e.getMessage());
4199        }
4200
4201        PackageSetting ps = null;
4202        PackageSetting updatedPkg;
4203        // reader
4204        synchronized (mPackages) {
4205            // Look to see if we already know about this package.
4206            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4207            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4208                // This package has been renamed to its original name.  Let's
4209                // use that.
4210                ps = mSettings.peekPackageLPr(oldName);
4211            }
4212            // If there was no original package, see one for the real package name.
4213            if (ps == null) {
4214                ps = mSettings.peekPackageLPr(pkg.packageName);
4215            }
4216            // Check to see if this package could be hiding/updating a system
4217            // package.  Must look for it either under the original or real
4218            // package name depending on our state.
4219            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4220            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4221        }
4222        boolean updatedPkgBetter = false;
4223        // First check if this is a system package that may involve an update
4224        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4225            if (ps != null && !ps.codePath.equals(scanFile)) {
4226                // The path has changed from what was last scanned...  check the
4227                // version of the new path against what we have stored to determine
4228                // what to do.
4229                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4230                if (pkg.mVersionCode < ps.versionCode) {
4231                    // The system package has been updated and the code path does not match
4232                    // Ignore entry. Skip it.
4233                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4234                            + " ignored: updated version " + ps.versionCode
4235                            + " better than this " + pkg.mVersionCode);
4236                    if (!updatedPkg.codePath.equals(scanFile)) {
4237                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4238                                + ps.name + " changing from " + updatedPkg.codePathString
4239                                + " to " + scanFile);
4240                        updatedPkg.codePath = scanFile;
4241                        updatedPkg.codePathString = scanFile.toString();
4242                        // This is the point at which we know that the system-disk APK
4243                        // for this package has moved during a reboot (e.g. due to an OTA),
4244                        // so we need to reevaluate it for privilege policy.
4245                        if (locationIsPrivileged(scanFile)) {
4246                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4247                        }
4248                    }
4249                    updatedPkg.pkg = pkg;
4250                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4251                } else {
4252                    // The current app on the system partition is better than
4253                    // what we have updated to on the data partition; switch
4254                    // back to the system partition version.
4255                    // At this point, its safely assumed that package installation for
4256                    // apps in system partition will go through. If not there won't be a working
4257                    // version of the app
4258                    // writer
4259                    synchronized (mPackages) {
4260                        // Just remove the loaded entries from package lists.
4261                        mPackages.remove(ps.name);
4262                    }
4263                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4264                            + "reverting from " + ps.codePathString
4265                            + ": new version " + pkg.mVersionCode
4266                            + " better than installed " + ps.versionCode);
4267
4268                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4269                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4270                            getAppDexInstructionSets(ps), isMultiArch(ps));
4271                    synchronized (mInstallLock) {
4272                        args.cleanUpResourcesLI();
4273                    }
4274                    synchronized (mPackages) {
4275                        mSettings.enableSystemPackageLPw(ps.name);
4276                    }
4277                    updatedPkgBetter = true;
4278                }
4279            }
4280        }
4281
4282        if (updatedPkg != null) {
4283            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4284            // initially
4285            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4286
4287            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4288            // flag set initially
4289            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4290                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4291            }
4292        }
4293
4294        // Verify certificates against what was last scanned
4295        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4296
4297        /*
4298         * A new system app appeared, but we already had a non-system one of the
4299         * same name installed earlier.
4300         */
4301        boolean shouldHideSystemApp = false;
4302        if (updatedPkg == null && ps != null
4303                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4304            /*
4305             * Check to make sure the signatures match first. If they don't,
4306             * wipe the installed application and its data.
4307             */
4308            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4309                    != PackageManager.SIGNATURE_MATCH) {
4310                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4311                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4312                ps = null;
4313            } else {
4314                /*
4315                 * If the newly-added system app is an older version than the
4316                 * already installed version, hide it. It will be scanned later
4317                 * and re-added like an update.
4318                 */
4319                if (pkg.mVersionCode < ps.versionCode) {
4320                    shouldHideSystemApp = true;
4321                } else {
4322                    /*
4323                     * The newly found system app is a newer version that the
4324                     * one previously installed. Simply remove the
4325                     * already-installed application and replace it with our own
4326                     * while keeping the application data.
4327                     */
4328                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4329                            + ps.codePathString + ": new version " + pkg.mVersionCode
4330                            + " better than installed " + ps.versionCode);
4331                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4332                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4333                            getAppDexInstructionSets(ps), isMultiArch(ps));
4334                    synchronized (mInstallLock) {
4335                        args.cleanUpResourcesLI();
4336                    }
4337                }
4338            }
4339        }
4340
4341        // The apk is forward locked (not public) if its code and resources
4342        // are kept in different files. (except for app in either system or
4343        // vendor path).
4344        // TODO grab this value from PackageSettings
4345        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4346            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4347                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4348            }
4349        }
4350
4351        // TODO: extend to support forward-locked splits
4352        String resourcePath = null;
4353        String baseResourcePath = null;
4354        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4355            if (ps != null && ps.resourcePathString != null) {
4356                resourcePath = ps.resourcePathString;
4357                baseResourcePath = ps.resourcePathString;
4358            } else {
4359                // Should not happen at all. Just log an error.
4360                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4361            }
4362        } else {
4363            resourcePath = pkg.codePath;
4364            baseResourcePath = pkg.baseCodePath;
4365        }
4366
4367        // Set application objects path explicitly.
4368        pkg.applicationInfo.setCodePath(pkg.codePath);
4369        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4370        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4371        pkg.applicationInfo.setResourcePath(resourcePath);
4372        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4373        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4374
4375        // Note that we invoke the following method only if we are about to unpack an application
4376        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4377                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4378
4379        /*
4380         * If the system app should be overridden by a previously installed
4381         * data, hide the system app now and let the /data/app scan pick it up
4382         * again.
4383         */
4384        if (shouldHideSystemApp) {
4385            synchronized (mPackages) {
4386                /*
4387                 * We have to grant systems permissions before we hide, because
4388                 * grantPermissions will assume the package update is trying to
4389                 * expand its permissions.
4390                 */
4391                grantPermissionsLPw(pkg, true);
4392                mSettings.disableSystemPackageLPw(pkg.packageName);
4393            }
4394        }
4395
4396        return scannedPkg;
4397    }
4398
4399    private static String fixProcessName(String defProcessName,
4400            String processName, int uid) {
4401        if (processName == null) {
4402            return defProcessName;
4403        }
4404        return processName;
4405    }
4406
4407    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4408            throws PackageManagerException {
4409        if (pkgSetting.signatures.mSignatures != null) {
4410            // Already existing package. Make sure signatures match
4411            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4412                    == PackageManager.SIGNATURE_MATCH;
4413            if (!match) {
4414                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4415                        == PackageManager.SIGNATURE_MATCH;
4416            }
4417            if (!match) {
4418                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4419                        + pkg.packageName + " signatures do not match the "
4420                        + "previously installed version; ignoring!");
4421            }
4422        }
4423
4424        // Check for shared user signatures
4425        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4426            // Already existing package. Make sure signatures match
4427            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4428                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4429            if (!match) {
4430                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4431                        == PackageManager.SIGNATURE_MATCH;
4432            }
4433            if (!match) {
4434                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4435                        "Package " + pkg.packageName
4436                        + " has no signatures that match those in shared user "
4437                        + pkgSetting.sharedUser.name + "; ignoring!");
4438            }
4439        }
4440    }
4441
4442    /**
4443     * Enforces that only the system UID or root's UID can call a method exposed
4444     * via Binder.
4445     *
4446     * @param message used as message if SecurityException is thrown
4447     * @throws SecurityException if the caller is not system or root
4448     */
4449    private static final void enforceSystemOrRoot(String message) {
4450        final int uid = Binder.getCallingUid();
4451        if (uid != Process.SYSTEM_UID && uid != 0) {
4452            throw new SecurityException(message);
4453        }
4454    }
4455
4456    @Override
4457    public void performBootDexOpt() {
4458        enforceSystemOrRoot("Only the system can request dexopt be performed");
4459
4460        final HashSet<PackageParser.Package> pkgs;
4461        synchronized (mPackages) {
4462            pkgs = mDeferredDexOpt;
4463            mDeferredDexOpt = null;
4464        }
4465
4466        if (pkgs != null) {
4467            // Filter out packages that aren't recently used.
4468            //
4469            // The exception is first boot of a non-eng device, which
4470            // should do a full dexopt.
4471            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4472            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4473                // TODO: add a property to control this?
4474                long dexOptLRUThresholdInMinutes;
4475                if (eng) {
4476                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4477                } else {
4478                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4479                }
4480                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4481
4482                int total = pkgs.size();
4483                int skipped = 0;
4484                long now = System.currentTimeMillis();
4485                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4486                    PackageParser.Package pkg = i.next();
4487                    long then = pkg.mLastPackageUsageTimeInMills;
4488                    if (then + dexOptLRUThresholdInMills < now) {
4489                        if (DEBUG_DEXOPT) {
4490                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4491                                  ((then == 0) ? "never" : new Date(then)));
4492                        }
4493                        i.remove();
4494                        skipped++;
4495                    }
4496                }
4497                if (DEBUG_DEXOPT) {
4498                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4499                }
4500            }
4501
4502            int i = 0;
4503            for (PackageParser.Package pkg : pkgs) {
4504                i++;
4505                if (DEBUG_DEXOPT) {
4506                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4507                          + ": " + pkg.packageName);
4508                }
4509                if (!isFirstBoot()) {
4510                    try {
4511                        ActivityManagerNative.getDefault().showBootMessage(
4512                                mContext.getResources().getString(
4513                                        R.string.android_upgrading_apk,
4514                                        i, pkgs.size()), true);
4515                    } catch (RemoteException e) {
4516                    }
4517                }
4518                PackageParser.Package p = pkg;
4519                synchronized (mInstallLock) {
4520                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4521                            true /* include dependencies */);
4522                }
4523            }
4524        }
4525    }
4526
4527    @Override
4528    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4529        return performDexOpt(packageName, instructionSet, true);
4530    }
4531
4532    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4533        if (info.primaryCpuAbi == null) {
4534            return getPreferredInstructionSet();
4535        }
4536
4537        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4538    }
4539
4540    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4541        PackageParser.Package p;
4542        final String targetInstructionSet;
4543        synchronized (mPackages) {
4544            p = mPackages.get(packageName);
4545            if (p == null) {
4546                return false;
4547            }
4548            if (updateUsage) {
4549                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4550            }
4551            mPackageUsage.write(false);
4552
4553            targetInstructionSet = instructionSet != null ? instructionSet :
4554                    getPrimaryInstructionSet(p.applicationInfo);
4555            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4556                return false;
4557            }
4558        }
4559
4560        synchronized (mInstallLock) {
4561            final String[] instructionSets = new String[] { targetInstructionSet };
4562            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4563                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4564        }
4565    }
4566
4567    public HashSet<String> getPackagesThatNeedDexOpt() {
4568        HashSet<String> pkgs = null;
4569        synchronized (mPackages) {
4570            for (PackageParser.Package p : mPackages.values()) {
4571                if (DEBUG_DEXOPT) {
4572                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4573                }
4574                if (!p.mDexOptPerformed.isEmpty()) {
4575                    continue;
4576                }
4577                if (pkgs == null) {
4578                    pkgs = new HashSet<String>();
4579                }
4580                pkgs.add(p.packageName);
4581            }
4582        }
4583        return pkgs;
4584    }
4585
4586    public void shutdown() {
4587        mPackageUsage.write(true);
4588    }
4589
4590    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4591             boolean forceDex, boolean defer, HashSet<String> done) {
4592        for (int i=0; i<libs.size(); i++) {
4593            PackageParser.Package libPkg;
4594            String libName;
4595            synchronized (mPackages) {
4596                libName = libs.get(i);
4597                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4598                if (lib != null && lib.apk != null) {
4599                    libPkg = mPackages.get(lib.apk);
4600                } else {
4601                    libPkg = null;
4602                }
4603            }
4604            if (libPkg != null && !done.contains(libName)) {
4605                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4606            }
4607        }
4608    }
4609
4610    static final int DEX_OPT_SKIPPED = 0;
4611    static final int DEX_OPT_PERFORMED = 1;
4612    static final int DEX_OPT_DEFERRED = 2;
4613    static final int DEX_OPT_FAILED = -1;
4614
4615    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4616            boolean forceDex, boolean defer, HashSet<String> done) {
4617        final String[] instructionSets = targetInstructionSets != null ?
4618                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4619
4620        if (done != null) {
4621            done.add(pkg.packageName);
4622            if (pkg.usesLibraries != null) {
4623                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4624            }
4625            if (pkg.usesOptionalLibraries != null) {
4626                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4627            }
4628        }
4629
4630        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4631            return DEX_OPT_SKIPPED;
4632        }
4633
4634        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4635        boolean performedDexOpt = false;
4636        // There are three basic cases here:
4637        // 1.) we need to dexopt, either because we are forced or it is needed
4638        // 2.) we are defering a needed dexopt
4639        // 3.) we are skipping an unneeded dexopt
4640        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4641        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4642            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4643                continue;
4644            }
4645
4646            for (String path : paths) {
4647                try {
4648                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4649                    // patckage or the one we find does not match the image checksum (i.e. it was
4650                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4651                    // odex file and it matches the checksum of the image but not its base address,
4652                    // meaning we need to move it.
4653                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4654                            pkg.packageName, dexCodeInstructionSet, defer);
4655                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4656                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4657                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet);
4658                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4659                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4660                                pkg.packageName, dexCodeInstructionSet);
4661
4662                        if (ret < 0) {
4663                            // Don't bother running dexopt again if we failed, it will probably
4664                            // just result in an error again. Also, don't bother dexopting for other
4665                            // paths & ISAs.
4666                            return DEX_OPT_FAILED;
4667                        }
4668
4669                        performedDexOpt = true;
4670                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4671                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4672                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4673                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4674                                pkg.packageName, dexCodeInstructionSet);
4675
4676                        if (ret < 0) {
4677                            // Don't bother running patchoat again if we failed, it will probably
4678                            // just result in an error again. Also, don't bother dexopting for other
4679                            // paths & ISAs.
4680                            return DEX_OPT_FAILED;
4681                        }
4682
4683                        performedDexOpt = true;
4684                    }
4685
4686                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4687                    // paths and instruction sets. We'll deal with them all together when we process
4688                    // our list of deferred dexopts.
4689                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4690                        if (mDeferredDexOpt == null) {
4691                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4692                        }
4693                        mDeferredDexOpt.add(pkg);
4694                        return DEX_OPT_DEFERRED;
4695                    }
4696                } catch (FileNotFoundException e) {
4697                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4698                    return DEX_OPT_FAILED;
4699                } catch (IOException e) {
4700                    Slog.w(TAG, "IOException reading apk: " + path, e);
4701                    return DEX_OPT_FAILED;
4702                } catch (StaleDexCacheError e) {
4703                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4704                    return DEX_OPT_FAILED;
4705                } catch (Exception e) {
4706                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4707                    return DEX_OPT_FAILED;
4708                }
4709            }
4710
4711            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4712            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4713            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4714            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4715            // it.
4716            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4717        }
4718
4719        // If we've gotten here, we're sure that no error occurred and that we haven't
4720        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4721        // we've skipped all of them because they are up to date. In both cases this
4722        // package doesn't need dexopt any longer.
4723        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4724    }
4725
4726    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4727        if (info.primaryCpuAbi != null) {
4728            if (info.secondaryCpuAbi != null) {
4729                return new String[] {
4730                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4731                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4732            } else {
4733                return new String[] {
4734                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4735            }
4736        }
4737
4738        return new String[] { getPreferredInstructionSet() };
4739    }
4740
4741    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4742        if (ps.primaryCpuAbiString != null) {
4743            if (ps.secondaryCpuAbiString != null) {
4744                return new String[] {
4745                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4746                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4747            } else {
4748                return new String[] {
4749                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4750            }
4751        }
4752
4753        return new String[] { getPreferredInstructionSet() };
4754    }
4755
4756    private static String getPreferredInstructionSet() {
4757        if (sPreferredInstructionSet == null) {
4758            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4759        }
4760
4761        return sPreferredInstructionSet;
4762    }
4763
4764    private static List<String> getAllInstructionSets() {
4765        final String[] allAbis = Build.SUPPORTED_ABIS;
4766        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4767
4768        for (String abi : allAbis) {
4769            final String instructionSet = VMRuntime.getInstructionSet(abi);
4770            if (!allInstructionSets.contains(instructionSet)) {
4771                allInstructionSets.add(instructionSet);
4772            }
4773        }
4774
4775        return allInstructionSets;
4776    }
4777
4778    /**
4779     * Returns the instruction set that should be used to compile dex code. In the presence of
4780     * a native bridge this might be different than the one shared libraries use.
4781     */
4782    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4783        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4784        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4785    }
4786
4787    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4788        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4789        for (String instructionSet : instructionSets) {
4790            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4791        }
4792        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4793    }
4794
4795    @Override
4796    public void forceDexOpt(String packageName) {
4797        enforceSystemOrRoot("forceDexOpt");
4798
4799        PackageParser.Package pkg;
4800        synchronized (mPackages) {
4801            pkg = mPackages.get(packageName);
4802            if (pkg == null) {
4803                throw new IllegalArgumentException("Missing package: " + packageName);
4804            }
4805        }
4806
4807        synchronized (mInstallLock) {
4808            final String[] instructionSets = new String[] {
4809                    getPrimaryInstructionSet(pkg.applicationInfo) };
4810            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4811            if (res != DEX_OPT_PERFORMED) {
4812                throw new IllegalStateException("Failed to dexopt: " + res);
4813            }
4814        }
4815    }
4816
4817    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4818                                boolean forceDex, boolean defer, boolean inclDependencies) {
4819        HashSet<String> done;
4820        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4821            done = new HashSet<String>();
4822            done.add(pkg.packageName);
4823        } else {
4824            done = null;
4825        }
4826        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4827    }
4828
4829    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4830        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4831            Slog.w(TAG, "Unable to update from " + oldPkg.name
4832                    + " to " + newPkg.packageName
4833                    + ": old package not in system partition");
4834            return false;
4835        } else if (mPackages.get(oldPkg.name) != null) {
4836            Slog.w(TAG, "Unable to update from " + oldPkg.name
4837                    + " to " + newPkg.packageName
4838                    + ": old package still exists");
4839            return false;
4840        }
4841        return true;
4842    }
4843
4844    File getDataPathForUser(int userId) {
4845        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4846    }
4847
4848    private File getDataPathForPackage(String packageName, int userId) {
4849        /*
4850         * Until we fully support multiple users, return the directory we
4851         * previously would have. The PackageManagerTests will need to be
4852         * revised when this is changed back..
4853         */
4854        if (userId == 0) {
4855            return new File(mAppDataDir, packageName);
4856        } else {
4857            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4858                + File.separator + packageName);
4859        }
4860    }
4861
4862    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4863        int[] users = sUserManager.getUserIds();
4864        int res = mInstaller.install(packageName, uid, uid, seinfo);
4865        if (res < 0) {
4866            return res;
4867        }
4868        for (int user : users) {
4869            if (user != 0) {
4870                res = mInstaller.createUserData(packageName,
4871                        UserHandle.getUid(user, uid), user, seinfo);
4872                if (res < 0) {
4873                    return res;
4874                }
4875            }
4876        }
4877        return res;
4878    }
4879
4880    private int removeDataDirsLI(String packageName) {
4881        int[] users = sUserManager.getUserIds();
4882        int res = 0;
4883        for (int user : users) {
4884            int resInner = mInstaller.remove(packageName, user);
4885            if (resInner < 0) {
4886                res = resInner;
4887            }
4888        }
4889
4890        return res;
4891    }
4892
4893    private int deleteCodeCacheDirsLI(String packageName) {
4894        int[] users = sUserManager.getUserIds();
4895        int res = 0;
4896        for (int user : users) {
4897            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4898            if (resInner < 0) {
4899                res = resInner;
4900            }
4901        }
4902        return res;
4903    }
4904
4905    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4906            PackageParser.Package changingLib) {
4907        if (file.path != null) {
4908            usesLibraryFiles.add(file.path);
4909            return;
4910        }
4911        PackageParser.Package p = mPackages.get(file.apk);
4912        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4913            // If we are doing this while in the middle of updating a library apk,
4914            // then we need to make sure to use that new apk for determining the
4915            // dependencies here.  (We haven't yet finished committing the new apk
4916            // to the package manager state.)
4917            if (p == null || p.packageName.equals(changingLib.packageName)) {
4918                p = changingLib;
4919            }
4920        }
4921        if (p != null) {
4922            usesLibraryFiles.addAll(p.getAllCodePaths());
4923        }
4924    }
4925
4926    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4927            PackageParser.Package changingLib) throws PackageManagerException {
4928        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4929            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4930            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4931            for (int i=0; i<N; i++) {
4932                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4933                if (file == null) {
4934                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4935                            "Package " + pkg.packageName + " requires unavailable shared library "
4936                            + pkg.usesLibraries.get(i) + "; failing!");
4937                }
4938                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4939            }
4940            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4941            for (int i=0; i<N; i++) {
4942                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4943                if (file == null) {
4944                    Slog.w(TAG, "Package " + pkg.packageName
4945                            + " desires unavailable shared library "
4946                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4947                } else {
4948                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4949                }
4950            }
4951            N = usesLibraryFiles.size();
4952            if (N > 0) {
4953                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4954            } else {
4955                pkg.usesLibraryFiles = null;
4956            }
4957        }
4958    }
4959
4960    private static boolean hasString(List<String> list, List<String> which) {
4961        if (list == null) {
4962            return false;
4963        }
4964        for (int i=list.size()-1; i>=0; i--) {
4965            for (int j=which.size()-1; j>=0; j--) {
4966                if (which.get(j).equals(list.get(i))) {
4967                    return true;
4968                }
4969            }
4970        }
4971        return false;
4972    }
4973
4974    private void updateAllSharedLibrariesLPw() {
4975        for (PackageParser.Package pkg : mPackages.values()) {
4976            try {
4977                updateSharedLibrariesLPw(pkg, null);
4978            } catch (PackageManagerException e) {
4979                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4980            }
4981        }
4982    }
4983
4984    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4985            PackageParser.Package changingPkg) {
4986        ArrayList<PackageParser.Package> res = null;
4987        for (PackageParser.Package pkg : mPackages.values()) {
4988            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4989                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4990                if (res == null) {
4991                    res = new ArrayList<PackageParser.Package>();
4992                }
4993                res.add(pkg);
4994                try {
4995                    updateSharedLibrariesLPw(pkg, changingPkg);
4996                } catch (PackageManagerException e) {
4997                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4998                }
4999            }
5000        }
5001        return res;
5002    }
5003
5004    /**
5005     * Derive the value of the {@code cpuAbiOverride} based on the provided
5006     * value and an optional stored value from the package settings.
5007     */
5008    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5009        String cpuAbiOverride = null;
5010
5011        if (CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5012            cpuAbiOverride = null;
5013        } else if (abiOverride != null) {
5014            cpuAbiOverride = abiOverride;
5015        } else if (settings != null) {
5016            cpuAbiOverride = settings.cpuAbiOverrideString;
5017        }
5018
5019        return cpuAbiOverride;
5020    }
5021
5022    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5023            int scanMode, long currentTime, UserHandle user)
5024            throws PackageManagerException {
5025        final File scanFile = new File(pkg.codePath);
5026        if (pkg.applicationInfo.getCodePath() == null ||
5027                pkg.applicationInfo.getResourcePath() == null) {
5028            // Bail out. The resource and code paths haven't been set.
5029            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5030                    "Code and resource paths haven't been set correctly");
5031        }
5032
5033        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5034            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5035        }
5036
5037        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5038            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5039        }
5040
5041        if (mCustomResolverComponentName != null &&
5042                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5043            setUpCustomResolverActivity(pkg);
5044        }
5045
5046        if (pkg.packageName.equals("android")) {
5047            synchronized (mPackages) {
5048                if (mAndroidApplication != null) {
5049                    Slog.w(TAG, "*************************************************");
5050                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5051                    Slog.w(TAG, " file=" + scanFile);
5052                    Slog.w(TAG, "*************************************************");
5053                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5054                            "Core android package being redefined.  Skipping.");
5055                }
5056
5057                // Set up information for our fall-back user intent resolution activity.
5058                mPlatformPackage = pkg;
5059                pkg.mVersionCode = mSdkVersion;
5060                mAndroidApplication = pkg.applicationInfo;
5061
5062                if (!mResolverReplaced) {
5063                    mResolveActivity.applicationInfo = mAndroidApplication;
5064                    mResolveActivity.name = ResolverActivity.class.getName();
5065                    mResolveActivity.packageName = mAndroidApplication.packageName;
5066                    mResolveActivity.processName = "system:ui";
5067                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5068                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5069                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5070                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5071                    mResolveActivity.exported = true;
5072                    mResolveActivity.enabled = true;
5073                    mResolveInfo.activityInfo = mResolveActivity;
5074                    mResolveInfo.priority = 0;
5075                    mResolveInfo.preferredOrder = 0;
5076                    mResolveInfo.match = 0;
5077                    mResolveComponentName = new ComponentName(
5078                            mAndroidApplication.packageName, mResolveActivity.name);
5079                }
5080            }
5081        }
5082
5083        if (DEBUG_PACKAGE_SCANNING) {
5084            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5085                Log.d(TAG, "Scanning package " + pkg.packageName);
5086        }
5087
5088        if (mPackages.containsKey(pkg.packageName)
5089                || mSharedLibraries.containsKey(pkg.packageName)) {
5090            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5091                    "Application package " + pkg.packageName
5092                    + " already installed.  Skipping duplicate.");
5093        }
5094
5095        // Initialize package source and resource directories
5096        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5097        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5098
5099        SharedUserSetting suid = null;
5100        PackageSetting pkgSetting = null;
5101
5102        if (!isSystemApp(pkg)) {
5103            // Only system apps can use these features.
5104            pkg.mOriginalPackages = null;
5105            pkg.mRealPackage = null;
5106            pkg.mAdoptPermissions = null;
5107        }
5108
5109        // writer
5110        synchronized (mPackages) {
5111            if (pkg.mSharedUserId != null) {
5112                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5113                if (suid == null) {
5114                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5115                            "Creating application package " + pkg.packageName
5116                            + " for shared user failed");
5117                }
5118                if (DEBUG_PACKAGE_SCANNING) {
5119                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5120                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5121                                + "): packages=" + suid.packages);
5122                }
5123            }
5124
5125            // Check if we are renaming from an original package name.
5126            PackageSetting origPackage = null;
5127            String realName = null;
5128            if (pkg.mOriginalPackages != null) {
5129                // This package may need to be renamed to a previously
5130                // installed name.  Let's check on that...
5131                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5132                if (pkg.mOriginalPackages.contains(renamed)) {
5133                    // This package had originally been installed as the
5134                    // original name, and we have already taken care of
5135                    // transitioning to the new one.  Just update the new
5136                    // one to continue using the old name.
5137                    realName = pkg.mRealPackage;
5138                    if (!pkg.packageName.equals(renamed)) {
5139                        // Callers into this function may have already taken
5140                        // care of renaming the package; only do it here if
5141                        // it is not already done.
5142                        pkg.setPackageName(renamed);
5143                    }
5144
5145                } else {
5146                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5147                        if ((origPackage = mSettings.peekPackageLPr(
5148                                pkg.mOriginalPackages.get(i))) != null) {
5149                            // We do have the package already installed under its
5150                            // original name...  should we use it?
5151                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5152                                // New package is not compatible with original.
5153                                origPackage = null;
5154                                continue;
5155                            } else if (origPackage.sharedUser != null) {
5156                                // Make sure uid is compatible between packages.
5157                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5158                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5159                                            + " to " + pkg.packageName + ": old uid "
5160                                            + origPackage.sharedUser.name
5161                                            + " differs from " + pkg.mSharedUserId);
5162                                    origPackage = null;
5163                                    continue;
5164                                }
5165                            } else {
5166                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5167                                        + pkg.packageName + " to old name " + origPackage.name);
5168                            }
5169                            break;
5170                        }
5171                    }
5172                }
5173            }
5174
5175            if (mTransferedPackages.contains(pkg.packageName)) {
5176                Slog.w(TAG, "Package " + pkg.packageName
5177                        + " was transferred to another, but its .apk remains");
5178            }
5179
5180            // Just create the setting, don't add it yet. For already existing packages
5181            // the PkgSetting exists already and doesn't have to be created.
5182            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5183                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5184                    pkg.applicationInfo.primaryCpuAbi,
5185                    pkg.applicationInfo.secondaryCpuAbi,
5186                    pkg.applicationInfo.flags, user, false);
5187            if (pkgSetting == null) {
5188                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5189                        "Creating application package " + pkg.packageName + " failed");
5190            }
5191
5192            if (pkgSetting.origPackage != null) {
5193                // If we are first transitioning from an original package,
5194                // fix up the new package's name now.  We need to do this after
5195                // looking up the package under its new name, so getPackageLP
5196                // can take care of fiddling things correctly.
5197                pkg.setPackageName(origPackage.name);
5198
5199                // File a report about this.
5200                String msg = "New package " + pkgSetting.realName
5201                        + " renamed to replace old package " + pkgSetting.name;
5202                reportSettingsProblem(Log.WARN, msg);
5203
5204                // Make a note of it.
5205                mTransferedPackages.add(origPackage.name);
5206
5207                // No longer need to retain this.
5208                pkgSetting.origPackage = null;
5209            }
5210
5211            if (realName != null) {
5212                // Make a note of it.
5213                mTransferedPackages.add(pkg.packageName);
5214            }
5215
5216            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5217                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5218            }
5219
5220            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5221                // Check all shared libraries and map to their actual file path.
5222                // We only do this here for apps not on a system dir, because those
5223                // are the only ones that can fail an install due to this.  We
5224                // will take care of the system apps by updating all of their
5225                // library paths after the scan is done.
5226                updateSharedLibrariesLPw(pkg, null);
5227            }
5228
5229            if (mFoundPolicyFile) {
5230                SELinuxMMAC.assignSeinfoValue(pkg);
5231            }
5232
5233            pkg.applicationInfo.uid = pkgSetting.appId;
5234            pkg.mExtras = pkgSetting;
5235            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5236                try {
5237                    verifySignaturesLP(pkgSetting, pkg);
5238                } catch (PackageManagerException e) {
5239                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5240                        throw e;
5241                    }
5242                    // The signature has changed, but this package is in the system
5243                    // image...  let's recover!
5244                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5245                    // However...  if this package is part of a shared user, but it
5246                    // doesn't match the signature of the shared user, let's fail.
5247                    // What this means is that you can't change the signatures
5248                    // associated with an overall shared user, which doesn't seem all
5249                    // that unreasonable.
5250                    if (pkgSetting.sharedUser != null) {
5251                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5252                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5253                            throw new PackageManagerException(
5254                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5255                                            "Signature mismatch for shared user : "
5256                                            + pkgSetting.sharedUser);
5257                        }
5258                    }
5259                    // File a report about this.
5260                    String msg = "System package " + pkg.packageName
5261                        + " signature changed; retaining data.";
5262                    reportSettingsProblem(Log.WARN, msg);
5263                }
5264            } else {
5265                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5266                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5267                            + pkg.packageName + " upgrade keys do not match the "
5268                            + "previously installed version");
5269                } else {
5270                    // signatures may have changed as result of upgrade
5271                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5272                }
5273            }
5274            // Verify that this new package doesn't have any content providers
5275            // that conflict with existing packages.  Only do this if the
5276            // package isn't already installed, since we don't want to break
5277            // things that are installed.
5278            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5279                final int N = pkg.providers.size();
5280                int i;
5281                for (i=0; i<N; i++) {
5282                    PackageParser.Provider p = pkg.providers.get(i);
5283                    if (p.info.authority != null) {
5284                        String names[] = p.info.authority.split(";");
5285                        for (int j = 0; j < names.length; j++) {
5286                            if (mProvidersByAuthority.containsKey(names[j])) {
5287                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5288                                final String otherPackageName =
5289                                        ((other != null && other.getComponentName() != null) ?
5290                                                other.getComponentName().getPackageName() : "?");
5291                                throw new PackageManagerException(
5292                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5293                                                "Can't install because provider name " + names[j]
5294                                                + " (in package " + pkg.applicationInfo.packageName
5295                                                + ") is already used by " + otherPackageName);
5296                            }
5297                        }
5298                    }
5299                }
5300            }
5301
5302            if (pkg.mAdoptPermissions != null) {
5303                // This package wants to adopt ownership of permissions from
5304                // another package.
5305                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5306                    final String origName = pkg.mAdoptPermissions.get(i);
5307                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5308                    if (orig != null) {
5309                        if (verifyPackageUpdateLPr(orig, pkg)) {
5310                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5311                                    + pkg.packageName);
5312                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5313                        }
5314                    }
5315                }
5316            }
5317        }
5318
5319        final String pkgName = pkg.packageName;
5320
5321        final long scanFileTime = scanFile.lastModified();
5322        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5323        pkg.applicationInfo.processName = fixProcessName(
5324                pkg.applicationInfo.packageName,
5325                pkg.applicationInfo.processName,
5326                pkg.applicationInfo.uid);
5327
5328        File dataPath;
5329        if (mPlatformPackage == pkg) {
5330            // The system package is special.
5331            dataPath = new File (Environment.getDataDirectory(), "system");
5332            pkg.applicationInfo.dataDir = dataPath.getPath();
5333
5334        } else {
5335            // This is a normal package, need to make its data directory.
5336            dataPath = getDataPathForPackage(pkg.packageName, 0);
5337
5338            boolean uidError = false;
5339
5340            if (dataPath.exists()) {
5341                int currentUid = 0;
5342                try {
5343                    StructStat stat = Os.stat(dataPath.getPath());
5344                    currentUid = stat.st_uid;
5345                } catch (ErrnoException e) {
5346                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5347                }
5348
5349                // If we have mismatched owners for the data path, we have a problem.
5350                if (currentUid != pkg.applicationInfo.uid) {
5351                    boolean recovered = false;
5352                    if (currentUid == 0) {
5353                        // The directory somehow became owned by root.  Wow.
5354                        // This is probably because the system was stopped while
5355                        // installd was in the middle of messing with its libs
5356                        // directory.  Ask installd to fix that.
5357                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5358                                pkg.applicationInfo.uid);
5359                        if (ret >= 0) {
5360                            recovered = true;
5361                            String msg = "Package " + pkg.packageName
5362                                    + " unexpectedly changed to uid 0; recovered to " +
5363                                    + pkg.applicationInfo.uid;
5364                            reportSettingsProblem(Log.WARN, msg);
5365                        }
5366                    }
5367                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5368                            || (scanMode&SCAN_BOOTING) != 0)) {
5369                        // If this is a system app, we can at least delete its
5370                        // current data so the application will still work.
5371                        int ret = removeDataDirsLI(pkgName);
5372                        if (ret >= 0) {
5373                            // TODO: Kill the processes first
5374                            // Old data gone!
5375                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5376                                    ? "System package " : "Third party package ";
5377                            String msg = prefix + pkg.packageName
5378                                    + " has changed from uid: "
5379                                    + currentUid + " to "
5380                                    + pkg.applicationInfo.uid + "; old data erased";
5381                            reportSettingsProblem(Log.WARN, msg);
5382                            recovered = true;
5383
5384                            // And now re-install the app.
5385                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5386                                                   pkg.applicationInfo.seinfo);
5387                            if (ret == -1) {
5388                                // Ack should not happen!
5389                                msg = prefix + pkg.packageName
5390                                        + " could not have data directory re-created after delete.";
5391                                reportSettingsProblem(Log.WARN, msg);
5392                                throw new PackageManagerException(
5393                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5394                            }
5395                        }
5396                        if (!recovered) {
5397                            mHasSystemUidErrors = true;
5398                        }
5399                    } else if (!recovered) {
5400                        // If we allow this install to proceed, we will be broken.
5401                        // Abort, abort!
5402                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5403                                "scanPackageLI");
5404                    }
5405                    if (!recovered) {
5406                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5407                            + pkg.applicationInfo.uid + "/fs_"
5408                            + currentUid;
5409                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5410                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5411                        String msg = "Package " + pkg.packageName
5412                                + " has mismatched uid: "
5413                                + currentUid + " on disk, "
5414                                + pkg.applicationInfo.uid + " in settings";
5415                        // writer
5416                        synchronized (mPackages) {
5417                            mSettings.mReadMessages.append(msg);
5418                            mSettings.mReadMessages.append('\n');
5419                            uidError = true;
5420                            if (!pkgSetting.uidError) {
5421                                reportSettingsProblem(Log.ERROR, msg);
5422                            }
5423                        }
5424                    }
5425                }
5426                pkg.applicationInfo.dataDir = dataPath.getPath();
5427                if (mShouldRestoreconData) {
5428                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5429                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5430                                pkg.applicationInfo.uid);
5431                }
5432            } else {
5433                if (DEBUG_PACKAGE_SCANNING) {
5434                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5435                        Log.v(TAG, "Want this data dir: " + dataPath);
5436                }
5437                //invoke installer to do the actual installation
5438                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5439                                           pkg.applicationInfo.seinfo);
5440                if (ret < 0) {
5441                    // Error from installer
5442                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5443                            "Unable to create data dirs [errorCode=" + ret + "]");
5444                }
5445
5446                if (dataPath.exists()) {
5447                    pkg.applicationInfo.dataDir = dataPath.getPath();
5448                } else {
5449                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5450                    pkg.applicationInfo.dataDir = null;
5451                }
5452            }
5453
5454            pkgSetting.uidError = uidError;
5455        }
5456
5457        final String path = scanFile.getPath();
5458        final String codePath = pkg.applicationInfo.getCodePath();
5459        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5460        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5461            setBundledAppAbisAndRoots(pkg, pkgSetting);
5462
5463            // If we haven't found any native libraries for the app, check if it has
5464            // renderscript code. We'll need to force the app to 32 bit if it has
5465            // renderscript bitcode.
5466            if (pkg.applicationInfo.primaryCpuAbi == null
5467                    && pkg.applicationInfo.secondaryCpuAbi == null
5468                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5469                NativeLibraryHelper.Handle handle = null;
5470                try {
5471                    handle = NativeLibraryHelper.Handle.create(scanFile);
5472                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5473                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5474                    }
5475                } catch (IOException ioe) {
5476                    Slog.w(TAG, "Error scanning system app : " + ioe);
5477                } finally {
5478                    IoUtils.closeQuietly(handle);
5479                }
5480            }
5481
5482            setNativeLibraryPaths(pkg);
5483        } else {
5484            // TODO: We can probably be smarter about this stuff. For installed apps,
5485            // we can calculate this information at install time once and for all. For
5486            // system apps, we can probably assume that this information doesn't change
5487            // after the first boot scan. As things stand, we do lots of unnecessary work.
5488
5489            // Give ourselves some initial paths; we'll come back for another
5490            // pass once we've determined ABI below.
5491            setNativeLibraryPaths(pkg);
5492
5493            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5494            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5495            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5496
5497            NativeLibraryHelper.Handle handle = null;
5498            try {
5499                handle = NativeLibraryHelper.Handle.create(scanFile);
5500                // TODO(multiArch): This can be null for apps that didn't go through the
5501                // usual installation process. We can calculate it again, like we
5502                // do during install time.
5503                //
5504                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5505                // unnecessary.
5506                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5507
5508                // Null out the abis so that they can be recalculated.
5509                pkg.applicationInfo.primaryCpuAbi = null;
5510                pkg.applicationInfo.secondaryCpuAbi = null;
5511                if (isMultiArch(pkg.applicationInfo)) {
5512                    // Warn if we've set an abiOverride for multi-lib packages..
5513                    // By definition, we need to copy both 32 and 64 bit libraries for
5514                    // such packages.
5515                    if (pkg.cpuAbiOverride != null && !CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5516                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5517                    }
5518
5519                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5520                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5521                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5522                        if (isAsec) {
5523                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5524                        } else {
5525                            abi32 = copyNativeLibrariesForInternalApp(handle,
5526                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5527                        }
5528                    }
5529
5530                    maybeThrowExceptionForMultiArchCopy(
5531                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5532
5533                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5534                        if (isAsec) {
5535                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5536                        } else {
5537                            abi64 = copyNativeLibrariesForInternalApp(handle,
5538                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5539                        }
5540                    }
5541
5542                    maybeThrowExceptionForMultiArchCopy(
5543                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5544
5545                    if (abi64 >= 0) {
5546                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5547                    }
5548
5549                    if (abi32 >= 0) {
5550                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5551                        if (abi64 >= 0) {
5552                            pkg.applicationInfo.secondaryCpuAbi = abi;
5553                        } else {
5554                            pkg.applicationInfo.primaryCpuAbi = abi;
5555                        }
5556                    }
5557                } else {
5558                    String[] abiList = (cpuAbiOverride != null) ?
5559                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5560
5561                    // Enable gross and lame hacks for apps that are built with old
5562                    // SDK tools. We must scan their APKs for renderscript bitcode and
5563                    // not launch them if it's present. Don't bother checking on devices
5564                    // that don't have 64 bit support.
5565                    boolean needsRenderScriptOverride = false;
5566                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5567                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5568                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5569                        needsRenderScriptOverride = true;
5570                    }
5571
5572                    final int copyRet;
5573                    if (isAsec) {
5574                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5575                    } else {
5576                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5577                                useIsaSpecificSubdirs);
5578                    }
5579
5580                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5581                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5582                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5583                    }
5584
5585                    if (copyRet >= 0) {
5586                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5587                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5588                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5589                    } else if (needsRenderScriptOverride) {
5590                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5591                    }
5592                }
5593            } catch (IOException ioe) {
5594                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5595            } finally {
5596                IoUtils.closeQuietly(handle);
5597            }
5598
5599            // Now that we've calculated the ABIs and determined if it's an internal app,
5600            // we will go ahead and populate the nativeLibraryPath.
5601            setNativeLibraryPaths(pkg);
5602
5603            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5604            final int[] userIds = sUserManager.getUserIds();
5605            synchronized (mInstallLock) {
5606                // Create a native library symlink only if we have native libraries
5607                // and if the native libraries are 32 bit libraries. We do not provide
5608                // this symlink for 64 bit libraries.
5609                if (pkg.applicationInfo.primaryCpuAbi != null &&
5610                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5611                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5612                    for (int userId : userIds) {
5613                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5614                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5615                                    "Failed linking native library dir (user=" + userId + ")");
5616                        }
5617                    }
5618                }
5619            }
5620        }
5621
5622        // This is a special case for the "system" package, where the ABI is
5623        // dictated by the zygote configuration (and init.rc). We should keep track
5624        // of this ABI so that we can deal with "normal" applications that run under
5625        // the same UID correctly.
5626        if (mPlatformPackage == pkg) {
5627            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5628                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5629        }
5630
5631        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5632        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5633        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5634        // Copy the derived override back to the parsed package, so that we can
5635        // update the package settings accordingly.
5636        pkg.cpuAbiOverride = cpuAbiOverride;
5637
5638        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5639                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5640                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5641
5642        // Push the derived path down into PackageSettings so we know what to
5643        // clean up at uninstall time.
5644        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5645
5646        if (DEBUG_ABI_SELECTION) {
5647            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5648                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5649                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5650        }
5651
5652        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5653            // We don't do this here during boot because we can do it all
5654            // at once after scanning all existing packages.
5655            //
5656            // We also do this *before* we perform dexopt on this package, so that
5657            // we can avoid redundant dexopts, and also to make sure we've got the
5658            // code and package path correct.
5659            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5660                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5661        }
5662
5663        if ((scanMode&SCAN_NO_DEX) == 0) {
5664            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5665                    == DEX_OPT_FAILED) {
5666                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5667                    removeDataDirsLI(pkg.packageName);
5668                }
5669
5670                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5671            }
5672        }
5673
5674        if (mFactoryTest && pkg.requestedPermissions.contains(
5675                android.Manifest.permission.FACTORY_TEST)) {
5676            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5677        }
5678
5679        ArrayList<PackageParser.Package> clientLibPkgs = null;
5680
5681        // writer
5682        synchronized (mPackages) {
5683            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5684                // Only system apps can add new shared libraries.
5685                if (pkg.libraryNames != null) {
5686                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5687                        String name = pkg.libraryNames.get(i);
5688                        boolean allowed = false;
5689                        if (isUpdatedSystemApp(pkg)) {
5690                            // New library entries can only be added through the
5691                            // system image.  This is important to get rid of a lot
5692                            // of nasty edge cases: for example if we allowed a non-
5693                            // system update of the app to add a library, then uninstalling
5694                            // the update would make the library go away, and assumptions
5695                            // we made such as through app install filtering would now
5696                            // have allowed apps on the device which aren't compatible
5697                            // with it.  Better to just have the restriction here, be
5698                            // conservative, and create many fewer cases that can negatively
5699                            // impact the user experience.
5700                            final PackageSetting sysPs = mSettings
5701                                    .getDisabledSystemPkgLPr(pkg.packageName);
5702                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5703                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5704                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5705                                        allowed = true;
5706                                        allowed = true;
5707                                        break;
5708                                    }
5709                                }
5710                            }
5711                        } else {
5712                            allowed = true;
5713                        }
5714                        if (allowed) {
5715                            if (!mSharedLibraries.containsKey(name)) {
5716                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5717                            } else if (!name.equals(pkg.packageName)) {
5718                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5719                                        + name + " already exists; skipping");
5720                            }
5721                        } else {
5722                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5723                                    + name + " that is not declared on system image; skipping");
5724                        }
5725                    }
5726                    if ((scanMode&SCAN_BOOTING) == 0) {
5727                        // If we are not booting, we need to update any applications
5728                        // that are clients of our shared library.  If we are booting,
5729                        // this will all be done once the scan is complete.
5730                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5731                    }
5732                }
5733            }
5734        }
5735
5736        // We also need to dexopt any apps that are dependent on this library.  Note that
5737        // if these fail, we should abort the install since installing the library will
5738        // result in some apps being broken.
5739        if (clientLibPkgs != null) {
5740            if ((scanMode&SCAN_NO_DEX) == 0) {
5741                for (int i=0; i<clientLibPkgs.size(); i++) {
5742                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5743                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5744                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5745                            == DEX_OPT_FAILED) {
5746                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5747                            removeDataDirsLI(pkg.packageName);
5748                        }
5749
5750                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5751                                "scanPackageLI failed to dexopt clientLibPkgs");
5752                    }
5753                }
5754            }
5755        }
5756
5757        // Request the ActivityManager to kill the process(only for existing packages)
5758        // so that we do not end up in a confused state while the user is still using the older
5759        // version of the application while the new one gets installed.
5760        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5761            // If the package lives in an asec, tell everyone that the container is going
5762            // away so they can clean up any references to its resources (which would prevent
5763            // vold from being able to unmount the asec)
5764            if (isForwardLocked(pkg) || isExternal(pkg)) {
5765                if (DEBUG_INSTALL) {
5766                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5767                }
5768                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5769                final ArrayList<String> pkgList = new ArrayList<String>(1);
5770                pkgList.add(pkg.applicationInfo.packageName);
5771                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5772            }
5773
5774            // Post the request that it be killed now that the going-away broadcast is en route
5775            killApplication(pkg.applicationInfo.packageName,
5776                        pkg.applicationInfo.uid, "update pkg");
5777        }
5778
5779        // Also need to kill any apps that are dependent on the library.
5780        if (clientLibPkgs != null) {
5781            for (int i=0; i<clientLibPkgs.size(); i++) {
5782                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5783                killApplication(clientPkg.applicationInfo.packageName,
5784                        clientPkg.applicationInfo.uid, "update lib");
5785            }
5786        }
5787
5788        // writer
5789        synchronized (mPackages) {
5790            // We don't expect installation to fail beyond this point,
5791            if ((scanMode&SCAN_MONITOR) != 0) {
5792                mAppDirs.put(pkg.codePath, pkg);
5793            }
5794            // Add the new setting to mSettings
5795            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5796            // Add the new setting to mPackages
5797            mPackages.put(pkg.applicationInfo.packageName, pkg);
5798            // Make sure we don't accidentally delete its data.
5799            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5800            while (iter.hasNext()) {
5801                PackageCleanItem item = iter.next();
5802                if (pkgName.equals(item.packageName)) {
5803                    iter.remove();
5804                }
5805            }
5806
5807            // Take care of first install / last update times.
5808            if (currentTime != 0) {
5809                if (pkgSetting.firstInstallTime == 0) {
5810                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5811                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5812                    pkgSetting.lastUpdateTime = currentTime;
5813                }
5814            } else if (pkgSetting.firstInstallTime == 0) {
5815                // We need *something*.  Take time time stamp of the file.
5816                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5817            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5818                if (scanFileTime != pkgSetting.timeStamp) {
5819                    // A package on the system image has changed; consider this
5820                    // to be an update.
5821                    pkgSetting.lastUpdateTime = scanFileTime;
5822                }
5823            }
5824
5825            // Add the package's KeySets to the global KeySetManagerService
5826            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5827            try {
5828                // Old KeySetData no longer valid.
5829                ksms.removeAppKeySetDataLPw(pkg.packageName);
5830                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5831                if (pkg.mKeySetMapping != null) {
5832                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5833                            pkg.mKeySetMapping.entrySet()) {
5834                        if (entry.getValue() != null) {
5835                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5836                                                          entry.getValue(), entry.getKey());
5837                        }
5838                    }
5839                    if (pkg.mUpgradeKeySets != null) {
5840                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5841                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5842                        }
5843                    }
5844                }
5845            } catch (NullPointerException e) {
5846                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5847            } catch (IllegalArgumentException e) {
5848                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5849            }
5850
5851            int N = pkg.providers.size();
5852            StringBuilder r = null;
5853            int i;
5854            for (i=0; i<N; i++) {
5855                PackageParser.Provider p = pkg.providers.get(i);
5856                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5857                        p.info.processName, pkg.applicationInfo.uid);
5858                mProviders.addProvider(p);
5859                p.syncable = p.info.isSyncable;
5860                if (p.info.authority != null) {
5861                    String names[] = p.info.authority.split(";");
5862                    p.info.authority = null;
5863                    for (int j = 0; j < names.length; j++) {
5864                        if (j == 1 && p.syncable) {
5865                            // We only want the first authority for a provider to possibly be
5866                            // syncable, so if we already added this provider using a different
5867                            // authority clear the syncable flag. We copy the provider before
5868                            // changing it because the mProviders object contains a reference
5869                            // to a provider that we don't want to change.
5870                            // Only do this for the second authority since the resulting provider
5871                            // object can be the same for all future authorities for this provider.
5872                            p = new PackageParser.Provider(p);
5873                            p.syncable = false;
5874                        }
5875                        if (!mProvidersByAuthority.containsKey(names[j])) {
5876                            mProvidersByAuthority.put(names[j], p);
5877                            if (p.info.authority == null) {
5878                                p.info.authority = names[j];
5879                            } else {
5880                                p.info.authority = p.info.authority + ";" + names[j];
5881                            }
5882                            if (DEBUG_PACKAGE_SCANNING) {
5883                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5884                                    Log.d(TAG, "Registered content provider: " + names[j]
5885                                            + ", className = " + p.info.name + ", isSyncable = "
5886                                            + p.info.isSyncable);
5887                            }
5888                        } else {
5889                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5890                            Slog.w(TAG, "Skipping provider name " + names[j] +
5891                                    " (in package " + pkg.applicationInfo.packageName +
5892                                    "): name already used by "
5893                                    + ((other != null && other.getComponentName() != null)
5894                                            ? other.getComponentName().getPackageName() : "?"));
5895                        }
5896                    }
5897                }
5898                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5899                    if (r == null) {
5900                        r = new StringBuilder(256);
5901                    } else {
5902                        r.append(' ');
5903                    }
5904                    r.append(p.info.name);
5905                }
5906            }
5907            if (r != null) {
5908                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5909            }
5910
5911            N = pkg.services.size();
5912            r = null;
5913            for (i=0; i<N; i++) {
5914                PackageParser.Service s = pkg.services.get(i);
5915                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5916                        s.info.processName, pkg.applicationInfo.uid);
5917                mServices.addService(s);
5918                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5919                    if (r == null) {
5920                        r = new StringBuilder(256);
5921                    } else {
5922                        r.append(' ');
5923                    }
5924                    r.append(s.info.name);
5925                }
5926            }
5927            if (r != null) {
5928                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5929            }
5930
5931            N = pkg.receivers.size();
5932            r = null;
5933            for (i=0; i<N; i++) {
5934                PackageParser.Activity a = pkg.receivers.get(i);
5935                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5936                        a.info.processName, pkg.applicationInfo.uid);
5937                mReceivers.addActivity(a, "receiver");
5938                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5939                    if (r == null) {
5940                        r = new StringBuilder(256);
5941                    } else {
5942                        r.append(' ');
5943                    }
5944                    r.append(a.info.name);
5945                }
5946            }
5947            if (r != null) {
5948                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5949            }
5950
5951            N = pkg.activities.size();
5952            r = null;
5953            for (i=0; i<N; i++) {
5954                PackageParser.Activity a = pkg.activities.get(i);
5955                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5956                        a.info.processName, pkg.applicationInfo.uid);
5957                mActivities.addActivity(a, "activity");
5958                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5959                    if (r == null) {
5960                        r = new StringBuilder(256);
5961                    } else {
5962                        r.append(' ');
5963                    }
5964                    r.append(a.info.name);
5965                }
5966            }
5967            if (r != null) {
5968                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5969            }
5970
5971            N = pkg.permissionGroups.size();
5972            r = null;
5973            for (i=0; i<N; i++) {
5974                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5975                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5976                if (cur == null) {
5977                    mPermissionGroups.put(pg.info.name, pg);
5978                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5979                        if (r == null) {
5980                            r = new StringBuilder(256);
5981                        } else {
5982                            r.append(' ');
5983                        }
5984                        r.append(pg.info.name);
5985                    }
5986                } else {
5987                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5988                            + pg.info.packageName + " ignored: original from "
5989                            + cur.info.packageName);
5990                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5991                        if (r == null) {
5992                            r = new StringBuilder(256);
5993                        } else {
5994                            r.append(' ');
5995                        }
5996                        r.append("DUP:");
5997                        r.append(pg.info.name);
5998                    }
5999                }
6000            }
6001            if (r != null) {
6002                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6003            }
6004
6005            N = pkg.permissions.size();
6006            r = null;
6007            for (i=0; i<N; i++) {
6008                PackageParser.Permission p = pkg.permissions.get(i);
6009                HashMap<String, BasePermission> permissionMap =
6010                        p.tree ? mSettings.mPermissionTrees
6011                        : mSettings.mPermissions;
6012                p.group = mPermissionGroups.get(p.info.group);
6013                if (p.info.group == null || p.group != null) {
6014                    BasePermission bp = permissionMap.get(p.info.name);
6015                    if (bp == null) {
6016                        bp = new BasePermission(p.info.name, p.info.packageName,
6017                                BasePermission.TYPE_NORMAL);
6018                        permissionMap.put(p.info.name, bp);
6019                    }
6020                    if (bp.perm == null) {
6021                        if (bp.sourcePackage != null
6022                                && !bp.sourcePackage.equals(p.info.packageName)) {
6023                            // If this is a permission that was formerly defined by a non-system
6024                            // app, but is now defined by a system app (following an upgrade),
6025                            // discard the previous declaration and consider the system's to be
6026                            // canonical.
6027                            if (isSystemApp(p.owner)) {
6028                                String msg = "New decl " + p.owner + " of permission  "
6029                                        + p.info.name + " is system";
6030                                reportSettingsProblem(Log.WARN, msg);
6031                                bp.sourcePackage = null;
6032                            }
6033                        }
6034                        if (bp.sourcePackage == null
6035                                || bp.sourcePackage.equals(p.info.packageName)) {
6036                            BasePermission tree = findPermissionTreeLP(p.info.name);
6037                            if (tree == null
6038                                    || tree.sourcePackage.equals(p.info.packageName)) {
6039                                bp.packageSetting = pkgSetting;
6040                                bp.perm = p;
6041                                bp.uid = pkg.applicationInfo.uid;
6042                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6043                                    if (r == null) {
6044                                        r = new StringBuilder(256);
6045                                    } else {
6046                                        r.append(' ');
6047                                    }
6048                                    r.append(p.info.name);
6049                                }
6050                            } else {
6051                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6052                                        + p.info.packageName + " ignored: base tree "
6053                                        + tree.name + " is from package "
6054                                        + tree.sourcePackage);
6055                            }
6056                        } else {
6057                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6058                                    + p.info.packageName + " ignored: original from "
6059                                    + bp.sourcePackage);
6060                        }
6061                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6062                        if (r == null) {
6063                            r = new StringBuilder(256);
6064                        } else {
6065                            r.append(' ');
6066                        }
6067                        r.append("DUP:");
6068                        r.append(p.info.name);
6069                    }
6070                    if (bp.perm == p) {
6071                        bp.protectionLevel = p.info.protectionLevel;
6072                    }
6073                } else {
6074                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6075                            + p.info.packageName + " ignored: no group "
6076                            + p.group);
6077                }
6078            }
6079            if (r != null) {
6080                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6081            }
6082
6083            N = pkg.instrumentation.size();
6084            r = null;
6085            for (i=0; i<N; i++) {
6086                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6087                a.info.packageName = pkg.applicationInfo.packageName;
6088                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6089                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6090                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6091                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6092                a.info.dataDir = pkg.applicationInfo.dataDir;
6093
6094                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6095                // need other information about the application, like the ABI and what not ?
6096                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6097                mInstrumentation.put(a.getComponentName(), a);
6098                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6099                    if (r == null) {
6100                        r = new StringBuilder(256);
6101                    } else {
6102                        r.append(' ');
6103                    }
6104                    r.append(a.info.name);
6105                }
6106            }
6107            if (r != null) {
6108                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6109            }
6110
6111            if (pkg.protectedBroadcasts != null) {
6112                N = pkg.protectedBroadcasts.size();
6113                for (i=0; i<N; i++) {
6114                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6115                }
6116            }
6117
6118            pkgSetting.setTimeStamp(scanFileTime);
6119
6120            // Create idmap files for pairs of (packages, overlay packages).
6121            // Note: "android", ie framework-res.apk, is handled by native layers.
6122            if (pkg.mOverlayTarget != null) {
6123                // This is an overlay package.
6124                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6125                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6126                        mOverlays.put(pkg.mOverlayTarget,
6127                                new HashMap<String, PackageParser.Package>());
6128                    }
6129                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6130                    map.put(pkg.packageName, pkg);
6131                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6132                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6133                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6134                                "scanPackageLI failed to createIdmap");
6135                    }
6136                }
6137            } else if (mOverlays.containsKey(pkg.packageName) &&
6138                    !pkg.packageName.equals("android")) {
6139                // This is a regular package, with one or more known overlay packages.
6140                createIdmapsForPackageLI(pkg);
6141            }
6142        }
6143
6144        return pkg;
6145    }
6146
6147    /**
6148     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6149     * i.e, so that all packages can be run inside a single process if required.
6150     *
6151     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6152     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6153     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6154     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6155     * updating a package that belongs to a shared user.
6156     *
6157     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6158     * adds unnecessary complexity.
6159     */
6160    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6161            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6162        String requiredInstructionSet = null;
6163        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6164            requiredInstructionSet = VMRuntime.getInstructionSet(
6165                     scannedPackage.applicationInfo.primaryCpuAbi);
6166        }
6167
6168        PackageSetting requirer = null;
6169        for (PackageSetting ps : packagesForUser) {
6170            // If packagesForUser contains scannedPackage, we skip it. This will happen
6171            // when scannedPackage is an update of an existing package. Without this check,
6172            // we will never be able to change the ABI of any package belonging to a shared
6173            // user, even if it's compatible with other packages.
6174            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6175                if (ps.primaryCpuAbiString == null) {
6176                    continue;
6177                }
6178
6179                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6180                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6181                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6182                    // this but there's not much we can do.
6183                    String errorMessage = "Instruction set mismatch, "
6184                            + ((requirer == null) ? "[caller]" : requirer)
6185                            + " requires " + requiredInstructionSet + " whereas " + ps
6186                            + " requires " + instructionSet;
6187                    Slog.w(TAG, errorMessage);
6188                }
6189
6190                if (requiredInstructionSet == null) {
6191                    requiredInstructionSet = instructionSet;
6192                    requirer = ps;
6193                }
6194            }
6195        }
6196
6197        if (requiredInstructionSet != null) {
6198            String adjustedAbi;
6199            if (requirer != null) {
6200                // requirer != null implies that either scannedPackage was null or that scannedPackage
6201                // did not require an ABI, in which case we have to adjust scannedPackage to match
6202                // the ABI of the set (which is the same as requirer's ABI)
6203                adjustedAbi = requirer.primaryCpuAbiString;
6204                if (scannedPackage != null) {
6205                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6206                }
6207            } else {
6208                // requirer == null implies that we're updating all ABIs in the set to
6209                // match scannedPackage.
6210                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6211            }
6212
6213            for (PackageSetting ps : packagesForUser) {
6214                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6215                    if (ps.primaryCpuAbiString != null) {
6216                        continue;
6217                    }
6218
6219                    ps.primaryCpuAbiString = adjustedAbi;
6220                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6221                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6222                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6223
6224                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6225                                deferDexOpt, true) == DEX_OPT_FAILED) {
6226                            ps.primaryCpuAbiString = null;
6227                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6228                            return;
6229                        } else {
6230                            mInstaller.rmdex(ps.codePathString,
6231                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6232                        }
6233                    }
6234                }
6235            }
6236        }
6237    }
6238
6239    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6240        synchronized (mPackages) {
6241            mResolverReplaced = true;
6242            // Set up information for custom user intent resolution activity.
6243            mResolveActivity.applicationInfo = pkg.applicationInfo;
6244            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6245            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6246            mResolveActivity.processName = null;
6247            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6248            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6249                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6250            mResolveActivity.theme = 0;
6251            mResolveActivity.exported = true;
6252            mResolveActivity.enabled = true;
6253            mResolveInfo.activityInfo = mResolveActivity;
6254            mResolveInfo.priority = 0;
6255            mResolveInfo.preferredOrder = 0;
6256            mResolveInfo.match = 0;
6257            mResolveComponentName = mCustomResolverComponentName;
6258            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6259                    mResolveComponentName);
6260        }
6261    }
6262
6263    private static String calculateBundledApkRoot(final String codePathString) {
6264        final File codePath = new File(codePathString);
6265        final File codeRoot;
6266        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6267            codeRoot = Environment.getRootDirectory();
6268        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6269            codeRoot = Environment.getOemDirectory();
6270        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6271            codeRoot = Environment.getVendorDirectory();
6272        } else {
6273            // Unrecognized code path; take its top real segment as the apk root:
6274            // e.g. /something/app/blah.apk => /something
6275            try {
6276                File f = codePath.getCanonicalFile();
6277                File parent = f.getParentFile();    // non-null because codePath is a file
6278                File tmp;
6279                while ((tmp = parent.getParentFile()) != null) {
6280                    f = parent;
6281                    parent = tmp;
6282                }
6283                codeRoot = f;
6284                Slog.w(TAG, "Unrecognized code path "
6285                        + codePath + " - using " + codeRoot);
6286            } catch (IOException e) {
6287                // Can't canonicalize the code path -- shenanigans?
6288                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6289                return Environment.getRootDirectory().getPath();
6290            }
6291        }
6292        return codeRoot.getPath();
6293    }
6294
6295    /**
6296     * Derive and set the location of native libraries for the given package,
6297     * which varies depending on where and how the package was installed.
6298     */
6299    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6300        final ApplicationInfo info = pkg.applicationInfo;
6301        final String codePath = pkg.codePath;
6302        final File codeFile = new File(codePath);
6303        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6304        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6305
6306        info.nativeLibraryRootDir = null;
6307        info.nativeLibraryRootRequiresIsa = false;
6308        info.nativeLibraryDir = null;
6309        info.secondaryNativeLibraryDir = null;
6310
6311        if (isApkFile(codeFile)) {
6312            // Monolithic install
6313            if (bundledApp) {
6314                // If "/system/lib64/apkname" exists, assume that is the per-package
6315                // native library directory to use; otherwise use "/system/lib/apkname".
6316                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6317                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6318                        getPrimaryInstructionSet(info));
6319
6320                // This is a bundled system app so choose the path based on the ABI.
6321                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6322                // is just the default path.
6323                final String apkName = deriveCodePathName(codePath);
6324                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6325                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6326                        apkName).getAbsolutePath();
6327
6328                if (info.secondaryCpuAbi != null) {
6329                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6330                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6331                            secondaryLibDir, apkName).getAbsolutePath();
6332                }
6333            } else if (asecApp) {
6334                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6335                        .getAbsolutePath();
6336            } else {
6337                final String apkName = deriveCodePathName(codePath);
6338                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6339                        .getAbsolutePath();
6340            }
6341
6342            info.nativeLibraryRootRequiresIsa = false;
6343            info.nativeLibraryDir = info.nativeLibraryRootDir;
6344        } else {
6345            // Cluster install
6346            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6347            info.nativeLibraryRootRequiresIsa = true;
6348
6349            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6350                    getPrimaryInstructionSet(info)).getAbsolutePath();
6351
6352            if (info.secondaryCpuAbi != null) {
6353                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6354                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6355            }
6356        }
6357    }
6358
6359    /**
6360     * Calculate the abis and roots for a bundled app. These can uniquely
6361     * be determined from the contents of the system partition, i.e whether
6362     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6363     * of this information, and instead assume that the system was built
6364     * sensibly.
6365     */
6366    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6367                                           PackageSetting pkgSetting) {
6368        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6369
6370        // If "/system/lib64/apkname" exists, assume that is the per-package
6371        // native library directory to use; otherwise use "/system/lib/apkname".
6372        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6373        setBundledAppAbi(pkg, apkRoot, apkName);
6374        // pkgSetting might be null during rescan following uninstall of updates
6375        // to a bundled app, so accommodate that possibility.  The settings in
6376        // that case will be established later from the parsed package.
6377        //
6378        // If the settings aren't null, sync them up with what we've just derived.
6379        // note that apkRoot isn't stored in the package settings.
6380        if (pkgSetting != null) {
6381            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6382            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6383        }
6384    }
6385
6386    /**
6387     * Deduces the ABI of a bundled app and sets the relevant fields on the
6388     * parsed pkg object.
6389     *
6390     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6391     *        under which system libraries are installed.
6392     * @param apkName the name of the installed package.
6393     */
6394    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6395        final File codeFile = new File(pkg.codePath);
6396
6397        final boolean has64BitLibs;
6398        final boolean has32BitLibs;
6399        if (isApkFile(codeFile)) {
6400            // Monolithic install
6401            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6402            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6403        } else {
6404            // Cluster install
6405            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6406            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6407                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6408                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6409                has64BitLibs = (new File(rootDir, isa)).exists();
6410            } else {
6411                has64BitLibs = false;
6412            }
6413            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6414                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6415                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6416                has32BitLibs = (new File(rootDir, isa)).exists();
6417            } else {
6418                has32BitLibs = false;
6419            }
6420        }
6421
6422        if (has64BitLibs && !has32BitLibs) {
6423            // The package has 64 bit libs, but not 32 bit libs. Its primary
6424            // ABI should be 64 bit. We can safely assume here that the bundled
6425            // native libraries correspond to the most preferred ABI in the list.
6426
6427            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6428            pkg.applicationInfo.secondaryCpuAbi = null;
6429        } else if (has32BitLibs && !has64BitLibs) {
6430            // The package has 32 bit libs but not 64 bit libs. Its primary
6431            // ABI should be 32 bit.
6432
6433            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6434            pkg.applicationInfo.secondaryCpuAbi = null;
6435        } else if (has32BitLibs && has64BitLibs) {
6436            // The application has both 64 and 32 bit bundled libraries. We check
6437            // here that the app declares multiArch support, and warn if it doesn't.
6438            //
6439            // We will be lenient here and record both ABIs. The primary will be the
6440            // ABI that's higher on the list, i.e, a device that's configured to prefer
6441            // 64 bit apps will see a 64 bit primary ABI,
6442
6443            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6444                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6445            }
6446
6447            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6448                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6449                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6450            } else {
6451                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6452                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6453            }
6454        } else {
6455            pkg.applicationInfo.primaryCpuAbi = null;
6456            pkg.applicationInfo.secondaryCpuAbi = null;
6457        }
6458    }
6459
6460    private static void createNativeLibrarySubdir(File path) throws IOException {
6461        if (!path.isDirectory()) {
6462            path.delete();
6463
6464            if (!path.mkdir()) {
6465                throw new IOException("Cannot create " + path.getPath());
6466            }
6467
6468            try {
6469                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6470            } catch (ErrnoException e) {
6471                throw new IOException("Cannot chmod native library directory "
6472                        + path.getPath(), e);
6473            }
6474        } else if (!SELinux.restorecon(path)) {
6475            throw new IOException("Cannot set SELinux context for " + path.getPath());
6476        }
6477    }
6478
6479    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6480            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6481        createNativeLibrarySubdir(nativeLibraryRoot);
6482
6483        /*
6484         * If this is an internal application or our nativeLibraryPath points to
6485         * the app-lib directory, unpack the libraries if necessary.
6486         */
6487        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6488        if (abi >= 0) {
6489            /*
6490             * If we have a matching instruction set, construct a subdir under the native
6491             * library root that corresponds to this instruction set.
6492             */
6493            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6494            final File subDir;
6495            if (useIsaSubdir) {
6496                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6497                createNativeLibrarySubdir(isaSubdir);
6498                subDir = isaSubdir;
6499            } else {
6500                subDir = nativeLibraryRoot;
6501            }
6502
6503            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6504            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6505                return copyRet;
6506            }
6507        }
6508
6509        return abi;
6510    }
6511
6512    private void killApplication(String pkgName, int appId, String reason) {
6513        // Request the ActivityManager to kill the process(only for existing packages)
6514        // so that we do not end up in a confused state while the user is still using the older
6515        // version of the application while the new one gets installed.
6516        IActivityManager am = ActivityManagerNative.getDefault();
6517        if (am != null) {
6518            try {
6519                am.killApplicationWithAppId(pkgName, appId, reason);
6520            } catch (RemoteException e) {
6521            }
6522        }
6523    }
6524
6525    void removePackageLI(PackageSetting ps, boolean chatty) {
6526        if (DEBUG_INSTALL) {
6527            if (chatty)
6528                Log.d(TAG, "Removing package " + ps.name);
6529        }
6530
6531        // writer
6532        synchronized (mPackages) {
6533            mPackages.remove(ps.name);
6534            if (ps.codePathString != null) {
6535                mAppDirs.remove(ps.codePathString);
6536            }
6537
6538            final PackageParser.Package pkg = ps.pkg;
6539            if (pkg != null) {
6540                cleanPackageDataStructuresLILPw(pkg, chatty);
6541            }
6542        }
6543    }
6544
6545    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6546        if (DEBUG_INSTALL) {
6547            if (chatty)
6548                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6549        }
6550
6551        // writer
6552        synchronized (mPackages) {
6553            mPackages.remove(pkg.applicationInfo.packageName);
6554            if (pkg.codePath != null) {
6555                mAppDirs.remove(pkg.codePath);
6556            }
6557            cleanPackageDataStructuresLILPw(pkg, chatty);
6558        }
6559    }
6560
6561    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6562        int N = pkg.providers.size();
6563        StringBuilder r = null;
6564        int i;
6565        for (i=0; i<N; i++) {
6566            PackageParser.Provider p = pkg.providers.get(i);
6567            mProviders.removeProvider(p);
6568            if (p.info.authority == null) {
6569
6570                /* There was another ContentProvider with this authority when
6571                 * this app was installed so this authority is null,
6572                 * Ignore it as we don't have to unregister the provider.
6573                 */
6574                continue;
6575            }
6576            String names[] = p.info.authority.split(";");
6577            for (int j = 0; j < names.length; j++) {
6578                if (mProvidersByAuthority.get(names[j]) == p) {
6579                    mProvidersByAuthority.remove(names[j]);
6580                    if (DEBUG_REMOVE) {
6581                        if (chatty)
6582                            Log.d(TAG, "Unregistered content provider: " + names[j]
6583                                    + ", className = " + p.info.name + ", isSyncable = "
6584                                    + p.info.isSyncable);
6585                    }
6586                }
6587            }
6588            if (DEBUG_REMOVE && chatty) {
6589                if (r == null) {
6590                    r = new StringBuilder(256);
6591                } else {
6592                    r.append(' ');
6593                }
6594                r.append(p.info.name);
6595            }
6596        }
6597        if (r != null) {
6598            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6599        }
6600
6601        N = pkg.services.size();
6602        r = null;
6603        for (i=0; i<N; i++) {
6604            PackageParser.Service s = pkg.services.get(i);
6605            mServices.removeService(s);
6606            if (chatty) {
6607                if (r == null) {
6608                    r = new StringBuilder(256);
6609                } else {
6610                    r.append(' ');
6611                }
6612                r.append(s.info.name);
6613            }
6614        }
6615        if (r != null) {
6616            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6617        }
6618
6619        N = pkg.receivers.size();
6620        r = null;
6621        for (i=0; i<N; i++) {
6622            PackageParser.Activity a = pkg.receivers.get(i);
6623            mReceivers.removeActivity(a, "receiver");
6624            if (DEBUG_REMOVE && chatty) {
6625                if (r == null) {
6626                    r = new StringBuilder(256);
6627                } else {
6628                    r.append(' ');
6629                }
6630                r.append(a.info.name);
6631            }
6632        }
6633        if (r != null) {
6634            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6635        }
6636
6637        N = pkg.activities.size();
6638        r = null;
6639        for (i=0; i<N; i++) {
6640            PackageParser.Activity a = pkg.activities.get(i);
6641            mActivities.removeActivity(a, "activity");
6642            if (DEBUG_REMOVE && chatty) {
6643                if (r == null) {
6644                    r = new StringBuilder(256);
6645                } else {
6646                    r.append(' ');
6647                }
6648                r.append(a.info.name);
6649            }
6650        }
6651        if (r != null) {
6652            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6653        }
6654
6655        N = pkg.permissions.size();
6656        r = null;
6657        for (i=0; i<N; i++) {
6658            PackageParser.Permission p = pkg.permissions.get(i);
6659            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6660            if (bp == null) {
6661                bp = mSettings.mPermissionTrees.get(p.info.name);
6662            }
6663            if (bp != null && bp.perm == p) {
6664                bp.perm = null;
6665                if (DEBUG_REMOVE && chatty) {
6666                    if (r == null) {
6667                        r = new StringBuilder(256);
6668                    } else {
6669                        r.append(' ');
6670                    }
6671                    r.append(p.info.name);
6672                }
6673            }
6674            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6675                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6676                if (appOpPerms != null) {
6677                    appOpPerms.remove(pkg.packageName);
6678                }
6679            }
6680        }
6681        if (r != null) {
6682            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6683        }
6684
6685        N = pkg.requestedPermissions.size();
6686        r = null;
6687        for (i=0; i<N; i++) {
6688            String perm = pkg.requestedPermissions.get(i);
6689            BasePermission bp = mSettings.mPermissions.get(perm);
6690            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6691                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6692                if (appOpPerms != null) {
6693                    appOpPerms.remove(pkg.packageName);
6694                    if (appOpPerms.isEmpty()) {
6695                        mAppOpPermissionPackages.remove(perm);
6696                    }
6697                }
6698            }
6699        }
6700        if (r != null) {
6701            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6702        }
6703
6704        N = pkg.instrumentation.size();
6705        r = null;
6706        for (i=0; i<N; i++) {
6707            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6708            mInstrumentation.remove(a.getComponentName());
6709            if (DEBUG_REMOVE && chatty) {
6710                if (r == null) {
6711                    r = new StringBuilder(256);
6712                } else {
6713                    r.append(' ');
6714                }
6715                r.append(a.info.name);
6716            }
6717        }
6718        if (r != null) {
6719            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6720        }
6721
6722        r = null;
6723        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6724            // Only system apps can hold shared libraries.
6725            if (pkg.libraryNames != null) {
6726                for (i=0; i<pkg.libraryNames.size(); i++) {
6727                    String name = pkg.libraryNames.get(i);
6728                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6729                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6730                        mSharedLibraries.remove(name);
6731                        if (DEBUG_REMOVE && chatty) {
6732                            if (r == null) {
6733                                r = new StringBuilder(256);
6734                            } else {
6735                                r.append(' ');
6736                            }
6737                            r.append(name);
6738                        }
6739                    }
6740                }
6741            }
6742        }
6743        if (r != null) {
6744            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6745        }
6746    }
6747
6748    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6749        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6750            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6751                return true;
6752            }
6753        }
6754        return false;
6755    }
6756
6757    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6758    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6759    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6760
6761    private void updatePermissionsLPw(String changingPkg,
6762            PackageParser.Package pkgInfo, int flags) {
6763        // Make sure there are no dangling permission trees.
6764        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6765        while (it.hasNext()) {
6766            final BasePermission bp = it.next();
6767            if (bp.packageSetting == null) {
6768                // We may not yet have parsed the package, so just see if
6769                // we still know about its settings.
6770                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6771            }
6772            if (bp.packageSetting == null) {
6773                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6774                        + " from package " + bp.sourcePackage);
6775                it.remove();
6776            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6777                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6778                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6779                            + " from package " + bp.sourcePackage);
6780                    flags |= UPDATE_PERMISSIONS_ALL;
6781                    it.remove();
6782                }
6783            }
6784        }
6785
6786        // Make sure all dynamic permissions have been assigned to a package,
6787        // and make sure there are no dangling permissions.
6788        it = mSettings.mPermissions.values().iterator();
6789        while (it.hasNext()) {
6790            final BasePermission bp = it.next();
6791            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6792                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6793                        + bp.name + " pkg=" + bp.sourcePackage
6794                        + " info=" + bp.pendingInfo);
6795                if (bp.packageSetting == null && bp.pendingInfo != null) {
6796                    final BasePermission tree = findPermissionTreeLP(bp.name);
6797                    if (tree != null && tree.perm != null) {
6798                        bp.packageSetting = tree.packageSetting;
6799                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6800                                new PermissionInfo(bp.pendingInfo));
6801                        bp.perm.info.packageName = tree.perm.info.packageName;
6802                        bp.perm.info.name = bp.name;
6803                        bp.uid = tree.uid;
6804                    }
6805                }
6806            }
6807            if (bp.packageSetting == null) {
6808                // We may not yet have parsed the package, so just see if
6809                // we still know about its settings.
6810                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6811            }
6812            if (bp.packageSetting == null) {
6813                Slog.w(TAG, "Removing dangling permission: " + bp.name
6814                        + " from package " + bp.sourcePackage);
6815                it.remove();
6816            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6817                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6818                    Slog.i(TAG, "Removing old permission: " + bp.name
6819                            + " from package " + bp.sourcePackage);
6820                    flags |= UPDATE_PERMISSIONS_ALL;
6821                    it.remove();
6822                }
6823            }
6824        }
6825
6826        // Now update the permissions for all packages, in particular
6827        // replace the granted permissions of the system packages.
6828        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6829            for (PackageParser.Package pkg : mPackages.values()) {
6830                if (pkg != pkgInfo) {
6831                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6832                }
6833            }
6834        }
6835
6836        if (pkgInfo != null) {
6837            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6838        }
6839    }
6840
6841    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6842        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6843        if (ps == null) {
6844            return;
6845        }
6846        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6847        HashSet<String> origPermissions = gp.grantedPermissions;
6848        boolean changedPermission = false;
6849
6850        if (replace) {
6851            ps.permissionsFixed = false;
6852            if (gp == ps) {
6853                origPermissions = new HashSet<String>(gp.grantedPermissions);
6854                gp.grantedPermissions.clear();
6855                gp.gids = mGlobalGids;
6856            }
6857        }
6858
6859        if (gp.gids == null) {
6860            gp.gids = mGlobalGids;
6861        }
6862
6863        final int N = pkg.requestedPermissions.size();
6864        for (int i=0; i<N; i++) {
6865            final String name = pkg.requestedPermissions.get(i);
6866            final boolean required = pkg.requestedPermissionsRequired.get(i);
6867            final BasePermission bp = mSettings.mPermissions.get(name);
6868            if (DEBUG_INSTALL) {
6869                if (gp != ps) {
6870                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6871                }
6872            }
6873
6874            if (bp == null || bp.packageSetting == null) {
6875                Slog.w(TAG, "Unknown permission " + name
6876                        + " in package " + pkg.packageName);
6877                continue;
6878            }
6879
6880            final String perm = bp.name;
6881            boolean allowed;
6882            boolean allowedSig = false;
6883            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6884                // Keep track of app op permissions.
6885                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6886                if (pkgs == null) {
6887                    pkgs = new ArraySet<>();
6888                    mAppOpPermissionPackages.put(bp.name, pkgs);
6889                }
6890                pkgs.add(pkg.packageName);
6891            }
6892            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6893            if (level == PermissionInfo.PROTECTION_NORMAL
6894                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6895                // We grant a normal or dangerous permission if any of the following
6896                // are true:
6897                // 1) The permission is required
6898                // 2) The permission is optional, but was granted in the past
6899                // 3) The permission is optional, but was requested by an
6900                //    app in /system (not /data)
6901                //
6902                // Otherwise, reject the permission.
6903                allowed = (required || origPermissions.contains(perm)
6904                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6905            } else if (bp.packageSetting == null) {
6906                // This permission is invalid; skip it.
6907                allowed = false;
6908            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6909                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6910                if (allowed) {
6911                    allowedSig = true;
6912                }
6913            } else {
6914                allowed = false;
6915            }
6916            if (DEBUG_INSTALL) {
6917                if (gp != ps) {
6918                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6919                }
6920            }
6921            if (allowed) {
6922                if (!isSystemApp(ps) && ps.permissionsFixed) {
6923                    // If this is an existing, non-system package, then
6924                    // we can't add any new permissions to it.
6925                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6926                        // Except...  if this is a permission that was added
6927                        // to the platform (note: need to only do this when
6928                        // updating the platform).
6929                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6930                    }
6931                }
6932                if (allowed) {
6933                    if (!gp.grantedPermissions.contains(perm)) {
6934                        changedPermission = true;
6935                        gp.grantedPermissions.add(perm);
6936                        gp.gids = appendInts(gp.gids, bp.gids);
6937                    } else if (!ps.haveGids) {
6938                        gp.gids = appendInts(gp.gids, bp.gids);
6939                    }
6940                } else {
6941                    Slog.w(TAG, "Not granting permission " + perm
6942                            + " to package " + pkg.packageName
6943                            + " because it was previously installed without");
6944                }
6945            } else {
6946                if (gp.grantedPermissions.remove(perm)) {
6947                    changedPermission = true;
6948                    gp.gids = removeInts(gp.gids, bp.gids);
6949                    Slog.i(TAG, "Un-granting permission " + perm
6950                            + " from package " + pkg.packageName
6951                            + " (protectionLevel=" + bp.protectionLevel
6952                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6953                            + ")");
6954                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6955                    // Don't print warning for app op permissions, since it is fine for them
6956                    // not to be granted, there is a UI for the user to decide.
6957                    Slog.w(TAG, "Not granting permission " + perm
6958                            + " to package " + pkg.packageName
6959                            + " (protectionLevel=" + bp.protectionLevel
6960                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6961                            + ")");
6962                }
6963            }
6964        }
6965
6966        if ((changedPermission || replace) && !ps.permissionsFixed &&
6967                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6968            // This is the first that we have heard about this package, so the
6969            // permissions we have now selected are fixed until explicitly
6970            // changed.
6971            ps.permissionsFixed = true;
6972        }
6973        ps.haveGids = true;
6974    }
6975
6976    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6977        boolean allowed = false;
6978        final int NP = PackageParser.NEW_PERMISSIONS.length;
6979        for (int ip=0; ip<NP; ip++) {
6980            final PackageParser.NewPermissionInfo npi
6981                    = PackageParser.NEW_PERMISSIONS[ip];
6982            if (npi.name.equals(perm)
6983                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6984                allowed = true;
6985                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6986                        + pkg.packageName);
6987                break;
6988            }
6989        }
6990        return allowed;
6991    }
6992
6993    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6994                                          BasePermission bp, HashSet<String> origPermissions) {
6995        boolean allowed;
6996        allowed = (compareSignatures(
6997                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6998                        == PackageManager.SIGNATURE_MATCH)
6999                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7000                        == PackageManager.SIGNATURE_MATCH);
7001        if (!allowed && (bp.protectionLevel
7002                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7003            if (isSystemApp(pkg)) {
7004                // For updated system applications, a system permission
7005                // is granted only if it had been defined by the original application.
7006                if (isUpdatedSystemApp(pkg)) {
7007                    final PackageSetting sysPs = mSettings
7008                            .getDisabledSystemPkgLPr(pkg.packageName);
7009                    final GrantedPermissions origGp = sysPs.sharedUser != null
7010                            ? sysPs.sharedUser : sysPs;
7011
7012                    if (origGp.grantedPermissions.contains(perm)) {
7013                        // If the original was granted this permission, we take
7014                        // that grant decision as read and propagate it to the
7015                        // update.
7016                        allowed = true;
7017                    } else {
7018                        // The system apk may have been updated with an older
7019                        // version of the one on the data partition, but which
7020                        // granted a new system permission that it didn't have
7021                        // before.  In this case we do want to allow the app to
7022                        // now get the new permission if the ancestral apk is
7023                        // privileged to get it.
7024                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7025                            for (int j=0;
7026                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7027                                if (perm.equals(
7028                                        sysPs.pkg.requestedPermissions.get(j))) {
7029                                    allowed = true;
7030                                    break;
7031                                }
7032                            }
7033                        }
7034                    }
7035                } else {
7036                    allowed = isPrivilegedApp(pkg);
7037                }
7038            }
7039        }
7040        if (!allowed && (bp.protectionLevel
7041                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7042            // For development permissions, a development permission
7043            // is granted only if it was already granted.
7044            allowed = origPermissions.contains(perm);
7045        }
7046        return allowed;
7047    }
7048
7049    final class ActivityIntentResolver
7050            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7051        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7052                boolean defaultOnly, int userId) {
7053            if (!sUserManager.exists(userId)) return null;
7054            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7055            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7056        }
7057
7058        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7059                int userId) {
7060            if (!sUserManager.exists(userId)) return null;
7061            mFlags = flags;
7062            return super.queryIntent(intent, resolvedType,
7063                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7064        }
7065
7066        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7067                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7068            if (!sUserManager.exists(userId)) return null;
7069            if (packageActivities == null) {
7070                return null;
7071            }
7072            mFlags = flags;
7073            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7074            final int N = packageActivities.size();
7075            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7076                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7077
7078            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7079            for (int i = 0; i < N; ++i) {
7080                intentFilters = packageActivities.get(i).intents;
7081                if (intentFilters != null && intentFilters.size() > 0) {
7082                    PackageParser.ActivityIntentInfo[] array =
7083                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7084                    intentFilters.toArray(array);
7085                    listCut.add(array);
7086                }
7087            }
7088            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7089        }
7090
7091        public final void addActivity(PackageParser.Activity a, String type) {
7092            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7093            mActivities.put(a.getComponentName(), a);
7094            if (DEBUG_SHOW_INFO)
7095                Log.v(
7096                TAG, "  " + type + " " +
7097                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7098            if (DEBUG_SHOW_INFO)
7099                Log.v(TAG, "    Class=" + a.info.name);
7100            final int NI = a.intents.size();
7101            for (int j=0; j<NI; j++) {
7102                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7103                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7104                    intent.setPriority(0);
7105                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7106                            + a.className + " with priority > 0, forcing to 0");
7107                }
7108                if (DEBUG_SHOW_INFO) {
7109                    Log.v(TAG, "    IntentFilter:");
7110                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7111                }
7112                if (!intent.debugCheck()) {
7113                    Log.w(TAG, "==> For Activity " + a.info.name);
7114                }
7115                addFilter(intent);
7116            }
7117        }
7118
7119        public final void removeActivity(PackageParser.Activity a, String type) {
7120            mActivities.remove(a.getComponentName());
7121            if (DEBUG_SHOW_INFO) {
7122                Log.v(TAG, "  " + type + " "
7123                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7124                                : a.info.name) + ":");
7125                Log.v(TAG, "    Class=" + a.info.name);
7126            }
7127            final int NI = a.intents.size();
7128            for (int j=0; j<NI; j++) {
7129                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7130                if (DEBUG_SHOW_INFO) {
7131                    Log.v(TAG, "    IntentFilter:");
7132                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7133                }
7134                removeFilter(intent);
7135            }
7136        }
7137
7138        @Override
7139        protected boolean allowFilterResult(
7140                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7141            ActivityInfo filterAi = filter.activity.info;
7142            for (int i=dest.size()-1; i>=0; i--) {
7143                ActivityInfo destAi = dest.get(i).activityInfo;
7144                if (destAi.name == filterAi.name
7145                        && destAi.packageName == filterAi.packageName) {
7146                    return false;
7147                }
7148            }
7149            return true;
7150        }
7151
7152        @Override
7153        protected ActivityIntentInfo[] newArray(int size) {
7154            return new ActivityIntentInfo[size];
7155        }
7156
7157        @Override
7158        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7159            if (!sUserManager.exists(userId)) return true;
7160            PackageParser.Package p = filter.activity.owner;
7161            if (p != null) {
7162                PackageSetting ps = (PackageSetting)p.mExtras;
7163                if (ps != null) {
7164                    // System apps are never considered stopped for purposes of
7165                    // filtering, because there may be no way for the user to
7166                    // actually re-launch them.
7167                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7168                            && ps.getStopped(userId);
7169                }
7170            }
7171            return false;
7172        }
7173
7174        @Override
7175        protected boolean isPackageForFilter(String packageName,
7176                PackageParser.ActivityIntentInfo info) {
7177            return packageName.equals(info.activity.owner.packageName);
7178        }
7179
7180        @Override
7181        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7182                int match, int userId) {
7183            if (!sUserManager.exists(userId)) return null;
7184            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7185                return null;
7186            }
7187            final PackageParser.Activity activity = info.activity;
7188            if (mSafeMode && (activity.info.applicationInfo.flags
7189                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7190                return null;
7191            }
7192            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7193            if (ps == null) {
7194                return null;
7195            }
7196            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7197                    ps.readUserState(userId), userId);
7198            if (ai == null) {
7199                return null;
7200            }
7201            final ResolveInfo res = new ResolveInfo();
7202            res.activityInfo = ai;
7203            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7204                res.filter = info;
7205            }
7206            res.priority = info.getPriority();
7207            res.preferredOrder = activity.owner.mPreferredOrder;
7208            //System.out.println("Result: " + res.activityInfo.className +
7209            //                   " = " + res.priority);
7210            res.match = match;
7211            res.isDefault = info.hasDefault;
7212            res.labelRes = info.labelRes;
7213            res.nonLocalizedLabel = info.nonLocalizedLabel;
7214            if (userNeedsBadging(userId)) {
7215                res.noResourceId = true;
7216            } else {
7217                res.icon = info.icon;
7218            }
7219            res.system = isSystemApp(res.activityInfo.applicationInfo);
7220            return res;
7221        }
7222
7223        @Override
7224        protected void sortResults(List<ResolveInfo> results) {
7225            Collections.sort(results, mResolvePrioritySorter);
7226        }
7227
7228        @Override
7229        protected void dumpFilter(PrintWriter out, String prefix,
7230                PackageParser.ActivityIntentInfo filter) {
7231            out.print(prefix); out.print(
7232                    Integer.toHexString(System.identityHashCode(filter.activity)));
7233                    out.print(' ');
7234                    filter.activity.printComponentShortName(out);
7235                    out.print(" filter ");
7236                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7237        }
7238
7239//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7240//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7241//            final List<ResolveInfo> retList = Lists.newArrayList();
7242//            while (i.hasNext()) {
7243//                final ResolveInfo resolveInfo = i.next();
7244//                if (isEnabledLP(resolveInfo.activityInfo)) {
7245//                    retList.add(resolveInfo);
7246//                }
7247//            }
7248//            return retList;
7249//        }
7250
7251        // Keys are String (activity class name), values are Activity.
7252        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7253                = new HashMap<ComponentName, PackageParser.Activity>();
7254        private int mFlags;
7255    }
7256
7257    private final class ServiceIntentResolver
7258            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7259        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7260                boolean defaultOnly, int userId) {
7261            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7262            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7263        }
7264
7265        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7266                int userId) {
7267            if (!sUserManager.exists(userId)) return null;
7268            mFlags = flags;
7269            return super.queryIntent(intent, resolvedType,
7270                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7271        }
7272
7273        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7274                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7275            if (!sUserManager.exists(userId)) return null;
7276            if (packageServices == null) {
7277                return null;
7278            }
7279            mFlags = flags;
7280            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7281            final int N = packageServices.size();
7282            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7283                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7284
7285            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7286            for (int i = 0; i < N; ++i) {
7287                intentFilters = packageServices.get(i).intents;
7288                if (intentFilters != null && intentFilters.size() > 0) {
7289                    PackageParser.ServiceIntentInfo[] array =
7290                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7291                    intentFilters.toArray(array);
7292                    listCut.add(array);
7293                }
7294            }
7295            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7296        }
7297
7298        public final void addService(PackageParser.Service s) {
7299            mServices.put(s.getComponentName(), s);
7300            if (DEBUG_SHOW_INFO) {
7301                Log.v(TAG, "  "
7302                        + (s.info.nonLocalizedLabel != null
7303                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7304                Log.v(TAG, "    Class=" + s.info.name);
7305            }
7306            final int NI = s.intents.size();
7307            int j;
7308            for (j=0; j<NI; j++) {
7309                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7310                if (DEBUG_SHOW_INFO) {
7311                    Log.v(TAG, "    IntentFilter:");
7312                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7313                }
7314                if (!intent.debugCheck()) {
7315                    Log.w(TAG, "==> For Service " + s.info.name);
7316                }
7317                addFilter(intent);
7318            }
7319        }
7320
7321        public final void removeService(PackageParser.Service s) {
7322            mServices.remove(s.getComponentName());
7323            if (DEBUG_SHOW_INFO) {
7324                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7325                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7326                Log.v(TAG, "    Class=" + s.info.name);
7327            }
7328            final int NI = s.intents.size();
7329            int j;
7330            for (j=0; j<NI; j++) {
7331                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7332                if (DEBUG_SHOW_INFO) {
7333                    Log.v(TAG, "    IntentFilter:");
7334                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7335                }
7336                removeFilter(intent);
7337            }
7338        }
7339
7340        @Override
7341        protected boolean allowFilterResult(
7342                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7343            ServiceInfo filterSi = filter.service.info;
7344            for (int i=dest.size()-1; i>=0; i--) {
7345                ServiceInfo destAi = dest.get(i).serviceInfo;
7346                if (destAi.name == filterSi.name
7347                        && destAi.packageName == filterSi.packageName) {
7348                    return false;
7349                }
7350            }
7351            return true;
7352        }
7353
7354        @Override
7355        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7356            return new PackageParser.ServiceIntentInfo[size];
7357        }
7358
7359        @Override
7360        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7361            if (!sUserManager.exists(userId)) return true;
7362            PackageParser.Package p = filter.service.owner;
7363            if (p != null) {
7364                PackageSetting ps = (PackageSetting)p.mExtras;
7365                if (ps != null) {
7366                    // System apps are never considered stopped for purposes of
7367                    // filtering, because there may be no way for the user to
7368                    // actually re-launch them.
7369                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7370                            && ps.getStopped(userId);
7371                }
7372            }
7373            return false;
7374        }
7375
7376        @Override
7377        protected boolean isPackageForFilter(String packageName,
7378                PackageParser.ServiceIntentInfo info) {
7379            return packageName.equals(info.service.owner.packageName);
7380        }
7381
7382        @Override
7383        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7384                int match, int userId) {
7385            if (!sUserManager.exists(userId)) return null;
7386            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7387            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7388                return null;
7389            }
7390            final PackageParser.Service service = info.service;
7391            if (mSafeMode && (service.info.applicationInfo.flags
7392                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7393                return null;
7394            }
7395            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7396            if (ps == null) {
7397                return null;
7398            }
7399            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7400                    ps.readUserState(userId), userId);
7401            if (si == null) {
7402                return null;
7403            }
7404            final ResolveInfo res = new ResolveInfo();
7405            res.serviceInfo = si;
7406            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7407                res.filter = filter;
7408            }
7409            res.priority = info.getPriority();
7410            res.preferredOrder = service.owner.mPreferredOrder;
7411            //System.out.println("Result: " + res.activityInfo.className +
7412            //                   " = " + res.priority);
7413            res.match = match;
7414            res.isDefault = info.hasDefault;
7415            res.labelRes = info.labelRes;
7416            res.nonLocalizedLabel = info.nonLocalizedLabel;
7417            res.icon = info.icon;
7418            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7419            return res;
7420        }
7421
7422        @Override
7423        protected void sortResults(List<ResolveInfo> results) {
7424            Collections.sort(results, mResolvePrioritySorter);
7425        }
7426
7427        @Override
7428        protected void dumpFilter(PrintWriter out, String prefix,
7429                PackageParser.ServiceIntentInfo filter) {
7430            out.print(prefix); out.print(
7431                    Integer.toHexString(System.identityHashCode(filter.service)));
7432                    out.print(' ');
7433                    filter.service.printComponentShortName(out);
7434                    out.print(" filter ");
7435                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7436        }
7437
7438//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7439//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7440//            final List<ResolveInfo> retList = Lists.newArrayList();
7441//            while (i.hasNext()) {
7442//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7443//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7444//                    retList.add(resolveInfo);
7445//                }
7446//            }
7447//            return retList;
7448//        }
7449
7450        // Keys are String (activity class name), values are Activity.
7451        private final HashMap<ComponentName, PackageParser.Service> mServices
7452                = new HashMap<ComponentName, PackageParser.Service>();
7453        private int mFlags;
7454    };
7455
7456    private final class ProviderIntentResolver
7457            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7458        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7459                boolean defaultOnly, int userId) {
7460            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7461            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7462        }
7463
7464        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7465                int userId) {
7466            if (!sUserManager.exists(userId))
7467                return null;
7468            mFlags = flags;
7469            return super.queryIntent(intent, resolvedType,
7470                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7471        }
7472
7473        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7474                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7475            if (!sUserManager.exists(userId))
7476                return null;
7477            if (packageProviders == null) {
7478                return null;
7479            }
7480            mFlags = flags;
7481            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7482            final int N = packageProviders.size();
7483            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7484                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7485
7486            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7487            for (int i = 0; i < N; ++i) {
7488                intentFilters = packageProviders.get(i).intents;
7489                if (intentFilters != null && intentFilters.size() > 0) {
7490                    PackageParser.ProviderIntentInfo[] array =
7491                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7492                    intentFilters.toArray(array);
7493                    listCut.add(array);
7494                }
7495            }
7496            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7497        }
7498
7499        public final void addProvider(PackageParser.Provider p) {
7500            if (mProviders.containsKey(p.getComponentName())) {
7501                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7502                return;
7503            }
7504
7505            mProviders.put(p.getComponentName(), p);
7506            if (DEBUG_SHOW_INFO) {
7507                Log.v(TAG, "  "
7508                        + (p.info.nonLocalizedLabel != null
7509                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7510                Log.v(TAG, "    Class=" + p.info.name);
7511            }
7512            final int NI = p.intents.size();
7513            int j;
7514            for (j = 0; j < NI; j++) {
7515                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7516                if (DEBUG_SHOW_INFO) {
7517                    Log.v(TAG, "    IntentFilter:");
7518                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7519                }
7520                if (!intent.debugCheck()) {
7521                    Log.w(TAG, "==> For Provider " + p.info.name);
7522                }
7523                addFilter(intent);
7524            }
7525        }
7526
7527        public final void removeProvider(PackageParser.Provider p) {
7528            mProviders.remove(p.getComponentName());
7529            if (DEBUG_SHOW_INFO) {
7530                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7531                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7532                Log.v(TAG, "    Class=" + p.info.name);
7533            }
7534            final int NI = p.intents.size();
7535            int j;
7536            for (j = 0; j < NI; j++) {
7537                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7538                if (DEBUG_SHOW_INFO) {
7539                    Log.v(TAG, "    IntentFilter:");
7540                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7541                }
7542                removeFilter(intent);
7543            }
7544        }
7545
7546        @Override
7547        protected boolean allowFilterResult(
7548                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7549            ProviderInfo filterPi = filter.provider.info;
7550            for (int i = dest.size() - 1; i >= 0; i--) {
7551                ProviderInfo destPi = dest.get(i).providerInfo;
7552                if (destPi.name == filterPi.name
7553                        && destPi.packageName == filterPi.packageName) {
7554                    return false;
7555                }
7556            }
7557            return true;
7558        }
7559
7560        @Override
7561        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7562            return new PackageParser.ProviderIntentInfo[size];
7563        }
7564
7565        @Override
7566        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7567            if (!sUserManager.exists(userId))
7568                return true;
7569            PackageParser.Package p = filter.provider.owner;
7570            if (p != null) {
7571                PackageSetting ps = (PackageSetting) p.mExtras;
7572                if (ps != null) {
7573                    // System apps are never considered stopped for purposes of
7574                    // filtering, because there may be no way for the user to
7575                    // actually re-launch them.
7576                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7577                            && ps.getStopped(userId);
7578                }
7579            }
7580            return false;
7581        }
7582
7583        @Override
7584        protected boolean isPackageForFilter(String packageName,
7585                PackageParser.ProviderIntentInfo info) {
7586            return packageName.equals(info.provider.owner.packageName);
7587        }
7588
7589        @Override
7590        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7591                int match, int userId) {
7592            if (!sUserManager.exists(userId))
7593                return null;
7594            final PackageParser.ProviderIntentInfo info = filter;
7595            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7596                return null;
7597            }
7598            final PackageParser.Provider provider = info.provider;
7599            if (mSafeMode && (provider.info.applicationInfo.flags
7600                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7601                return null;
7602            }
7603            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7604            if (ps == null) {
7605                return null;
7606            }
7607            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7608                    ps.readUserState(userId), userId);
7609            if (pi == null) {
7610                return null;
7611            }
7612            final ResolveInfo res = new ResolveInfo();
7613            res.providerInfo = pi;
7614            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7615                res.filter = filter;
7616            }
7617            res.priority = info.getPriority();
7618            res.preferredOrder = provider.owner.mPreferredOrder;
7619            res.match = match;
7620            res.isDefault = info.hasDefault;
7621            res.labelRes = info.labelRes;
7622            res.nonLocalizedLabel = info.nonLocalizedLabel;
7623            res.icon = info.icon;
7624            res.system = isSystemApp(res.providerInfo.applicationInfo);
7625            return res;
7626        }
7627
7628        @Override
7629        protected void sortResults(List<ResolveInfo> results) {
7630            Collections.sort(results, mResolvePrioritySorter);
7631        }
7632
7633        @Override
7634        protected void dumpFilter(PrintWriter out, String prefix,
7635                PackageParser.ProviderIntentInfo filter) {
7636            out.print(prefix);
7637            out.print(
7638                    Integer.toHexString(System.identityHashCode(filter.provider)));
7639            out.print(' ');
7640            filter.provider.printComponentShortName(out);
7641            out.print(" filter ");
7642            out.println(Integer.toHexString(System.identityHashCode(filter)));
7643        }
7644
7645        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7646                = new HashMap<ComponentName, PackageParser.Provider>();
7647        private int mFlags;
7648    };
7649
7650    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7651            new Comparator<ResolveInfo>() {
7652        public int compare(ResolveInfo r1, ResolveInfo r2) {
7653            int v1 = r1.priority;
7654            int v2 = r2.priority;
7655            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7656            if (v1 != v2) {
7657                return (v1 > v2) ? -1 : 1;
7658            }
7659            v1 = r1.preferredOrder;
7660            v2 = r2.preferredOrder;
7661            if (v1 != v2) {
7662                return (v1 > v2) ? -1 : 1;
7663            }
7664            if (r1.isDefault != r2.isDefault) {
7665                return r1.isDefault ? -1 : 1;
7666            }
7667            v1 = r1.match;
7668            v2 = r2.match;
7669            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7670            if (v1 != v2) {
7671                return (v1 > v2) ? -1 : 1;
7672            }
7673            if (r1.system != r2.system) {
7674                return r1.system ? -1 : 1;
7675            }
7676            return 0;
7677        }
7678    };
7679
7680    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7681            new Comparator<ProviderInfo>() {
7682        public int compare(ProviderInfo p1, ProviderInfo p2) {
7683            final int v1 = p1.initOrder;
7684            final int v2 = p2.initOrder;
7685            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7686        }
7687    };
7688
7689    static final void sendPackageBroadcast(String action, String pkg,
7690            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7691            int[] userIds) {
7692        IActivityManager am = ActivityManagerNative.getDefault();
7693        if (am != null) {
7694            try {
7695                if (userIds == null) {
7696                    userIds = am.getRunningUserIds();
7697                }
7698                for (int id : userIds) {
7699                    final Intent intent = new Intent(action,
7700                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7701                    if (extras != null) {
7702                        intent.putExtras(extras);
7703                    }
7704                    if (targetPkg != null) {
7705                        intent.setPackage(targetPkg);
7706                    }
7707                    // Modify the UID when posting to other users
7708                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7709                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7710                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7711                        intent.putExtra(Intent.EXTRA_UID, uid);
7712                    }
7713                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7714                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7715                    if (DEBUG_BROADCASTS) {
7716                        RuntimeException here = new RuntimeException("here");
7717                        here.fillInStackTrace();
7718                        Slog.d(TAG, "Sending to user " + id + ": "
7719                                + intent.toShortString(false, true, false, false)
7720                                + " " + intent.getExtras(), here);
7721                    }
7722                    am.broadcastIntent(null, intent, null, finishedReceiver,
7723                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7724                            finishedReceiver != null, false, id);
7725                }
7726            } catch (RemoteException ex) {
7727            }
7728        }
7729    }
7730
7731    /**
7732     * Check if the external storage media is available. This is true if there
7733     * is a mounted external storage medium or if the external storage is
7734     * emulated.
7735     */
7736    private boolean isExternalMediaAvailable() {
7737        return mMediaMounted || Environment.isExternalStorageEmulated();
7738    }
7739
7740    @Override
7741    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7742        // writer
7743        synchronized (mPackages) {
7744            if (!isExternalMediaAvailable()) {
7745                // If the external storage is no longer mounted at this point,
7746                // the caller may not have been able to delete all of this
7747                // packages files and can not delete any more.  Bail.
7748                return null;
7749            }
7750            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7751            if (lastPackage != null) {
7752                pkgs.remove(lastPackage);
7753            }
7754            if (pkgs.size() > 0) {
7755                return pkgs.get(0);
7756            }
7757        }
7758        return null;
7759    }
7760
7761    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7762        if (false) {
7763            RuntimeException here = new RuntimeException("here");
7764            here.fillInStackTrace();
7765            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7766                    + " andCode=" + andCode, here);
7767        }
7768        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7769                userId, andCode ? 1 : 0, packageName));
7770    }
7771
7772    void startCleaningPackages() {
7773        // reader
7774        synchronized (mPackages) {
7775            if (!isExternalMediaAvailable()) {
7776                return;
7777            }
7778            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7779                return;
7780            }
7781        }
7782        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7783        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7784        IActivityManager am = ActivityManagerNative.getDefault();
7785        if (am != null) {
7786            try {
7787                am.startService(null, intent, null, UserHandle.USER_OWNER);
7788            } catch (RemoteException e) {
7789            }
7790        }
7791    }
7792
7793    @Override
7794    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7795            String installerPackageName, VerificationParams verificationParams,
7796            String packageAbiOverride) {
7797        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7798                null);
7799
7800        final File originFile = new File(originPath);
7801        final int uid = Binder.getCallingUid();
7802        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7803            try {
7804                if (observer != null) {
7805                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7806                }
7807            } catch (RemoteException re) {
7808            }
7809            return;
7810        }
7811
7812        UserHandle user;
7813        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7814            user = UserHandle.ALL;
7815        } else {
7816            user = new UserHandle(UserHandle.getUserId(uid));
7817        }
7818
7819        final int filteredFlags;
7820        if (uid == Process.SHELL_UID || uid == 0) {
7821            if (DEBUG_INSTALL) {
7822                Slog.v(TAG, "Install from ADB");
7823            }
7824            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7825        } else {
7826            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7827        }
7828
7829        verificationParams.setInstallerUid(uid);
7830
7831        final Message msg = mHandler.obtainMessage(INIT_COPY);
7832        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7833                installerPackageName, verificationParams, user, packageAbiOverride);
7834        mHandler.sendMessage(msg);
7835    }
7836
7837    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7838            PackageInstaller.SessionParams params, String installerPackageName, int installerUid,
7839            UserHandle user) {
7840        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7841                params.referrerUri, installerUid, null);
7842
7843        final Message msg = mHandler.obtainMessage(INIT_COPY);
7844        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7845                installerPackageName, verifParams, user, params.abiOverride);
7846        mHandler.sendMessage(msg);
7847    }
7848
7849    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7850        Bundle extras = new Bundle(1);
7851        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7852
7853        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7854                packageName, extras, null, null, new int[] {userId});
7855        try {
7856            IActivityManager am = ActivityManagerNative.getDefault();
7857            final boolean isSystem =
7858                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7859            if (isSystem && am.isUserRunning(userId, false)) {
7860                // The just-installed/enabled app is bundled on the system, so presumed
7861                // to be able to run automatically without needing an explicit launch.
7862                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7863                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7864                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7865                        .setPackage(packageName);
7866                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7867                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7868            }
7869        } catch (RemoteException e) {
7870            // shouldn't happen
7871            Slog.w(TAG, "Unable to bootstrap installed package", e);
7872        }
7873    }
7874
7875    @Override
7876    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7877            int userId) {
7878        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7879        PackageSetting pkgSetting;
7880        final int uid = Binder.getCallingUid();
7881        if (UserHandle.getUserId(uid) != userId) {
7882            mContext.enforceCallingOrSelfPermission(
7883                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7884                    "setApplicationHiddenSetting for user " + userId);
7885        }
7886
7887        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7888            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7889            return false;
7890        }
7891
7892        long callingId = Binder.clearCallingIdentity();
7893        try {
7894            boolean sendAdded = false;
7895            boolean sendRemoved = false;
7896            // writer
7897            synchronized (mPackages) {
7898                pkgSetting = mSettings.mPackages.get(packageName);
7899                if (pkgSetting == null) {
7900                    return false;
7901                }
7902                if (pkgSetting.getHidden(userId) != hidden) {
7903                    pkgSetting.setHidden(hidden, userId);
7904                    mSettings.writePackageRestrictionsLPr(userId);
7905                    if (hidden) {
7906                        sendRemoved = true;
7907                    } else {
7908                        sendAdded = true;
7909                    }
7910                }
7911            }
7912            if (sendAdded) {
7913                sendPackageAddedForUser(packageName, pkgSetting, userId);
7914                return true;
7915            }
7916            if (sendRemoved) {
7917                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7918                        "hiding pkg");
7919                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7920            }
7921        } finally {
7922            Binder.restoreCallingIdentity(callingId);
7923        }
7924        return false;
7925    }
7926
7927    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7928            int userId) {
7929        final PackageRemovedInfo info = new PackageRemovedInfo();
7930        info.removedPackage = packageName;
7931        info.removedUsers = new int[] {userId};
7932        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7933        info.sendBroadcast(false, false, false);
7934    }
7935
7936    /**
7937     * Returns true if application is not found or there was an error. Otherwise it returns
7938     * the hidden state of the package for the given user.
7939     */
7940    @Override
7941    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7942        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7943        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7944                "getApplicationHidden for user " + userId);
7945        PackageSetting pkgSetting;
7946        long callingId = Binder.clearCallingIdentity();
7947        try {
7948            // writer
7949            synchronized (mPackages) {
7950                pkgSetting = mSettings.mPackages.get(packageName);
7951                if (pkgSetting == null) {
7952                    return true;
7953                }
7954                return pkgSetting.getHidden(userId);
7955            }
7956        } finally {
7957            Binder.restoreCallingIdentity(callingId);
7958        }
7959    }
7960
7961    /**
7962     * @hide
7963     */
7964    @Override
7965    public int installExistingPackageAsUser(String packageName, int userId) {
7966        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7967                null);
7968        PackageSetting pkgSetting;
7969        final int uid = Binder.getCallingUid();
7970        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7971        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7972            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7973        }
7974
7975        long callingId = Binder.clearCallingIdentity();
7976        try {
7977            boolean sendAdded = false;
7978            Bundle extras = new Bundle(1);
7979
7980            // writer
7981            synchronized (mPackages) {
7982                pkgSetting = mSettings.mPackages.get(packageName);
7983                if (pkgSetting == null) {
7984                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7985                }
7986                if (!pkgSetting.getInstalled(userId)) {
7987                    pkgSetting.setInstalled(true, userId);
7988                    pkgSetting.setHidden(false, userId);
7989                    mSettings.writePackageRestrictionsLPr(userId);
7990                    sendAdded = true;
7991                }
7992            }
7993
7994            if (sendAdded) {
7995                sendPackageAddedForUser(packageName, pkgSetting, userId);
7996            }
7997        } finally {
7998            Binder.restoreCallingIdentity(callingId);
7999        }
8000
8001        return PackageManager.INSTALL_SUCCEEDED;
8002    }
8003
8004    boolean isUserRestricted(int userId, String restrictionKey) {
8005        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8006        if (restrictions.getBoolean(restrictionKey, false)) {
8007            Log.w(TAG, "User is restricted: " + restrictionKey);
8008            return true;
8009        }
8010        return false;
8011    }
8012
8013    @Override
8014    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8015        mContext.enforceCallingOrSelfPermission(
8016                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8017                "Only package verification agents can verify applications");
8018
8019        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8020        final PackageVerificationResponse response = new PackageVerificationResponse(
8021                verificationCode, Binder.getCallingUid());
8022        msg.arg1 = id;
8023        msg.obj = response;
8024        mHandler.sendMessage(msg);
8025    }
8026
8027    @Override
8028    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8029            long millisecondsToDelay) {
8030        mContext.enforceCallingOrSelfPermission(
8031                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8032                "Only package verification agents can extend verification timeouts");
8033
8034        final PackageVerificationState state = mPendingVerification.get(id);
8035        final PackageVerificationResponse response = new PackageVerificationResponse(
8036                verificationCodeAtTimeout, Binder.getCallingUid());
8037
8038        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8039            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8040        }
8041        if (millisecondsToDelay < 0) {
8042            millisecondsToDelay = 0;
8043        }
8044        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8045                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8046            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8047        }
8048
8049        if ((state != null) && !state.timeoutExtended()) {
8050            state.extendTimeout();
8051
8052            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8053            msg.arg1 = id;
8054            msg.obj = response;
8055            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8056        }
8057    }
8058
8059    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8060            int verificationCode, UserHandle user) {
8061        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8062        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8063        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8064        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8065        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8066
8067        mContext.sendBroadcastAsUser(intent, user,
8068                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8069    }
8070
8071    private ComponentName matchComponentForVerifier(String packageName,
8072            List<ResolveInfo> receivers) {
8073        ActivityInfo targetReceiver = null;
8074
8075        final int NR = receivers.size();
8076        for (int i = 0; i < NR; i++) {
8077            final ResolveInfo info = receivers.get(i);
8078            if (info.activityInfo == null) {
8079                continue;
8080            }
8081
8082            if (packageName.equals(info.activityInfo.packageName)) {
8083                targetReceiver = info.activityInfo;
8084                break;
8085            }
8086        }
8087
8088        if (targetReceiver == null) {
8089            return null;
8090        }
8091
8092        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8093    }
8094
8095    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8096            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8097        if (pkgInfo.verifiers.length == 0) {
8098            return null;
8099        }
8100
8101        final int N = pkgInfo.verifiers.length;
8102        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8103        for (int i = 0; i < N; i++) {
8104            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8105
8106            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8107                    receivers);
8108            if (comp == null) {
8109                continue;
8110            }
8111
8112            final int verifierUid = getUidForVerifier(verifierInfo);
8113            if (verifierUid == -1) {
8114                continue;
8115            }
8116
8117            if (DEBUG_VERIFY) {
8118                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8119                        + " with the correct signature");
8120            }
8121            sufficientVerifiers.add(comp);
8122            verificationState.addSufficientVerifier(verifierUid);
8123        }
8124
8125        return sufficientVerifiers;
8126    }
8127
8128    private int getUidForVerifier(VerifierInfo verifierInfo) {
8129        synchronized (mPackages) {
8130            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8131            if (pkg == null) {
8132                return -1;
8133            } else if (pkg.mSignatures.length != 1) {
8134                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8135                        + " has more than one signature; ignoring");
8136                return -1;
8137            }
8138
8139            /*
8140             * If the public key of the package's signature does not match
8141             * our expected public key, then this is a different package and
8142             * we should skip.
8143             */
8144
8145            final byte[] expectedPublicKey;
8146            try {
8147                final Signature verifierSig = pkg.mSignatures[0];
8148                final PublicKey publicKey = verifierSig.getPublicKey();
8149                expectedPublicKey = publicKey.getEncoded();
8150            } catch (CertificateException e) {
8151                return -1;
8152            }
8153
8154            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8155
8156            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8157                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8158                        + " does not have the expected public key; ignoring");
8159                return -1;
8160            }
8161
8162            return pkg.applicationInfo.uid;
8163        }
8164    }
8165
8166    @Override
8167    public void finishPackageInstall(int token) {
8168        enforceSystemOrRoot("Only the system is allowed to finish installs");
8169
8170        if (DEBUG_INSTALL) {
8171            Slog.v(TAG, "BM finishing package install for " + token);
8172        }
8173
8174        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8175        mHandler.sendMessage(msg);
8176    }
8177
8178    /**
8179     * Get the verification agent timeout.
8180     *
8181     * @return verification timeout in milliseconds
8182     */
8183    private long getVerificationTimeout() {
8184        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8185                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8186                DEFAULT_VERIFICATION_TIMEOUT);
8187    }
8188
8189    /**
8190     * Get the default verification agent response code.
8191     *
8192     * @return default verification response code
8193     */
8194    private int getDefaultVerificationResponse() {
8195        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8196                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8197                DEFAULT_VERIFICATION_RESPONSE);
8198    }
8199
8200    /**
8201     * Check whether or not package verification has been enabled.
8202     *
8203     * @return true if verification should be performed
8204     */
8205    private boolean isVerificationEnabled(int userId, int flags) {
8206        if (!DEFAULT_VERIFY_ENABLE) {
8207            return false;
8208        }
8209
8210        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8211
8212        // Check if installing from ADB
8213        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8214            // Do not run verification in a test harness environment
8215            if (ActivityManager.isRunningInTestHarness()) {
8216                return false;
8217            }
8218            if (ensureVerifyAppsEnabled) {
8219                return true;
8220            }
8221            // Check if the developer does not want package verification for ADB installs
8222            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8223                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8224                return false;
8225            }
8226        }
8227
8228        if (ensureVerifyAppsEnabled) {
8229            return true;
8230        }
8231
8232        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8233                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8234    }
8235
8236    /**
8237     * Get the "allow unknown sources" setting.
8238     *
8239     * @return the current "allow unknown sources" setting
8240     */
8241    private int getUnknownSourcesSettings() {
8242        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8243                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8244                -1);
8245    }
8246
8247    @Override
8248    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8249        final int uid = Binder.getCallingUid();
8250        // writer
8251        synchronized (mPackages) {
8252            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8253            if (targetPackageSetting == null) {
8254                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8255            }
8256
8257            PackageSetting installerPackageSetting;
8258            if (installerPackageName != null) {
8259                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8260                if (installerPackageSetting == null) {
8261                    throw new IllegalArgumentException("Unknown installer package: "
8262                            + installerPackageName);
8263                }
8264            } else {
8265                installerPackageSetting = null;
8266            }
8267
8268            Signature[] callerSignature;
8269            Object obj = mSettings.getUserIdLPr(uid);
8270            if (obj != null) {
8271                if (obj instanceof SharedUserSetting) {
8272                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8273                } else if (obj instanceof PackageSetting) {
8274                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8275                } else {
8276                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8277                }
8278            } else {
8279                throw new SecurityException("Unknown calling uid " + uid);
8280            }
8281
8282            // Verify: can't set installerPackageName to a package that is
8283            // not signed with the same cert as the caller.
8284            if (installerPackageSetting != null) {
8285                if (compareSignatures(callerSignature,
8286                        installerPackageSetting.signatures.mSignatures)
8287                        != PackageManager.SIGNATURE_MATCH) {
8288                    throw new SecurityException(
8289                            "Caller does not have same cert as new installer package "
8290                            + installerPackageName);
8291                }
8292            }
8293
8294            // Verify: if target already has an installer package, it must
8295            // be signed with the same cert as the caller.
8296            if (targetPackageSetting.installerPackageName != null) {
8297                PackageSetting setting = mSettings.mPackages.get(
8298                        targetPackageSetting.installerPackageName);
8299                // If the currently set package isn't valid, then it's always
8300                // okay to change it.
8301                if (setting != null) {
8302                    if (compareSignatures(callerSignature,
8303                            setting.signatures.mSignatures)
8304                            != PackageManager.SIGNATURE_MATCH) {
8305                        throw new SecurityException(
8306                                "Caller does not have same cert as old installer package "
8307                                + targetPackageSetting.installerPackageName);
8308                    }
8309                }
8310            }
8311
8312            // Okay!
8313            targetPackageSetting.installerPackageName = installerPackageName;
8314            scheduleWriteSettingsLocked();
8315        }
8316    }
8317
8318    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8319        // Queue up an async operation since the package installation may take a little while.
8320        mHandler.post(new Runnable() {
8321            public void run() {
8322                mHandler.removeCallbacks(this);
8323                 // Result object to be returned
8324                PackageInstalledInfo res = new PackageInstalledInfo();
8325                res.returnCode = currentStatus;
8326                res.uid = -1;
8327                res.pkg = null;
8328                res.removedInfo = new PackageRemovedInfo();
8329                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8330                    args.doPreInstall(res.returnCode);
8331                    synchronized (mInstallLock) {
8332                        installPackageLI(args, true, res);
8333                    }
8334                    args.doPostInstall(res.returnCode, res.uid);
8335                }
8336
8337                // A restore should be performed at this point if (a) the install
8338                // succeeded, (b) the operation is not an update, and (c) the new
8339                // package has not opted out of backup participation.
8340                final boolean update = res.removedInfo.removedPackage != null;
8341                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8342                boolean doRestore = !update
8343                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8344
8345                // Set up the post-install work request bookkeeping.  This will be used
8346                // and cleaned up by the post-install event handling regardless of whether
8347                // there's a restore pass performed.  Token values are >= 1.
8348                int token;
8349                if (mNextInstallToken < 0) mNextInstallToken = 1;
8350                token = mNextInstallToken++;
8351
8352                PostInstallData data = new PostInstallData(args, res);
8353                mRunningInstalls.put(token, data);
8354                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8355
8356                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8357                    // Pass responsibility to the Backup Manager.  It will perform a
8358                    // restore if appropriate, then pass responsibility back to the
8359                    // Package Manager to run the post-install observer callbacks
8360                    // and broadcasts.
8361                    IBackupManager bm = IBackupManager.Stub.asInterface(
8362                            ServiceManager.getService(Context.BACKUP_SERVICE));
8363                    if (bm != null) {
8364                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8365                                + " to BM for possible restore");
8366                        try {
8367                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8368                        } catch (RemoteException e) {
8369                            // can't happen; the backup manager is local
8370                        } catch (Exception e) {
8371                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8372                            doRestore = false;
8373                        }
8374                    } else {
8375                        Slog.e(TAG, "Backup Manager not found!");
8376                        doRestore = false;
8377                    }
8378                }
8379
8380                if (!doRestore) {
8381                    // No restore possible, or the Backup Manager was mysteriously not
8382                    // available -- just fire the post-install work request directly.
8383                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8384                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8385                    mHandler.sendMessage(msg);
8386                }
8387            }
8388        });
8389    }
8390
8391    private abstract class HandlerParams {
8392        private static final int MAX_RETRIES = 4;
8393
8394        /**
8395         * Number of times startCopy() has been attempted and had a non-fatal
8396         * error.
8397         */
8398        private int mRetries = 0;
8399
8400        /** User handle for the user requesting the information or installation. */
8401        private final UserHandle mUser;
8402
8403        HandlerParams(UserHandle user) {
8404            mUser = user;
8405        }
8406
8407        UserHandle getUser() {
8408            return mUser;
8409        }
8410
8411        final boolean startCopy() {
8412            boolean res;
8413            try {
8414                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8415
8416                if (++mRetries > MAX_RETRIES) {
8417                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8418                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8419                    handleServiceError();
8420                    return false;
8421                } else {
8422                    handleStartCopy();
8423                    res = true;
8424                }
8425            } catch (RemoteException e) {
8426                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8427                mHandler.sendEmptyMessage(MCS_RECONNECT);
8428                res = false;
8429            }
8430            handleReturnCode();
8431            return res;
8432        }
8433
8434        final void serviceError() {
8435            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8436            handleServiceError();
8437            handleReturnCode();
8438        }
8439
8440        abstract void handleStartCopy() throws RemoteException;
8441        abstract void handleServiceError();
8442        abstract void handleReturnCode();
8443    }
8444
8445    class MeasureParams extends HandlerParams {
8446        private final PackageStats mStats;
8447        private boolean mSuccess;
8448
8449        private final IPackageStatsObserver mObserver;
8450
8451        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8452            super(new UserHandle(stats.userHandle));
8453            mObserver = observer;
8454            mStats = stats;
8455        }
8456
8457        @Override
8458        public String toString() {
8459            return "MeasureParams{"
8460                + Integer.toHexString(System.identityHashCode(this))
8461                + " " + mStats.packageName + "}";
8462        }
8463
8464        @Override
8465        void handleStartCopy() throws RemoteException {
8466            synchronized (mInstallLock) {
8467                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8468            }
8469
8470            if (mSuccess) {
8471                final boolean mounted;
8472                if (Environment.isExternalStorageEmulated()) {
8473                    mounted = true;
8474                } else {
8475                    final String status = Environment.getExternalStorageState();
8476                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8477                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8478                }
8479
8480                if (mounted) {
8481                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8482
8483                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8484                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8485
8486                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8487                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8488
8489                    // Always subtract cache size, since it's a subdirectory
8490                    mStats.externalDataSize -= mStats.externalCacheSize;
8491
8492                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8493                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8494
8495                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8496                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8497                }
8498            }
8499        }
8500
8501        @Override
8502        void handleReturnCode() {
8503            if (mObserver != null) {
8504                try {
8505                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8506                } catch (RemoteException e) {
8507                    Slog.i(TAG, "Observer no longer exists.");
8508                }
8509            }
8510        }
8511
8512        @Override
8513        void handleServiceError() {
8514            Slog.e(TAG, "Could not measure application " + mStats.packageName
8515                            + " external storage");
8516        }
8517    }
8518
8519    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8520            throws RemoteException {
8521        long result = 0;
8522        for (File path : paths) {
8523            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8524        }
8525        return result;
8526    }
8527
8528    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8529        for (File path : paths) {
8530            try {
8531                mcs.clearDirectory(path.getAbsolutePath());
8532            } catch (RemoteException e) {
8533            }
8534        }
8535    }
8536
8537    class InstallParams extends HandlerParams {
8538        /**
8539         * Location where install is coming from, before it has been
8540         * copied/renamed into place. This could be a single monolithic APK
8541         * file, or a cluster directory. This location may be untrusted.
8542         */
8543        final File originFile;
8544
8545        /**
8546         * Flag indicating that {@link #originFile} has already been staged,
8547         * meaning downstream users don't need to defensively copy the contents.
8548         */
8549        boolean originStaged;
8550
8551        final IPackageInstallObserver2 observer;
8552        int flags;
8553        final String installerPackageName;
8554        final VerificationParams verificationParams;
8555        private InstallArgs mArgs;
8556        private int mRet;
8557        final String packageAbiOverride;
8558        boolean multiArch;
8559
8560        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8561                int flags, String installerPackageName, VerificationParams verificationParams,
8562                UserHandle user, String packageAbiOverride) {
8563            super(user);
8564            this.originFile = Preconditions.checkNotNull(originFile);
8565            this.originStaged = originStaged;
8566            this.observer = observer;
8567            this.flags = flags;
8568            this.installerPackageName = installerPackageName;
8569            this.verificationParams = verificationParams;
8570            this.packageAbiOverride = packageAbiOverride;
8571        }
8572
8573        @Override
8574        public String toString() {
8575            return "InstallParams{"
8576                + Integer.toHexString(System.identityHashCode(this))
8577                + " " + originFile + "}";
8578        }
8579
8580        public ManifestDigest getManifestDigest() {
8581            if (verificationParams == null) {
8582                return null;
8583            }
8584            return verificationParams.getManifestDigest();
8585        }
8586
8587        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8588            String packageName = pkgLite.packageName;
8589            int installLocation = pkgLite.installLocation;
8590            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8591            // reader
8592            synchronized (mPackages) {
8593                PackageParser.Package pkg = mPackages.get(packageName);
8594                if (pkg != null) {
8595                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8596                        // Check for downgrading.
8597                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8598                            if (pkgLite.versionCode < pkg.mVersionCode) {
8599                                Slog.w(TAG, "Can't install update of " + packageName
8600                                        + " update version " + pkgLite.versionCode
8601                                        + " is older than installed version "
8602                                        + pkg.mVersionCode);
8603                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8604                            }
8605                        }
8606                        // Check for updated system application.
8607                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8608                            if (onSd) {
8609                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8610                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8611                            }
8612                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8613                        } else {
8614                            if (onSd) {
8615                                // Install flag overrides everything.
8616                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8617                            }
8618                            // If current upgrade specifies particular preference
8619                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8620                                // Application explicitly specified internal.
8621                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8622                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8623                                // App explictly prefers external. Let policy decide
8624                            } else {
8625                                // Prefer previous location
8626                                if (isExternal(pkg)) {
8627                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8628                                }
8629                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8630                            }
8631                        }
8632                    } else {
8633                        // Invalid install. Return error code
8634                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8635                    }
8636                }
8637            }
8638            // All the special cases have been taken care of.
8639            // Return result based on recommended install location.
8640            if (onSd) {
8641                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8642            }
8643            return pkgLite.recommendedInstallLocation;
8644        }
8645
8646        private long getMemoryLowThreshold() {
8647            final DeviceStorageMonitorInternal
8648                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8649            if (dsm == null) {
8650                return 0L;
8651            }
8652            return dsm.getMemoryLowThreshold();
8653        }
8654
8655        /*
8656         * Invoke remote method to get package information and install
8657         * location values. Override install location based on default
8658         * policy if needed and then create install arguments based
8659         * on the install location.
8660         */
8661        public void handleStartCopy() throws RemoteException {
8662            int ret = PackageManager.INSTALL_SUCCEEDED;
8663            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8664            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8665            PackageInfoLite pkgLite = null;
8666
8667            if (onInt && onSd) {
8668                // Check if both bits are set.
8669                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8670                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8671            } else {
8672                final long lowThreshold = getMemoryLowThreshold();
8673                if (lowThreshold == 0L) {
8674                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8675                }
8676
8677                // Remote call to find out default install location
8678                final String originPath = originFile.getAbsolutePath();
8679                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8680                        packageAbiOverride);
8681                // Keep track of whether this package is a multiArch package until
8682                // we perform a full scan of it. We need to do this because we might
8683                // end up extracting the package shared libraries before we perform
8684                // a full scan.
8685                multiArch = pkgLite.multiArch;
8686
8687                /*
8688                 * If we have too little free space, try to free cache
8689                 * before giving up.
8690                 */
8691                if (pkgLite.recommendedInstallLocation
8692                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8693                    final long size = mContainerService.calculateInstalledSize(
8694                            originPath, isForwardLocked(), packageAbiOverride);
8695                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8696                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8697                                lowThreshold, packageAbiOverride);
8698                    }
8699                    /*
8700                     * The cache free must have deleted the file we
8701                     * downloaded to install.
8702                     *
8703                     * TODO: fix the "freeCache" call to not delete
8704                     *       the file we care about.
8705                     */
8706                    if (pkgLite.recommendedInstallLocation
8707                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8708                        pkgLite.recommendedInstallLocation
8709                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8710                    }
8711                }
8712            }
8713
8714            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8715                int loc = pkgLite.recommendedInstallLocation;
8716                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8717                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8718                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8719                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8720                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8721                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8722                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8723                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8724                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8725                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8726                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8727                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8728                } else {
8729                    // Override with defaults if needed.
8730                    loc = installLocationPolicy(pkgLite, flags);
8731                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8732                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8733                    } else if (!onSd && !onInt) {
8734                        // Override install location with flags
8735                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8736                            // Set the flag to install on external media.
8737                            flags |= PackageManager.INSTALL_EXTERNAL;
8738                            flags &= ~PackageManager.INSTALL_INTERNAL;
8739                        } else {
8740                            // Make sure the flag for installing on external
8741                            // media is unset
8742                            flags |= PackageManager.INSTALL_INTERNAL;
8743                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8744                        }
8745                    }
8746                }
8747            }
8748
8749            final InstallArgs args = createInstallArgs(this);
8750            mArgs = args;
8751
8752            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8753                 /*
8754                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8755                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8756                 */
8757                int userIdentifier = getUser().getIdentifier();
8758                if (userIdentifier == UserHandle.USER_ALL
8759                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8760                    userIdentifier = UserHandle.USER_OWNER;
8761                }
8762
8763                /*
8764                 * Determine if we have any installed package verifiers. If we
8765                 * do, then we'll defer to them to verify the packages.
8766                 */
8767                final int requiredUid = mRequiredVerifierPackage == null ? -1
8768                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8769                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8770                    // TODO: send verifier the install session instead of uri
8771                    final Intent verification = new Intent(
8772                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8773                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8774                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8775
8776                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8777                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8778                            0 /* TODO: Which userId? */);
8779
8780                    if (DEBUG_VERIFY) {
8781                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8782                                + verification.toString() + " with " + pkgLite.verifiers.length
8783                                + " optional verifiers");
8784                    }
8785
8786                    final int verificationId = mPendingVerificationToken++;
8787
8788                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8789
8790                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8791                            installerPackageName);
8792
8793                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8794
8795                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8796                            pkgLite.packageName);
8797
8798                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8799                            pkgLite.versionCode);
8800
8801                    if (verificationParams != null) {
8802                        if (verificationParams.getVerificationURI() != null) {
8803                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8804                                 verificationParams.getVerificationURI());
8805                        }
8806                        if (verificationParams.getOriginatingURI() != null) {
8807                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8808                                  verificationParams.getOriginatingURI());
8809                        }
8810                        if (verificationParams.getReferrer() != null) {
8811                            verification.putExtra(Intent.EXTRA_REFERRER,
8812                                  verificationParams.getReferrer());
8813                        }
8814                        if (verificationParams.getOriginatingUid() >= 0) {
8815                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8816                                  verificationParams.getOriginatingUid());
8817                        }
8818                        if (verificationParams.getInstallerUid() >= 0) {
8819                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8820                                  verificationParams.getInstallerUid());
8821                        }
8822                    }
8823
8824                    final PackageVerificationState verificationState = new PackageVerificationState(
8825                            requiredUid, args);
8826
8827                    mPendingVerification.append(verificationId, verificationState);
8828
8829                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8830                            receivers, verificationState);
8831
8832                    /*
8833                     * If any sufficient verifiers were listed in the package
8834                     * manifest, attempt to ask them.
8835                     */
8836                    if (sufficientVerifiers != null) {
8837                        final int N = sufficientVerifiers.size();
8838                        if (N == 0) {
8839                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8840                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8841                        } else {
8842                            for (int i = 0; i < N; i++) {
8843                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8844
8845                                final Intent sufficientIntent = new Intent(verification);
8846                                sufficientIntent.setComponent(verifierComponent);
8847
8848                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8849                            }
8850                        }
8851                    }
8852
8853                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8854                            mRequiredVerifierPackage, receivers);
8855                    if (ret == PackageManager.INSTALL_SUCCEEDED
8856                            && mRequiredVerifierPackage != null) {
8857                        /*
8858                         * Send the intent to the required verification agent,
8859                         * but only start the verification timeout after the
8860                         * target BroadcastReceivers have run.
8861                         */
8862                        verification.setComponent(requiredVerifierComponent);
8863                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8864                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8865                                new BroadcastReceiver() {
8866                                    @Override
8867                                    public void onReceive(Context context, Intent intent) {
8868                                        final Message msg = mHandler
8869                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8870                                        msg.arg1 = verificationId;
8871                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8872                                    }
8873                                }, null, 0, null, null);
8874
8875                        /*
8876                         * We don't want the copy to proceed until verification
8877                         * succeeds, so null out this field.
8878                         */
8879                        mArgs = null;
8880                    }
8881                } else {
8882                    /*
8883                     * No package verification is enabled, so immediately start
8884                     * the remote call to initiate copy using temporary file.
8885                     */
8886                    ret = args.copyApk(mContainerService, true);
8887                }
8888            }
8889
8890            mRet = ret;
8891        }
8892
8893        @Override
8894        void handleReturnCode() {
8895            // If mArgs is null, then MCS couldn't be reached. When it
8896            // reconnects, it will try again to install. At that point, this
8897            // will succeed.
8898            if (mArgs != null) {
8899                processPendingInstall(mArgs, mRet);
8900            }
8901        }
8902
8903        @Override
8904        void handleServiceError() {
8905            mArgs = createInstallArgs(this);
8906            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8907        }
8908
8909        public boolean isForwardLocked() {
8910            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8911        }
8912    }
8913
8914    /*
8915     * Utility class used in movePackage api.
8916     * srcArgs and targetArgs are not set for invalid flags and make
8917     * sure to do null checks when invoking methods on them.
8918     * We probably want to return ErrorPrams for both failed installs
8919     * and moves.
8920     */
8921    class MoveParams extends HandlerParams {
8922        final IPackageMoveObserver observer;
8923        final int flags;
8924        final String packageName;
8925        final InstallArgs srcArgs;
8926        final InstallArgs targetArgs;
8927        int uid;
8928        int mRet;
8929
8930        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8931                String packageName, String[] instructionSets, int uid, UserHandle user,
8932                boolean isMultiArch) {
8933            super(user);
8934            this.srcArgs = srcArgs;
8935            this.observer = observer;
8936            this.flags = flags;
8937            this.packageName = packageName;
8938            this.uid = uid;
8939            if (srcArgs != null) {
8940                final String codePath = srcArgs.getCodePath();
8941                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8942                        instructionSets, isMultiArch);
8943            } else {
8944                targetArgs = null;
8945            }
8946        }
8947
8948        @Override
8949        public String toString() {
8950            return "MoveParams{"
8951                + Integer.toHexString(System.identityHashCode(this))
8952                + " " + packageName + "}";
8953        }
8954
8955        public void handleStartCopy() throws RemoteException {
8956            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8957            // Check for storage space on target medium
8958            if (!targetArgs.checkFreeStorage(mContainerService)) {
8959                Log.w(TAG, "Insufficient storage to install");
8960                return;
8961            }
8962
8963            mRet = srcArgs.doPreCopy();
8964            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8965                return;
8966            }
8967
8968            mRet = targetArgs.copyApk(mContainerService, false);
8969            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8970                srcArgs.doPostCopy(uid);
8971                return;
8972            }
8973
8974            mRet = srcArgs.doPostCopy(uid);
8975            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8976                return;
8977            }
8978
8979            mRet = targetArgs.doPreInstall(mRet);
8980            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8981                return;
8982            }
8983
8984            if (DEBUG_SD_INSTALL) {
8985                StringBuilder builder = new StringBuilder();
8986                if (srcArgs != null) {
8987                    builder.append("src: ");
8988                    builder.append(srcArgs.getCodePath());
8989                }
8990                if (targetArgs != null) {
8991                    builder.append(" target : ");
8992                    builder.append(targetArgs.getCodePath());
8993                }
8994                Log.i(TAG, builder.toString());
8995            }
8996        }
8997
8998        @Override
8999        void handleReturnCode() {
9000            targetArgs.doPostInstall(mRet, uid);
9001            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9002            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
9003                currentStatus = PackageManager.MOVE_SUCCEEDED;
9004            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
9005                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9006            }
9007            processPendingMove(this, currentStatus);
9008        }
9009
9010        @Override
9011        void handleServiceError() {
9012            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9013        }
9014    }
9015
9016    /**
9017     * Used during creation of InstallArgs
9018     *
9019     * @param flags package installation flags
9020     * @return true if should be installed on external storage
9021     */
9022    private static boolean installOnSd(int flags) {
9023        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
9024            return false;
9025        }
9026        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9027            return true;
9028        }
9029        return false;
9030    }
9031
9032    /**
9033     * Used during creation of InstallArgs
9034     *
9035     * @param flags package installation flags
9036     * @return true if should be installed as forward locked
9037     */
9038    private static boolean installForwardLocked(int flags) {
9039        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9040    }
9041
9042    private InstallArgs createInstallArgs(InstallParams params) {
9043        // TODO: extend to support incoming zero-copy locations
9044
9045        if (installOnSd(params.flags) || params.isForwardLocked()) {
9046            return new AsecInstallArgs(params);
9047        } else {
9048            return new FileInstallArgs(params);
9049        }
9050    }
9051
9052    /**
9053     * Create args that describe an existing installed package. Typically used
9054     * when cleaning up old installs, or used as a move source.
9055     */
9056    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9057            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9058            boolean isMultiArch) {
9059        final boolean isInAsec;
9060        if (installOnSd(flags)) {
9061            /* Apps on SD card are always in ASEC containers. */
9062            isInAsec = true;
9063        } else if (installForwardLocked(flags)
9064                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9065            /*
9066             * Forward-locked apps are only in ASEC containers if they're the
9067             * new style
9068             */
9069            isInAsec = true;
9070        } else {
9071            isInAsec = false;
9072        }
9073
9074        if (isInAsec) {
9075            return new AsecInstallArgs(codePath, instructionSets,
9076                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9077        } else {
9078            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9079                    instructionSets, isMultiArch);
9080        }
9081    }
9082
9083    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9084            String[] instructionSets, boolean isMultiArch) {
9085        final File codeFile = new File(codePath);
9086        if (installOnSd(flags) || installForwardLocked(flags)) {
9087            String cid = getNextCodePath(codePath, pkgName, "/"
9088                    + AsecInstallArgs.RES_FILE_NAME);
9089            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9090                    installForwardLocked(flags), isMultiArch);
9091        } else {
9092            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9093        }
9094    }
9095
9096    static abstract class InstallArgs {
9097        /** @see InstallParams#originFile */
9098        final File originFile;
9099        /** @see InstallParams#originStaged */
9100        final boolean originStaged;
9101
9102        // TODO: define inherit location
9103
9104        final IPackageInstallObserver2 observer;
9105        // Always refers to PackageManager flags only
9106        final int flags;
9107        final String installerPackageName;
9108        final ManifestDigest manifestDigest;
9109        final UserHandle user;
9110        final String abiOverride;
9111        final boolean multiArch;
9112
9113        // The list of instruction sets supported by this app. This is currently
9114        // only used during the rmdex() phase to clean up resources. We can get rid of this
9115        // if we move dex files under the common app path.
9116        /* nullable */ String[] instructionSets;
9117
9118        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9119                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9120                    UserHandle user, String[] instructionSets,
9121                    String abiOverride, boolean multiArch) {
9122            this.originFile = originFile;
9123            this.originStaged = originStaged;
9124            this.flags = flags;
9125            this.observer = observer;
9126            this.installerPackageName = installerPackageName;
9127            this.manifestDigest = manifestDigest;
9128            this.user = user;
9129            this.instructionSets = instructionSets;
9130            this.abiOverride = abiOverride;
9131            this.multiArch = multiArch;
9132        }
9133
9134        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9135        abstract int doPreInstall(int status);
9136
9137        /**
9138         * Rename package into final resting place. All paths on the given
9139         * scanned package should be updated to reflect the rename.
9140         */
9141        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9142        abstract int doPostInstall(int status, int uid);
9143
9144        /** @see PackageSettingBase#codePathString */
9145        abstract String getCodePath();
9146        /** @see PackageSettingBase#resourcePathString */
9147        abstract String getResourcePath();
9148        abstract String getLegacyNativeLibraryPath();
9149
9150        // Need installer lock especially for dex file removal.
9151        abstract void cleanUpResourcesLI();
9152        abstract boolean doPostDeleteLI(boolean delete);
9153        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9154
9155        /**
9156         * Called before the source arguments are copied. This is used mostly
9157         * for MoveParams when it needs to read the source file to put it in the
9158         * destination.
9159         */
9160        int doPreCopy() {
9161            return PackageManager.INSTALL_SUCCEEDED;
9162        }
9163
9164        /**
9165         * Called after the source arguments are copied. This is used mostly for
9166         * MoveParams when it needs to read the source file to put it in the
9167         * destination.
9168         *
9169         * @return
9170         */
9171        int doPostCopy(int uid) {
9172            return PackageManager.INSTALL_SUCCEEDED;
9173        }
9174
9175        protected boolean isFwdLocked() {
9176            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9177        }
9178
9179        UserHandle getUser() {
9180            return user;
9181        }
9182    }
9183
9184    /**
9185     * Logic to handle installation of non-ASEC applications, including copying
9186     * and renaming logic.
9187     */
9188    class FileInstallArgs extends InstallArgs {
9189        private File codeFile;
9190        private File resourceFile;
9191        private File legacyNativeLibraryPath;
9192
9193        // Example topology:
9194        // /data/app/com.example/base.apk
9195        // /data/app/com.example/split_foo.apk
9196        // /data/app/com.example/lib/arm/libfoo.so
9197        // /data/app/com.example/lib/arm64/libfoo.so
9198        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9199
9200        /** New install */
9201        FileInstallArgs(InstallParams params) {
9202            super(params.originFile, params.originStaged, params.observer, params.flags,
9203                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9204                    null /* instruction sets */, params.packageAbiOverride,
9205                    params.multiArch);
9206            if (isFwdLocked()) {
9207                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9208            }
9209        }
9210
9211        /** Existing install */
9212        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9213                String[] instructionSets, boolean isMultiArch) {
9214            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9215            this.codeFile = (codePath != null) ? new File(codePath) : null;
9216            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9217            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9218                    new File(legacyNativeLibraryPath) : null;
9219        }
9220
9221        /** New install from existing */
9222        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9223            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9224                    isMultiArch);
9225        }
9226
9227        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9228            final long lowThreshold;
9229
9230            final DeviceStorageMonitorInternal
9231                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9232            if (dsm == null) {
9233                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9234                lowThreshold = 0L;
9235            } else {
9236                if (dsm.isMemoryLow()) {
9237                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9238                    return false;
9239                }
9240
9241                lowThreshold = dsm.getMemoryLowThreshold();
9242            }
9243
9244            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9245                    lowThreshold);
9246        }
9247
9248        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9249            int ret = PackageManager.INSTALL_SUCCEEDED;
9250
9251            if (originStaged) {
9252                Slog.d(TAG, originFile + " already staged; skipping copy");
9253                codeFile = originFile;
9254                resourceFile = originFile;
9255            } else {
9256                try {
9257                    final File tempDir = mInstallerService.allocateSessionDir();
9258                    codeFile = tempDir;
9259                    resourceFile = tempDir;
9260                } catch (IOException e) {
9261                    Slog.w(TAG, "Failed to create copy file: " + e);
9262                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9263                }
9264
9265                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9266                    @Override
9267                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9268                        if (!FileUtils.isValidExtFilename(name)) {
9269                            throw new IllegalArgumentException("Invalid filename: " + name);
9270                        }
9271                        try {
9272                            final File file = new File(codeFile, name);
9273                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9274                                    O_RDWR | O_CREAT, 0644);
9275                            Os.chmod(file.getAbsolutePath(), 0644);
9276                            return new ParcelFileDescriptor(fd);
9277                        } catch (ErrnoException e) {
9278                            throw new RemoteException("Failed to open: " + e.getMessage());
9279                        }
9280                    }
9281                };
9282
9283                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9284                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9285                    Slog.e(TAG, "Failed to copy package");
9286                    return ret;
9287                }
9288            }
9289
9290            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9291            NativeLibraryHelper.Handle handle = null;
9292            try {
9293                handle = NativeLibraryHelper.Handle.create(codeFile);
9294                if (multiArch) {
9295                    // Warn if we've set an abiOverride for multi-lib packages..
9296                    // By definition, we need to copy both 32 and 64 bit libraries for
9297                    // such packages.
9298                    if (abiOverride != null &&  !CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9299                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9300                    }
9301
9302                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9303                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9304                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9305                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9306                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9307                    }
9308
9309                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9310                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9311                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9312                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9313                    }
9314                } else {
9315                    final String cpuAbiOverride = deriveAbiOverride(this.abiOverride, null /* package setting */);
9316                    String[] abiList = (cpuAbiOverride != null) ?
9317                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9318
9319                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9320                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9321                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9322                    }
9323
9324                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9325                            true /* use isa specific subdirs */);
9326                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9327                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9328                        return copyRet;
9329                    }
9330                }
9331            } catch (IOException e) {
9332                Slog.e(TAG, "Copying native libraries failed", e);
9333                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9334            } catch (PackageManagerException pme) {
9335                Slog.e(TAG, "Copying native libraries failed", pme);
9336                ret = pme.error;
9337            } finally {
9338                IoUtils.closeQuietly(handle);
9339            }
9340
9341            return ret;
9342        }
9343
9344        int doPreInstall(int status) {
9345            if (status != PackageManager.INSTALL_SUCCEEDED) {
9346                cleanUp();
9347            }
9348            return status;
9349        }
9350
9351        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9352            if (status != PackageManager.INSTALL_SUCCEEDED) {
9353                cleanUp();
9354                return false;
9355            } else {
9356                final File beforeCodeFile = codeFile;
9357                final File afterCodeFile = getNextCodePath(pkg.packageName);
9358
9359                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9360                try {
9361                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9362                } catch (ErrnoException e) {
9363                    Slog.d(TAG, "Failed to rename", e);
9364                    return false;
9365                }
9366
9367                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9368                    Slog.d(TAG, "Failed to restorecon");
9369                    return false;
9370                }
9371
9372                // Reflect the rename internally
9373                codeFile = afterCodeFile;
9374                resourceFile = afterCodeFile;
9375
9376                // Reflect the rename in scanned details
9377                pkg.codePath = afterCodeFile.getAbsolutePath();
9378                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9379                        pkg.baseCodePath);
9380                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9381                        pkg.splitCodePaths);
9382
9383                // Reflect the rename in app info
9384                pkg.applicationInfo.setCodePath(pkg.codePath);
9385                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9386                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9387                pkg.applicationInfo.setResourcePath(pkg.codePath);
9388                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9389                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9390
9391                return true;
9392            }
9393        }
9394
9395        int doPostInstall(int status, int uid) {
9396            if (status != PackageManager.INSTALL_SUCCEEDED) {
9397                cleanUp();
9398            }
9399            return status;
9400        }
9401
9402        @Override
9403        String getCodePath() {
9404            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9405        }
9406
9407        @Override
9408        String getResourcePath() {
9409            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9410        }
9411
9412        @Override
9413        String getLegacyNativeLibraryPath() {
9414            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9415        }
9416
9417        private boolean cleanUp() {
9418            if (codeFile == null || !codeFile.exists()) {
9419                return false;
9420            }
9421
9422            if (codeFile.isDirectory()) {
9423                FileUtils.deleteContents(codeFile);
9424            }
9425            codeFile.delete();
9426
9427            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9428                resourceFile.delete();
9429            }
9430
9431            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9432                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9433                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9434                }
9435                legacyNativeLibraryPath.delete();
9436            }
9437
9438            return true;
9439        }
9440
9441        void cleanUpResourcesLI() {
9442            // Try enumerating all code paths before deleting
9443            List<String> allCodePaths = Collections.EMPTY_LIST;
9444            if (codeFile != null && codeFile.exists()) {
9445                try {
9446                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9447                    allCodePaths = pkg.getAllCodePaths();
9448                } catch (PackageParserException e) {
9449                    // Ignored; we tried our best
9450                }
9451            }
9452
9453            cleanUp();
9454
9455            if (!allCodePaths.isEmpty()) {
9456                if (instructionSets == null) {
9457                    throw new IllegalStateException("instructionSet == null");
9458                }
9459                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9460                for (String codePath : allCodePaths) {
9461                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9462                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9463                        if (retCode < 0) {
9464                            Slog.w(TAG, "Couldn't remove dex file for package: "
9465                                    + " at location " + codePath + ", retcode=" + retCode);
9466                            // we don't consider this to be a failure of the core package deletion
9467                        }
9468                    }
9469                }
9470            }
9471        }
9472
9473        boolean doPostDeleteLI(boolean delete) {
9474            // XXX err, shouldn't we respect the delete flag?
9475            cleanUpResourcesLI();
9476            return true;
9477        }
9478    }
9479
9480    private boolean isAsecExternal(String cid) {
9481        final String asecPath = PackageHelper.getSdFilesystem(cid);
9482        return !asecPath.startsWith(mAsecInternalPath);
9483    }
9484
9485    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9486            PackageManagerException {
9487        if (copyRet < 0) {
9488            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9489                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9490                throw new PackageManagerException(copyRet, message);
9491            }
9492        }
9493    }
9494
9495    /**
9496     * Extract the MountService "container ID" from the full code path of an
9497     * .apk.
9498     */
9499    static String cidFromCodePath(String fullCodePath) {
9500        int eidx = fullCodePath.lastIndexOf("/");
9501        String subStr1 = fullCodePath.substring(0, eidx);
9502        int sidx = subStr1.lastIndexOf("/");
9503        return subStr1.substring(sidx+1, eidx);
9504    }
9505
9506    /**
9507     * Logic to handle installation of ASEC applications, including copying and
9508     * renaming logic.
9509     */
9510    class AsecInstallArgs extends InstallArgs {
9511        // TODO: teach about handling cluster directories
9512
9513        static final String RES_FILE_NAME = "pkg.apk";
9514        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9515
9516        String cid;
9517        String packagePath;
9518        String resourcePath;
9519        String legacyNativeLibraryDir;
9520
9521        /** New install */
9522        AsecInstallArgs(InstallParams params) {
9523            super(params.originFile, params.originStaged, params.observer, params.flags,
9524                    params.installerPackageName, params.getManifestDigest(),
9525                    params.getUser(), null /* instruction sets */,
9526                    params.packageAbiOverride, params.multiArch);
9527        }
9528
9529        /** Existing install */
9530        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9531                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9532            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9533                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9534                    instructionSets, null, isMultiArch);
9535            // Extract cid from fullCodePath
9536            int eidx = fullCodePath.lastIndexOf("/");
9537            String subStr1 = fullCodePath.substring(0, eidx);
9538            int sidx = subStr1.lastIndexOf("/");
9539            cid = subStr1.substring(sidx+1, eidx);
9540            setCachePath(subStr1);
9541        }
9542
9543        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9544                        boolean isMultiArch) {
9545            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9546                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9547                    instructionSets, null, isMultiArch);
9548            this.cid = cid;
9549            setCachePath(PackageHelper.getSdDir(cid));
9550        }
9551
9552        /** New install from existing */
9553        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9554                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9555            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9556                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9557                    instructionSets, null, isMultiArch);
9558            this.cid = cid;
9559        }
9560
9561        void createCopyFile() {
9562            cid = getTempContainerId();
9563        }
9564
9565        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9566            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9567                    abiOverride);
9568        }
9569
9570        private final boolean isExternal() {
9571            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9572        }
9573
9574        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9575            if (temp) {
9576                createCopyFile();
9577            } else {
9578                /*
9579                 * Pre-emptively destroy the container since it's destroyed if
9580                 * copying fails due to it existing anyway.
9581                 */
9582                PackageHelper.destroySdDir(cid);
9583            }
9584
9585            final String newCachePath = imcs.copyPackageToContainer(
9586                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9587                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9588
9589            if (newCachePath != null) {
9590                setCachePath(newCachePath);
9591                return PackageManager.INSTALL_SUCCEEDED;
9592            } else {
9593                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9594            }
9595        }
9596
9597        @Override
9598        String getCodePath() {
9599            return packagePath;
9600        }
9601
9602        @Override
9603        String getResourcePath() {
9604            return resourcePath;
9605        }
9606
9607        @Override
9608        String getLegacyNativeLibraryPath() {
9609            return legacyNativeLibraryDir;
9610        }
9611
9612        int doPreInstall(int status) {
9613            if (status != PackageManager.INSTALL_SUCCEEDED) {
9614                // Destroy container
9615                PackageHelper.destroySdDir(cid);
9616            } else {
9617                boolean mounted = PackageHelper.isContainerMounted(cid);
9618                if (!mounted) {
9619                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9620                            Process.SYSTEM_UID);
9621                    if (newCachePath != null) {
9622                        setCachePath(newCachePath);
9623                    } else {
9624                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9625                    }
9626                }
9627            }
9628            return status;
9629        }
9630
9631        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9632            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9633            String newCachePath = null;
9634            if (PackageHelper.isContainerMounted(cid)) {
9635                // Unmount the container
9636                if (!PackageHelper.unMountSdDir(cid)) {
9637                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9638                    return false;
9639                }
9640            }
9641            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9642                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9643                        " which might be stale. Will try to clean up.");
9644                // Clean up the stale container and proceed to recreate.
9645                if (!PackageHelper.destroySdDir(newCacheId)) {
9646                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9647                    return false;
9648                }
9649                // Successfully cleaned up stale container. Try to rename again.
9650                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9651                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9652                            + " inspite of cleaning it up.");
9653                    return false;
9654                }
9655            }
9656            if (!PackageHelper.isContainerMounted(newCacheId)) {
9657                Slog.w(TAG, "Mounting container " + newCacheId);
9658                newCachePath = PackageHelper.mountSdDir(newCacheId,
9659                        getEncryptKey(), Process.SYSTEM_UID);
9660            } else {
9661                newCachePath = PackageHelper.getSdDir(newCacheId);
9662            }
9663            if (newCachePath == null) {
9664                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9665                return false;
9666            }
9667            Log.i(TAG, "Succesfully renamed " + cid +
9668                    " to " + newCacheId +
9669                    " at new path: " + newCachePath);
9670            cid = newCacheId;
9671            setCachePath(newCachePath);
9672
9673            // TODO: extend to support split APKs
9674            pkg.codePath = getCodePath();
9675            pkg.baseCodePath = getCodePath();
9676            pkg.splitCodePaths = null;
9677
9678            pkg.applicationInfo.setCodePath(getCodePath());
9679            pkg.applicationInfo.setBaseCodePath(getCodePath());
9680            pkg.applicationInfo.setSplitCodePaths(null);
9681            pkg.applicationInfo.setResourcePath(getResourcePath());
9682            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9683            pkg.applicationInfo.setSplitResourcePaths(null);
9684
9685            return true;
9686        }
9687
9688        private void setCachePath(String newCachePath) {
9689            File cachePath = new File(newCachePath);
9690            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9691            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9692
9693            if (isFwdLocked()) {
9694                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9695            } else {
9696                resourcePath = packagePath;
9697            }
9698        }
9699
9700        int doPostInstall(int status, int uid) {
9701            if (status != PackageManager.INSTALL_SUCCEEDED) {
9702                cleanUp();
9703            } else {
9704                final int groupOwner;
9705                final String protectedFile;
9706                if (isFwdLocked()) {
9707                    groupOwner = UserHandle.getSharedAppGid(uid);
9708                    protectedFile = RES_FILE_NAME;
9709                } else {
9710                    groupOwner = -1;
9711                    protectedFile = null;
9712                }
9713
9714                if (uid < Process.FIRST_APPLICATION_UID
9715                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9716                    Slog.e(TAG, "Failed to finalize " + cid);
9717                    PackageHelper.destroySdDir(cid);
9718                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9719                }
9720
9721                boolean mounted = PackageHelper.isContainerMounted(cid);
9722                if (!mounted) {
9723                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9724                }
9725            }
9726            return status;
9727        }
9728
9729        private void cleanUp() {
9730            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9731
9732            // Destroy secure container
9733            PackageHelper.destroySdDir(cid);
9734        }
9735
9736        void cleanUpResourcesLI() {
9737            String sourceFile = getCodePath();
9738            // Remove dex file
9739            if (instructionSets == null) {
9740                throw new IllegalStateException("instructionSet == null");
9741            }
9742            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9743            for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9744                int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet);
9745                if (retCode < 0) {
9746                    Slog.w(TAG, "Couldn't remove dex file for package: "
9747                            + " at location "
9748                            + sourceFile.toString() + ", retcode=" + retCode);
9749                    // we don't consider this to be a failure of the core package deletion
9750                }
9751            }
9752            cleanUp();
9753        }
9754
9755        boolean matchContainer(String app) {
9756            if (cid.startsWith(app)) {
9757                return true;
9758            }
9759            return false;
9760        }
9761
9762        String getPackageName() {
9763            return getAsecPackageName(cid);
9764        }
9765
9766        boolean doPostDeleteLI(boolean delete) {
9767            boolean ret = false;
9768            boolean mounted = PackageHelper.isContainerMounted(cid);
9769            if (mounted) {
9770                // Unmount first
9771                ret = PackageHelper.unMountSdDir(cid);
9772            }
9773            if (ret && delete) {
9774                cleanUpResourcesLI();
9775            }
9776            return ret;
9777        }
9778
9779        @Override
9780        int doPreCopy() {
9781            if (isFwdLocked()) {
9782                if (!PackageHelper.fixSdPermissions(cid,
9783                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9784                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9785                }
9786            }
9787
9788            return PackageManager.INSTALL_SUCCEEDED;
9789        }
9790
9791        @Override
9792        int doPostCopy(int uid) {
9793            if (isFwdLocked()) {
9794                if (uid < Process.FIRST_APPLICATION_UID
9795                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9796                                RES_FILE_NAME)) {
9797                    Slog.e(TAG, "Failed to finalize " + cid);
9798                    PackageHelper.destroySdDir(cid);
9799                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9800                }
9801            }
9802
9803            return PackageManager.INSTALL_SUCCEEDED;
9804        }
9805    }
9806
9807    static String getAsecPackageName(String packageCid) {
9808        int idx = packageCid.lastIndexOf("-");
9809        if (idx == -1) {
9810            return packageCid;
9811        }
9812        return packageCid.substring(0, idx);
9813    }
9814
9815    // Utility method used to create code paths based on package name and available index.
9816    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9817        String idxStr = "";
9818        int idx = 1;
9819        // Fall back to default value of idx=1 if prefix is not
9820        // part of oldCodePath
9821        if (oldCodePath != null) {
9822            String subStr = oldCodePath;
9823            // Drop the suffix right away
9824            if (suffix != null && subStr.endsWith(suffix)) {
9825                subStr = subStr.substring(0, subStr.length() - suffix.length());
9826            }
9827            // If oldCodePath already contains prefix find out the
9828            // ending index to either increment or decrement.
9829            int sidx = subStr.lastIndexOf(prefix);
9830            if (sidx != -1) {
9831                subStr = subStr.substring(sidx + prefix.length());
9832                if (subStr != null) {
9833                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9834                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9835                    }
9836                    try {
9837                        idx = Integer.parseInt(subStr);
9838                        if (idx <= 1) {
9839                            idx++;
9840                        } else {
9841                            idx--;
9842                        }
9843                    } catch(NumberFormatException e) {
9844                    }
9845                }
9846            }
9847        }
9848        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9849        return prefix + idxStr;
9850    }
9851
9852    private File getNextCodePath(String packageName) {
9853        int suffix = 1;
9854        File result;
9855        do {
9856            result = new File(mAppInstallDir, packageName + "-" + suffix);
9857            suffix++;
9858        } while (result.exists());
9859        return result;
9860    }
9861
9862    // Utility method used to ignore ADD/REMOVE events
9863    // by directory observer.
9864    private static boolean ignoreCodePath(String fullPathStr) {
9865        String apkName = deriveCodePathName(fullPathStr);
9866        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9867        if (idx != -1 && ((idx+1) < apkName.length())) {
9868            // Make sure the package ends with a numeral
9869            String version = apkName.substring(idx+1);
9870            try {
9871                Integer.parseInt(version);
9872                return true;
9873            } catch (NumberFormatException e) {}
9874        }
9875        return false;
9876    }
9877
9878    // Utility method that returns the relative package path with respect
9879    // to the installation directory. Like say for /data/data/com.test-1.apk
9880    // string com.test-1 is returned.
9881    static String deriveCodePathName(String codePath) {
9882        if (codePath == null) {
9883            return null;
9884        }
9885        final File codeFile = new File(codePath);
9886        final String name = codeFile.getName();
9887        if (codeFile.isDirectory()) {
9888            return name;
9889        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9890            final int lastDot = name.lastIndexOf('.');
9891            return name.substring(0, lastDot);
9892        } else {
9893            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9894            return null;
9895        }
9896    }
9897
9898    class PackageInstalledInfo {
9899        String name;
9900        int uid;
9901        // The set of users that originally had this package installed.
9902        int[] origUsers;
9903        // The set of users that now have this package installed.
9904        int[] newUsers;
9905        PackageParser.Package pkg;
9906        int returnCode;
9907        String returnMsg;
9908        PackageRemovedInfo removedInfo;
9909
9910        public void setError(int code, String msg) {
9911            returnCode = code;
9912            returnMsg = msg;
9913            Slog.w(TAG, msg);
9914        }
9915
9916        public void setError(String msg, PackageParserException e) {
9917            returnCode = e.error;
9918            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9919            Slog.w(TAG, msg, e);
9920        }
9921
9922        public void setError(String msg, PackageManagerException e) {
9923            returnCode = e.error;
9924            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9925            Slog.w(TAG, msg, e);
9926        }
9927
9928        // In some error cases we want to convey more info back to the observer
9929        String origPackage;
9930        String origPermission;
9931    }
9932
9933    /*
9934     * Install a non-existing package.
9935     */
9936    private void installNewPackageLI(PackageParser.Package pkg,
9937            int parseFlags, int scanMode, UserHandle user,
9938            String installerPackageName, PackageInstalledInfo res) {
9939        // Remember this for later, in case we need to rollback this install
9940        String pkgName = pkg.packageName;
9941
9942        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9943        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9944        synchronized(mPackages) {
9945            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9946                // A package with the same name is already installed, though
9947                // it has been renamed to an older name.  The package we
9948                // are trying to install should be installed as an update to
9949                // the existing one, but that has not been requested, so bail.
9950                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9951                        + " without first uninstalling package running as "
9952                        + mSettings.mRenamedPackages.get(pkgName));
9953                return;
9954            }
9955            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9956                // Don't allow installation over an existing package with the same name.
9957                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9958                        + " without first uninstalling.");
9959                return;
9960            }
9961        }
9962
9963        try {
9964            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9965                    System.currentTimeMillis(), user);
9966
9967            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9968            // delete the partially installed application. the data directory will have to be
9969            // restored if it was already existing
9970            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9971                // remove package from internal structures.  Note that we want deletePackageX to
9972                // delete the package data and cache directories that it created in
9973                // scanPackageLocked, unless those directories existed before we even tried to
9974                // install.
9975                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9976                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9977                                res.removedInfo, true);
9978            }
9979
9980        } catch (PackageManagerException e) {
9981            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9982        }
9983    }
9984
9985    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9986        // Upgrade keysets are being used.  Determine if new package has a superset of the
9987        // required keys.
9988        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9989        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9990        for (int i = 0; i < upgradeKeySets.length; i++) {
9991            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9992            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9993                return true;
9994            }
9995        }
9996        return false;
9997    }
9998
9999    private void replacePackageLI(PackageParser.Package pkg,
10000            int parseFlags, int scanMode, UserHandle user,
10001            String installerPackageName, PackageInstalledInfo res) {
10002        PackageParser.Package oldPackage;
10003        String pkgName = pkg.packageName;
10004        int[] allUsers;
10005        boolean[] perUserInstalled;
10006
10007        // First find the old package info and check signatures
10008        synchronized(mPackages) {
10009            oldPackage = mPackages.get(pkgName);
10010            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10011            PackageSetting ps = mSettings.mPackages.get(pkgName);
10012            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10013                // default to original signature matching
10014                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10015                    != PackageManager.SIGNATURE_MATCH) {
10016                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10017                            "New package has a different signature: " + pkgName);
10018                    return;
10019                }
10020            } else {
10021                if(!checkUpgradeKeySetLP(ps, pkg)) {
10022                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10023                            "New package not signed by keys specified by upgrade-keysets: "
10024                            + pkgName);
10025                    return;
10026                }
10027            }
10028
10029            // In case of rollback, remember per-user/profile install state
10030            allUsers = sUserManager.getUserIds();
10031            perUserInstalled = new boolean[allUsers.length];
10032            for (int i = 0; i < allUsers.length; i++) {
10033                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10034            }
10035        }
10036
10037        boolean sysPkg = (isSystemApp(oldPackage));
10038        if (sysPkg) {
10039            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10040                    user, allUsers, perUserInstalled, installerPackageName, res);
10041        } else {
10042            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
10043                    user, allUsers, perUserInstalled, installerPackageName, res);
10044        }
10045    }
10046
10047    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10048            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10049            int[] allUsers, boolean[] perUserInstalled,
10050            String installerPackageName, PackageInstalledInfo res) {
10051        String pkgName = deletedPackage.packageName;
10052        boolean deletedPkg = true;
10053        boolean updatedSettings = false;
10054
10055        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10056                + deletedPackage);
10057        long origUpdateTime;
10058        if (pkg.mExtras != null) {
10059            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10060        } else {
10061            origUpdateTime = 0;
10062        }
10063
10064        // First delete the existing package while retaining the data directory
10065        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10066                res.removedInfo, true)) {
10067            // If the existing package wasn't successfully deleted
10068            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10069            deletedPkg = false;
10070        } else {
10071            // Successfully deleted the old package. Now proceed with re-installation
10072            deleteCodeCacheDirsLI(pkgName);
10073            try {
10074                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10075                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10076                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10077                updatedSettings = true;
10078            } catch (PackageManagerException e) {
10079                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10080            }
10081        }
10082
10083        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10084            // remove package from internal structures.  Note that we want deletePackageX to
10085            // delete the package data and cache directories that it created in
10086            // scanPackageLocked, unless those directories existed before we even tried to
10087            // install.
10088            if(updatedSettings) {
10089                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10090                deletePackageLI(
10091                        pkgName, null, true, allUsers, perUserInstalled,
10092                        PackageManager.DELETE_KEEP_DATA,
10093                                res.removedInfo, true);
10094            }
10095            // Since we failed to install the new package we need to restore the old
10096            // package that we deleted.
10097            if (deletedPkg) {
10098                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10099                File restoreFile = new File(deletedPackage.codePath);
10100                // Parse old package
10101                boolean oldOnSd = isExternal(deletedPackage);
10102                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10103                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10104                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10105                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10106                        | SCAN_UPDATE_TIME;
10107                try {
10108                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null);
10109                } catch (PackageManagerException e) {
10110                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10111                            + e.getMessage());
10112                    return;
10113                }
10114                // Restore of old package succeeded. Update permissions.
10115                // writer
10116                synchronized (mPackages) {
10117                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10118                            UPDATE_PERMISSIONS_ALL);
10119                    // can downgrade to reader
10120                    mSettings.writeLPr();
10121                }
10122                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10123            }
10124        }
10125    }
10126
10127    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10128            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10129            int[] allUsers, boolean[] perUserInstalled,
10130            String installerPackageName, PackageInstalledInfo res) {
10131        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10132                + ", old=" + deletedPackage);
10133        boolean updatedSettings = false;
10134        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10135                PackageParser.PARSE_IS_SYSTEM;
10136        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10137            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10138        }
10139        String packageName = deletedPackage.packageName;
10140        if (packageName == null) {
10141            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10142                    "Attempt to delete null packageName.");
10143            return;
10144        }
10145        PackageParser.Package oldPkg;
10146        PackageSetting oldPkgSetting;
10147        // reader
10148        synchronized (mPackages) {
10149            oldPkg = mPackages.get(packageName);
10150            oldPkgSetting = mSettings.mPackages.get(packageName);
10151            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10152                    (oldPkgSetting == null)) {
10153                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10154                        "Couldn't find package:" + packageName + " information");
10155                return;
10156            }
10157        }
10158
10159        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10160
10161        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10162        res.removedInfo.removedPackage = packageName;
10163        // Remove existing system package
10164        removePackageLI(oldPkgSetting, true);
10165        // writer
10166        synchronized (mPackages) {
10167            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10168                // We didn't need to disable the .apk as a current system package,
10169                // which means we are replacing another update that is already
10170                // installed.  We need to make sure to delete the older one's .apk.
10171                res.removedInfo.args = createInstallArgsForExisting(0,
10172                        deletedPackage.applicationInfo.getCodePath(),
10173                        deletedPackage.applicationInfo.getResourcePath(),
10174                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10175                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10176                        isMultiArch(deletedPackage.applicationInfo));
10177            } else {
10178                res.removedInfo.args = null;
10179            }
10180        }
10181
10182        // Successfully disabled the old package. Now proceed with re-installation
10183        deleteCodeCacheDirsLI(packageName);
10184
10185        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10186        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10187
10188        PackageParser.Package newPackage = null;
10189        try {
10190            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
10191            if (newPackage.mExtras != null) {
10192                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10193                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10194                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10195
10196                // is the update attempting to change shared user? that isn't going to work...
10197                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10198                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10199                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10200                            + " to " + newPkgSetting.sharedUser);
10201                    updatedSettings = true;
10202                }
10203            }
10204
10205            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10206                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10207                updatedSettings = true;
10208            }
10209
10210        } catch (PackageManagerException e) {
10211            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10212        }
10213
10214        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10215            // Re installation failed. Restore old information
10216            // Remove new pkg information
10217            if (newPackage != null) {
10218                removeInstalledPackageLI(newPackage, true);
10219            }
10220            // Add back the old system package
10221            try {
10222                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
10223            } catch (PackageManagerException e) {
10224                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10225            }
10226            // Restore the old system information in Settings
10227            synchronized(mPackages) {
10228                if (updatedSettings) {
10229                    mSettings.enableSystemPackageLPw(packageName);
10230                    mSettings.setInstallerPackageName(packageName,
10231                            oldPkgSetting.installerPackageName);
10232                }
10233                mSettings.writeLPr();
10234            }
10235        }
10236    }
10237
10238    // Utility method used to move dex files during install.
10239    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10240        // TODO: extend to move split APK dex files
10241        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10242            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10243            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10244            for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10245                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10246                        dexCodeInstructionSet);
10247                if (retCode != 0) {
10248                /*
10249                 * Programs may be lazily run through dexopt, so the
10250                 * source may not exist. However, something seems to
10251                 * have gone wrong, so note that dexopt needs to be
10252                 * run again and remove the source file. In addition,
10253                 * remove the target to make sure there isn't a stale
10254                 * file from a previous version of the package.
10255                 */
10256                    newPackage.mDexOptPerformed.clear();
10257                    mInstaller.rmdex(oldCodePath, dexCodeInstructionSet);
10258                    mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet);
10259                }
10260            }
10261        }
10262        return PackageManager.INSTALL_SUCCEEDED;
10263    }
10264
10265    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10266            int[] allUsers, boolean[] perUserInstalled,
10267            PackageInstalledInfo res) {
10268        String pkgName = newPackage.packageName;
10269        synchronized (mPackages) {
10270            //write settings. the installStatus will be incomplete at this stage.
10271            //note that the new package setting would have already been
10272            //added to mPackages. It hasn't been persisted yet.
10273            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10274            mSettings.writeLPr();
10275        }
10276
10277        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10278
10279        synchronized (mPackages) {
10280            updatePermissionsLPw(newPackage.packageName, newPackage,
10281                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10282                            ? UPDATE_PERMISSIONS_ALL : 0));
10283            // For system-bundled packages, we assume that installing an upgraded version
10284            // of the package implies that the user actually wants to run that new code,
10285            // so we enable the package.
10286            if (isSystemApp(newPackage)) {
10287                // NB: implicit assumption that system package upgrades apply to all users
10288                if (DEBUG_INSTALL) {
10289                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10290                }
10291                PackageSetting ps = mSettings.mPackages.get(pkgName);
10292                if (ps != null) {
10293                    if (res.origUsers != null) {
10294                        for (int userHandle : res.origUsers) {
10295                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10296                                    userHandle, installerPackageName);
10297                        }
10298                    }
10299                    // Also convey the prior install/uninstall state
10300                    if (allUsers != null && perUserInstalled != null) {
10301                        for (int i = 0; i < allUsers.length; i++) {
10302                            if (DEBUG_INSTALL) {
10303                                Slog.d(TAG, "    user " + allUsers[i]
10304                                        + " => " + perUserInstalled[i]);
10305                            }
10306                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10307                        }
10308                        // these install state changes will be persisted in the
10309                        // upcoming call to mSettings.writeLPr().
10310                    }
10311                }
10312            }
10313            res.name = pkgName;
10314            res.uid = newPackage.applicationInfo.uid;
10315            res.pkg = newPackage;
10316            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10317            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10318            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10319            //to update install status
10320            mSettings.writeLPr();
10321        }
10322    }
10323
10324    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10325        int pFlags = args.flags;
10326        String installerPackageName = args.installerPackageName;
10327        File tmpPackageFile = new File(args.getCodePath());
10328        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10329        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10330        boolean replace = false;
10331        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10332                | (newInstall ? SCAN_NEW_INSTALL : 0);
10333        // Result object to be returned
10334        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10335
10336        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10337        // Retrieve PackageSettings and parse package
10338        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10339                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10340                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10341        PackageParser pp = new PackageParser();
10342        pp.setSeparateProcesses(mSeparateProcesses);
10343        pp.setDisplayMetrics(mMetrics);
10344
10345        final PackageParser.Package pkg;
10346        try {
10347            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10348        } catch (PackageParserException e) {
10349            res.setError("Failed parse during installPackageLI", e);
10350            return;
10351        }
10352
10353        // Mark that we have an install time CPU ABI override.
10354        pkg.cpuAbiOverride = args.abiOverride;
10355
10356        String pkgName = res.name = pkg.packageName;
10357        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10358            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10359                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10360                return;
10361            }
10362        }
10363
10364        try {
10365            pp.collectCertificates(pkg, parseFlags);
10366            pp.collectManifestDigest(pkg);
10367        } catch (PackageParserException e) {
10368            res.setError("Failed collect during installPackageLI", e);
10369            return;
10370        }
10371
10372        /* If the installer passed in a manifest digest, compare it now. */
10373        if (args.manifestDigest != null) {
10374            if (DEBUG_INSTALL) {
10375                final String parsedManifest = pkg.manifestDigest == null ? "null"
10376                        : pkg.manifestDigest.toString();
10377                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10378                        + parsedManifest);
10379            }
10380
10381            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10382                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10383                return;
10384            }
10385        } else if (DEBUG_INSTALL) {
10386            final String parsedManifest = pkg.manifestDigest == null
10387                    ? "null" : pkg.manifestDigest.toString();
10388            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10389        }
10390
10391        // Get rid of all references to package scan path via parser.
10392        pp = null;
10393        String oldCodePath = null;
10394        boolean systemApp = false;
10395        synchronized (mPackages) {
10396            // Check whether the newly-scanned package wants to define an already-defined perm
10397            int N = pkg.permissions.size();
10398            for (int i = N-1; i >= 0; i--) {
10399                PackageParser.Permission perm = pkg.permissions.get(i);
10400                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10401                if (bp != null) {
10402                    // If the defining package is signed with our cert, it's okay.  This
10403                    // also includes the "updating the same package" case, of course.
10404                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10405                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10406                        // If the owning package is the system itself, we log but allow
10407                        // install to proceed; we fail the install on all other permission
10408                        // redefinitions.
10409                        if (!bp.sourcePackage.equals("android")) {
10410                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10411                                    + pkg.packageName + " attempting to redeclare permission "
10412                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10413                            res.origPermission = perm.info.name;
10414                            res.origPackage = bp.sourcePackage;
10415                            return;
10416                        } else {
10417                            Slog.w(TAG, "Package " + pkg.packageName
10418                                    + " attempting to redeclare system permission "
10419                                    + perm.info.name + "; ignoring new declaration");
10420                            pkg.permissions.remove(i);
10421                        }
10422                    }
10423                }
10424            }
10425
10426            // Check if installing already existing package
10427            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10428                String oldName = mSettings.mRenamedPackages.get(pkgName);
10429                if (pkg.mOriginalPackages != null
10430                        && pkg.mOriginalPackages.contains(oldName)
10431                        && mPackages.containsKey(oldName)) {
10432                    // This package is derived from an original package,
10433                    // and this device has been updating from that original
10434                    // name.  We must continue using the original name, so
10435                    // rename the new package here.
10436                    pkg.setPackageName(oldName);
10437                    pkgName = pkg.packageName;
10438                    replace = true;
10439                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10440                            + oldName + " pkgName=" + pkgName);
10441                } else if (mPackages.containsKey(pkgName)) {
10442                    // This package, under its official name, already exists
10443                    // on the device; we should replace it.
10444                    replace = true;
10445                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10446                }
10447            }
10448            PackageSetting ps = mSettings.mPackages.get(pkgName);
10449            if (ps != null) {
10450                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10451                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10452                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10453                    systemApp = (ps.pkg.applicationInfo.flags &
10454                            ApplicationInfo.FLAG_SYSTEM) != 0;
10455                }
10456                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10457            }
10458        }
10459
10460        if (systemApp && onSd) {
10461            // Disable updates to system apps on sdcard
10462            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10463                    "Cannot install updates to system apps on sdcard");
10464            return;
10465        }
10466
10467        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10468            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10469            return;
10470        }
10471
10472        if (replace) {
10473            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10474                    installerPackageName, res);
10475        } else {
10476            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10477                    installerPackageName, res);
10478        }
10479        synchronized (mPackages) {
10480            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10481            if (ps != null) {
10482                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10483            }
10484        }
10485    }
10486
10487    private static boolean isForwardLocked(PackageParser.Package pkg) {
10488        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10489    }
10490
10491    private static boolean isForwardLocked(ApplicationInfo info) {
10492        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10493    }
10494
10495    private boolean isForwardLocked(PackageSetting ps) {
10496        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10497    }
10498
10499    private static boolean isMultiArch(PackageSetting ps) {
10500        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10501    }
10502
10503    private static boolean isMultiArch(ApplicationInfo info) {
10504        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10505    }
10506
10507    private static boolean isExternal(PackageParser.Package pkg) {
10508        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10509    }
10510
10511    private static boolean isExternal(PackageSetting ps) {
10512        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10513    }
10514
10515    private static boolean isExternal(ApplicationInfo info) {
10516        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10517    }
10518
10519    private static boolean isSystemApp(PackageParser.Package pkg) {
10520        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10521    }
10522
10523    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10524        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10525    }
10526
10527    private static boolean isSystemApp(ApplicationInfo info) {
10528        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10529    }
10530
10531    private static boolean isSystemApp(PackageSetting ps) {
10532        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10533    }
10534
10535    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10536        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10537    }
10538
10539    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10540        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10541    }
10542
10543    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10544        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10545    }
10546
10547    private int packageFlagsToInstallFlags(PackageSetting ps) {
10548        int installFlags = 0;
10549        if (isExternal(ps)) {
10550            installFlags |= PackageManager.INSTALL_EXTERNAL;
10551        }
10552        if (isForwardLocked(ps)) {
10553            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10554        }
10555        return installFlags;
10556    }
10557
10558    private void deleteTempPackageFiles() {
10559        final FilenameFilter filter = new FilenameFilter() {
10560            public boolean accept(File dir, String name) {
10561                return name.startsWith("vmdl") && name.endsWith(".tmp");
10562            }
10563        };
10564        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10565            file.delete();
10566        }
10567    }
10568
10569    @Override
10570    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10571            int flags) {
10572        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10573                flags);
10574    }
10575
10576    @Override
10577    public void deletePackage(final String packageName,
10578            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10579        mContext.enforceCallingOrSelfPermission(
10580                android.Manifest.permission.DELETE_PACKAGES, null);
10581        final int uid = Binder.getCallingUid();
10582        if (UserHandle.getUserId(uid) != userId) {
10583            mContext.enforceCallingPermission(
10584                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10585                    "deletePackage for user " + userId);
10586        }
10587        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10588            try {
10589                observer.onPackageDeleted(packageName,
10590                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10591            } catch (RemoteException re) {
10592            }
10593            return;
10594        }
10595
10596        boolean uninstallBlocked = false;
10597        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10598            int[] users = sUserManager.getUserIds();
10599            for (int i = 0; i < users.length; ++i) {
10600                if (getBlockUninstallForUser(packageName, users[i])) {
10601                    uninstallBlocked = true;
10602                    break;
10603                }
10604            }
10605        } else {
10606            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10607        }
10608        if (uninstallBlocked) {
10609            try {
10610                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10611                        null);
10612            } catch (RemoteException re) {
10613            }
10614            return;
10615        }
10616
10617        if (DEBUG_REMOVE) {
10618            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10619        }
10620        // Queue up an async operation since the package deletion may take a little while.
10621        mHandler.post(new Runnable() {
10622            public void run() {
10623                mHandler.removeCallbacks(this);
10624                final int returnCode = deletePackageX(packageName, userId, flags);
10625                if (observer != null) {
10626                    try {
10627                        observer.onPackageDeleted(packageName, returnCode, null);
10628                    } catch (RemoteException e) {
10629                        Log.i(TAG, "Observer no longer exists.");
10630                    } //end catch
10631                } //end if
10632            } //end run
10633        });
10634    }
10635
10636    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10637        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10638                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10639        try {
10640            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10641                    || dpm.isDeviceOwner(packageName))) {
10642                return true;
10643            }
10644        } catch (RemoteException e) {
10645        }
10646        return false;
10647    }
10648
10649    /**
10650     *  This method is an internal method that could be get invoked either
10651     *  to delete an installed package or to clean up a failed installation.
10652     *  After deleting an installed package, a broadcast is sent to notify any
10653     *  listeners that the package has been installed. For cleaning up a failed
10654     *  installation, the broadcast is not necessary since the package's
10655     *  installation wouldn't have sent the initial broadcast either
10656     *  The key steps in deleting a package are
10657     *  deleting the package information in internal structures like mPackages,
10658     *  deleting the packages base directories through installd
10659     *  updating mSettings to reflect current status
10660     *  persisting settings for later use
10661     *  sending a broadcast if necessary
10662     */
10663    private int deletePackageX(String packageName, int userId, int flags) {
10664        final PackageRemovedInfo info = new PackageRemovedInfo();
10665        final boolean res;
10666
10667        if (isPackageDeviceAdmin(packageName, userId)) {
10668            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10669            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10670        }
10671
10672        boolean removedForAllUsers = false;
10673        boolean systemUpdate = false;
10674
10675        // for the uninstall-updates case and restricted profiles, remember the per-
10676        // userhandle installed state
10677        int[] allUsers;
10678        boolean[] perUserInstalled;
10679        synchronized (mPackages) {
10680            PackageSetting ps = mSettings.mPackages.get(packageName);
10681            allUsers = sUserManager.getUserIds();
10682            perUserInstalled = new boolean[allUsers.length];
10683            for (int i = 0; i < allUsers.length; i++) {
10684                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10685            }
10686        }
10687
10688        synchronized (mInstallLock) {
10689            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10690            res = deletePackageLI(packageName,
10691                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10692                            ? UserHandle.ALL : new UserHandle(userId),
10693                    true, allUsers, perUserInstalled,
10694                    flags | REMOVE_CHATTY, info, true);
10695            systemUpdate = info.isRemovedPackageSystemUpdate;
10696            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10697                removedForAllUsers = true;
10698            }
10699            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10700                    + " removedForAllUsers=" + removedForAllUsers);
10701        }
10702
10703        if (res) {
10704            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10705
10706            // If the removed package was a system update, the old system package
10707            // was re-enabled; we need to broadcast this information
10708            if (systemUpdate) {
10709                Bundle extras = new Bundle(1);
10710                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10711                        ? info.removedAppId : info.uid);
10712                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10713
10714                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10715                        extras, null, null, null);
10716                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10717                        extras, null, null, null);
10718                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10719                        null, packageName, null, null);
10720            }
10721        }
10722        // Force a gc here.
10723        Runtime.getRuntime().gc();
10724        // Delete the resources here after sending the broadcast to let
10725        // other processes clean up before deleting resources.
10726        if (info.args != null) {
10727            synchronized (mInstallLock) {
10728                info.args.doPostDeleteLI(true);
10729            }
10730        }
10731
10732        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10733    }
10734
10735    static class PackageRemovedInfo {
10736        String removedPackage;
10737        int uid = -1;
10738        int removedAppId = -1;
10739        int[] removedUsers = null;
10740        boolean isRemovedPackageSystemUpdate = false;
10741        // Clean up resources deleted packages.
10742        InstallArgs args = null;
10743
10744        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10745            Bundle extras = new Bundle(1);
10746            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10747            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10748            if (replacing) {
10749                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10750            }
10751            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10752            if (removedPackage != null) {
10753                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10754                        extras, null, null, removedUsers);
10755                if (fullRemove && !replacing) {
10756                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10757                            extras, null, null, removedUsers);
10758                }
10759            }
10760            if (removedAppId >= 0) {
10761                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10762                        removedUsers);
10763            }
10764        }
10765    }
10766
10767    /*
10768     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10769     * flag is not set, the data directory is removed as well.
10770     * make sure this flag is set for partially installed apps. If not its meaningless to
10771     * delete a partially installed application.
10772     */
10773    private void removePackageDataLI(PackageSetting ps,
10774            int[] allUserHandles, boolean[] perUserInstalled,
10775            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10776        String packageName = ps.name;
10777        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10778        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10779        // Retrieve object to delete permissions for shared user later on
10780        final PackageSetting deletedPs;
10781        // reader
10782        synchronized (mPackages) {
10783            deletedPs = mSettings.mPackages.get(packageName);
10784            if (outInfo != null) {
10785                outInfo.removedPackage = packageName;
10786                outInfo.removedUsers = deletedPs != null
10787                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10788                        : null;
10789            }
10790        }
10791        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10792            removeDataDirsLI(packageName);
10793            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10794        }
10795        // writer
10796        synchronized (mPackages) {
10797            if (deletedPs != null) {
10798                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10799                    if (outInfo != null) {
10800                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10801                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10802                    }
10803                    if (deletedPs != null) {
10804                        updatePermissionsLPw(deletedPs.name, null, 0);
10805                        if (deletedPs.sharedUser != null) {
10806                            // remove permissions associated with package
10807                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10808                        }
10809                    }
10810                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10811                }
10812                // make sure to preserve per-user disabled state if this removal was just
10813                // a downgrade of a system app to the factory package
10814                if (allUserHandles != null && perUserInstalled != null) {
10815                    if (DEBUG_REMOVE) {
10816                        Slog.d(TAG, "Propagating install state across downgrade");
10817                    }
10818                    for (int i = 0; i < allUserHandles.length; i++) {
10819                        if (DEBUG_REMOVE) {
10820                            Slog.d(TAG, "    user " + allUserHandles[i]
10821                                    + " => " + perUserInstalled[i]);
10822                        }
10823                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10824                    }
10825                }
10826            }
10827            // can downgrade to reader
10828            if (writeSettings) {
10829                // Save settings now
10830                mSettings.writeLPr();
10831            }
10832        }
10833        if (outInfo != null) {
10834            // A user ID was deleted here. Go through all users and remove it
10835            // from KeyStore.
10836            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10837        }
10838    }
10839
10840    static boolean locationIsPrivileged(File path) {
10841        try {
10842            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10843                    .getCanonicalPath();
10844            return path.getCanonicalPath().startsWith(privilegedAppDir);
10845        } catch (IOException e) {
10846            Slog.e(TAG, "Unable to access code path " + path);
10847        }
10848        return false;
10849    }
10850
10851    /*
10852     * Tries to delete system package.
10853     */
10854    private boolean deleteSystemPackageLI(PackageSetting newPs,
10855            int[] allUserHandles, boolean[] perUserInstalled,
10856            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10857        final boolean applyUserRestrictions
10858                = (allUserHandles != null) && (perUserInstalled != null);
10859        PackageSetting disabledPs = null;
10860        // Confirm if the system package has been updated
10861        // An updated system app can be deleted. This will also have to restore
10862        // the system pkg from system partition
10863        // reader
10864        synchronized (mPackages) {
10865            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10866        }
10867        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10868                + " disabledPs=" + disabledPs);
10869        if (disabledPs == null) {
10870            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10871            return false;
10872        } else if (DEBUG_REMOVE) {
10873            Slog.d(TAG, "Deleting system pkg from data partition");
10874        }
10875        if (DEBUG_REMOVE) {
10876            if (applyUserRestrictions) {
10877                Slog.d(TAG, "Remembering install states:");
10878                for (int i = 0; i < allUserHandles.length; i++) {
10879                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10880                }
10881            }
10882        }
10883        // Delete the updated package
10884        outInfo.isRemovedPackageSystemUpdate = true;
10885        if (disabledPs.versionCode < newPs.versionCode) {
10886            // Delete data for downgrades
10887            flags &= ~PackageManager.DELETE_KEEP_DATA;
10888        } else {
10889            // Preserve data by setting flag
10890            flags |= PackageManager.DELETE_KEEP_DATA;
10891        }
10892        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10893                allUserHandles, perUserInstalled, outInfo, writeSettings);
10894        if (!ret) {
10895            return false;
10896        }
10897        // writer
10898        synchronized (mPackages) {
10899            // Reinstate the old system package
10900            mSettings.enableSystemPackageLPw(newPs.name);
10901            // Remove any native libraries from the upgraded package.
10902            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10903        }
10904        // Install the system package
10905        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10906        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10907        if (locationIsPrivileged(disabledPs.codePath)) {
10908            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10909        }
10910
10911        final PackageParser.Package newPkg;
10912        try {
10913            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10914        } catch (PackageManagerException e) {
10915            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10916            return false;
10917        }
10918
10919        // writer
10920        synchronized (mPackages) {
10921            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10922            updatePermissionsLPw(newPkg.packageName, newPkg,
10923                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10924            if (applyUserRestrictions) {
10925                if (DEBUG_REMOVE) {
10926                    Slog.d(TAG, "Propagating install state across reinstall");
10927                }
10928                for (int i = 0; i < allUserHandles.length; i++) {
10929                    if (DEBUG_REMOVE) {
10930                        Slog.d(TAG, "    user " + allUserHandles[i]
10931                                + " => " + perUserInstalled[i]);
10932                    }
10933                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10934                }
10935                // Regardless of writeSettings we need to ensure that this restriction
10936                // state propagation is persisted
10937                mSettings.writeAllUsersPackageRestrictionsLPr();
10938            }
10939            // can downgrade to reader here
10940            if (writeSettings) {
10941                mSettings.writeLPr();
10942            }
10943        }
10944        return true;
10945    }
10946
10947    private boolean deleteInstalledPackageLI(PackageSetting ps,
10948            boolean deleteCodeAndResources, int flags,
10949            int[] allUserHandles, boolean[] perUserInstalled,
10950            PackageRemovedInfo outInfo, boolean writeSettings) {
10951        if (outInfo != null) {
10952            outInfo.uid = ps.appId;
10953        }
10954
10955        // Delete package data from internal structures and also remove data if flag is set
10956        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10957
10958        // Delete application code and resources
10959        if (deleteCodeAndResources && (outInfo != null)) {
10960            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10961                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10962                    getAppDexInstructionSets(ps), isMultiArch(ps));
10963        }
10964        return true;
10965    }
10966
10967    @Override
10968    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10969            int userId) {
10970        mContext.enforceCallingOrSelfPermission(
10971                android.Manifest.permission.DELETE_PACKAGES, null);
10972        synchronized (mPackages) {
10973            PackageSetting ps = mSettings.mPackages.get(packageName);
10974            if (ps == null) {
10975                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10976                return false;
10977            }
10978            if (!ps.getInstalled(userId)) {
10979                // Can't block uninstall for an app that is not installed or enabled.
10980                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10981                return false;
10982            }
10983            ps.setBlockUninstall(blockUninstall, userId);
10984            mSettings.writePackageRestrictionsLPr(userId);
10985        }
10986        return true;
10987    }
10988
10989    @Override
10990    public boolean getBlockUninstallForUser(String packageName, int userId) {
10991        synchronized (mPackages) {
10992            PackageSetting ps = mSettings.mPackages.get(packageName);
10993            if (ps == null) {
10994                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10995                return false;
10996            }
10997            return ps.getBlockUninstall(userId);
10998        }
10999    }
11000
11001    /*
11002     * This method handles package deletion in general
11003     */
11004    private boolean deletePackageLI(String packageName, UserHandle user,
11005            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11006            int flags, PackageRemovedInfo outInfo,
11007            boolean writeSettings) {
11008        if (packageName == null) {
11009            Slog.w(TAG, "Attempt to delete null packageName.");
11010            return false;
11011        }
11012        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11013        PackageSetting ps;
11014        boolean dataOnly = false;
11015        int removeUser = -1;
11016        int appId = -1;
11017        synchronized (mPackages) {
11018            ps = mSettings.mPackages.get(packageName);
11019            if (ps == null) {
11020                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11021                return false;
11022            }
11023            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11024                    && user.getIdentifier() != UserHandle.USER_ALL) {
11025                // The caller is asking that the package only be deleted for a single
11026                // user.  To do this, we just mark its uninstalled state and delete
11027                // its data.  If this is a system app, we only allow this to happen if
11028                // they have set the special DELETE_SYSTEM_APP which requests different
11029                // semantics than normal for uninstalling system apps.
11030                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11031                ps.setUserState(user.getIdentifier(),
11032                        COMPONENT_ENABLED_STATE_DEFAULT,
11033                        false, //installed
11034                        true,  //stopped
11035                        true,  //notLaunched
11036                        false, //hidden
11037                        null, null, null,
11038                        false // blockUninstall
11039                        );
11040                if (!isSystemApp(ps)) {
11041                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11042                        // Other user still have this package installed, so all
11043                        // we need to do is clear this user's data and save that
11044                        // it is uninstalled.
11045                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11046                        removeUser = user.getIdentifier();
11047                        appId = ps.appId;
11048                        mSettings.writePackageRestrictionsLPr(removeUser);
11049                    } else {
11050                        // We need to set it back to 'installed' so the uninstall
11051                        // broadcasts will be sent correctly.
11052                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11053                        ps.setInstalled(true, user.getIdentifier());
11054                    }
11055                } else {
11056                    // This is a system app, so we assume that the
11057                    // other users still have this package installed, so all
11058                    // we need to do is clear this user's data and save that
11059                    // it is uninstalled.
11060                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11061                    removeUser = user.getIdentifier();
11062                    appId = ps.appId;
11063                    mSettings.writePackageRestrictionsLPr(removeUser);
11064                }
11065            }
11066        }
11067
11068        if (removeUser >= 0) {
11069            // From above, we determined that we are deleting this only
11070            // for a single user.  Continue the work here.
11071            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11072            if (outInfo != null) {
11073                outInfo.removedPackage = packageName;
11074                outInfo.removedAppId = appId;
11075                outInfo.removedUsers = new int[] {removeUser};
11076            }
11077            mInstaller.clearUserData(packageName, removeUser);
11078            removeKeystoreDataIfNeeded(removeUser, appId);
11079            schedulePackageCleaning(packageName, removeUser, false);
11080            return true;
11081        }
11082
11083        if (dataOnly) {
11084            // Delete application data first
11085            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11086            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11087            return true;
11088        }
11089
11090        boolean ret = false;
11091        if (isSystemApp(ps)) {
11092            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11093            // When an updated system application is deleted we delete the existing resources as well and
11094            // fall back to existing code in system partition
11095            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11096                    flags, outInfo, writeSettings);
11097        } else {
11098            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11099            // Kill application pre-emptively especially for apps on sd.
11100            killApplication(packageName, ps.appId, "uninstall pkg");
11101            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11102                    allUserHandles, perUserInstalled,
11103                    outInfo, writeSettings);
11104        }
11105
11106        return ret;
11107    }
11108
11109    private final class ClearStorageConnection implements ServiceConnection {
11110        IMediaContainerService mContainerService;
11111
11112        @Override
11113        public void onServiceConnected(ComponentName name, IBinder service) {
11114            synchronized (this) {
11115                mContainerService = IMediaContainerService.Stub.asInterface(service);
11116                notifyAll();
11117            }
11118        }
11119
11120        @Override
11121        public void onServiceDisconnected(ComponentName name) {
11122        }
11123    }
11124
11125    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11126        final boolean mounted;
11127        if (Environment.isExternalStorageEmulated()) {
11128            mounted = true;
11129        } else {
11130            final String status = Environment.getExternalStorageState();
11131
11132            mounted = status.equals(Environment.MEDIA_MOUNTED)
11133                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11134        }
11135
11136        if (!mounted) {
11137            return;
11138        }
11139
11140        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11141        int[] users;
11142        if (userId == UserHandle.USER_ALL) {
11143            users = sUserManager.getUserIds();
11144        } else {
11145            users = new int[] { userId };
11146        }
11147        final ClearStorageConnection conn = new ClearStorageConnection();
11148        if (mContext.bindServiceAsUser(
11149                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11150            try {
11151                for (int curUser : users) {
11152                    long timeout = SystemClock.uptimeMillis() + 5000;
11153                    synchronized (conn) {
11154                        long now = SystemClock.uptimeMillis();
11155                        while (conn.mContainerService == null && now < timeout) {
11156                            try {
11157                                conn.wait(timeout - now);
11158                            } catch (InterruptedException e) {
11159                            }
11160                        }
11161                    }
11162                    if (conn.mContainerService == null) {
11163                        return;
11164                    }
11165
11166                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11167                    clearDirectory(conn.mContainerService,
11168                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11169                    if (allData) {
11170                        clearDirectory(conn.mContainerService,
11171                                userEnv.buildExternalStorageAppDataDirs(packageName));
11172                        clearDirectory(conn.mContainerService,
11173                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11174                    }
11175                }
11176            } finally {
11177                mContext.unbindService(conn);
11178            }
11179        }
11180    }
11181
11182    @Override
11183    public void clearApplicationUserData(final String packageName,
11184            final IPackageDataObserver observer, final int userId) {
11185        mContext.enforceCallingOrSelfPermission(
11186                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11187        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11188        // Queue up an async operation since the package deletion may take a little while.
11189        mHandler.post(new Runnable() {
11190            public void run() {
11191                mHandler.removeCallbacks(this);
11192                final boolean succeeded;
11193                synchronized (mInstallLock) {
11194                    succeeded = clearApplicationUserDataLI(packageName, userId);
11195                }
11196                clearExternalStorageDataSync(packageName, userId, true);
11197                if (succeeded) {
11198                    // invoke DeviceStorageMonitor's update method to clear any notifications
11199                    DeviceStorageMonitorInternal
11200                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11201                    if (dsm != null) {
11202                        dsm.checkMemory();
11203                    }
11204                }
11205                if(observer != null) {
11206                    try {
11207                        observer.onRemoveCompleted(packageName, succeeded);
11208                    } catch (RemoteException e) {
11209                        Log.i(TAG, "Observer no longer exists.");
11210                    }
11211                } //end if observer
11212            } //end run
11213        });
11214    }
11215
11216    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11217        if (packageName == null) {
11218            Slog.w(TAG, "Attempt to delete null packageName.");
11219            return false;
11220        }
11221        PackageParser.Package p;
11222        boolean dataOnly = false;
11223        final int appId;
11224        synchronized (mPackages) {
11225            p = mPackages.get(packageName);
11226            if (p == null) {
11227                dataOnly = true;
11228                PackageSetting ps = mSettings.mPackages.get(packageName);
11229                if ((ps == null) || (ps.pkg == null)) {
11230                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11231                    return false;
11232                }
11233                p = ps.pkg;
11234            }
11235            if (!dataOnly) {
11236                // need to check this only for fully installed applications
11237                if (p == null) {
11238                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11239                    return false;
11240                }
11241                final ApplicationInfo applicationInfo = p.applicationInfo;
11242                if (applicationInfo == null) {
11243                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11244                    return false;
11245                }
11246            }
11247            if (p != null && p.applicationInfo != null) {
11248                appId = p.applicationInfo.uid;
11249            } else {
11250                appId = -1;
11251            }
11252        }
11253        int retCode = mInstaller.clearUserData(packageName, userId);
11254        if (retCode < 0) {
11255            Slog.w(TAG, "Couldn't remove cache files for package: "
11256                    + packageName);
11257            return false;
11258        }
11259        removeKeystoreDataIfNeeded(userId, appId);
11260        return true;
11261    }
11262
11263    /**
11264     * Remove entries from the keystore daemon. Will only remove it if the
11265     * {@code appId} is valid.
11266     */
11267    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11268        if (appId < 0) {
11269            return;
11270        }
11271
11272        final KeyStore keyStore = KeyStore.getInstance();
11273        if (keyStore != null) {
11274            if (userId == UserHandle.USER_ALL) {
11275                for (final int individual : sUserManager.getUserIds()) {
11276                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11277                }
11278            } else {
11279                keyStore.clearUid(UserHandle.getUid(userId, appId));
11280            }
11281        } else {
11282            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11283        }
11284    }
11285
11286    @Override
11287    public void deleteApplicationCacheFiles(final String packageName,
11288            final IPackageDataObserver observer) {
11289        mContext.enforceCallingOrSelfPermission(
11290                android.Manifest.permission.DELETE_CACHE_FILES, null);
11291        // Queue up an async operation since the package deletion may take a little while.
11292        final int userId = UserHandle.getCallingUserId();
11293        mHandler.post(new Runnable() {
11294            public void run() {
11295                mHandler.removeCallbacks(this);
11296                final boolean succeded;
11297                synchronized (mInstallLock) {
11298                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11299                }
11300                clearExternalStorageDataSync(packageName, userId, false);
11301                if(observer != null) {
11302                    try {
11303                        observer.onRemoveCompleted(packageName, succeded);
11304                    } catch (RemoteException e) {
11305                        Log.i(TAG, "Observer no longer exists.");
11306                    }
11307                } //end if observer
11308            } //end run
11309        });
11310    }
11311
11312    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11313        if (packageName == null) {
11314            Slog.w(TAG, "Attempt to delete null packageName.");
11315            return false;
11316        }
11317        PackageParser.Package p;
11318        synchronized (mPackages) {
11319            p = mPackages.get(packageName);
11320        }
11321        if (p == null) {
11322            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11323            return false;
11324        }
11325        final ApplicationInfo applicationInfo = p.applicationInfo;
11326        if (applicationInfo == null) {
11327            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11328            return false;
11329        }
11330        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11331        if (retCode < 0) {
11332            Slog.w(TAG, "Couldn't remove cache files for package: "
11333                       + packageName + " u" + userId);
11334            return false;
11335        }
11336        return true;
11337    }
11338
11339    @Override
11340    public void getPackageSizeInfo(final String packageName, int userHandle,
11341            final IPackageStatsObserver observer) {
11342        mContext.enforceCallingOrSelfPermission(
11343                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11344        if (packageName == null) {
11345            throw new IllegalArgumentException("Attempt to get size of null packageName");
11346        }
11347
11348        PackageStats stats = new PackageStats(packageName, userHandle);
11349
11350        /*
11351         * Queue up an async operation since the package measurement may take a
11352         * little while.
11353         */
11354        Message msg = mHandler.obtainMessage(INIT_COPY);
11355        msg.obj = new MeasureParams(stats, observer);
11356        mHandler.sendMessage(msg);
11357    }
11358
11359    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11360            PackageStats pStats) {
11361        if (packageName == null) {
11362            Slog.w(TAG, "Attempt to get size of null packageName.");
11363            return false;
11364        }
11365        PackageParser.Package p;
11366        boolean dataOnly = false;
11367        String libDirRoot = null;
11368        String asecPath = null;
11369        PackageSetting ps = null;
11370        synchronized (mPackages) {
11371            p = mPackages.get(packageName);
11372            ps = mSettings.mPackages.get(packageName);
11373            if(p == null) {
11374                dataOnly = true;
11375                if((ps == null) || (ps.pkg == null)) {
11376                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11377                    return false;
11378                }
11379                p = ps.pkg;
11380            }
11381            if (ps != null) {
11382                libDirRoot = ps.legacyNativeLibraryPathString;
11383            }
11384            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11385                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11386                if (secureContainerId != null) {
11387                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11388                }
11389            }
11390        }
11391        String publicSrcDir = null;
11392        if(!dataOnly) {
11393            final ApplicationInfo applicationInfo = p.applicationInfo;
11394            if (applicationInfo == null) {
11395                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11396                return false;
11397            }
11398            if (isForwardLocked(p)) {
11399                publicSrcDir = applicationInfo.getBaseResourcePath();
11400            }
11401        }
11402        // TODO: extend to measure size of split APKs
11403        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11404        // not just the first level.
11405        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11406        // just the primary.
11407        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11408        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11409                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11410        if (res < 0) {
11411            return false;
11412        }
11413
11414        // Fix-up for forward-locked applications in ASEC containers.
11415        if (!isExternal(p)) {
11416            pStats.codeSize += pStats.externalCodeSize;
11417            pStats.externalCodeSize = 0L;
11418        }
11419
11420        return true;
11421    }
11422
11423
11424    @Override
11425    public void addPackageToPreferred(String packageName) {
11426        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11427    }
11428
11429    @Override
11430    public void removePackageFromPreferred(String packageName) {
11431        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11432    }
11433
11434    @Override
11435    public List<PackageInfo> getPreferredPackages(int flags) {
11436        return new ArrayList<PackageInfo>();
11437    }
11438
11439    private int getUidTargetSdkVersionLockedLPr(int uid) {
11440        Object obj = mSettings.getUserIdLPr(uid);
11441        if (obj instanceof SharedUserSetting) {
11442            final SharedUserSetting sus = (SharedUserSetting) obj;
11443            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11444            final Iterator<PackageSetting> it = sus.packages.iterator();
11445            while (it.hasNext()) {
11446                final PackageSetting ps = it.next();
11447                if (ps.pkg != null) {
11448                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11449                    if (v < vers) vers = v;
11450                }
11451            }
11452            return vers;
11453        } else if (obj instanceof PackageSetting) {
11454            final PackageSetting ps = (PackageSetting) obj;
11455            if (ps.pkg != null) {
11456                return ps.pkg.applicationInfo.targetSdkVersion;
11457            }
11458        }
11459        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11460    }
11461
11462    @Override
11463    public void addPreferredActivity(IntentFilter filter, int match,
11464            ComponentName[] set, ComponentName activity, int userId) {
11465        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11466    }
11467
11468    private void addPreferredActivityInternal(IntentFilter filter, int match,
11469            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11470        // writer
11471        int callingUid = Binder.getCallingUid();
11472        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11473        if (filter.countActions() == 0) {
11474            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11475            return;
11476        }
11477        synchronized (mPackages) {
11478            if (mContext.checkCallingOrSelfPermission(
11479                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11480                    != PackageManager.PERMISSION_GRANTED) {
11481                if (getUidTargetSdkVersionLockedLPr(callingUid)
11482                        < Build.VERSION_CODES.FROYO) {
11483                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11484                            + callingUid);
11485                    return;
11486                }
11487                mContext.enforceCallingOrSelfPermission(
11488                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11489            }
11490
11491            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11492            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11493            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11494                    new PreferredActivity(filter, match, set, activity, always));
11495            mSettings.writePackageRestrictionsLPr(userId);
11496        }
11497    }
11498
11499    @Override
11500    public void replacePreferredActivity(IntentFilter filter, int match,
11501            ComponentName[] set, ComponentName activity, int userId) {
11502        if (filter.countActions() != 1) {
11503            throw new IllegalArgumentException(
11504                    "replacePreferredActivity expects filter to have only 1 action.");
11505        }
11506        if (filter.countDataAuthorities() != 0
11507                || filter.countDataPaths() != 0
11508                || filter.countDataSchemes() > 1
11509                || filter.countDataTypes() != 0) {
11510            throw new IllegalArgumentException(
11511                    "replacePreferredActivity expects filter to have no data authorities, " +
11512                    "paths, or types; and at most one scheme.");
11513        }
11514
11515        final int callingUid = Binder.getCallingUid();
11516        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11517        final int callingUserId = UserHandle.getUserId(callingUid);
11518        synchronized (mPackages) {
11519            if (mContext.checkCallingOrSelfPermission(
11520                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11521                    != PackageManager.PERMISSION_GRANTED) {
11522                if (getUidTargetSdkVersionLockedLPr(callingUid)
11523                        < Build.VERSION_CODES.FROYO) {
11524                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11525                            + Binder.getCallingUid());
11526                    return;
11527                }
11528                mContext.enforceCallingOrSelfPermission(
11529                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11530            }
11531
11532            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11533            if (pir != null) {
11534                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11535                if (filter.countDataSchemes() == 1) {
11536                    Uri.Builder builder = new Uri.Builder();
11537                    builder.scheme(filter.getDataScheme(0));
11538                    intent.setData(builder.build());
11539                }
11540                List<PreferredActivity> matches = pir.queryIntent(
11541                        intent, null, true, callingUserId);
11542                if (DEBUG_PREFERRED) {
11543                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11544                }
11545                for (int i = 0; i < matches.size(); i++) {
11546                    PreferredActivity pa = matches.get(i);
11547                    if (DEBUG_PREFERRED) {
11548                        Slog.i(TAG, "Removing preferred activity "
11549                                + pa.mPref.mComponent + ":");
11550                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11551                    }
11552                    pir.removeFilter(pa);
11553                }
11554            }
11555            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11556        }
11557    }
11558
11559    @Override
11560    public void clearPackagePreferredActivities(String packageName) {
11561        final int uid = Binder.getCallingUid();
11562        // writer
11563        synchronized (mPackages) {
11564            PackageParser.Package pkg = mPackages.get(packageName);
11565            if (pkg == null || pkg.applicationInfo.uid != uid) {
11566                if (mContext.checkCallingOrSelfPermission(
11567                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11568                        != PackageManager.PERMISSION_GRANTED) {
11569                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11570                            < Build.VERSION_CODES.FROYO) {
11571                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11572                                + Binder.getCallingUid());
11573                        return;
11574                    }
11575                    mContext.enforceCallingOrSelfPermission(
11576                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11577                }
11578            }
11579
11580            int user = UserHandle.getCallingUserId();
11581            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11582                mSettings.writePackageRestrictionsLPr(user);
11583                scheduleWriteSettingsLocked();
11584            }
11585        }
11586    }
11587
11588    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11589    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11590        ArrayList<PreferredActivity> removed = null;
11591        boolean changed = false;
11592        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11593            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11594            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11595            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11596                continue;
11597            }
11598            Iterator<PreferredActivity> it = pir.filterIterator();
11599            while (it.hasNext()) {
11600                PreferredActivity pa = it.next();
11601                // Mark entry for removal only if it matches the package name
11602                // and the entry is of type "always".
11603                if (packageName == null ||
11604                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11605                                && pa.mPref.mAlways)) {
11606                    if (removed == null) {
11607                        removed = new ArrayList<PreferredActivity>();
11608                    }
11609                    removed.add(pa);
11610                }
11611            }
11612            if (removed != null) {
11613                for (int j=0; j<removed.size(); j++) {
11614                    PreferredActivity pa = removed.get(j);
11615                    pir.removeFilter(pa);
11616                }
11617                changed = true;
11618            }
11619        }
11620        return changed;
11621    }
11622
11623    @Override
11624    public void resetPreferredActivities(int userId) {
11625        mContext.enforceCallingOrSelfPermission(
11626                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11627        // writer
11628        synchronized (mPackages) {
11629            int user = UserHandle.getCallingUserId();
11630            clearPackagePreferredActivitiesLPw(null, user);
11631            mSettings.readDefaultPreferredAppsLPw(this, user);
11632            mSettings.writePackageRestrictionsLPr(user);
11633            scheduleWriteSettingsLocked();
11634        }
11635    }
11636
11637    @Override
11638    public int getPreferredActivities(List<IntentFilter> outFilters,
11639            List<ComponentName> outActivities, String packageName) {
11640
11641        int num = 0;
11642        final int userId = UserHandle.getCallingUserId();
11643        // reader
11644        synchronized (mPackages) {
11645            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11646            if (pir != null) {
11647                final Iterator<PreferredActivity> it = pir.filterIterator();
11648                while (it.hasNext()) {
11649                    final PreferredActivity pa = it.next();
11650                    if (packageName == null
11651                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11652                                    && pa.mPref.mAlways)) {
11653                        if (outFilters != null) {
11654                            outFilters.add(new IntentFilter(pa));
11655                        }
11656                        if (outActivities != null) {
11657                            outActivities.add(pa.mPref.mComponent);
11658                        }
11659                    }
11660                }
11661            }
11662        }
11663
11664        return num;
11665    }
11666
11667    @Override
11668    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11669            int userId) {
11670        int callingUid = Binder.getCallingUid();
11671        if (callingUid != Process.SYSTEM_UID) {
11672            throw new SecurityException(
11673                    "addPersistentPreferredActivity can only be run by the system");
11674        }
11675        if (filter.countActions() == 0) {
11676            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11677            return;
11678        }
11679        synchronized (mPackages) {
11680            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11681                    " :");
11682            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11683            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11684                    new PersistentPreferredActivity(filter, activity));
11685            mSettings.writePackageRestrictionsLPr(userId);
11686        }
11687    }
11688
11689    @Override
11690    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11691        int callingUid = Binder.getCallingUid();
11692        if (callingUid != Process.SYSTEM_UID) {
11693            throw new SecurityException(
11694                    "clearPackagePersistentPreferredActivities can only be run by the system");
11695        }
11696        ArrayList<PersistentPreferredActivity> removed = null;
11697        boolean changed = false;
11698        synchronized (mPackages) {
11699            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11700                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11701                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11702                        .valueAt(i);
11703                if (userId != thisUserId) {
11704                    continue;
11705                }
11706                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11707                while (it.hasNext()) {
11708                    PersistentPreferredActivity ppa = it.next();
11709                    // Mark entry for removal only if it matches the package name.
11710                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11711                        if (removed == null) {
11712                            removed = new ArrayList<PersistentPreferredActivity>();
11713                        }
11714                        removed.add(ppa);
11715                    }
11716                }
11717                if (removed != null) {
11718                    for (int j=0; j<removed.size(); j++) {
11719                        PersistentPreferredActivity ppa = removed.get(j);
11720                        ppir.removeFilter(ppa);
11721                    }
11722                    changed = true;
11723                }
11724            }
11725
11726            if (changed) {
11727                mSettings.writePackageRestrictionsLPr(userId);
11728            }
11729        }
11730    }
11731
11732    @Override
11733    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11734            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11735        mContext.enforceCallingOrSelfPermission(
11736                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11737        int callingUid = Binder.getCallingUid();
11738        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11739        if (intentFilter.countActions() == 0) {
11740            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11741            return;
11742        }
11743        synchronized (mPackages) {
11744            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11745                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11746            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11747            mSettings.writePackageRestrictionsLPr(sourceUserId);
11748        }
11749    }
11750
11751    @Override
11752    public void addCrossProfileIntentsForPackage(String packageName,
11753            int sourceUserId, int targetUserId) {
11754        mContext.enforceCallingOrSelfPermission(
11755                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11756        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11757        mSettings.writePackageRestrictionsLPr(sourceUserId);
11758    }
11759
11760    @Override
11761    public void removeCrossProfileIntentsForPackage(String packageName,
11762            int sourceUserId, int targetUserId) {
11763        mContext.enforceCallingOrSelfPermission(
11764                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11765        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11766        mSettings.writePackageRestrictionsLPr(sourceUserId);
11767    }
11768
11769    @Override
11770    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11771            int ownerUserId) {
11772        mContext.enforceCallingOrSelfPermission(
11773                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11774        int callingUid = Binder.getCallingUid();
11775        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11776        int callingUserId = UserHandle.getUserId(callingUid);
11777        synchronized (mPackages) {
11778            CrossProfileIntentResolver resolver =
11779                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11780            HashSet<CrossProfileIntentFilter> set =
11781                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11782            for (CrossProfileIntentFilter filter : set) {
11783                if (filter.getOwnerPackage().equals(ownerPackage)
11784                        && filter.getOwnerUserId() == callingUserId) {
11785                    resolver.removeFilter(filter);
11786                }
11787            }
11788            mSettings.writePackageRestrictionsLPr(sourceUserId);
11789        }
11790    }
11791
11792    // Enforcing that callingUid is owning pkg on userId
11793    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11794        // The system owns everything.
11795        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11796            return;
11797        }
11798        int callingUserId = UserHandle.getUserId(callingUid);
11799        if (callingUserId != userId) {
11800            throw new SecurityException("calling uid " + callingUid
11801                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11802                    + callingUserId);
11803        }
11804        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11805        if (pi == null) {
11806            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11807                    + callingUserId);
11808        }
11809        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11810            throw new SecurityException("Calling uid " + callingUid
11811                    + " does not own package " + pkg);
11812        }
11813    }
11814
11815    @Override
11816    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11817        Intent intent = new Intent(Intent.ACTION_MAIN);
11818        intent.addCategory(Intent.CATEGORY_HOME);
11819
11820        final int callingUserId = UserHandle.getCallingUserId();
11821        List<ResolveInfo> list = queryIntentActivities(intent, null,
11822                PackageManager.GET_META_DATA, callingUserId);
11823        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11824                true, false, false, callingUserId);
11825
11826        allHomeCandidates.clear();
11827        if (list != null) {
11828            for (ResolveInfo ri : list) {
11829                allHomeCandidates.add(ri);
11830            }
11831        }
11832        return (preferred == null || preferred.activityInfo == null)
11833                ? null
11834                : new ComponentName(preferred.activityInfo.packageName,
11835                        preferred.activityInfo.name);
11836    }
11837
11838    /**
11839     * Check if calling UID is the current home app. This handles both the case
11840     * where the user has selected a specific home app, and where there is only
11841     * one home app.
11842     */
11843    public boolean checkCallerIsHomeApp() {
11844        final Intent intent = new Intent(Intent.ACTION_MAIN);
11845        intent.addCategory(Intent.CATEGORY_HOME);
11846
11847        final int callingUid = Binder.getCallingUid();
11848        final int callingUserId = UserHandle.getCallingUserId();
11849        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11850        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11851                false, false, callingUserId);
11852
11853        if (preferredHome != null) {
11854            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11855                return true;
11856            }
11857        } else {
11858            for (ResolveInfo info : allHomes) {
11859                if (callingUid == info.activityInfo.applicationInfo.uid) {
11860                    return true;
11861                }
11862            }
11863        }
11864
11865        return false;
11866    }
11867
11868    /**
11869     * Enforce that calling UID is the current home app. This handles both the
11870     * case where the user has selected a specific home app, and where there is
11871     * only one home app.
11872     */
11873    public void enforceCallerIsHomeApp() {
11874        if (!checkCallerIsHomeApp()) {
11875            throw new SecurityException("Caller is not currently selected home app");
11876        }
11877    }
11878
11879    @Override
11880    public void setApplicationEnabledSetting(String appPackageName,
11881            int newState, int flags, int userId, String callingPackage) {
11882        if (!sUserManager.exists(userId)) return;
11883        if (callingPackage == null) {
11884            callingPackage = Integer.toString(Binder.getCallingUid());
11885        }
11886        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11887    }
11888
11889    @Override
11890    public void setComponentEnabledSetting(ComponentName componentName,
11891            int newState, int flags, int userId) {
11892        if (!sUserManager.exists(userId)) return;
11893        setEnabledSetting(componentName.getPackageName(),
11894                componentName.getClassName(), newState, flags, userId, null);
11895    }
11896
11897    private void setEnabledSetting(final String packageName, String className, int newState,
11898            final int flags, int userId, String callingPackage) {
11899        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11900              || newState == COMPONENT_ENABLED_STATE_ENABLED
11901              || newState == COMPONENT_ENABLED_STATE_DISABLED
11902              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11903              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11904            throw new IllegalArgumentException("Invalid new component state: "
11905                    + newState);
11906        }
11907        PackageSetting pkgSetting;
11908        final int uid = Binder.getCallingUid();
11909        final int permission = mContext.checkCallingOrSelfPermission(
11910                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11911        enforceCrossUserPermission(uid, userId, false, "set enabled");
11912        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11913        boolean sendNow = false;
11914        boolean isApp = (className == null);
11915        String componentName = isApp ? packageName : className;
11916        int packageUid = -1;
11917        ArrayList<String> components;
11918
11919        // writer
11920        synchronized (mPackages) {
11921            pkgSetting = mSettings.mPackages.get(packageName);
11922            if (pkgSetting == null) {
11923                if (className == null) {
11924                    throw new IllegalArgumentException(
11925                            "Unknown package: " + packageName);
11926                }
11927                throw new IllegalArgumentException(
11928                        "Unknown component: " + packageName
11929                        + "/" + className);
11930            }
11931            // Allow root and verify that userId is not being specified by a different user
11932            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11933                throw new SecurityException(
11934                        "Permission Denial: attempt to change component state from pid="
11935                        + Binder.getCallingPid()
11936                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11937            }
11938            if (className == null) {
11939                // We're dealing with an application/package level state change
11940                if (pkgSetting.getEnabled(userId) == newState) {
11941                    // Nothing to do
11942                    return;
11943                }
11944                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11945                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11946                    // Don't care about who enables an app.
11947                    callingPackage = null;
11948                }
11949                pkgSetting.setEnabled(newState, userId, callingPackage);
11950                // pkgSetting.pkg.mSetEnabled = newState;
11951            } else {
11952                // We're dealing with a component level state change
11953                // First, verify that this is a valid class name.
11954                PackageParser.Package pkg = pkgSetting.pkg;
11955                if (pkg == null || !pkg.hasComponentClassName(className)) {
11956                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11957                        throw new IllegalArgumentException("Component class " + className
11958                                + " does not exist in " + packageName);
11959                    } else {
11960                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11961                                + className + " does not exist in " + packageName);
11962                    }
11963                }
11964                switch (newState) {
11965                case COMPONENT_ENABLED_STATE_ENABLED:
11966                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11967                        return;
11968                    }
11969                    break;
11970                case COMPONENT_ENABLED_STATE_DISABLED:
11971                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11972                        return;
11973                    }
11974                    break;
11975                case COMPONENT_ENABLED_STATE_DEFAULT:
11976                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11977                        return;
11978                    }
11979                    break;
11980                default:
11981                    Slog.e(TAG, "Invalid new component state: " + newState);
11982                    return;
11983                }
11984            }
11985            mSettings.writePackageRestrictionsLPr(userId);
11986            components = mPendingBroadcasts.get(userId, packageName);
11987            final boolean newPackage = components == null;
11988            if (newPackage) {
11989                components = new ArrayList<String>();
11990            }
11991            if (!components.contains(componentName)) {
11992                components.add(componentName);
11993            }
11994            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11995                sendNow = true;
11996                // Purge entry from pending broadcast list if another one exists already
11997                // since we are sending one right away.
11998                mPendingBroadcasts.remove(userId, packageName);
11999            } else {
12000                if (newPackage) {
12001                    mPendingBroadcasts.put(userId, packageName, components);
12002                }
12003                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12004                    // Schedule a message
12005                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12006                }
12007            }
12008        }
12009
12010        long callingId = Binder.clearCallingIdentity();
12011        try {
12012            if (sendNow) {
12013                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12014                sendPackageChangedBroadcast(packageName,
12015                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12016            }
12017        } finally {
12018            Binder.restoreCallingIdentity(callingId);
12019        }
12020    }
12021
12022    private void sendPackageChangedBroadcast(String packageName,
12023            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12024        if (DEBUG_INSTALL)
12025            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12026                    + componentNames);
12027        Bundle extras = new Bundle(4);
12028        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12029        String nameList[] = new String[componentNames.size()];
12030        componentNames.toArray(nameList);
12031        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12032        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12033        extras.putInt(Intent.EXTRA_UID, packageUid);
12034        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12035                new int[] {UserHandle.getUserId(packageUid)});
12036    }
12037
12038    @Override
12039    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12040        if (!sUserManager.exists(userId)) return;
12041        final int uid = Binder.getCallingUid();
12042        final int permission = mContext.checkCallingOrSelfPermission(
12043                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12044        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12045        enforceCrossUserPermission(uid, userId, true, "stop package");
12046        // writer
12047        synchronized (mPackages) {
12048            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12049                    uid, userId)) {
12050                scheduleWritePackageRestrictionsLocked(userId);
12051            }
12052        }
12053    }
12054
12055    @Override
12056    public String getInstallerPackageName(String packageName) {
12057        // reader
12058        synchronized (mPackages) {
12059            return mSettings.getInstallerPackageNameLPr(packageName);
12060        }
12061    }
12062
12063    @Override
12064    public int getApplicationEnabledSetting(String packageName, int userId) {
12065        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12066        int uid = Binder.getCallingUid();
12067        enforceCrossUserPermission(uid, userId, false, "get enabled");
12068        // reader
12069        synchronized (mPackages) {
12070            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12071        }
12072    }
12073
12074    @Override
12075    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12076        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12077        int uid = Binder.getCallingUid();
12078        enforceCrossUserPermission(uid, userId, false, "get component enabled");
12079        // reader
12080        synchronized (mPackages) {
12081            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12082        }
12083    }
12084
12085    @Override
12086    public void enterSafeMode() {
12087        enforceSystemOrRoot("Only the system can request entering safe mode");
12088
12089        if (!mSystemReady) {
12090            mSafeMode = true;
12091        }
12092    }
12093
12094    @Override
12095    public void systemReady() {
12096        mSystemReady = true;
12097
12098        // Read the compatibilty setting when the system is ready.
12099        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12100                mContext.getContentResolver(),
12101                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12102        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12103        if (DEBUG_SETTINGS) {
12104            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12105        }
12106
12107        synchronized (mPackages) {
12108            // Verify that all of the preferred activity components actually
12109            // exist.  It is possible for applications to be updated and at
12110            // that point remove a previously declared activity component that
12111            // had been set as a preferred activity.  We try to clean this up
12112            // the next time we encounter that preferred activity, but it is
12113            // possible for the user flow to never be able to return to that
12114            // situation so here we do a sanity check to make sure we haven't
12115            // left any junk around.
12116            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12117            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12118                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12119                removed.clear();
12120                for (PreferredActivity pa : pir.filterSet()) {
12121                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12122                        removed.add(pa);
12123                    }
12124                }
12125                if (removed.size() > 0) {
12126                    for (int r=0; r<removed.size(); r++) {
12127                        PreferredActivity pa = removed.get(r);
12128                        Slog.w(TAG, "Removing dangling preferred activity: "
12129                                + pa.mPref.mComponent);
12130                        pir.removeFilter(pa);
12131                    }
12132                    mSettings.writePackageRestrictionsLPr(
12133                            mSettings.mPreferredActivities.keyAt(i));
12134                }
12135            }
12136        }
12137        sUserManager.systemReady();
12138    }
12139
12140    @Override
12141    public boolean isSafeMode() {
12142        return mSafeMode;
12143    }
12144
12145    @Override
12146    public boolean hasSystemUidErrors() {
12147        return mHasSystemUidErrors;
12148    }
12149
12150    static String arrayToString(int[] array) {
12151        StringBuffer buf = new StringBuffer(128);
12152        buf.append('[');
12153        if (array != null) {
12154            for (int i=0; i<array.length; i++) {
12155                if (i > 0) buf.append(", ");
12156                buf.append(array[i]);
12157            }
12158        }
12159        buf.append(']');
12160        return buf.toString();
12161    }
12162
12163    static class DumpState {
12164        public static final int DUMP_LIBS = 1 << 0;
12165        public static final int DUMP_FEATURES = 1 << 1;
12166        public static final int DUMP_RESOLVERS = 1 << 2;
12167        public static final int DUMP_PERMISSIONS = 1 << 3;
12168        public static final int DUMP_PACKAGES = 1 << 4;
12169        public static final int DUMP_SHARED_USERS = 1 << 5;
12170        public static final int DUMP_MESSAGES = 1 << 6;
12171        public static final int DUMP_PROVIDERS = 1 << 7;
12172        public static final int DUMP_VERIFIERS = 1 << 8;
12173        public static final int DUMP_PREFERRED = 1 << 9;
12174        public static final int DUMP_PREFERRED_XML = 1 << 10;
12175        public static final int DUMP_KEYSETS = 1 << 11;
12176        public static final int DUMP_VERSION = 1 << 12;
12177        public static final int DUMP_INSTALLS = 1 << 13;
12178
12179        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12180
12181        private int mTypes;
12182
12183        private int mOptions;
12184
12185        private boolean mTitlePrinted;
12186
12187        private SharedUserSetting mSharedUser;
12188
12189        public boolean isDumping(int type) {
12190            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12191                return true;
12192            }
12193
12194            return (mTypes & type) != 0;
12195        }
12196
12197        public void setDump(int type) {
12198            mTypes |= type;
12199        }
12200
12201        public boolean isOptionEnabled(int option) {
12202            return (mOptions & option) != 0;
12203        }
12204
12205        public void setOptionEnabled(int option) {
12206            mOptions |= option;
12207        }
12208
12209        public boolean onTitlePrinted() {
12210            final boolean printed = mTitlePrinted;
12211            mTitlePrinted = true;
12212            return printed;
12213        }
12214
12215        public boolean getTitlePrinted() {
12216            return mTitlePrinted;
12217        }
12218
12219        public void setTitlePrinted(boolean enabled) {
12220            mTitlePrinted = enabled;
12221        }
12222
12223        public SharedUserSetting getSharedUser() {
12224            return mSharedUser;
12225        }
12226
12227        public void setSharedUser(SharedUserSetting user) {
12228            mSharedUser = user;
12229        }
12230    }
12231
12232    @Override
12233    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12234        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12235                != PackageManager.PERMISSION_GRANTED) {
12236            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12237                    + Binder.getCallingPid()
12238                    + ", uid=" + Binder.getCallingUid()
12239                    + " without permission "
12240                    + android.Manifest.permission.DUMP);
12241            return;
12242        }
12243
12244        DumpState dumpState = new DumpState();
12245        boolean fullPreferred = false;
12246        boolean checkin = false;
12247
12248        String packageName = null;
12249
12250        int opti = 0;
12251        while (opti < args.length) {
12252            String opt = args[opti];
12253            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12254                break;
12255            }
12256            opti++;
12257            if ("-a".equals(opt)) {
12258                // Right now we only know how to print all.
12259            } else if ("-h".equals(opt)) {
12260                pw.println("Package manager dump options:");
12261                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12262                pw.println("    --checkin: dump for a checkin");
12263                pw.println("    -f: print details of intent filters");
12264                pw.println("    -h: print this help");
12265                pw.println("  cmd may be one of:");
12266                pw.println("    l[ibraries]: list known shared libraries");
12267                pw.println("    f[ibraries]: list device features");
12268                pw.println("    k[eysets]: print known keysets");
12269                pw.println("    r[esolvers]: dump intent resolvers");
12270                pw.println("    perm[issions]: dump permissions");
12271                pw.println("    pref[erred]: print preferred package settings");
12272                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12273                pw.println("    prov[iders]: dump content providers");
12274                pw.println("    p[ackages]: dump installed packages");
12275                pw.println("    s[hared-users]: dump shared user IDs");
12276                pw.println("    m[essages]: print collected runtime messages");
12277                pw.println("    v[erifiers]: print package verifier info");
12278                pw.println("    version: print database version info");
12279                pw.println("    write: write current settings now");
12280                pw.println("    <package.name>: info about given package");
12281                pw.println("    installs: details about install sessions");
12282                return;
12283            } else if ("--checkin".equals(opt)) {
12284                checkin = true;
12285            } else if ("-f".equals(opt)) {
12286                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12287            } else {
12288                pw.println("Unknown argument: " + opt + "; use -h for help");
12289            }
12290        }
12291
12292        // Is the caller requesting to dump a particular piece of data?
12293        if (opti < args.length) {
12294            String cmd = args[opti];
12295            opti++;
12296            // Is this a package name?
12297            if ("android".equals(cmd) || cmd.contains(".")) {
12298                packageName = cmd;
12299                // When dumping a single package, we always dump all of its
12300                // filter information since the amount of data will be reasonable.
12301                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12302            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12303                dumpState.setDump(DumpState.DUMP_LIBS);
12304            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12305                dumpState.setDump(DumpState.DUMP_FEATURES);
12306            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12307                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12308            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12309                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12310            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12311                dumpState.setDump(DumpState.DUMP_PREFERRED);
12312            } else if ("preferred-xml".equals(cmd)) {
12313                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12314                if (opti < args.length && "--full".equals(args[opti])) {
12315                    fullPreferred = true;
12316                    opti++;
12317                }
12318            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12319                dumpState.setDump(DumpState.DUMP_PACKAGES);
12320            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12321                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12322            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12323                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12324            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12325                dumpState.setDump(DumpState.DUMP_MESSAGES);
12326            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12327                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12328            } else if ("version".equals(cmd)) {
12329                dumpState.setDump(DumpState.DUMP_VERSION);
12330            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12331                dumpState.setDump(DumpState.DUMP_KEYSETS);
12332            } else if ("write".equals(cmd)) {
12333                synchronized (mPackages) {
12334                    mSettings.writeLPr();
12335                    pw.println("Settings written.");
12336                    return;
12337                }
12338            } else if ("installs".equals(cmd)) {
12339                dumpState.setDump(DumpState.DUMP_INSTALLS);
12340            }
12341        }
12342
12343        if (checkin) {
12344            pw.println("vers,1");
12345        }
12346
12347        // reader
12348        synchronized (mPackages) {
12349            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12350                if (!checkin) {
12351                    if (dumpState.onTitlePrinted())
12352                        pw.println();
12353                    pw.println("Database versions:");
12354                    pw.print("  SDK Version:");
12355                    pw.print(" internal=");
12356                    pw.print(mSettings.mInternalSdkPlatform);
12357                    pw.print(" external=");
12358                    pw.println(mSettings.mExternalSdkPlatform);
12359                    pw.print("  DB Version:");
12360                    pw.print(" internal=");
12361                    pw.print(mSettings.mInternalDatabaseVersion);
12362                    pw.print(" external=");
12363                    pw.println(mSettings.mExternalDatabaseVersion);
12364                }
12365            }
12366
12367            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12368                if (!checkin) {
12369                    if (dumpState.onTitlePrinted())
12370                        pw.println();
12371                    pw.println("Verifiers:");
12372                    pw.print("  Required: ");
12373                    pw.print(mRequiredVerifierPackage);
12374                    pw.print(" (uid=");
12375                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12376                    pw.println(")");
12377                } else if (mRequiredVerifierPackage != null) {
12378                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12379                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12380                }
12381            }
12382
12383            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12384                boolean printedHeader = false;
12385                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12386                while (it.hasNext()) {
12387                    String name = it.next();
12388                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12389                    if (!checkin) {
12390                        if (!printedHeader) {
12391                            if (dumpState.onTitlePrinted())
12392                                pw.println();
12393                            pw.println("Libraries:");
12394                            printedHeader = true;
12395                        }
12396                        pw.print("  ");
12397                    } else {
12398                        pw.print("lib,");
12399                    }
12400                    pw.print(name);
12401                    if (!checkin) {
12402                        pw.print(" -> ");
12403                    }
12404                    if (ent.path != null) {
12405                        if (!checkin) {
12406                            pw.print("(jar) ");
12407                            pw.print(ent.path);
12408                        } else {
12409                            pw.print(",jar,");
12410                            pw.print(ent.path);
12411                        }
12412                    } else {
12413                        if (!checkin) {
12414                            pw.print("(apk) ");
12415                            pw.print(ent.apk);
12416                        } else {
12417                            pw.print(",apk,");
12418                            pw.print(ent.apk);
12419                        }
12420                    }
12421                    pw.println();
12422                }
12423            }
12424
12425            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12426                if (dumpState.onTitlePrinted())
12427                    pw.println();
12428                if (!checkin) {
12429                    pw.println("Features:");
12430                }
12431                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12432                while (it.hasNext()) {
12433                    String name = it.next();
12434                    if (!checkin) {
12435                        pw.print("  ");
12436                    } else {
12437                        pw.print("feat,");
12438                    }
12439                    pw.println(name);
12440                }
12441            }
12442
12443            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12444                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12445                        : "Activity Resolver Table:", "  ", packageName,
12446                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12447                    dumpState.setTitlePrinted(true);
12448                }
12449                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12450                        : "Receiver Resolver Table:", "  ", packageName,
12451                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12452                    dumpState.setTitlePrinted(true);
12453                }
12454                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12455                        : "Service Resolver Table:", "  ", packageName,
12456                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12457                    dumpState.setTitlePrinted(true);
12458                }
12459                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12460                        : "Provider Resolver Table:", "  ", packageName,
12461                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12462                    dumpState.setTitlePrinted(true);
12463                }
12464            }
12465
12466            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12467                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12468                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12469                    int user = mSettings.mPreferredActivities.keyAt(i);
12470                    if (pir.dump(pw,
12471                            dumpState.getTitlePrinted()
12472                                ? "\nPreferred Activities User " + user + ":"
12473                                : "Preferred Activities User " + user + ":", "  ",
12474                            packageName, true)) {
12475                        dumpState.setTitlePrinted(true);
12476                    }
12477                }
12478            }
12479
12480            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12481                pw.flush();
12482                FileOutputStream fout = new FileOutputStream(fd);
12483                BufferedOutputStream str = new BufferedOutputStream(fout);
12484                XmlSerializer serializer = new FastXmlSerializer();
12485                try {
12486                    serializer.setOutput(str, "utf-8");
12487                    serializer.startDocument(null, true);
12488                    serializer.setFeature(
12489                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12490                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12491                    serializer.endDocument();
12492                    serializer.flush();
12493                } catch (IllegalArgumentException e) {
12494                    pw.println("Failed writing: " + e);
12495                } catch (IllegalStateException e) {
12496                    pw.println("Failed writing: " + e);
12497                } catch (IOException e) {
12498                    pw.println("Failed writing: " + e);
12499                }
12500            }
12501
12502            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12503                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12504                if (packageName == null) {
12505                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12506                        if (iperm == 0) {
12507                            if (dumpState.onTitlePrinted())
12508                                pw.println();
12509                            pw.println("AppOp Permissions:");
12510                        }
12511                        pw.print("  AppOp Permission ");
12512                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12513                        pw.println(":");
12514                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12515                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12516                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12517                        }
12518                    }
12519                }
12520            }
12521
12522            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12523                boolean printedSomething = false;
12524                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12525                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12526                        continue;
12527                    }
12528                    if (!printedSomething) {
12529                        if (dumpState.onTitlePrinted())
12530                            pw.println();
12531                        pw.println("Registered ContentProviders:");
12532                        printedSomething = true;
12533                    }
12534                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12535                    pw.print("    "); pw.println(p.toString());
12536                }
12537                printedSomething = false;
12538                for (Map.Entry<String, PackageParser.Provider> entry :
12539                        mProvidersByAuthority.entrySet()) {
12540                    PackageParser.Provider p = entry.getValue();
12541                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12542                        continue;
12543                    }
12544                    if (!printedSomething) {
12545                        if (dumpState.onTitlePrinted())
12546                            pw.println();
12547                        pw.println("ContentProvider Authorities:");
12548                        printedSomething = true;
12549                    }
12550                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12551                    pw.print("    "); pw.println(p.toString());
12552                    if (p.info != null && p.info.applicationInfo != null) {
12553                        final String appInfo = p.info.applicationInfo.toString();
12554                        pw.print("      applicationInfo="); pw.println(appInfo);
12555                    }
12556                }
12557            }
12558
12559            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12560                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12561            }
12562
12563            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12564                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12565            }
12566
12567            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12568                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12569            }
12570
12571            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12572                if (dumpState.onTitlePrinted()) pw.println();
12573                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12574            }
12575
12576            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12577                if (dumpState.onTitlePrinted()) pw.println();
12578                mSettings.dumpReadMessagesLPr(pw, dumpState);
12579
12580                pw.println();
12581                pw.println("Package warning messages:");
12582                final File fname = getSettingsProblemFile();
12583                FileInputStream in = null;
12584                try {
12585                    in = new FileInputStream(fname);
12586                    final int avail = in.available();
12587                    final byte[] data = new byte[avail];
12588                    in.read(data);
12589                    pw.print(new String(data));
12590                } catch (FileNotFoundException e) {
12591                } catch (IOException e) {
12592                } finally {
12593                    if (in != null) {
12594                        try {
12595                            in.close();
12596                        } catch (IOException e) {
12597                        }
12598                    }
12599                }
12600            }
12601        }
12602    }
12603
12604    // ------- apps on sdcard specific code -------
12605    static final boolean DEBUG_SD_INSTALL = false;
12606
12607    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12608
12609    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12610
12611    private boolean mMediaMounted = false;
12612
12613    private String getEncryptKey() {
12614        try {
12615            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12616                    SD_ENCRYPTION_KEYSTORE_NAME);
12617            if (sdEncKey == null) {
12618                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12619                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12620                if (sdEncKey == null) {
12621                    Slog.e(TAG, "Failed to create encryption keys");
12622                    return null;
12623                }
12624            }
12625            return sdEncKey;
12626        } catch (NoSuchAlgorithmException nsae) {
12627            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12628            return null;
12629        } catch (IOException ioe) {
12630            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12631            return null;
12632        }
12633
12634    }
12635
12636    /* package */static String getTempContainerId() {
12637        int tmpIdx = 1;
12638        String list[] = PackageHelper.getSecureContainerList();
12639        if (list != null) {
12640            for (final String name : list) {
12641                // Ignore null and non-temporary container entries
12642                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12643                    continue;
12644                }
12645
12646                String subStr = name.substring(mTempContainerPrefix.length());
12647                try {
12648                    int cid = Integer.parseInt(subStr);
12649                    if (cid >= tmpIdx) {
12650                        tmpIdx = cid + 1;
12651                    }
12652                } catch (NumberFormatException e) {
12653                }
12654            }
12655        }
12656        return mTempContainerPrefix + tmpIdx;
12657    }
12658
12659    /*
12660     * Update media status on PackageManager.
12661     */
12662    @Override
12663    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12664        int callingUid = Binder.getCallingUid();
12665        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12666            throw new SecurityException("Media status can only be updated by the system");
12667        }
12668        // reader; this apparently protects mMediaMounted, but should probably
12669        // be a different lock in that case.
12670        synchronized (mPackages) {
12671            Log.i(TAG, "Updating external media status from "
12672                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12673                    + (mediaStatus ? "mounted" : "unmounted"));
12674            if (DEBUG_SD_INSTALL)
12675                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12676                        + ", mMediaMounted=" + mMediaMounted);
12677            if (mediaStatus == mMediaMounted) {
12678                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12679                        : 0, -1);
12680                mHandler.sendMessage(msg);
12681                return;
12682            }
12683            mMediaMounted = mediaStatus;
12684        }
12685        // Queue up an async operation since the package installation may take a
12686        // little while.
12687        mHandler.post(new Runnable() {
12688            public void run() {
12689                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12690            }
12691        });
12692    }
12693
12694    /**
12695     * Called by MountService when the initial ASECs to scan are available.
12696     * Should block until all the ASEC containers are finished being scanned.
12697     */
12698    public void scanAvailableAsecs() {
12699        updateExternalMediaStatusInner(true, false, false);
12700        if (mShouldRestoreconData) {
12701            SELinuxMMAC.setRestoreconDone();
12702            mShouldRestoreconData = false;
12703        }
12704    }
12705
12706    /*
12707     * Collect information of applications on external media, map them against
12708     * existing containers and update information based on current mount status.
12709     * Please note that we always have to report status if reportStatus has been
12710     * set to true especially when unloading packages.
12711     */
12712    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12713            boolean externalStorage) {
12714        // Collection of uids
12715        int uidArr[] = null;
12716        // Collection of stale containers
12717        HashSet<String> removeCids = new HashSet<String>();
12718        // Collection of packages on external media with valid containers.
12719        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12720        // Get list of secure containers.
12721        final String list[] = PackageHelper.getSecureContainerList();
12722        if (list == null || list.length == 0) {
12723            Log.i(TAG, "No secure containers on sdcard");
12724        } else {
12725            // Process list of secure containers and categorize them
12726            // as active or stale based on their package internal state.
12727            int uidList[] = new int[list.length];
12728            int num = 0;
12729            // reader
12730            synchronized (mPackages) {
12731                for (String cid : list) {
12732                    if (DEBUG_SD_INSTALL)
12733                        Log.i(TAG, "Processing container " + cid);
12734                    String pkgName = getAsecPackageName(cid);
12735                    if (pkgName == null) {
12736                        if (DEBUG_SD_INSTALL)
12737                            Log.i(TAG, "Container : " + cid + " stale");
12738                        removeCids.add(cid);
12739                        continue;
12740                    }
12741                    if (DEBUG_SD_INSTALL)
12742                        Log.i(TAG, "Looking for pkg : " + pkgName);
12743
12744                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12745                    if (ps == null) {
12746                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12747                        removeCids.add(cid);
12748                        continue;
12749                    }
12750
12751                    /*
12752                     * Skip packages that are not external if we're unmounting
12753                     * external storage.
12754                     */
12755                    if (externalStorage && !isMounted && !isExternal(ps)) {
12756                        continue;
12757                    }
12758
12759                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12760                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12761                    // The package status is changed only if the code path
12762                    // matches between settings and the container id.
12763                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12764                        if (DEBUG_SD_INSTALL) {
12765                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12766                                    + " at code path: " + ps.codePathString);
12767                        }
12768
12769                        // We do have a valid package installed on sdcard
12770                        processCids.put(args, ps.codePathString);
12771                        final int uid = ps.appId;
12772                        if (uid != -1) {
12773                            uidList[num++] = uid;
12774                        }
12775                    } else {
12776                        Log.i(TAG, "Deleting stale container for " + cid);
12777                        removeCids.add(cid);
12778                    }
12779                }
12780            }
12781
12782            if (num > 0) {
12783                // Sort uid list
12784                Arrays.sort(uidList, 0, num);
12785                // Throw away duplicates
12786                uidArr = new int[num];
12787                uidArr[0] = uidList[0];
12788                int di = 0;
12789                for (int i = 1; i < num; i++) {
12790                    if (uidList[i - 1] != uidList[i]) {
12791                        uidArr[di++] = uidList[i];
12792                    }
12793                }
12794            }
12795        }
12796        // Process packages with valid entries.
12797        if (isMounted) {
12798            if (DEBUG_SD_INSTALL)
12799                Log.i(TAG, "Loading packages");
12800            loadMediaPackages(processCids, uidArr, removeCids);
12801            startCleaningPackages();
12802        } else {
12803            if (DEBUG_SD_INSTALL)
12804                Log.i(TAG, "Unloading packages");
12805            unloadMediaPackages(processCids, uidArr, reportStatus);
12806        }
12807    }
12808
12809   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12810           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12811        int size = pkgList.size();
12812        if (size > 0) {
12813            // Send broadcasts here
12814            Bundle extras = new Bundle();
12815            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12816                    .toArray(new String[size]));
12817            if (uidArr != null) {
12818                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12819            }
12820            if (replacing) {
12821                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12822            }
12823            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12824                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12825            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12826        }
12827    }
12828
12829   /*
12830     * Look at potentially valid container ids from processCids If package
12831     * information doesn't match the one on record or package scanning fails,
12832     * the cid is added to list of removeCids. We currently don't delete stale
12833     * containers.
12834     */
12835   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12836            HashSet<String> removeCids) {
12837        ArrayList<String> pkgList = new ArrayList<String>();
12838        Set<AsecInstallArgs> keys = processCids.keySet();
12839        boolean doGc = false;
12840        for (AsecInstallArgs args : keys) {
12841            String codePath = processCids.get(args);
12842            if (DEBUG_SD_INSTALL)
12843                Log.i(TAG, "Loading container : " + args.cid);
12844            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12845            try {
12846                // Make sure there are no container errors first.
12847                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12848                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12849                            + " when installing from sdcard");
12850                    continue;
12851                }
12852                // Check code path here.
12853                if (codePath == null || !codePath.equals(args.getCodePath())) {
12854                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12855                            + " does not match one in settings " + codePath);
12856                    continue;
12857                }
12858                // Parse package
12859                int parseFlags = mDefParseFlags;
12860                if (args.isExternal()) {
12861                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12862                }
12863                if (args.isFwdLocked()) {
12864                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12865                }
12866
12867                doGc = true;
12868                synchronized (mInstallLock) {
12869                    PackageParser.Package pkg = null;
12870                    try {
12871                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12872                    } catch (PackageManagerException e) {
12873                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12874                    }
12875                    // Scan the package
12876                    if (pkg != null) {
12877                        /*
12878                         * TODO why is the lock being held? doPostInstall is
12879                         * called in other places without the lock. This needs
12880                         * to be straightened out.
12881                         */
12882                        // writer
12883                        synchronized (mPackages) {
12884                            retCode = PackageManager.INSTALL_SUCCEEDED;
12885                            pkgList.add(pkg.packageName);
12886                            // Post process args
12887                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12888                                    pkg.applicationInfo.uid);
12889                        }
12890                    } else {
12891                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12892                    }
12893                }
12894
12895            } finally {
12896                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12897                    // Don't destroy container here. Wait till gc clears things
12898                    // up.
12899                    removeCids.add(args.cid);
12900                }
12901            }
12902        }
12903        // writer
12904        synchronized (mPackages) {
12905            // If the platform SDK has changed since the last time we booted,
12906            // we need to re-grant app permission to catch any new ones that
12907            // appear. This is really a hack, and means that apps can in some
12908            // cases get permissions that the user didn't initially explicitly
12909            // allow... it would be nice to have some better way to handle
12910            // this situation.
12911            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12912            if (regrantPermissions)
12913                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12914                        + mSdkVersion + "; regranting permissions for external storage");
12915            mSettings.mExternalSdkPlatform = mSdkVersion;
12916
12917            // Make sure group IDs have been assigned, and any permission
12918            // changes in other apps are accounted for
12919            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12920                    | (regrantPermissions
12921                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12922                            : 0));
12923
12924            mSettings.updateExternalDatabaseVersion();
12925
12926            // can downgrade to reader
12927            // Persist settings
12928            mSettings.writeLPr();
12929        }
12930        // Send a broadcast to let everyone know we are done processing
12931        if (pkgList.size() > 0) {
12932            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12933        }
12934        // Force gc to avoid any stale parser references that we might have.
12935        if (doGc) {
12936            Runtime.getRuntime().gc();
12937        }
12938        // List stale containers and destroy stale temporary containers.
12939        if (removeCids != null) {
12940            for (String cid : removeCids) {
12941                if (cid.startsWith(mTempContainerPrefix)) {
12942                    Log.i(TAG, "Destroying stale temporary container " + cid);
12943                    PackageHelper.destroySdDir(cid);
12944                } else {
12945                    Log.w(TAG, "Container " + cid + " is stale");
12946               }
12947           }
12948        }
12949    }
12950
12951   /*
12952     * Utility method to unload a list of specified containers
12953     */
12954    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12955        // Just unmount all valid containers.
12956        for (AsecInstallArgs arg : cidArgs) {
12957            synchronized (mInstallLock) {
12958                arg.doPostDeleteLI(false);
12959           }
12960       }
12961   }
12962
12963    /*
12964     * Unload packages mounted on external media. This involves deleting package
12965     * data from internal structures, sending broadcasts about diabled packages,
12966     * gc'ing to free up references, unmounting all secure containers
12967     * corresponding to packages on external media, and posting a
12968     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12969     * that we always have to post this message if status has been requested no
12970     * matter what.
12971     */
12972    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12973            final boolean reportStatus) {
12974        if (DEBUG_SD_INSTALL)
12975            Log.i(TAG, "unloading media packages");
12976        ArrayList<String> pkgList = new ArrayList<String>();
12977        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12978        final Set<AsecInstallArgs> keys = processCids.keySet();
12979        for (AsecInstallArgs args : keys) {
12980            String pkgName = args.getPackageName();
12981            if (DEBUG_SD_INSTALL)
12982                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12983            // Delete package internally
12984            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12985            synchronized (mInstallLock) {
12986                boolean res = deletePackageLI(pkgName, null, false, null, null,
12987                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12988                if (res) {
12989                    pkgList.add(pkgName);
12990                } else {
12991                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12992                    failedList.add(args);
12993                }
12994            }
12995        }
12996
12997        // reader
12998        synchronized (mPackages) {
12999            // We didn't update the settings after removing each package;
13000            // write them now for all packages.
13001            mSettings.writeLPr();
13002        }
13003
13004        // We have to absolutely send UPDATED_MEDIA_STATUS only
13005        // after confirming that all the receivers processed the ordered
13006        // broadcast when packages get disabled, force a gc to clean things up.
13007        // and unload all the containers.
13008        if (pkgList.size() > 0) {
13009            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13010                    new IIntentReceiver.Stub() {
13011                public void performReceive(Intent intent, int resultCode, String data,
13012                        Bundle extras, boolean ordered, boolean sticky,
13013                        int sendingUser) throws RemoteException {
13014                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13015                            reportStatus ? 1 : 0, 1, keys);
13016                    mHandler.sendMessage(msg);
13017                }
13018            });
13019        } else {
13020            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13021                    keys);
13022            mHandler.sendMessage(msg);
13023        }
13024    }
13025
13026    /** Binder call */
13027    @Override
13028    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13029            final int flags) {
13030        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13031        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13032        int returnCode = PackageManager.MOVE_SUCCEEDED;
13033        int currFlags = 0;
13034        int newFlags = 0;
13035        // reader
13036        synchronized (mPackages) {
13037            PackageParser.Package pkg = mPackages.get(packageName);
13038            if (pkg == null) {
13039                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13040            } else {
13041                // Disable moving fwd locked apps and system packages
13042                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13043                    Slog.w(TAG, "Cannot move system application");
13044                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13045                } else if (pkg.mOperationPending) {
13046                    Slog.w(TAG, "Attempt to move package which has pending operations");
13047                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13048                } else {
13049                    // Find install location first
13050                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13051                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13052                        Slog.w(TAG, "Ambigous flags specified for move location.");
13053                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13054                    } else {
13055                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
13056                                : PackageManager.INSTALL_INTERNAL;
13057                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
13058                                : PackageManager.INSTALL_INTERNAL;
13059
13060                        if (newFlags == currFlags) {
13061                            Slog.w(TAG, "No move required. Trying to move to same location");
13062                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13063                        } else {
13064                            if (isForwardLocked(pkg)) {
13065                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13066                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13067                            }
13068                        }
13069                    }
13070                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13071                        pkg.mOperationPending = true;
13072                    }
13073                }
13074            }
13075
13076            /*
13077             * TODO this next block probably shouldn't be inside the lock. We
13078             * can't guarantee these won't change after this is fired off
13079             * anyway.
13080             */
13081            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13082                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
13083                        returnCode);
13084            } else {
13085                Message msg = mHandler.obtainMessage(INIT_COPY);
13086                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
13087                final boolean multiArch = isMultiArch(pkg.applicationInfo);
13088                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
13089                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
13090                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
13091                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
13092                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
13093                msg.obj = mp;
13094                mHandler.sendMessage(msg);
13095            }
13096        }
13097    }
13098
13099    private void processPendingMove(final MoveParams mp, final int currentStatus) {
13100        // Queue up an async operation since the package deletion may take a
13101        // little while.
13102        mHandler.post(new Runnable() {
13103            public void run() {
13104                // TODO fix this; this does nothing.
13105                mHandler.removeCallbacks(this);
13106                int returnCode = currentStatus;
13107                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13108                    int uidArr[] = null;
13109                    ArrayList<String> pkgList = null;
13110                    synchronized (mPackages) {
13111                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13112                        if (pkg == null) {
13113                            Slog.w(TAG, " Package " + mp.packageName
13114                                    + " doesn't exist. Aborting move");
13115                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13116                        } else if (!mp.srcArgs.getCodePath().equals(
13117                                pkg.applicationInfo.getCodePath())) {
13118                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13119                                    + mp.srcArgs.getCodePath() + " to "
13120                                    + pkg.applicationInfo.getCodePath()
13121                                    + " Aborting move and returning error");
13122                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13123                        } else {
13124                            uidArr = new int[] {
13125                                pkg.applicationInfo.uid
13126                            };
13127                            pkgList = new ArrayList<String>();
13128                            pkgList.add(mp.packageName);
13129                        }
13130                    }
13131                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13132                        // Send resources unavailable broadcast
13133                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13134                        // Update package code and resource paths
13135                        synchronized (mInstallLock) {
13136                            synchronized (mPackages) {
13137                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13138                                // Recheck for package again.
13139                                if (pkg == null) {
13140                                    Slog.w(TAG, " Package " + mp.packageName
13141                                            + " doesn't exist. Aborting move");
13142                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13143                                } else if (!mp.srcArgs.getCodePath().equals(
13144                                        pkg.applicationInfo.getCodePath())) {
13145                                    Slog.w(TAG, "Package " + mp.packageName
13146                                            + " code path changed from " + mp.srcArgs.getCodePath()
13147                                            + " to " + pkg.applicationInfo.getCodePath()
13148                                            + " Aborting move and returning error");
13149                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13150                                } else {
13151                                    final String oldCodePath = pkg.codePath;
13152                                    final String newCodePath = mp.targetArgs.getCodePath();
13153                                    final String newResPath = mp.targetArgs.getResourcePath();
13154                                    // TODO: This assumes the new style of installation.
13155                                    // should we look at legacyNativeLibraryPath ?
13156                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13157                                    final File newNativeDir = new File(newNativeRoot);
13158
13159                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13160                                        // TODO(multiArch): Fix this so that it looks at the existing
13161                                        // recorded CPU abis from the package. There's no need for a separate
13162                                        // round of ABI scanning here.
13163                                        NativeLibraryHelper.Handle handle = null;
13164                                        try {
13165                                            handle = NativeLibraryHelper.Handle.create(
13166                                                    new File(newCodePath));
13167                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13168                                                    handle, Build.SUPPORTED_ABIS);
13169                                            if (abi >= 0) {
13170                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13171                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13172                                            }
13173                                        } catch (IOException ioe) {
13174                                            Slog.w(TAG, "Unable to extract native libs for package :"
13175                                                    + mp.packageName, ioe);
13176                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13177                                        } finally {
13178                                            IoUtils.closeQuietly(handle);
13179                                        }
13180                                    }
13181
13182                                    final int[] users = sUserManager.getUserIds();
13183                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13184                                        for (int user : users) {
13185                                            // TODO(multiArch): Fix this so that it links to the
13186                                            // correct directory. We're currently pointing to root. but we
13187                                            // must point to the arch specific subdirectory (if applicable).
13188                                            //
13189                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13190                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13191                                                    newNativeRoot, user) < 0) {
13192                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13193                                            }
13194                                        }
13195                                    }
13196
13197                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13198                                        pkg.codePath = newCodePath;
13199                                        pkg.baseCodePath = newCodePath;
13200                                        // Move dex files around
13201                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13202                                            // Moving of dex files failed. Set
13203                                            // error code and abort move.
13204                                            pkg.codePath = oldCodePath;
13205                                            pkg.baseCodePath = oldCodePath;
13206                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13207                                        }
13208                                    }
13209
13210                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13211                                        pkg.applicationInfo.setCodePath(newCodePath);
13212                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13213                                        pkg.applicationInfo.setSplitCodePaths(null);
13214                                        pkg.applicationInfo.setResourcePath(newResPath);
13215                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13216                                        pkg.applicationInfo.setSplitResourcePaths(null);
13217
13218                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13219                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13220                                        ps.codePathString = ps.codePath.getPath();
13221                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13222                                        ps.resourcePathString = ps.resourcePath.getPath();
13223
13224                                        // Note that we don't have to recalculate the primary and secondary
13225                                        // CPU ABIs because they must already have been calculated during the
13226                                        // initial install of the app.
13227                                        ps.legacyNativeLibraryPathString = null;
13228
13229                                        // Set the application info flag
13230                                        // correctly.
13231                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13232                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13233                                        } else {
13234                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13235                                        }
13236                                        ps.setFlags(pkg.applicationInfo.flags);
13237                                        mAppDirs.remove(oldCodePath);
13238                                        mAppDirs.put(newCodePath, pkg);
13239                                        // Persist settings
13240                                        mSettings.writeLPr();
13241                                    }
13242                                }
13243                            }
13244                        }
13245                        // Send resources available broadcast
13246                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13247                    }
13248                }
13249                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13250                    // Clean up failed installation
13251                    if (mp.targetArgs != null) {
13252                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13253                                -1);
13254                    }
13255                } else {
13256                    // Force a gc to clear things up.
13257                    Runtime.getRuntime().gc();
13258                    // Delete older code
13259                    synchronized (mInstallLock) {
13260                        mp.srcArgs.doPostDeleteLI(true);
13261                    }
13262                }
13263
13264                // Allow more operations on this file if we didn't fail because
13265                // an operation was already pending for this package.
13266                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13267                    synchronized (mPackages) {
13268                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13269                        if (pkg != null) {
13270                            pkg.mOperationPending = false;
13271                       }
13272                   }
13273                }
13274
13275                IPackageMoveObserver observer = mp.observer;
13276                if (observer != null) {
13277                    try {
13278                        observer.packageMoved(mp.packageName, returnCode);
13279                    } catch (RemoteException e) {
13280                        Log.i(TAG, "Observer no longer exists.");
13281                    }
13282                }
13283            }
13284        });
13285    }
13286
13287    @Override
13288    public boolean setInstallLocation(int loc) {
13289        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13290                null);
13291        if (getInstallLocation() == loc) {
13292            return true;
13293        }
13294        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13295                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13296            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13297                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13298            return true;
13299        }
13300        return false;
13301   }
13302
13303    @Override
13304    public int getInstallLocation() {
13305        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13306                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13307                PackageHelper.APP_INSTALL_AUTO);
13308    }
13309
13310    /** Called by UserManagerService */
13311    void cleanUpUserLILPw(int userHandle) {
13312        mDirtyUsers.remove(userHandle);
13313        mSettings.removeUserLPw(userHandle);
13314        mPendingBroadcasts.remove(userHandle);
13315        if (mInstaller != null) {
13316            // Technically, we shouldn't be doing this with the package lock
13317            // held.  However, this is very rare, and there is already so much
13318            // other disk I/O going on, that we'll let it slide for now.
13319            mInstaller.removeUserDataDirs(userHandle);
13320        }
13321        mUserNeedsBadging.delete(userHandle);
13322    }
13323
13324    /** Called by UserManagerService */
13325    void createNewUserLILPw(int userHandle, File path) {
13326        if (mInstaller != null) {
13327            mInstaller.createUserConfig(userHandle);
13328            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13329        }
13330    }
13331
13332    @Override
13333    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13334        mContext.enforceCallingOrSelfPermission(
13335                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13336                "Only package verification agents can read the verifier device identity");
13337
13338        synchronized (mPackages) {
13339            return mSettings.getVerifierDeviceIdentityLPw();
13340        }
13341    }
13342
13343    @Override
13344    public void setPermissionEnforced(String permission, boolean enforced) {
13345        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13346        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13347            synchronized (mPackages) {
13348                if (mSettings.mReadExternalStorageEnforced == null
13349                        || mSettings.mReadExternalStorageEnforced != enforced) {
13350                    mSettings.mReadExternalStorageEnforced = enforced;
13351                    mSettings.writeLPr();
13352                }
13353            }
13354            // kill any non-foreground processes so we restart them and
13355            // grant/revoke the GID.
13356            final IActivityManager am = ActivityManagerNative.getDefault();
13357            if (am != null) {
13358                final long token = Binder.clearCallingIdentity();
13359                try {
13360                    am.killProcessesBelowForeground("setPermissionEnforcement");
13361                } catch (RemoteException e) {
13362                } finally {
13363                    Binder.restoreCallingIdentity(token);
13364                }
13365            }
13366        } else {
13367            throw new IllegalArgumentException("No selective enforcement for " + permission);
13368        }
13369    }
13370
13371    @Override
13372    @Deprecated
13373    public boolean isPermissionEnforced(String permission) {
13374        return true;
13375    }
13376
13377    @Override
13378    public boolean isStorageLow() {
13379        final long token = Binder.clearCallingIdentity();
13380        try {
13381            final DeviceStorageMonitorInternal
13382                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13383            if (dsm != null) {
13384                return dsm.isMemoryLow();
13385            } else {
13386                return false;
13387            }
13388        } finally {
13389            Binder.restoreCallingIdentity(token);
13390        }
13391    }
13392
13393    @Override
13394    public IPackageInstaller getPackageInstaller() {
13395        return mInstallerService;
13396    }
13397
13398    private boolean userNeedsBadging(int userId) {
13399        int index = mUserNeedsBadging.indexOfKey(userId);
13400        if (index < 0) {
13401            final UserInfo userInfo;
13402            final long token = Binder.clearCallingIdentity();
13403            try {
13404                userInfo = sUserManager.getUserInfo(userId);
13405            } finally {
13406                Binder.restoreCallingIdentity(token);
13407            }
13408            final boolean b;
13409            if (userInfo != null && userInfo.isManagedProfile()) {
13410                b = true;
13411            } else {
13412                b = false;
13413            }
13414            mUserNeedsBadging.put(userId, b);
13415            return b;
13416        }
13417        return mUserNeedsBadging.valueAt(index);
13418    }
13419
13420    @Override
13421    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13422        if (packageName == null || alias == null) {
13423            return null;
13424        }
13425        synchronized(mPackages) {
13426            final PackageParser.Package pkg = mPackages.get(packageName);
13427            if (pkg == null) {
13428                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13429                throw new IllegalArgumentException("Unknown package: " + packageName);
13430            }
13431            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13432                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13433                throw new SecurityException("May not access KeySets defined by"
13434                        + " aliases in other applications.");
13435            }
13436            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13437            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13438        }
13439    }
13440
13441    @Override
13442    public KeySetHandle getSigningKeySet(String packageName) {
13443        if (packageName == null) {
13444            return null;
13445        }
13446        synchronized(mPackages) {
13447            final PackageParser.Package pkg = mPackages.get(packageName);
13448            if (pkg == null) {
13449                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13450                throw new IllegalArgumentException("Unknown package: " + packageName);
13451            }
13452            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13453                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13454                throw new SecurityException("May not access signing KeySet of other apps.");
13455            }
13456            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13457            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13458        }
13459    }
13460
13461    @Override
13462    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13463        if (packageName == null || ks == null) {
13464            return false;
13465        }
13466        synchronized(mPackages) {
13467            final PackageParser.Package pkg = mPackages.get(packageName);
13468            if (pkg == null) {
13469                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13470                throw new IllegalArgumentException("Unknown package: " + packageName);
13471            }
13472            if (ks instanceof KeySetHandle) {
13473                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13474                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13475            }
13476            return false;
13477        }
13478    }
13479
13480    @Override
13481    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13482        if (packageName == null || ks == null) {
13483            return false;
13484        }
13485        synchronized(mPackages) {
13486            final PackageParser.Package pkg = mPackages.get(packageName);
13487            if (pkg == null) {
13488                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13489                throw new IllegalArgumentException("Unknown package: " + packageName);
13490            }
13491            if (ks instanceof KeySetHandle) {
13492                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13493                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13494            }
13495            return false;
13496        }
13497    }
13498}
13499