PackageManagerService.java revision 9d2f441f9bb2c8dcac1150e2cba1d15a86a4efb1
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_CPU_ABI_INCOMPATIBLE;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
47import static android.content.pm.PackageParser.isApkFile;
48import static android.os.Process.PACKAGE_INFO_GID;
49import static android.os.Process.SYSTEM_UID;
50import static android.system.OsConstants.O_CREAT;
51import static android.system.OsConstants.O_RDWR;
52import static android.system.OsConstants.S_IRGRP;
53import static android.system.OsConstants.S_IROTH;
54import static android.system.OsConstants.S_IRWXU;
55import static android.system.OsConstants.S_IXGRP;
56import static android.system.OsConstants.S_IXOTH;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
58import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
59import static com.android.internal.util.ArrayUtils.appendInt;
60import static com.android.internal.util.ArrayUtils.removeInt;
61
62import android.util.ArrayMap;
63
64import com.android.internal.R;
65import com.android.internal.app.IMediaContainerService;
66import com.android.internal.app.ResolverActivity;
67import com.android.internal.content.NativeLibraryHelper;
68import com.android.internal.content.PackageHelper;
69import com.android.internal.os.IParcelFileDescriptorFactory;
70import com.android.internal.util.ArrayUtils;
71import com.android.internal.util.FastPrintWriter;
72import com.android.internal.util.FastXmlSerializer;
73import com.android.internal.util.IndentingPrintWriter;
74import com.android.internal.util.Preconditions;
75import com.android.server.EventLogTags;
76import com.android.server.IntentResolver;
77import com.android.server.LocalServices;
78import com.android.server.ServiceThread;
79import com.android.server.SystemConfig;
80import com.android.server.Watchdog;
81import com.android.server.pm.Settings.DatabaseVersion;
82import com.android.server.storage.DeviceStorageMonitorInternal;
83
84import org.xmlpull.v1.XmlSerializer;
85
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.IActivityManager;
89import android.app.admin.IDevicePolicyManager;
90import android.app.backup.IBackupManager;
91import android.content.BroadcastReceiver;
92import android.content.ComponentName;
93import android.content.Context;
94import android.content.IIntentReceiver;
95import android.content.Intent;
96import android.content.IntentFilter;
97import android.content.IntentSender;
98import android.content.IntentSender.SendIntentException;
99import android.content.ServiceConnection;
100import android.content.pm.ActivityInfo;
101import android.content.pm.ApplicationInfo;
102import android.content.pm.FeatureInfo;
103import android.content.pm.IPackageDataObserver;
104import android.content.pm.IPackageDeleteObserver;
105import android.content.pm.IPackageInstallObserver2;
106import android.content.pm.IPackageInstaller;
107import android.content.pm.IPackageManager;
108import android.content.pm.IPackageMoveObserver;
109import android.content.pm.IPackageStatsObserver;
110import android.content.pm.InstallSessionParams;
111import android.content.pm.InstrumentationInfo;
112import android.content.pm.ManifestDigest;
113import android.content.pm.PackageCleanItem;
114import android.content.pm.PackageInfo;
115import android.content.pm.PackageInfoLite;
116import android.content.pm.PackageManager;
117import android.content.pm.PackageParser.ActivityIntentInfo;
118import android.content.pm.PackageParser.PackageLite;
119import android.content.pm.PackageParser.PackageParserException;
120import android.content.pm.PackageParser;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Environment;
141import android.os.Environment.UserEnvironment;
142import android.os.FileObserver;
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.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.File;
179import java.io.FileDescriptor;
180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.FilenameFilter;
184import java.io.IOException;
185import java.io.InputStream;
186import java.io.PrintWriter;
187import java.nio.charset.StandardCharsets;
188import java.security.NoSuchAlgorithmException;
189import java.security.PublicKey;
190import java.security.cert.CertificateEncodingException;
191import java.security.cert.CertificateException;
192import java.text.SimpleDateFormat;
193import java.util.ArrayList;
194import java.util.Arrays;
195import java.util.Collection;
196import java.util.Collections;
197import java.util.Comparator;
198import java.util.Date;
199import java.util.HashMap;
200import java.util.HashSet;
201import java.util.Iterator;
202import java.util.List;
203import java.util.Map;
204import java.util.Set;
205import java.util.concurrent.atomic.AtomicBoolean;
206import java.util.concurrent.atomic.AtomicLong;
207
208import dalvik.system.DexFile;
209import dalvik.system.StaleDexCacheError;
210import dalvik.system.VMRuntime;
211
212import libcore.io.IoUtils;
213
214/**
215 * Keep track of all those .apks everywhere.
216 *
217 * This is very central to the platform's security; please run the unit
218 * tests whenever making modifications here:
219 *
220mmm frameworks/base/tests/AndroidTests
221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
223 *
224 * {@hide}
225 */
226public class PackageManagerService extends IPackageManager.Stub {
227    static final String TAG = "PackageManager";
228    static final boolean DEBUG_SETTINGS = false;
229    static final boolean DEBUG_PREFERRED = false;
230    static final boolean DEBUG_UPGRADE = false;
231    private static final boolean DEBUG_INSTALL = false;
232    private static final boolean DEBUG_REMOVE = false;
233    private static final boolean DEBUG_BROADCASTS = false;
234    private static final boolean DEBUG_SHOW_INFO = false;
235    private static final boolean DEBUG_PACKAGE_INFO = false;
236    private static final boolean DEBUG_INTENT_MATCHING = false;
237    private static final boolean DEBUG_PACKAGE_SCANNING = false;
238    private static final boolean DEBUG_APP_DIR_OBSERVER = 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    private static final int REMOVE_EVENTS =
253        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
254    private static final int ADD_EVENTS =
255        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
256
257    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
258    // Suffix used during package installation when copying/moving
259    // package apks to install directory.
260    private static final String INSTALL_PACKAGE_SUFFIX = "-";
261
262    static final int SCAN_MONITOR = 1<<0;
263    static final int SCAN_NO_DEX = 1<<1;
264    static final int SCAN_FORCE_DEX = 1<<2;
265    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
266    static final int SCAN_NEW_INSTALL = 1<<4;
267    static final int SCAN_NO_PATHS = 1<<5;
268    static final int SCAN_UPDATE_TIME = 1<<6;
269    static final int SCAN_DEFER_DEX = 1<<7;
270    static final int SCAN_BOOTING = 1<<8;
271    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
272    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
273
274    static final int REMOVE_CHATTY = 1<<16;
275
276    /**
277     * Timeout (in milliseconds) after which the watchdog should declare that
278     * our handler thread is wedged.  The usual default for such things is one
279     * minute but we sometimes do very lengthy I/O operations on this thread,
280     * such as installing multi-gigabyte applications, so ours needs to be longer.
281     */
282    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
283
284    /**
285     * Whether verification is enabled by default.
286     */
287    private static final boolean DEFAULT_VERIFY_ENABLE = true;
288
289    /**
290     * The default maximum time to wait for the verification agent to return in
291     * milliseconds.
292     */
293    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
294
295    /**
296     * The default response for package verification timeout.
297     *
298     * This can be either PackageManager.VERIFICATION_ALLOW or
299     * PackageManager.VERIFICATION_REJECT.
300     */
301    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
302
303    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
304
305    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
306            DEFAULT_CONTAINER_PACKAGE,
307            "com.android.defcontainer.DefaultContainerService");
308
309    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
310
311    private static final String LIB_DIR_NAME = "lib";
312    private static final String LIB64_DIR_NAME = "lib64";
313
314    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
315
316    static final String mTempContainerPrefix = "smdl2tmp";
317
318    private static String sPreferredInstructionSet;
319
320    final ServiceThread mHandlerThread;
321
322    private static final String IDMAP_PREFIX = "/data/resource-cache/";
323    private static final String IDMAP_SUFFIX = "@idmap";
324
325    final PackageHandler mHandler;
326
327    final int mSdkVersion = Build.VERSION.SDK_INT;
328
329    final Context mContext;
330    final boolean mFactoryTest;
331    final boolean mOnlyCore;
332    final DisplayMetrics mMetrics;
333    final int mDefParseFlags;
334    final String[] mSeparateProcesses;
335
336    // This is where all application persistent data goes.
337    final File mAppDataDir;
338
339    // This is where all application persistent data goes for secondary users.
340    final File mUserAppDataDir;
341
342    /** The location for ASEC container files on internal storage. */
343    final String mAsecInternalPath;
344
345    // This is the object monitoring the framework dir.
346    final FileObserver mFrameworkInstallObserver;
347
348    // This is the object monitoring the system app dir.
349    final FileObserver mSystemInstallObserver;
350
351    // This is the object monitoring the privileged system app dir.
352    final FileObserver mPrivilegedInstallObserver;
353
354    // This is the object monitoring the vendor app dir.
355    final FileObserver mVendorInstallObserver;
356
357    // This is the object monitoring the vendor overlay package dir.
358    final FileObserver mVendorOverlayInstallObserver;
359
360    // This is the object monitoring the OEM app dir.
361    final FileObserver mOemInstallObserver;
362
363    // This is the object monitoring mAppInstallDir.
364    final FileObserver mAppInstallObserver;
365
366    // This is the object monitoring mDrmAppPrivateInstallDir.
367    final FileObserver mDrmAppInstallObserver;
368
369    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
370    // LOCK HELD.  Can be called with mInstallLock held.
371    final Installer mInstaller;
372
373    /** Directory where installed third-party apps stored */
374    final File mAppInstallDir;
375
376    /**
377     * Directory to which applications installed internally have their
378     * 32 bit native libraries copied.
379     */
380    private File mAppLib32InstallDir;
381
382    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
383    // apps.
384    final File mDrmAppPrivateInstallDir;
385
386    // ----------------------------------------------------------------
387
388    // Lock for state used when installing and doing other long running
389    // operations.  Methods that must be called with this lock held have
390    // the suffix "LI".
391    final Object mInstallLock = new Object();
392
393    // These are the directories in the 3rd party applications installed dir
394    // that we have currently loaded packages from.  Keys are the application's
395    // installed zip file (absolute codePath), and values are Package.
396    final HashMap<String, PackageParser.Package> mAppDirs =
397            new HashMap<String, PackageParser.Package>();
398
399    // ----------------------------------------------------------------
400
401    // Keys are String (package name), values are Package.  This also serves
402    // as the lock for the global state.  Methods that must be called with
403    // this lock held have the prefix "LP".
404    final HashMap<String, PackageParser.Package> mPackages =
405            new HashMap<String, PackageParser.Package>();
406
407    // Tracks available target package names -> overlay package paths.
408    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
409        new HashMap<String, HashMap<String, PackageParser.Package>>();
410
411    final Settings mSettings;
412    boolean mRestoredSettings;
413
414    // System configuration read by SystemConfig.
415    final int[] mGlobalGids;
416    final SparseArray<HashSet<String>> mSystemPermissions;
417    final HashMap<String, FeatureInfo> mAvailableFeatures;
418
419    // If mac_permissions.xml was found for seinfo labeling.
420    boolean mFoundPolicyFile;
421
422    // If a recursive restorecon of /data/data/<pkg> is needed.
423    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
424
425    public static final class SharedLibraryEntry {
426        public final String path;
427        public final String apk;
428
429        SharedLibraryEntry(String _path, String _apk) {
430            path = _path;
431            apk = _apk;
432        }
433    }
434
435    // Currently known shared libraries.
436    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
437            new HashMap<String, SharedLibraryEntry>();
438
439    // All available activities, for your resolving pleasure.
440    final ActivityIntentResolver mActivities =
441            new ActivityIntentResolver();
442
443    // All available receivers, for your resolving pleasure.
444    final ActivityIntentResolver mReceivers =
445            new ActivityIntentResolver();
446
447    // All available services, for your resolving pleasure.
448    final ServiceIntentResolver mServices = new ServiceIntentResolver();
449
450    // All available providers, for your resolving pleasure.
451    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
452
453    // Mapping from provider base names (first directory in content URI codePath)
454    // to the provider information.
455    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
456            new HashMap<String, PackageParser.Provider>();
457
458    // Mapping from instrumentation class names to info about them.
459    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
460            new HashMap<ComponentName, PackageParser.Instrumentation>();
461
462    // Mapping from permission names to info about them.
463    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
464            new HashMap<String, PackageParser.PermissionGroup>();
465
466    // Packages whose data we have transfered into another package, thus
467    // should no longer exist.
468    final HashSet<String> mTransferedPackages = new HashSet<String>();
469
470    // Broadcast actions that are only available to the system.
471    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
472
473    /** List of packages waiting for verification. */
474    final SparseArray<PackageVerificationState> mPendingVerification
475            = new SparseArray<PackageVerificationState>();
476
477    final PackageInstallerService mInstallerService;
478
479    HashSet<PackageParser.Package> mDeferredDexOpt = null;
480
481    // Cache of users who need badging.
482    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
483
484    /** Token for keys in mPendingVerification. */
485    private int mPendingVerificationToken = 0;
486
487    boolean mSystemReady;
488    boolean mSafeMode;
489    boolean mHasSystemUidErrors;
490
491    ApplicationInfo mAndroidApplication;
492    final ActivityInfo mResolveActivity = new ActivityInfo();
493    final ResolveInfo mResolveInfo = new ResolveInfo();
494    ComponentName mResolveComponentName;
495    PackageParser.Package mPlatformPackage;
496    ComponentName mCustomResolverComponentName;
497
498    boolean mResolverReplaced = false;
499
500    // Set of pending broadcasts for aggregating enable/disable of components.
501    static class PendingPackageBroadcasts {
502        // for each user id, a map of <package name -> components within that package>
503        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
504
505        public PendingPackageBroadcasts() {
506            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
507        }
508
509        public ArrayList<String> get(int userId, String packageName) {
510            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
511            return packages.get(packageName);
512        }
513
514        public void put(int userId, String packageName, ArrayList<String> components) {
515            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
516            packages.put(packageName, components);
517        }
518
519        public void remove(int userId, String packageName) {
520            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
521            if (packages != null) {
522                packages.remove(packageName);
523            }
524        }
525
526        public void remove(int userId) {
527            mUidMap.remove(userId);
528        }
529
530        public int userIdCount() {
531            return mUidMap.size();
532        }
533
534        public int userIdAt(int n) {
535            return mUidMap.keyAt(n);
536        }
537
538        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
539            return mUidMap.get(userId);
540        }
541
542        public int size() {
543            // total number of pending broadcast entries across all userIds
544            int num = 0;
545            for (int i = 0; i< mUidMap.size(); i++) {
546                num += mUidMap.valueAt(i).size();
547            }
548            return num;
549        }
550
551        public void clear() {
552            mUidMap.clear();
553        }
554
555        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
556            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
557            if (map == null) {
558                map = new HashMap<String, ArrayList<String>>();
559                mUidMap.put(userId, map);
560            }
561            return map;
562        }
563    }
564    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
565
566    // Service Connection to remote media container service to copy
567    // package uri's from external media onto secure containers
568    // or internal storage.
569    private IMediaContainerService mContainerService = null;
570
571    static final int SEND_PENDING_BROADCAST = 1;
572    static final int MCS_BOUND = 3;
573    static final int END_COPY = 4;
574    static final int INIT_COPY = 5;
575    static final int MCS_UNBIND = 6;
576    static final int START_CLEANING_PACKAGE = 7;
577    static final int FIND_INSTALL_LOC = 8;
578    static final int POST_INSTALL = 9;
579    static final int MCS_RECONNECT = 10;
580    static final int MCS_GIVE_UP = 11;
581    static final int UPDATED_MEDIA_STATUS = 12;
582    static final int WRITE_SETTINGS = 13;
583    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
584    static final int PACKAGE_VERIFIED = 15;
585    static final int CHECK_PENDING_VERIFICATION = 16;
586
587    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
588
589    // Delay time in millisecs
590    static final int BROADCAST_DELAY = 10 * 1000;
591
592    static UserManagerService sUserManager;
593
594    // Stores a list of users whose package restrictions file needs to be updated
595    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
596
597    final private DefaultContainerConnection mDefContainerConn =
598            new DefaultContainerConnection();
599    class DefaultContainerConnection implements ServiceConnection {
600        public void onServiceConnected(ComponentName name, IBinder service) {
601            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
602            IMediaContainerService imcs =
603                IMediaContainerService.Stub.asInterface(service);
604            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
605        }
606
607        public void onServiceDisconnected(ComponentName name) {
608            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
609        }
610    };
611
612    // Recordkeeping of restore-after-install operations that are currently in flight
613    // between the Package Manager and the Backup Manager
614    class PostInstallData {
615        public InstallArgs args;
616        public PackageInstalledInfo res;
617
618        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
619            args = _a;
620            res = _r;
621        }
622    };
623    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
624    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
625
626    private final String mRequiredVerifierPackage;
627
628    private final PackageUsage mPackageUsage = new PackageUsage();
629
630    private class PackageUsage {
631        private static final int WRITE_INTERVAL
632            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
633
634        private final Object mFileLock = new Object();
635        private final AtomicLong mLastWritten = new AtomicLong(0);
636        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
637
638        private boolean mIsHistoricalPackageUsageAvailable = true;
639
640        boolean isHistoricalPackageUsageAvailable() {
641            return mIsHistoricalPackageUsageAvailable;
642        }
643
644        void write(boolean force) {
645            if (force) {
646                writeInternal();
647                return;
648            }
649            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
650                && !DEBUG_DEXOPT) {
651                return;
652            }
653            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
654                new Thread("PackageUsage_DiskWriter") {
655                    @Override
656                    public void run() {
657                        try {
658                            writeInternal();
659                        } finally {
660                            mBackgroundWriteRunning.set(false);
661                        }
662                    }
663                }.start();
664            }
665        }
666
667        private void writeInternal() {
668            synchronized (mPackages) {
669                synchronized (mFileLock) {
670                    AtomicFile file = getFile();
671                    FileOutputStream f = null;
672                    try {
673                        f = file.startWrite();
674                        BufferedOutputStream out = new BufferedOutputStream(f);
675                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
676                        StringBuilder sb = new StringBuilder();
677                        for (PackageParser.Package pkg : mPackages.values()) {
678                            if (pkg.mLastPackageUsageTimeInMills == 0) {
679                                continue;
680                            }
681                            sb.setLength(0);
682                            sb.append(pkg.packageName);
683                            sb.append(' ');
684                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
685                            sb.append('\n');
686                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
687                        }
688                        out.flush();
689                        file.finishWrite(f);
690                    } catch (IOException e) {
691                        if (f != null) {
692                            file.failWrite(f);
693                        }
694                        Log.e(TAG, "Failed to write package usage times", e);
695                    }
696                }
697            }
698            mLastWritten.set(SystemClock.elapsedRealtime());
699        }
700
701        void readLP() {
702            synchronized (mFileLock) {
703                AtomicFile file = getFile();
704                BufferedInputStream in = null;
705                try {
706                    in = new BufferedInputStream(file.openRead());
707                    StringBuffer sb = new StringBuffer();
708                    while (true) {
709                        String packageName = readToken(in, sb, ' ');
710                        if (packageName == null) {
711                            break;
712                        }
713                        String timeInMillisString = readToken(in, sb, '\n');
714                        if (timeInMillisString == null) {
715                            throw new IOException("Failed to find last usage time for package "
716                                                  + packageName);
717                        }
718                        PackageParser.Package pkg = mPackages.get(packageName);
719                        if (pkg == null) {
720                            continue;
721                        }
722                        long timeInMillis;
723                        try {
724                            timeInMillis = Long.parseLong(timeInMillisString.toString());
725                        } catch (NumberFormatException e) {
726                            throw new IOException("Failed to parse " + timeInMillisString
727                                                  + " as a long.", e);
728                        }
729                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
730                    }
731                } catch (FileNotFoundException expected) {
732                    mIsHistoricalPackageUsageAvailable = false;
733                } catch (IOException e) {
734                    Log.w(TAG, "Failed to read package usage times", e);
735                } finally {
736                    IoUtils.closeQuietly(in);
737                }
738            }
739            mLastWritten.set(SystemClock.elapsedRealtime());
740        }
741
742        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
743                throws IOException {
744            sb.setLength(0);
745            while (true) {
746                int ch = in.read();
747                if (ch == -1) {
748                    if (sb.length() == 0) {
749                        return null;
750                    }
751                    throw new IOException("Unexpected EOF");
752                }
753                if (ch == endOfToken) {
754                    return sb.toString();
755                }
756                sb.append((char)ch);
757            }
758        }
759
760        private AtomicFile getFile() {
761            File dataDir = Environment.getDataDirectory();
762            File systemDir = new File(dataDir, "system");
763            File fname = new File(systemDir, "package-usage.list");
764            return new AtomicFile(fname);
765        }
766    }
767
768    class PackageHandler extends Handler {
769        private boolean mBound = false;
770        final ArrayList<HandlerParams> mPendingInstalls =
771            new ArrayList<HandlerParams>();
772
773        private boolean connectToService() {
774            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
775                    " DefaultContainerService");
776            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            if (mContext.bindServiceAsUser(service, mDefContainerConn,
779                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
780                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781                mBound = true;
782                return true;
783            }
784            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
785            return false;
786        }
787
788        private void disconnectService() {
789            mContainerService = null;
790            mBound = false;
791            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
792            mContext.unbindService(mDefContainerConn);
793            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
794        }
795
796        PackageHandler(Looper looper) {
797            super(looper);
798        }
799
800        public void handleMessage(Message msg) {
801            try {
802                doHandleMessage(msg);
803            } finally {
804                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
805            }
806        }
807
808        void doHandleMessage(Message msg) {
809            switch (msg.what) {
810                case INIT_COPY: {
811                    HandlerParams params = (HandlerParams) msg.obj;
812                    int idx = mPendingInstalls.size();
813                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
814                    // If a bind was already initiated we dont really
815                    // need to do anything. The pending install
816                    // will be processed later on.
817                    if (!mBound) {
818                        // If this is the only one pending we might
819                        // have to bind to the service again.
820                        if (!connectToService()) {
821                            Slog.e(TAG, "Failed to bind to media container service");
822                            params.serviceError();
823                            return;
824                        } else {
825                            // Once we bind to the service, the first
826                            // pending request will be processed.
827                            mPendingInstalls.add(idx, params);
828                        }
829                    } else {
830                        mPendingInstalls.add(idx, params);
831                        // Already bound to the service. Just make
832                        // sure we trigger off processing the first request.
833                        if (idx == 0) {
834                            mHandler.sendEmptyMessage(MCS_BOUND);
835                        }
836                    }
837                    break;
838                }
839                case MCS_BOUND: {
840                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
841                    if (msg.obj != null) {
842                        mContainerService = (IMediaContainerService) msg.obj;
843                    }
844                    if (mContainerService == null) {
845                        // Something seriously wrong. Bail out
846                        Slog.e(TAG, "Cannot bind to media container service");
847                        for (HandlerParams params : mPendingInstalls) {
848                            // Indicate service bind error
849                            params.serviceError();
850                        }
851                        mPendingInstalls.clear();
852                    } else if (mPendingInstalls.size() > 0) {
853                        HandlerParams params = mPendingInstalls.get(0);
854                        if (params != null) {
855                            if (params.startCopy()) {
856                                // We are done...  look for more work or to
857                                // go idle.
858                                if (DEBUG_SD_INSTALL) Log.i(TAG,
859                                        "Checking for more work or unbind...");
860                                // Delete pending install
861                                if (mPendingInstalls.size() > 0) {
862                                    mPendingInstalls.remove(0);
863                                }
864                                if (mPendingInstalls.size() == 0) {
865                                    if (mBound) {
866                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
867                                                "Posting delayed MCS_UNBIND");
868                                        removeMessages(MCS_UNBIND);
869                                        Message ubmsg = obtainMessage(MCS_UNBIND);
870                                        // Unbind after a little delay, to avoid
871                                        // continual thrashing.
872                                        sendMessageDelayed(ubmsg, 10000);
873                                    }
874                                } else {
875                                    // There are more pending requests in queue.
876                                    // Just post MCS_BOUND message to trigger processing
877                                    // of next pending install.
878                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
879                                            "Posting MCS_BOUND for next work");
880                                    mHandler.sendEmptyMessage(MCS_BOUND);
881                                }
882                            }
883                        }
884                    } else {
885                        // Should never happen ideally.
886                        Slog.w(TAG, "Empty queue");
887                    }
888                    break;
889                }
890                case MCS_RECONNECT: {
891                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
892                    if (mPendingInstalls.size() > 0) {
893                        if (mBound) {
894                            disconnectService();
895                        }
896                        if (!connectToService()) {
897                            Slog.e(TAG, "Failed to bind to media container service");
898                            for (HandlerParams params : mPendingInstalls) {
899                                // Indicate service bind error
900                                params.serviceError();
901                            }
902                            mPendingInstalls.clear();
903                        }
904                    }
905                    break;
906                }
907                case MCS_UNBIND: {
908                    // If there is no actual work left, then time to unbind.
909                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
910
911                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
912                        if (mBound) {
913                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
914
915                            disconnectService();
916                        }
917                    } else if (mPendingInstalls.size() > 0) {
918                        // There are more pending requests in queue.
919                        // Just post MCS_BOUND message to trigger processing
920                        // of next pending install.
921                        mHandler.sendEmptyMessage(MCS_BOUND);
922                    }
923
924                    break;
925                }
926                case MCS_GIVE_UP: {
927                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
928                    mPendingInstalls.remove(0);
929                    break;
930                }
931                case SEND_PENDING_BROADCAST: {
932                    String packages[];
933                    ArrayList<String> components[];
934                    int size = 0;
935                    int uids[];
936                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
937                    synchronized (mPackages) {
938                        if (mPendingBroadcasts == null) {
939                            return;
940                        }
941                        size = mPendingBroadcasts.size();
942                        if (size <= 0) {
943                            // Nothing to be done. Just return
944                            return;
945                        }
946                        packages = new String[size];
947                        components = new ArrayList[size];
948                        uids = new int[size];
949                        int i = 0;  // filling out the above arrays
950
951                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
952                            int packageUserId = mPendingBroadcasts.userIdAt(n);
953                            Iterator<Map.Entry<String, ArrayList<String>>> it
954                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
955                                            .entrySet().iterator();
956                            while (it.hasNext() && i < size) {
957                                Map.Entry<String, ArrayList<String>> ent = it.next();
958                                packages[i] = ent.getKey();
959                                components[i] = ent.getValue();
960                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
961                                uids[i] = (ps != null)
962                                        ? UserHandle.getUid(packageUserId, ps.appId)
963                                        : -1;
964                                i++;
965                            }
966                        }
967                        size = i;
968                        mPendingBroadcasts.clear();
969                    }
970                    // Send broadcasts
971                    for (int i = 0; i < size; i++) {
972                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
973                    }
974                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
975                    break;
976                }
977                case START_CLEANING_PACKAGE: {
978                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
979                    final String packageName = (String)msg.obj;
980                    final int userId = msg.arg1;
981                    final boolean andCode = msg.arg2 != 0;
982                    synchronized (mPackages) {
983                        if (userId == UserHandle.USER_ALL) {
984                            int[] users = sUserManager.getUserIds();
985                            for (int user : users) {
986                                mSettings.addPackageToCleanLPw(
987                                        new PackageCleanItem(user, packageName, andCode));
988                            }
989                        } else {
990                            mSettings.addPackageToCleanLPw(
991                                    new PackageCleanItem(userId, packageName, andCode));
992                        }
993                    }
994                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
995                    startCleaningPackages();
996                } break;
997                case POST_INSTALL: {
998                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
999                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1000                    mRunningInstalls.delete(msg.arg1);
1001                    boolean deleteOld = false;
1002
1003                    if (data != null) {
1004                        InstallArgs args = data.args;
1005                        PackageInstalledInfo res = data.res;
1006
1007                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1008                            res.removedInfo.sendBroadcast(false, true, false);
1009                            Bundle extras = new Bundle(1);
1010                            extras.putInt(Intent.EXTRA_UID, res.uid);
1011                            // Determine the set of users who are adding this
1012                            // package for the first time vs. those who are seeing
1013                            // an update.
1014                            int[] firstUsers;
1015                            int[] updateUsers = new int[0];
1016                            if (res.origUsers == null || res.origUsers.length == 0) {
1017                                firstUsers = res.newUsers;
1018                            } else {
1019                                firstUsers = new int[0];
1020                                for (int i=0; i<res.newUsers.length; i++) {
1021                                    int user = res.newUsers[i];
1022                                    boolean isNew = true;
1023                                    for (int j=0; j<res.origUsers.length; j++) {
1024                                        if (res.origUsers[j] == user) {
1025                                            isNew = false;
1026                                            break;
1027                                        }
1028                                    }
1029                                    if (isNew) {
1030                                        int[] newFirst = new int[firstUsers.length+1];
1031                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1032                                                firstUsers.length);
1033                                        newFirst[firstUsers.length] = user;
1034                                        firstUsers = newFirst;
1035                                    } else {
1036                                        int[] newUpdate = new int[updateUsers.length+1];
1037                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1038                                                updateUsers.length);
1039                                        newUpdate[updateUsers.length] = user;
1040                                        updateUsers = newUpdate;
1041                                    }
1042                                }
1043                            }
1044                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1045                                    res.pkg.applicationInfo.packageName,
1046                                    extras, null, null, firstUsers);
1047                            final boolean update = res.removedInfo.removedPackage != null;
1048                            if (update) {
1049                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1050                            }
1051                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1052                                    res.pkg.applicationInfo.packageName,
1053                                    extras, null, null, updateUsers);
1054                            if (update) {
1055                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1056                                        res.pkg.applicationInfo.packageName,
1057                                        extras, null, null, updateUsers);
1058                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1059                                        null, null,
1060                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1061
1062                                // treat asec-hosted packages like removable media on upgrade
1063                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1064                                    if (DEBUG_INSTALL) {
1065                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1066                                                + " is ASEC-hosted -> AVAILABLE");
1067                                    }
1068                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1069                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1070                                    pkgList.add(res.pkg.applicationInfo.packageName);
1071                                    sendResourcesChangedBroadcast(true, true,
1072                                            pkgList,uidArray, null);
1073                                }
1074                            }
1075                            if (res.removedInfo.args != null) {
1076                                // Remove the replaced package's older resources safely now
1077                                deleteOld = true;
1078                            }
1079
1080                            // Log current value of "unknown sources" setting
1081                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1082                                getUnknownSourcesSettings());
1083                        }
1084                        // Force a gc to clear up things
1085                        Runtime.getRuntime().gc();
1086                        // We delete after a gc for applications  on sdcard.
1087                        if (deleteOld) {
1088                            synchronized (mInstallLock) {
1089                                res.removedInfo.args.doPostDeleteLI(true);
1090                            }
1091                        }
1092                        if (args.observer != null) {
1093                            try {
1094                                Bundle extras = extrasForInstallResult(res);
1095                                args.observer.packageInstalled(res.name, extras, res.returnCode,
1096                                        res.returnMsg);
1097                            } catch (RemoteException e) {
1098                                Slog.i(TAG, "Observer no longer exists.");
1099                            }
1100                        }
1101                    } else {
1102                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1103                    }
1104                } break;
1105                case UPDATED_MEDIA_STATUS: {
1106                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1107                    boolean reportStatus = msg.arg1 == 1;
1108                    boolean doGc = msg.arg2 == 1;
1109                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1110                    if (doGc) {
1111                        // Force a gc to clear up stale containers.
1112                        Runtime.getRuntime().gc();
1113                    }
1114                    if (msg.obj != null) {
1115                        @SuppressWarnings("unchecked")
1116                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1117                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1118                        // Unload containers
1119                        unloadAllContainers(args);
1120                    }
1121                    if (reportStatus) {
1122                        try {
1123                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1124                            PackageHelper.getMountService().finishMediaUpdate();
1125                        } catch (RemoteException e) {
1126                            Log.e(TAG, "MountService not running?");
1127                        }
1128                    }
1129                } break;
1130                case WRITE_SETTINGS: {
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1132                    synchronized (mPackages) {
1133                        removeMessages(WRITE_SETTINGS);
1134                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1135                        mSettings.writeLPr();
1136                        mDirtyUsers.clear();
1137                    }
1138                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139                } break;
1140                case WRITE_PACKAGE_RESTRICTIONS: {
1141                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1142                    synchronized (mPackages) {
1143                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1144                        for (int userId : mDirtyUsers) {
1145                            mSettings.writePackageRestrictionsLPr(userId);
1146                        }
1147                        mDirtyUsers.clear();
1148                    }
1149                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150                } break;
1151                case CHECK_PENDING_VERIFICATION: {
1152                    final int verificationId = msg.arg1;
1153                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1154
1155                    if ((state != null) && !state.timeoutExtended()) {
1156                        final InstallArgs args = state.getInstallArgs();
1157                        final Uri originUri = Uri.fromFile(args.originFile);
1158
1159                        Slog.i(TAG, "Verification timed out for " + originUri);
1160                        mPendingVerification.remove(verificationId);
1161
1162                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1163
1164                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1165                            Slog.i(TAG, "Continuing with installation of " + originUri);
1166                            state.setVerifierResponse(Binder.getCallingUid(),
1167                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1168                            broadcastPackageVerified(verificationId, originUri,
1169                                    PackageManager.VERIFICATION_ALLOW,
1170                                    state.getInstallArgs().getUser());
1171                            try {
1172                                ret = args.copyApk(mContainerService, true);
1173                            } catch (RemoteException e) {
1174                                Slog.e(TAG, "Could not contact the ContainerService");
1175                            }
1176                        } else {
1177                            broadcastPackageVerified(verificationId, originUri,
1178                                    PackageManager.VERIFICATION_REJECT,
1179                                    state.getInstallArgs().getUser());
1180                        }
1181
1182                        processPendingInstall(args, ret);
1183                        mHandler.sendEmptyMessage(MCS_UNBIND);
1184                    }
1185                    break;
1186                }
1187                case PACKAGE_VERIFIED: {
1188                    final int verificationId = msg.arg1;
1189
1190                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1191                    if (state == null) {
1192                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1193                        break;
1194                    }
1195
1196                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1197
1198                    state.setVerifierResponse(response.callerUid, response.code);
1199
1200                    if (state.isVerificationComplete()) {
1201                        mPendingVerification.remove(verificationId);
1202
1203                        final InstallArgs args = state.getInstallArgs();
1204                        final Uri originUri = Uri.fromFile(args.originFile);
1205
1206                        int ret;
1207                        if (state.isInstallAllowed()) {
1208                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1209                            broadcastPackageVerified(verificationId, originUri,
1210                                    response.code, state.getInstallArgs().getUser());
1211                            try {
1212                                ret = args.copyApk(mContainerService, true);
1213                            } catch (RemoteException e) {
1214                                Slog.e(TAG, "Could not contact the ContainerService");
1215                            }
1216                        } else {
1217                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1218                        }
1219
1220                        processPendingInstall(args, ret);
1221
1222                        mHandler.sendEmptyMessage(MCS_UNBIND);
1223                    }
1224
1225                    break;
1226                }
1227            }
1228        }
1229    }
1230
1231    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1232        Bundle extras = null;
1233        switch (res.returnCode) {
1234            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1235                extras = new Bundle();
1236                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1237                        res.origPermission);
1238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1239                        res.origPackage);
1240                break;
1241            }
1242        }
1243        return extras;
1244    }
1245
1246    void scheduleWriteSettingsLocked() {
1247        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1248            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1249        }
1250    }
1251
1252    void scheduleWritePackageRestrictionsLocked(int userId) {
1253        if (!sUserManager.exists(userId)) return;
1254        mDirtyUsers.add(userId);
1255        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1256            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1257        }
1258    }
1259
1260    public static final PackageManagerService main(Context context, Installer installer,
1261            boolean factoryTest, boolean onlyCore) {
1262        PackageManagerService m = new PackageManagerService(context, installer,
1263                factoryTest, onlyCore);
1264        ServiceManager.addService("package", m);
1265        return m;
1266    }
1267
1268    static String[] splitString(String str, char sep) {
1269        int count = 1;
1270        int i = 0;
1271        while ((i=str.indexOf(sep, i)) >= 0) {
1272            count++;
1273            i++;
1274        }
1275
1276        String[] res = new String[count];
1277        i=0;
1278        count = 0;
1279        int lastI=0;
1280        while ((i=str.indexOf(sep, i)) >= 0) {
1281            res[count] = str.substring(lastI, i);
1282            count++;
1283            i++;
1284            lastI = i;
1285        }
1286        res[count] = str.substring(lastI, str.length());
1287        return res;
1288    }
1289
1290    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1291        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1292                Context.DISPLAY_SERVICE);
1293        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1294    }
1295
1296    public PackageManagerService(Context context, Installer installer,
1297            boolean factoryTest, boolean onlyCore) {
1298        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1299                SystemClock.uptimeMillis());
1300
1301        if (mSdkVersion <= 0) {
1302            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1303        }
1304
1305        mContext = context;
1306        mFactoryTest = factoryTest;
1307        mOnlyCore = onlyCore;
1308        mMetrics = new DisplayMetrics();
1309        mSettings = new Settings(context);
1310        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1313                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1314        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1315                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1316        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1317                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1318        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1319                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1320        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1321                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1322
1323        String separateProcesses = SystemProperties.get("debug.separate_processes");
1324        if (separateProcesses != null && separateProcesses.length() > 0) {
1325            if ("*".equals(separateProcesses)) {
1326                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1327                mSeparateProcesses = null;
1328                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1329            } else {
1330                mDefParseFlags = 0;
1331                mSeparateProcesses = separateProcesses.split(",");
1332                Slog.w(TAG, "Running with debug.separate_processes: "
1333                        + separateProcesses);
1334            }
1335        } else {
1336            mDefParseFlags = 0;
1337            mSeparateProcesses = null;
1338        }
1339
1340        mInstaller = installer;
1341
1342        getDefaultDisplayMetrics(context, mMetrics);
1343
1344        SystemConfig systemConfig = SystemConfig.getInstance();
1345        mGlobalGids = systemConfig.getGlobalGids();
1346        mSystemPermissions = systemConfig.getSystemPermissions();
1347        mAvailableFeatures = systemConfig.getAvailableFeatures();
1348
1349        synchronized (mInstallLock) {
1350        // writer
1351        synchronized (mPackages) {
1352            mHandlerThread = new ServiceThread(TAG,
1353                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1354            mHandlerThread.start();
1355            mHandler = new PackageHandler(mHandlerThread.getLooper());
1356            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1357
1358            File dataDir = Environment.getDataDirectory();
1359            mAppDataDir = new File(dataDir, "data");
1360            mAppInstallDir = new File(dataDir, "app");
1361            mAppLib32InstallDir = new File(dataDir, "app-lib");
1362            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1363            mUserAppDataDir = new File(dataDir, "user");
1364            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1365
1366            sUserManager = new UserManagerService(context, this,
1367                    mInstallLock, mPackages);
1368
1369            // Propagate permission configuration in to package manager.
1370            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1371                    = systemConfig.getPermissions();
1372            for (int i=0; i<permConfig.size(); i++) {
1373                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1374                BasePermission bp = mSettings.mPermissions.get(perm.name);
1375                if (bp == null) {
1376                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1377                    mSettings.mPermissions.put(perm.name, bp);
1378                }
1379                if (perm.gids != null) {
1380                    bp.gids = appendInts(bp.gids, perm.gids);
1381                }
1382            }
1383
1384            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1385            for (int i=0; i<libConfig.size(); i++) {
1386                mSharedLibraries.put(libConfig.keyAt(i),
1387                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1388            }
1389
1390            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1391
1392            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1393                    mSdkVersion, mOnlyCore);
1394
1395            String customResolverActivity = Resources.getSystem().getString(
1396                    R.string.config_customResolverActivity);
1397            if (TextUtils.isEmpty(customResolverActivity)) {
1398                customResolverActivity = null;
1399            } else {
1400                mCustomResolverComponentName = ComponentName.unflattenFromString(
1401                        customResolverActivity);
1402            }
1403
1404            long startTime = SystemClock.uptimeMillis();
1405
1406            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1407                    startTime);
1408
1409            // Set flag to monitor and not change apk file paths when
1410            // scanning install directories.
1411            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1412
1413            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1414
1415            /**
1416             * Add everything in the in the boot class path to the
1417             * list of process files because dexopt will have been run
1418             * if necessary during zygote startup.
1419             */
1420            String bootClassPath = System.getProperty("java.boot.class.path");
1421            if (bootClassPath != null) {
1422                String[] paths = splitString(bootClassPath, ':');
1423                for (int i=0; i<paths.length; i++) {
1424                    alreadyDexOpted.add(paths[i]);
1425                }
1426            } else {
1427                Slog.w(TAG, "No BOOTCLASSPATH found!");
1428            }
1429
1430            boolean didDexOptLibraryOrTool = false;
1431
1432            final List<String> instructionSets = getAllInstructionSets();
1433
1434            /**
1435             * Ensure all external libraries have had dexopt run on them.
1436             */
1437            if (mSharedLibraries.size() > 0) {
1438                // NOTE: For now, we're compiling these system "shared libraries"
1439                // (and framework jars) into all available architectures. It's possible
1440                // to compile them only when we come across an app that uses them (there's
1441                // already logic for that in scanPackageLI) but that adds some complexity.
1442                for (String instructionSet : instructionSets) {
1443                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1444                        final String lib = libEntry.path;
1445                        if (lib == null) {
1446                            continue;
1447                        }
1448
1449                        try {
1450                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1451                                alreadyDexOpted.add(lib);
1452
1453                                // The list of "shared libraries" we have at this point is
1454                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1455                                didDexOptLibraryOrTool = true;
1456                            }
1457                        } catch (FileNotFoundException e) {
1458                            Slog.w(TAG, "Library not found: " + lib);
1459                        } catch (IOException e) {
1460                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1461                                    + e.getMessage());
1462                        }
1463                    }
1464                }
1465            }
1466
1467            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1468
1469            // Gross hack for now: we know this file doesn't contain any
1470            // code, so don't dexopt it to avoid the resulting log spew.
1471            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1472
1473            // Gross hack for now: we know this file is only part of
1474            // the boot class path for art, so don't dexopt it to
1475            // avoid the resulting log spew.
1476            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1477
1478            /**
1479             * And there are a number of commands implemented in Java, which
1480             * we currently need to do the dexopt on so that they can be
1481             * run from a non-root shell.
1482             */
1483            String[] frameworkFiles = frameworkDir.list();
1484            if (frameworkFiles != null) {
1485                // TODO: We could compile these only for the most preferred ABI. We should
1486                // first double check that the dex files for these commands are not referenced
1487                // by other system apps.
1488                for (String instructionSet : instructionSets) {
1489                    for (int i=0; i<frameworkFiles.length; i++) {
1490                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1491                        String path = libPath.getPath();
1492                        // Skip the file if we already did it.
1493                        if (alreadyDexOpted.contains(path)) {
1494                            continue;
1495                        }
1496                        // Skip the file if it is not a type we want to dexopt.
1497                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1498                            continue;
1499                        }
1500                        try {
1501                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1502                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1503                                didDexOptLibraryOrTool = true;
1504                            }
1505                        } catch (FileNotFoundException e) {
1506                            Slog.w(TAG, "Jar not found: " + path);
1507                        } catch (IOException e) {
1508                            Slog.w(TAG, "Exception reading jar: " + path, e);
1509                        }
1510                    }
1511                }
1512            }
1513
1514            if (didDexOptLibraryOrTool) {
1515                // If we dexopted a library or tool, then something on the system has
1516                // changed. Consider this significant, and wipe away all other
1517                // existing dexopt files to ensure we don't leave any dangling around.
1518                //
1519                // TODO: This should be revisited because it isn't as good an indicator
1520                // as it used to be. It used to include the boot classpath but at some point
1521                // DexFile.isDexOptNeeded started returning false for the boot
1522                // class path files in all cases. It is very possible in a
1523                // small maintenance release update that the library and tool
1524                // jars may be unchanged but APK could be removed resulting in
1525                // unused dalvik-cache files.
1526                for (String instructionSet : instructionSets) {
1527                    mInstaller.pruneDexCache(instructionSet);
1528                }
1529
1530                // Additionally, delete all dex files from the root directory
1531                // since there shouldn't be any there anyway, unless we're upgrading
1532                // from an older OS version or a build that contained the "old" style
1533                // flat scheme.
1534                mInstaller.pruneDexCache(".");
1535            }
1536
1537            // Collect vendor overlay packages.
1538            // (Do this before scanning any apps.)
1539            // For security and version matching reason, only consider
1540            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1541            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1542            mVendorOverlayInstallObserver = new AppDirObserver(
1543                    vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1544            mVendorOverlayInstallObserver.startWatching();
1545            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1547
1548            // Find base frameworks (resource packages without code).
1549            mFrameworkInstallObserver = new AppDirObserver(
1550                    frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1551            mFrameworkInstallObserver.startWatching();
1552            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1553                    | PackageParser.PARSE_IS_SYSTEM_DIR
1554                    | PackageParser.PARSE_IS_PRIVILEGED,
1555                    scanMode | SCAN_NO_DEX, 0);
1556
1557            // Collected privileged system packages.
1558            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1559            mPrivilegedInstallObserver = new AppDirObserver(
1560                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1561            mPrivilegedInstallObserver.startWatching();
1562            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1563                    | PackageParser.PARSE_IS_SYSTEM_DIR
1564                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1565
1566            // Collect ordinary system packages.
1567            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1568            mSystemInstallObserver = new AppDirObserver(
1569                    systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1570            mSystemInstallObserver.startWatching();
1571            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1572                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1573
1574            // Collect all vendor packages.
1575            File vendorAppDir = new File("/vendor/app");
1576            try {
1577                vendorAppDir = vendorAppDir.getCanonicalFile();
1578            } catch (IOException e) {
1579                // failed to look up canonical path, continue with original one
1580            }
1581            mVendorInstallObserver = new AppDirObserver(
1582                    vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1583            mVendorInstallObserver.startWatching();
1584            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1585                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1586
1587            // Collect all OEM packages.
1588            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1589            mOemInstallObserver = new AppDirObserver(
1590                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1591            mOemInstallObserver.startWatching();
1592            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1593                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1594
1595            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1596            mInstaller.moveFiles();
1597
1598            // Prune any system packages that no longer exist.
1599            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1600            if (!mOnlyCore) {
1601                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1602                while (psit.hasNext()) {
1603                    PackageSetting ps = psit.next();
1604
1605                    /*
1606                     * If this is not a system app, it can't be a
1607                     * disable system app.
1608                     */
1609                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1610                        continue;
1611                    }
1612
1613                    /*
1614                     * If the package is scanned, it's not erased.
1615                     */
1616                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1617                    if (scannedPkg != null) {
1618                        /*
1619                         * If the system app is both scanned and in the
1620                         * disabled packages list, then it must have been
1621                         * added via OTA. Remove it from the currently
1622                         * scanned package so the previously user-installed
1623                         * application can be scanned.
1624                         */
1625                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1626                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1627                                    + "; removing system app");
1628                            removePackageLI(ps, true);
1629                        }
1630
1631                        continue;
1632                    }
1633
1634                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1635                        psit.remove();
1636                        String msg = "System package " + ps.name
1637                                + " no longer exists; wiping its data";
1638                        reportSettingsProblem(Log.WARN, msg);
1639                        removeDataDirsLI(ps.name);
1640                    } else {
1641                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1642                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1643                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1644                        }
1645                    }
1646                }
1647            }
1648
1649            //look for any incomplete package installations
1650            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1651            //clean up list
1652            for(int i = 0; i < deletePkgsList.size(); i++) {
1653                //clean up here
1654                cleanupInstallFailedPackage(deletePkgsList.get(i));
1655            }
1656            //delete tmp files
1657            deleteTempPackageFiles();
1658
1659            // Remove any shared userIDs that have no associated packages
1660            mSettings.pruneSharedUsersLPw();
1661
1662            if (!mOnlyCore) {
1663                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1664                        SystemClock.uptimeMillis());
1665                mAppInstallObserver = new AppDirObserver(
1666                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1667                mAppInstallObserver.startWatching();
1668                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1669
1670                mDrmAppInstallObserver = new AppDirObserver(
1671                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1672                mDrmAppInstallObserver.startWatching();
1673                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1674                        scanMode, 0);
1675
1676                /**
1677                 * Remove disable package settings for any updated system
1678                 * apps that were removed via an OTA. If they're not a
1679                 * previously-updated app, remove them completely.
1680                 * Otherwise, just revoke their system-level permissions.
1681                 */
1682                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1683                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1684                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1685
1686                    String msg;
1687                    if (deletedPkg == null) {
1688                        msg = "Updated system package " + deletedAppName
1689                                + " no longer exists; wiping its data";
1690                        removeDataDirsLI(deletedAppName);
1691                    } else {
1692                        msg = "Updated system app + " + deletedAppName
1693                                + " no longer present; removing system privileges for "
1694                                + deletedAppName;
1695
1696                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1697
1698                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1699                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1700                    }
1701                    reportSettingsProblem(Log.WARN, msg);
1702                }
1703            } else {
1704                mAppInstallObserver = null;
1705                mDrmAppInstallObserver = null;
1706            }
1707
1708            // Now that we know all of the shared libraries, update all clients to have
1709            // the correct library paths.
1710            updateAllSharedLibrariesLPw();
1711
1712            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1713                // NOTE: We ignore potential failures here during a system scan (like
1714                // the rest of the commands above) because there's precious little we
1715                // can do about it. A settings error is reported, though.
1716                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1717                        false /* force dexopt */, false /* defer dexopt */);
1718            }
1719
1720            // Now that we know all the packages we are keeping,
1721            // read and update their last usage times.
1722            mPackageUsage.readLP();
1723
1724            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1725                    SystemClock.uptimeMillis());
1726            Slog.i(TAG, "Time to scan packages: "
1727                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1728                    + " seconds");
1729
1730            // If the platform SDK has changed since the last time we booted,
1731            // we need to re-grant app permission to catch any new ones that
1732            // appear.  This is really a hack, and means that apps can in some
1733            // cases get permissions that the user didn't initially explicitly
1734            // allow...  it would be nice to have some better way to handle
1735            // this situation.
1736            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1737                    != mSdkVersion;
1738            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1739                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1740                    + "; regranting permissions for internal storage");
1741            mSettings.mInternalSdkPlatform = mSdkVersion;
1742
1743            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1744                    | (regrantPermissions
1745                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1746                            : 0));
1747
1748            // If this is the first boot, and it is a normal boot, then
1749            // we need to initialize the default preferred apps.
1750            if (!mRestoredSettings && !onlyCore) {
1751                mSettings.readDefaultPreferredAppsLPw(this, 0);
1752            }
1753
1754            // All the changes are done during package scanning.
1755            mSettings.updateInternalDatabaseVersion();
1756
1757            // can downgrade to reader
1758            mSettings.writeLPr();
1759
1760            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1761                    SystemClock.uptimeMillis());
1762
1763
1764            mRequiredVerifierPackage = getRequiredVerifierLPr();
1765        } // synchronized (mPackages)
1766        } // synchronized (mInstallLock)
1767
1768        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1769
1770        // Now after opening every single application zip, make sure they
1771        // are all flushed.  Not really needed, but keeps things nice and
1772        // tidy.
1773        Runtime.getRuntime().gc();
1774    }
1775
1776    @Override
1777    public boolean isFirstBoot() {
1778        return !mRestoredSettings;
1779    }
1780
1781    @Override
1782    public boolean isOnlyCoreApps() {
1783        return mOnlyCore;
1784    }
1785
1786    private String getRequiredVerifierLPr() {
1787        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1788        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1789                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1790
1791        String requiredVerifier = null;
1792
1793        final int N = receivers.size();
1794        for (int i = 0; i < N; i++) {
1795            final ResolveInfo info = receivers.get(i);
1796
1797            if (info.activityInfo == null) {
1798                continue;
1799            }
1800
1801            final String packageName = info.activityInfo.packageName;
1802
1803            final PackageSetting ps = mSettings.mPackages.get(packageName);
1804            if (ps == null) {
1805                continue;
1806            }
1807
1808            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1809            if (!gp.grantedPermissions
1810                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1811                continue;
1812            }
1813
1814            if (requiredVerifier != null) {
1815                throw new RuntimeException("There can be only one required verifier");
1816            }
1817
1818            requiredVerifier = packageName;
1819        }
1820
1821        return requiredVerifier;
1822    }
1823
1824    @Override
1825    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1826            throws RemoteException {
1827        try {
1828            return super.onTransact(code, data, reply, flags);
1829        } catch (RuntimeException e) {
1830            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1831                Slog.wtf(TAG, "Package Manager Crash", e);
1832            }
1833            throw e;
1834        }
1835    }
1836
1837    void cleanupInstallFailedPackage(PackageSetting ps) {
1838        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1839        removeDataDirsLI(ps.name);
1840
1841        // TODO: try cleaning up codePath directory contents first, since it
1842        // might be a cluster
1843
1844        if (ps.codePath != null) {
1845            if (!ps.codePath.delete()) {
1846                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1847            }
1848        }
1849        if (ps.resourcePath != null) {
1850            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1851                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1852            }
1853        }
1854        mSettings.removePackageLPw(ps.name);
1855    }
1856
1857    static int[] appendInts(int[] cur, int[] add) {
1858        if (add == null) return cur;
1859        if (cur == null) return add;
1860        final int N = add.length;
1861        for (int i=0; i<N; i++) {
1862            cur = appendInt(cur, add[i]);
1863        }
1864        return cur;
1865    }
1866
1867    static int[] removeInts(int[] cur, int[] rem) {
1868        if (rem == null) return cur;
1869        if (cur == null) return cur;
1870        final int N = rem.length;
1871        for (int i=0; i<N; i++) {
1872            cur = removeInt(cur, rem[i]);
1873        }
1874        return cur;
1875    }
1876
1877    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1878        if (!sUserManager.exists(userId)) return null;
1879        final PackageSetting ps = (PackageSetting) p.mExtras;
1880        if (ps == null) {
1881            return null;
1882        }
1883        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1884        final PackageUserState state = ps.readUserState(userId);
1885        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1886                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1887                state, userId);
1888    }
1889
1890    @Override
1891    public boolean isPackageAvailable(String packageName, int userId) {
1892        if (!sUserManager.exists(userId)) return false;
1893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1894        synchronized (mPackages) {
1895            PackageParser.Package p = mPackages.get(packageName);
1896            if (p != null) {
1897                final PackageSetting ps = (PackageSetting) p.mExtras;
1898                if (ps != null) {
1899                    final PackageUserState state = ps.readUserState(userId);
1900                    if (state != null) {
1901                        return PackageParser.isAvailable(state);
1902                    }
1903                }
1904            }
1905        }
1906        return false;
1907    }
1908
1909    @Override
1910    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1911        if (!sUserManager.exists(userId)) return null;
1912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1913        // reader
1914        synchronized (mPackages) {
1915            PackageParser.Package p = mPackages.get(packageName);
1916            if (DEBUG_PACKAGE_INFO)
1917                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1918            if (p != null) {
1919                return generatePackageInfo(p, flags, userId);
1920            }
1921            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1922                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1923            }
1924        }
1925        return null;
1926    }
1927
1928    @Override
1929    public String[] currentToCanonicalPackageNames(String[] names) {
1930        String[] out = new String[names.length];
1931        // reader
1932        synchronized (mPackages) {
1933            for (int i=names.length-1; i>=0; i--) {
1934                PackageSetting ps = mSettings.mPackages.get(names[i]);
1935                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1936            }
1937        }
1938        return out;
1939    }
1940
1941    @Override
1942    public String[] canonicalToCurrentPackageNames(String[] names) {
1943        String[] out = new String[names.length];
1944        // reader
1945        synchronized (mPackages) {
1946            for (int i=names.length-1; i>=0; i--) {
1947                String cur = mSettings.mRenamedPackages.get(names[i]);
1948                out[i] = cur != null ? cur : names[i];
1949            }
1950        }
1951        return out;
1952    }
1953
1954    @Override
1955    public int getPackageUid(String packageName, int userId) {
1956        if (!sUserManager.exists(userId)) return -1;
1957        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1958        // reader
1959        synchronized (mPackages) {
1960            PackageParser.Package p = mPackages.get(packageName);
1961            if(p != null) {
1962                return UserHandle.getUid(userId, p.applicationInfo.uid);
1963            }
1964            PackageSetting ps = mSettings.mPackages.get(packageName);
1965            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1966                return -1;
1967            }
1968            p = ps.pkg;
1969            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1970        }
1971    }
1972
1973    @Override
1974    public int[] getPackageGids(String packageName) {
1975        // reader
1976        synchronized (mPackages) {
1977            PackageParser.Package p = mPackages.get(packageName);
1978            if (DEBUG_PACKAGE_INFO)
1979                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1980            if (p != null) {
1981                final PackageSetting ps = (PackageSetting)p.mExtras;
1982                return ps.getGids();
1983            }
1984        }
1985        // stupid thing to indicate an error.
1986        return new int[0];
1987    }
1988
1989    static final PermissionInfo generatePermissionInfo(
1990            BasePermission bp, int flags) {
1991        if (bp.perm != null) {
1992            return PackageParser.generatePermissionInfo(bp.perm, flags);
1993        }
1994        PermissionInfo pi = new PermissionInfo();
1995        pi.name = bp.name;
1996        pi.packageName = bp.sourcePackage;
1997        pi.nonLocalizedLabel = bp.name;
1998        pi.protectionLevel = bp.protectionLevel;
1999        return pi;
2000    }
2001
2002    @Override
2003    public PermissionInfo getPermissionInfo(String name, int flags) {
2004        // reader
2005        synchronized (mPackages) {
2006            final BasePermission p = mSettings.mPermissions.get(name);
2007            if (p != null) {
2008                return generatePermissionInfo(p, flags);
2009            }
2010            return null;
2011        }
2012    }
2013
2014    @Override
2015    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2016        // reader
2017        synchronized (mPackages) {
2018            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2019            for (BasePermission p : mSettings.mPermissions.values()) {
2020                if (group == null) {
2021                    if (p.perm == null || p.perm.info.group == null) {
2022                        out.add(generatePermissionInfo(p, flags));
2023                    }
2024                } else {
2025                    if (p.perm != null && group.equals(p.perm.info.group)) {
2026                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2027                    }
2028                }
2029            }
2030
2031            if (out.size() > 0) {
2032                return out;
2033            }
2034            return mPermissionGroups.containsKey(group) ? out : null;
2035        }
2036    }
2037
2038    @Override
2039    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2040        // reader
2041        synchronized (mPackages) {
2042            return PackageParser.generatePermissionGroupInfo(
2043                    mPermissionGroups.get(name), flags);
2044        }
2045    }
2046
2047    @Override
2048    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2049        // reader
2050        synchronized (mPackages) {
2051            final int N = mPermissionGroups.size();
2052            ArrayList<PermissionGroupInfo> out
2053                    = new ArrayList<PermissionGroupInfo>(N);
2054            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2055                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2056            }
2057            return out;
2058        }
2059    }
2060
2061    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2062            int userId) {
2063        if (!sUserManager.exists(userId)) return null;
2064        PackageSetting ps = mSettings.mPackages.get(packageName);
2065        if (ps != null) {
2066            if (ps.pkg == null) {
2067                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2068                        flags, userId);
2069                if (pInfo != null) {
2070                    return pInfo.applicationInfo;
2071                }
2072                return null;
2073            }
2074            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2075                    ps.readUserState(userId), userId);
2076        }
2077        return null;
2078    }
2079
2080    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2081            int userId) {
2082        if (!sUserManager.exists(userId)) return null;
2083        PackageSetting ps = mSettings.mPackages.get(packageName);
2084        if (ps != null) {
2085            PackageParser.Package pkg = ps.pkg;
2086            if (pkg == null) {
2087                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2088                    return null;
2089                }
2090                // Only data remains, so we aren't worried about code paths
2091                pkg = new PackageParser.Package(packageName);
2092                pkg.applicationInfo.packageName = packageName;
2093                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2094                pkg.applicationInfo.dataDir =
2095                        getDataPathForPackage(packageName, 0).getPath();
2096                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2097                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2098            }
2099            return generatePackageInfo(pkg, flags, userId);
2100        }
2101        return null;
2102    }
2103
2104    @Override
2105    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2106        if (!sUserManager.exists(userId)) return null;
2107        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2108        // writer
2109        synchronized (mPackages) {
2110            PackageParser.Package p = mPackages.get(packageName);
2111            if (DEBUG_PACKAGE_INFO) Log.v(
2112                    TAG, "getApplicationInfo " + packageName
2113                    + ": " + p);
2114            if (p != null) {
2115                PackageSetting ps = mSettings.mPackages.get(packageName);
2116                if (ps == null) return null;
2117                // Note: isEnabledLP() does not apply here - always return info
2118                return PackageParser.generateApplicationInfo(
2119                        p, flags, ps.readUserState(userId), userId);
2120            }
2121            if ("android".equals(packageName)||"system".equals(packageName)) {
2122                return mAndroidApplication;
2123            }
2124            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2125                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2126            }
2127        }
2128        return null;
2129    }
2130
2131
2132    @Override
2133    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2134        mContext.enforceCallingOrSelfPermission(
2135                android.Manifest.permission.CLEAR_APP_CACHE, null);
2136        // Queue up an async operation since clearing cache may take a little while.
2137        mHandler.post(new Runnable() {
2138            public void run() {
2139                mHandler.removeCallbacks(this);
2140                int retCode = -1;
2141                synchronized (mInstallLock) {
2142                    retCode = mInstaller.freeCache(freeStorageSize);
2143                    if (retCode < 0) {
2144                        Slog.w(TAG, "Couldn't clear application caches");
2145                    }
2146                }
2147                if (observer != null) {
2148                    try {
2149                        observer.onRemoveCompleted(null, (retCode >= 0));
2150                    } catch (RemoteException e) {
2151                        Slog.w(TAG, "RemoveException when invoking call back");
2152                    }
2153                }
2154            }
2155        });
2156    }
2157
2158    @Override
2159    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2160        mContext.enforceCallingOrSelfPermission(
2161                android.Manifest.permission.CLEAR_APP_CACHE, null);
2162        // Queue up an async operation since clearing cache may take a little while.
2163        mHandler.post(new Runnable() {
2164            public void run() {
2165                mHandler.removeCallbacks(this);
2166                int retCode = -1;
2167                synchronized (mInstallLock) {
2168                    retCode = mInstaller.freeCache(freeStorageSize);
2169                    if (retCode < 0) {
2170                        Slog.w(TAG, "Couldn't clear application caches");
2171                    }
2172                }
2173                if(pi != null) {
2174                    try {
2175                        // Callback via pending intent
2176                        int code = (retCode >= 0) ? 1 : 0;
2177                        pi.sendIntent(null, code, null,
2178                                null, null);
2179                    } catch (SendIntentException e1) {
2180                        Slog.i(TAG, "Failed to send pending intent");
2181                    }
2182                }
2183            }
2184        });
2185    }
2186
2187    void freeStorage(long freeStorageSize) throws IOException {
2188        synchronized (mInstallLock) {
2189            if (mInstaller.freeCache(freeStorageSize) < 0) {
2190                throw new IOException("Failed to free enough space");
2191            }
2192        }
2193    }
2194
2195    @Override
2196    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2197        if (!sUserManager.exists(userId)) return null;
2198        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2199        synchronized (mPackages) {
2200            PackageParser.Activity a = mActivities.mActivities.get(component);
2201
2202            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2203            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2204                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2205                if (ps == null) return null;
2206                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2207                        userId);
2208            }
2209            if (mResolveComponentName.equals(component)) {
2210                return mResolveActivity;
2211            }
2212        }
2213        return null;
2214    }
2215
2216    @Override
2217    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2218            String resolvedType) {
2219        synchronized (mPackages) {
2220            PackageParser.Activity a = mActivities.mActivities.get(component);
2221            if (a == null) {
2222                return false;
2223            }
2224            for (int i=0; i<a.intents.size(); i++) {
2225                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2226                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2227                    return true;
2228                }
2229            }
2230            return false;
2231        }
2232    }
2233
2234    @Override
2235    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2236        if (!sUserManager.exists(userId)) return null;
2237        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2238        synchronized (mPackages) {
2239            PackageParser.Activity a = mReceivers.mActivities.get(component);
2240            if (DEBUG_PACKAGE_INFO) Log.v(
2241                TAG, "getReceiverInfo " + component + ": " + a);
2242            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2243                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2244                if (ps == null) return null;
2245                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2246                        userId);
2247            }
2248        }
2249        return null;
2250    }
2251
2252    @Override
2253    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2254        if (!sUserManager.exists(userId)) return null;
2255        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2256        synchronized (mPackages) {
2257            PackageParser.Service s = mServices.mServices.get(component);
2258            if (DEBUG_PACKAGE_INFO) Log.v(
2259                TAG, "getServiceInfo " + component + ": " + s);
2260            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2261                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2262                if (ps == null) return null;
2263                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2264                        userId);
2265            }
2266        }
2267        return null;
2268    }
2269
2270    @Override
2271    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2272        if (!sUserManager.exists(userId)) return null;
2273        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2274        synchronized (mPackages) {
2275            PackageParser.Provider p = mProviders.mProviders.get(component);
2276            if (DEBUG_PACKAGE_INFO) Log.v(
2277                TAG, "getProviderInfo " + component + ": " + p);
2278            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2279                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2280                if (ps == null) return null;
2281                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2282                        userId);
2283            }
2284        }
2285        return null;
2286    }
2287
2288    @Override
2289    public String[] getSystemSharedLibraryNames() {
2290        Set<String> libSet;
2291        synchronized (mPackages) {
2292            libSet = mSharedLibraries.keySet();
2293            int size = libSet.size();
2294            if (size > 0) {
2295                String[] libs = new String[size];
2296                libSet.toArray(libs);
2297                return libs;
2298            }
2299        }
2300        return null;
2301    }
2302
2303    @Override
2304    public FeatureInfo[] getSystemAvailableFeatures() {
2305        Collection<FeatureInfo> featSet;
2306        synchronized (mPackages) {
2307            featSet = mAvailableFeatures.values();
2308            int size = featSet.size();
2309            if (size > 0) {
2310                FeatureInfo[] features = new FeatureInfo[size+1];
2311                featSet.toArray(features);
2312                FeatureInfo fi = new FeatureInfo();
2313                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2314                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2315                features[size] = fi;
2316                return features;
2317            }
2318        }
2319        return null;
2320    }
2321
2322    @Override
2323    public boolean hasSystemFeature(String name) {
2324        synchronized (mPackages) {
2325            return mAvailableFeatures.containsKey(name);
2326        }
2327    }
2328
2329    private void checkValidCaller(int uid, int userId) {
2330        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2331            return;
2332
2333        throw new SecurityException("Caller uid=" + uid
2334                + " is not privileged to communicate with user=" + userId);
2335    }
2336
2337    @Override
2338    public int checkPermission(String permName, String pkgName) {
2339        synchronized (mPackages) {
2340            PackageParser.Package p = mPackages.get(pkgName);
2341            if (p != null && p.mExtras != null) {
2342                PackageSetting ps = (PackageSetting)p.mExtras;
2343                if (ps.sharedUser != null) {
2344                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2345                        return PackageManager.PERMISSION_GRANTED;
2346                    }
2347                } else if (ps.grantedPermissions.contains(permName)) {
2348                    return PackageManager.PERMISSION_GRANTED;
2349                }
2350            }
2351        }
2352        return PackageManager.PERMISSION_DENIED;
2353    }
2354
2355    @Override
2356    public int checkUidPermission(String permName, int uid) {
2357        synchronized (mPackages) {
2358            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2359            if (obj != null) {
2360                GrantedPermissions gp = (GrantedPermissions)obj;
2361                if (gp.grantedPermissions.contains(permName)) {
2362                    return PackageManager.PERMISSION_GRANTED;
2363                }
2364            } else {
2365                HashSet<String> perms = mSystemPermissions.get(uid);
2366                if (perms != null && perms.contains(permName)) {
2367                    return PackageManager.PERMISSION_GRANTED;
2368                }
2369            }
2370        }
2371        return PackageManager.PERMISSION_DENIED;
2372    }
2373
2374    /**
2375     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2376     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2377     * @param message the message to log on security exception
2378     */
2379    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2380            String message) {
2381        if (userId < 0) {
2382            throw new IllegalArgumentException("Invalid userId " + userId);
2383        }
2384        if (userId == UserHandle.getUserId(callingUid)) return;
2385        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2386            if (requireFullPermission) {
2387                mContext.enforceCallingOrSelfPermission(
2388                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2389            } else {
2390                try {
2391                    mContext.enforceCallingOrSelfPermission(
2392                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2393                } catch (SecurityException se) {
2394                    mContext.enforceCallingOrSelfPermission(
2395                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2396                }
2397            }
2398        }
2399    }
2400
2401    private BasePermission findPermissionTreeLP(String permName) {
2402        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2403            if (permName.startsWith(bp.name) &&
2404                    permName.length() > bp.name.length() &&
2405                    permName.charAt(bp.name.length()) == '.') {
2406                return bp;
2407            }
2408        }
2409        return null;
2410    }
2411
2412    private BasePermission checkPermissionTreeLP(String permName) {
2413        if (permName != null) {
2414            BasePermission bp = findPermissionTreeLP(permName);
2415            if (bp != null) {
2416                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2417                    return bp;
2418                }
2419                throw new SecurityException("Calling uid "
2420                        + Binder.getCallingUid()
2421                        + " is not allowed to add to permission tree "
2422                        + bp.name + " owned by uid " + bp.uid);
2423            }
2424        }
2425        throw new SecurityException("No permission tree found for " + permName);
2426    }
2427
2428    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2429        if (s1 == null) {
2430            return s2 == null;
2431        }
2432        if (s2 == null) {
2433            return false;
2434        }
2435        if (s1.getClass() != s2.getClass()) {
2436            return false;
2437        }
2438        return s1.equals(s2);
2439    }
2440
2441    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2442        if (pi1.icon != pi2.icon) return false;
2443        if (pi1.logo != pi2.logo) return false;
2444        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2445        if (!compareStrings(pi1.name, pi2.name)) return false;
2446        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2447        // We'll take care of setting this one.
2448        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2449        // These are not currently stored in settings.
2450        //if (!compareStrings(pi1.group, pi2.group)) return false;
2451        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2452        //if (pi1.labelRes != pi2.labelRes) return false;
2453        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2454        return true;
2455    }
2456
2457    int permissionInfoFootprint(PermissionInfo info) {
2458        int size = info.name.length();
2459        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2460        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2461        return size;
2462    }
2463
2464    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2465        int size = 0;
2466        for (BasePermission perm : mSettings.mPermissions.values()) {
2467            if (perm.uid == tree.uid) {
2468                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2469            }
2470        }
2471        return size;
2472    }
2473
2474    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2475        // We calculate the max size of permissions defined by this uid and throw
2476        // if that plus the size of 'info' would exceed our stated maximum.
2477        if (tree.uid != Process.SYSTEM_UID) {
2478            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2479            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2480                throw new SecurityException("Permission tree size cap exceeded");
2481            }
2482        }
2483    }
2484
2485    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2486        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2487            throw new SecurityException("Label must be specified in permission");
2488        }
2489        BasePermission tree = checkPermissionTreeLP(info.name);
2490        BasePermission bp = mSettings.mPermissions.get(info.name);
2491        boolean added = bp == null;
2492        boolean changed = true;
2493        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2494        if (added) {
2495            enforcePermissionCapLocked(info, tree);
2496            bp = new BasePermission(info.name, tree.sourcePackage,
2497                    BasePermission.TYPE_DYNAMIC);
2498        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2499            throw new SecurityException(
2500                    "Not allowed to modify non-dynamic permission "
2501                    + info.name);
2502        } else {
2503            if (bp.protectionLevel == fixedLevel
2504                    && bp.perm.owner.equals(tree.perm.owner)
2505                    && bp.uid == tree.uid
2506                    && comparePermissionInfos(bp.perm.info, info)) {
2507                changed = false;
2508            }
2509        }
2510        bp.protectionLevel = fixedLevel;
2511        info = new PermissionInfo(info);
2512        info.protectionLevel = fixedLevel;
2513        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2514        bp.perm.info.packageName = tree.perm.info.packageName;
2515        bp.uid = tree.uid;
2516        if (added) {
2517            mSettings.mPermissions.put(info.name, bp);
2518        }
2519        if (changed) {
2520            if (!async) {
2521                mSettings.writeLPr();
2522            } else {
2523                scheduleWriteSettingsLocked();
2524            }
2525        }
2526        return added;
2527    }
2528
2529    @Override
2530    public boolean addPermission(PermissionInfo info) {
2531        synchronized (mPackages) {
2532            return addPermissionLocked(info, false);
2533        }
2534    }
2535
2536    @Override
2537    public boolean addPermissionAsync(PermissionInfo info) {
2538        synchronized (mPackages) {
2539            return addPermissionLocked(info, true);
2540        }
2541    }
2542
2543    @Override
2544    public void removePermission(String name) {
2545        synchronized (mPackages) {
2546            checkPermissionTreeLP(name);
2547            BasePermission bp = mSettings.mPermissions.get(name);
2548            if (bp != null) {
2549                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2550                    throw new SecurityException(
2551                            "Not allowed to modify non-dynamic permission "
2552                            + name);
2553                }
2554                mSettings.mPermissions.remove(name);
2555                mSettings.writeLPr();
2556            }
2557        }
2558    }
2559
2560    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2561        int index = pkg.requestedPermissions.indexOf(bp.name);
2562        if (index == -1) {
2563            throw new SecurityException("Package " + pkg.packageName
2564                    + " has not requested permission " + bp.name);
2565        }
2566        boolean isNormal =
2567                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2568                        == PermissionInfo.PROTECTION_NORMAL);
2569        boolean isDangerous =
2570                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2571                        == PermissionInfo.PROTECTION_DANGEROUS);
2572        boolean isDevelopment =
2573                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2574
2575        if (!isNormal && !isDangerous && !isDevelopment) {
2576            throw new SecurityException("Permission " + bp.name
2577                    + " is not a changeable permission type");
2578        }
2579
2580        if (isNormal || isDangerous) {
2581            if (pkg.requestedPermissionsRequired.get(index)) {
2582                throw new SecurityException("Can't change " + bp.name
2583                        + ". It is required by the application");
2584            }
2585        }
2586    }
2587
2588    @Override
2589    public void grantPermission(String packageName, String permissionName) {
2590        mContext.enforceCallingOrSelfPermission(
2591                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2592        synchronized (mPackages) {
2593            final PackageParser.Package pkg = mPackages.get(packageName);
2594            if (pkg == null) {
2595                throw new IllegalArgumentException("Unknown package: " + packageName);
2596            }
2597            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2598            if (bp == null) {
2599                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2600            }
2601
2602            checkGrantRevokePermissions(pkg, bp);
2603
2604            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2605            if (ps == null) {
2606                return;
2607            }
2608            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2609            if (gp.grantedPermissions.add(permissionName)) {
2610                if (ps.haveGids) {
2611                    gp.gids = appendInts(gp.gids, bp.gids);
2612                }
2613                mSettings.writeLPr();
2614            }
2615        }
2616    }
2617
2618    @Override
2619    public void revokePermission(String packageName, String permissionName) {
2620        int changedAppId = -1;
2621
2622        synchronized (mPackages) {
2623            final PackageParser.Package pkg = mPackages.get(packageName);
2624            if (pkg == null) {
2625                throw new IllegalArgumentException("Unknown package: " + packageName);
2626            }
2627            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2628                mContext.enforceCallingOrSelfPermission(
2629                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2630            }
2631            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2632            if (bp == null) {
2633                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2634            }
2635
2636            checkGrantRevokePermissions(pkg, bp);
2637
2638            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2639            if (ps == null) {
2640                return;
2641            }
2642            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2643            if (gp.grantedPermissions.remove(permissionName)) {
2644                gp.grantedPermissions.remove(permissionName);
2645                if (ps.haveGids) {
2646                    gp.gids = removeInts(gp.gids, bp.gids);
2647                }
2648                mSettings.writeLPr();
2649                changedAppId = ps.appId;
2650            }
2651        }
2652
2653        if (changedAppId >= 0) {
2654            // We changed the perm on someone, kill its processes.
2655            IActivityManager am = ActivityManagerNative.getDefault();
2656            if (am != null) {
2657                final int callingUserId = UserHandle.getCallingUserId();
2658                final long ident = Binder.clearCallingIdentity();
2659                try {
2660                    //XXX we should only revoke for the calling user's app permissions,
2661                    // but for now we impact all users.
2662                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2663                    //        "revoke " + permissionName);
2664                    int[] users = sUserManager.getUserIds();
2665                    for (int user : users) {
2666                        am.killUid(UserHandle.getUid(user, changedAppId),
2667                                "revoke " + permissionName);
2668                    }
2669                } catch (RemoteException e) {
2670                } finally {
2671                    Binder.restoreCallingIdentity(ident);
2672                }
2673            }
2674        }
2675    }
2676
2677    @Override
2678    public boolean isProtectedBroadcast(String actionName) {
2679        synchronized (mPackages) {
2680            return mProtectedBroadcasts.contains(actionName);
2681        }
2682    }
2683
2684    @Override
2685    public int checkSignatures(String pkg1, String pkg2) {
2686        synchronized (mPackages) {
2687            final PackageParser.Package p1 = mPackages.get(pkg1);
2688            final PackageParser.Package p2 = mPackages.get(pkg2);
2689            if (p1 == null || p1.mExtras == null
2690                    || p2 == null || p2.mExtras == null) {
2691                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2692            }
2693            return compareSignatures(p1.mSignatures, p2.mSignatures);
2694        }
2695    }
2696
2697    @Override
2698    public int checkUidSignatures(int uid1, int uid2) {
2699        // Map to base uids.
2700        uid1 = UserHandle.getAppId(uid1);
2701        uid2 = UserHandle.getAppId(uid2);
2702        // reader
2703        synchronized (mPackages) {
2704            Signature[] s1;
2705            Signature[] s2;
2706            Object obj = mSettings.getUserIdLPr(uid1);
2707            if (obj != null) {
2708                if (obj instanceof SharedUserSetting) {
2709                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2710                } else if (obj instanceof PackageSetting) {
2711                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2712                } else {
2713                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2714                }
2715            } else {
2716                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2717            }
2718            obj = mSettings.getUserIdLPr(uid2);
2719            if (obj != null) {
2720                if (obj instanceof SharedUserSetting) {
2721                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2722                } else if (obj instanceof PackageSetting) {
2723                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2724                } else {
2725                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2726                }
2727            } else {
2728                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2729            }
2730            return compareSignatures(s1, s2);
2731        }
2732    }
2733
2734    /**
2735     * Compares two sets of signatures. Returns:
2736     * <br />
2737     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2738     * <br />
2739     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2740     * <br />
2741     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2742     * <br />
2743     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2744     * <br />
2745     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2746     */
2747    static int compareSignatures(Signature[] s1, Signature[] s2) {
2748        if (s1 == null) {
2749            return s2 == null
2750                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2751                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2752        }
2753
2754        if (s2 == null) {
2755            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2756        }
2757
2758        if (s1.length != s2.length) {
2759            return PackageManager.SIGNATURE_NO_MATCH;
2760        }
2761
2762        // Since both signature sets are of size 1, we can compare without HashSets.
2763        if (s1.length == 1) {
2764            return s1[0].equals(s2[0]) ?
2765                    PackageManager.SIGNATURE_MATCH :
2766                    PackageManager.SIGNATURE_NO_MATCH;
2767        }
2768
2769        HashSet<Signature> set1 = new HashSet<Signature>();
2770        for (Signature sig : s1) {
2771            set1.add(sig);
2772        }
2773        HashSet<Signature> set2 = new HashSet<Signature>();
2774        for (Signature sig : s2) {
2775            set2.add(sig);
2776        }
2777        // Make sure s2 contains all signatures in s1.
2778        if (set1.equals(set2)) {
2779            return PackageManager.SIGNATURE_MATCH;
2780        }
2781        return PackageManager.SIGNATURE_NO_MATCH;
2782    }
2783
2784    /**
2785     * If the database version for this type of package (internal storage or
2786     * external storage) is less than the version where package signatures
2787     * were updated, return true.
2788     */
2789    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2790        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2791                DatabaseVersion.SIGNATURE_END_ENTITY))
2792                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2793                        DatabaseVersion.SIGNATURE_END_ENTITY));
2794    }
2795
2796    /**
2797     * Used for backward compatibility to make sure any packages with
2798     * certificate chains get upgraded to the new style. {@code existingSigs}
2799     * will be in the old format (since they were stored on disk from before the
2800     * system upgrade) and {@code scannedSigs} will be in the newer format.
2801     */
2802    private int compareSignaturesCompat(PackageSignatures existingSigs,
2803            PackageParser.Package scannedPkg) {
2804        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2805            return PackageManager.SIGNATURE_NO_MATCH;
2806        }
2807
2808        HashSet<Signature> existingSet = new HashSet<Signature>();
2809        for (Signature sig : existingSigs.mSignatures) {
2810            existingSet.add(sig);
2811        }
2812        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2813        for (Signature sig : scannedPkg.mSignatures) {
2814            try {
2815                Signature[] chainSignatures = sig.getChainSignatures();
2816                for (Signature chainSig : chainSignatures) {
2817                    scannedCompatSet.add(chainSig);
2818                }
2819            } catch (CertificateEncodingException e) {
2820                scannedCompatSet.add(sig);
2821            }
2822        }
2823        /*
2824         * Make sure the expanded scanned set contains all signatures in the
2825         * existing one.
2826         */
2827        if (scannedCompatSet.equals(existingSet)) {
2828            // Migrate the old signatures to the new scheme.
2829            existingSigs.assignSignatures(scannedPkg.mSignatures);
2830            // The new KeySets will be re-added later in the scanning process.
2831            synchronized (mPackages) {
2832                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2833            }
2834            return PackageManager.SIGNATURE_MATCH;
2835        }
2836        return PackageManager.SIGNATURE_NO_MATCH;
2837    }
2838
2839    @Override
2840    public String[] getPackagesForUid(int uid) {
2841        uid = UserHandle.getAppId(uid);
2842        // reader
2843        synchronized (mPackages) {
2844            Object obj = mSettings.getUserIdLPr(uid);
2845            if (obj instanceof SharedUserSetting) {
2846                final SharedUserSetting sus = (SharedUserSetting) obj;
2847                final int N = sus.packages.size();
2848                final String[] res = new String[N];
2849                final Iterator<PackageSetting> it = sus.packages.iterator();
2850                int i = 0;
2851                while (it.hasNext()) {
2852                    res[i++] = it.next().name;
2853                }
2854                return res;
2855            } else if (obj instanceof PackageSetting) {
2856                final PackageSetting ps = (PackageSetting) obj;
2857                return new String[] { ps.name };
2858            }
2859        }
2860        return null;
2861    }
2862
2863    @Override
2864    public String getNameForUid(int uid) {
2865        // reader
2866        synchronized (mPackages) {
2867            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2868            if (obj instanceof SharedUserSetting) {
2869                final SharedUserSetting sus = (SharedUserSetting) obj;
2870                return sus.name + ":" + sus.userId;
2871            } else if (obj instanceof PackageSetting) {
2872                final PackageSetting ps = (PackageSetting) obj;
2873                return ps.name;
2874            }
2875        }
2876        return null;
2877    }
2878
2879    @Override
2880    public int getUidForSharedUser(String sharedUserName) {
2881        if(sharedUserName == null) {
2882            return -1;
2883        }
2884        // reader
2885        synchronized (mPackages) {
2886            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2887            if (suid == null) {
2888                return -1;
2889            }
2890            return suid.userId;
2891        }
2892    }
2893
2894    @Override
2895    public int getFlagsForUid(int uid) {
2896        synchronized (mPackages) {
2897            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2898            if (obj instanceof SharedUserSetting) {
2899                final SharedUserSetting sus = (SharedUserSetting) obj;
2900                return sus.pkgFlags;
2901            } else if (obj instanceof PackageSetting) {
2902                final PackageSetting ps = (PackageSetting) obj;
2903                return ps.pkgFlags;
2904            }
2905        }
2906        return 0;
2907    }
2908
2909    @Override
2910    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2911            int flags, int userId) {
2912        if (!sUserManager.exists(userId)) return null;
2913        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2914        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2915        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2916    }
2917
2918    @Override
2919    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2920            IntentFilter filter, int match, ComponentName activity) {
2921        final int userId = UserHandle.getCallingUserId();
2922        if (DEBUG_PREFERRED) {
2923            Log.v(TAG, "setLastChosenActivity intent=" + intent
2924                + " resolvedType=" + resolvedType
2925                + " flags=" + flags
2926                + " filter=" + filter
2927                + " match=" + match
2928                + " activity=" + activity);
2929            filter.dump(new PrintStreamPrinter(System.out), "    ");
2930        }
2931        intent.setComponent(null);
2932        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2933        // Find any earlier preferred or last chosen entries and nuke them
2934        findPreferredActivity(intent, resolvedType,
2935                flags, query, 0, false, true, false, userId);
2936        // Add the new activity as the last chosen for this filter
2937        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2938    }
2939
2940    @Override
2941    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2942        final int userId = UserHandle.getCallingUserId();
2943        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2944        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2945        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2946                false, false, false, userId);
2947    }
2948
2949    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2950            int flags, List<ResolveInfo> query, int userId) {
2951        if (query != null) {
2952            final int N = query.size();
2953            if (N == 1) {
2954                return query.get(0);
2955            } else if (N > 1) {
2956                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2957                // If there is more than one activity with the same priority,
2958                // then let the user decide between them.
2959                ResolveInfo r0 = query.get(0);
2960                ResolveInfo r1 = query.get(1);
2961                if (DEBUG_INTENT_MATCHING || debug) {
2962                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2963                            + r1.activityInfo.name + "=" + r1.priority);
2964                }
2965                // If the first activity has a higher priority, or a different
2966                // default, then it is always desireable to pick it.
2967                if (r0.priority != r1.priority
2968                        || r0.preferredOrder != r1.preferredOrder
2969                        || r0.isDefault != r1.isDefault) {
2970                    return query.get(0);
2971                }
2972                // If we have saved a preference for a preferred activity for
2973                // this Intent, use that.
2974                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2975                        flags, query, r0.priority, true, false, debug, userId);
2976                if (ri != null) {
2977                    return ri;
2978                }
2979                if (userId != 0) {
2980                    ri = new ResolveInfo(mResolveInfo);
2981                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2982                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2983                            ri.activityInfo.applicationInfo);
2984                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2985                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2986                    return ri;
2987                }
2988                return mResolveInfo;
2989            }
2990        }
2991        return null;
2992    }
2993
2994    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2995            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2996        final int N = query.size();
2997        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2998                .get(userId);
2999        // Get the list of persistent preferred activities that handle the intent
3000        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3001        List<PersistentPreferredActivity> pprefs = ppir != null
3002                ? ppir.queryIntent(intent, resolvedType,
3003                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3004                : null;
3005        if (pprefs != null && pprefs.size() > 0) {
3006            final int M = pprefs.size();
3007            for (int i=0; i<M; i++) {
3008                final PersistentPreferredActivity ppa = pprefs.get(i);
3009                if (DEBUG_PREFERRED || debug) {
3010                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3011                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3012                            + "\n  component=" + ppa.mComponent);
3013                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3014                }
3015                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3016                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3017                if (DEBUG_PREFERRED || debug) {
3018                    Slog.v(TAG, "Found persistent preferred activity:");
3019                    if (ai != null) {
3020                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3021                    } else {
3022                        Slog.v(TAG, "  null");
3023                    }
3024                }
3025                if (ai == null) {
3026                    // This previously registered persistent preferred activity
3027                    // component is no longer known. Ignore it and do NOT remove it.
3028                    continue;
3029                }
3030                for (int j=0; j<N; j++) {
3031                    final ResolveInfo ri = query.get(j);
3032                    if (!ri.activityInfo.applicationInfo.packageName
3033                            .equals(ai.applicationInfo.packageName)) {
3034                        continue;
3035                    }
3036                    if (!ri.activityInfo.name.equals(ai.name)) {
3037                        continue;
3038                    }
3039                    //  Found a persistent preference that can handle the intent.
3040                    if (DEBUG_PREFERRED || debug) {
3041                        Slog.v(TAG, "Returning persistent preferred activity: " +
3042                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3043                    }
3044                    return ri;
3045                }
3046            }
3047        }
3048        return null;
3049    }
3050
3051    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3052            List<ResolveInfo> query, int priority, boolean always,
3053            boolean removeMatches, boolean debug, int userId) {
3054        if (!sUserManager.exists(userId)) return null;
3055        // writer
3056        synchronized (mPackages) {
3057            if (intent.getSelector() != null) {
3058                intent = intent.getSelector();
3059            }
3060            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3061
3062            // Try to find a matching persistent preferred activity.
3063            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3064                    debug, userId);
3065
3066            // If a persistent preferred activity matched, use it.
3067            if (pri != null) {
3068                return pri;
3069            }
3070
3071            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3072            // Get the list of preferred activities that handle the intent
3073            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3074            List<PreferredActivity> prefs = pir != null
3075                    ? pir.queryIntent(intent, resolvedType,
3076                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3077                    : null;
3078            if (prefs != null && prefs.size() > 0) {
3079                // First figure out how good the original match set is.
3080                // We will only allow preferred activities that came
3081                // from the same match quality.
3082                int match = 0;
3083
3084                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3085
3086                final int N = query.size();
3087                for (int j=0; j<N; j++) {
3088                    final ResolveInfo ri = query.get(j);
3089                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3090                            + ": 0x" + Integer.toHexString(match));
3091                    if (ri.match > match) {
3092                        match = ri.match;
3093                    }
3094                }
3095
3096                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3097                        + Integer.toHexString(match));
3098
3099                match &= IntentFilter.MATCH_CATEGORY_MASK;
3100                final int M = prefs.size();
3101                for (int i=0; i<M; i++) {
3102                    final PreferredActivity pa = prefs.get(i);
3103                    if (DEBUG_PREFERRED || debug) {
3104                        Slog.v(TAG, "Checking PreferredActivity ds="
3105                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3106                                + "\n  component=" + pa.mPref.mComponent);
3107                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3108                    }
3109                    if (pa.mPref.mMatch != match) {
3110                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3111                                + Integer.toHexString(pa.mPref.mMatch));
3112                        continue;
3113                    }
3114                    // If it's not an "always" type preferred activity and that's what we're
3115                    // looking for, skip it.
3116                    if (always && !pa.mPref.mAlways) {
3117                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3118                        continue;
3119                    }
3120                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3121                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3122                    if (DEBUG_PREFERRED || debug) {
3123                        Slog.v(TAG, "Found preferred activity:");
3124                        if (ai != null) {
3125                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3126                        } else {
3127                            Slog.v(TAG, "  null");
3128                        }
3129                    }
3130                    if (ai == null) {
3131                        // This previously registered preferred activity
3132                        // component is no longer known.  Most likely an update
3133                        // to the app was installed and in the new version this
3134                        // component no longer exists.  Clean it up by removing
3135                        // it from the preferred activities list, and skip it.
3136                        Slog.w(TAG, "Removing dangling preferred activity: "
3137                                + pa.mPref.mComponent);
3138                        pir.removeFilter(pa);
3139                        continue;
3140                    }
3141                    for (int j=0; j<N; j++) {
3142                        final ResolveInfo ri = query.get(j);
3143                        if (!ri.activityInfo.applicationInfo.packageName
3144                                .equals(ai.applicationInfo.packageName)) {
3145                            continue;
3146                        }
3147                        if (!ri.activityInfo.name.equals(ai.name)) {
3148                            continue;
3149                        }
3150
3151                        if (removeMatches) {
3152                            pir.removeFilter(pa);
3153                            if (DEBUG_PREFERRED) {
3154                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3155                            }
3156                            break;
3157                        }
3158
3159                        // Okay we found a previously set preferred or last chosen app.
3160                        // If the result set is different from when this
3161                        // was created, we need to clear it and re-ask the
3162                        // user their preference, if we're looking for an "always" type entry.
3163                        if (always && !pa.mPref.sameSet(query, priority)) {
3164                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3165                                    + intent + " type " + resolvedType);
3166                            if (DEBUG_PREFERRED) {
3167                                Slog.v(TAG, "Removing preferred activity since set changed "
3168                                        + pa.mPref.mComponent);
3169                            }
3170                            pir.removeFilter(pa);
3171                            // Re-add the filter as a "last chosen" entry (!always)
3172                            PreferredActivity lastChosen = new PreferredActivity(
3173                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3174                            pir.addFilter(lastChosen);
3175                            mSettings.writePackageRestrictionsLPr(userId);
3176                            return null;
3177                        }
3178
3179                        // Yay! Either the set matched or we're looking for the last chosen
3180                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3181                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3182                        mSettings.writePackageRestrictionsLPr(userId);
3183                        return ri;
3184                    }
3185                }
3186            }
3187            mSettings.writePackageRestrictionsLPr(userId);
3188        }
3189        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3190        return null;
3191    }
3192
3193    /*
3194     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3195     */
3196    @Override
3197    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3198            int targetUserId) {
3199        mContext.enforceCallingOrSelfPermission(
3200                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3201        List<CrossProfileIntentFilter> matches =
3202                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3203        if (matches != null) {
3204            int size = matches.size();
3205            for (int i = 0; i < size; i++) {
3206                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3207            }
3208        }
3209
3210        ArrayList<String> packageNames = null;
3211        SparseArray<ArrayList<String>> fromSource =
3212                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3213        if (fromSource != null) {
3214            packageNames = fromSource.get(targetUserId);
3215        }
3216        if (packageNames.contains(intent.getPackage())) {
3217            return true;
3218        }
3219        // We need the package name, so we try to resolve with the loosest flags possible
3220        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3221                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3222        int count = resolveInfos.size();
3223        for (int i = 0; i < count; i++) {
3224            ResolveInfo resolveInfo = resolveInfos.get(i);
3225            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3226                return true;
3227            }
3228        }
3229        return false;
3230    }
3231
3232    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3233            String resolvedType, int userId) {
3234        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3235        if (resolver != null) {
3236            return resolver.queryIntent(intent, resolvedType, false, userId);
3237        }
3238        return null;
3239    }
3240
3241    @Override
3242    public List<ResolveInfo> queryIntentActivities(Intent intent,
3243            String resolvedType, int flags, int userId) {
3244        if (!sUserManager.exists(userId)) return Collections.emptyList();
3245        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3246        ComponentName comp = intent.getComponent();
3247        if (comp == null) {
3248            if (intent.getSelector() != null) {
3249                intent = intent.getSelector();
3250                comp = intent.getComponent();
3251            }
3252        }
3253
3254        if (comp != null) {
3255            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3256            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3257            if (ai != null) {
3258                final ResolveInfo ri = new ResolveInfo();
3259                ri.activityInfo = ai;
3260                list.add(ri);
3261            }
3262            return list;
3263        }
3264
3265        // reader
3266        synchronized (mPackages) {
3267            final String pkgName = intent.getPackage();
3268            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3269            if (pkgName == null) {
3270                ResolveInfo resolveInfo = null;
3271                if (queryCrossProfile) {
3272                    // Check if the intent needs to be forwarded to another user for this package
3273                    ArrayList<ResolveInfo> crossProfileResult =
3274                            queryIntentActivitiesCrossProfilePackage(
3275                                    intent, resolvedType, flags, userId);
3276                    if (!crossProfileResult.isEmpty()) {
3277                        // Skip the current profile
3278                        return crossProfileResult;
3279                    }
3280                    List<CrossProfileIntentFilter> matchingFilters =
3281                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3282                    // Check for results that need to skip the current profile.
3283                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3284                            resolvedType, flags, userId);
3285                    if (resolveInfo != null) {
3286                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3287                        result.add(resolveInfo);
3288                        return result;
3289                    }
3290                    // Check for cross profile results.
3291                    resolveInfo = queryCrossProfileIntents(
3292                            matchingFilters, intent, resolvedType, flags, userId);
3293                }
3294                // Check for results in the current profile.
3295                List<ResolveInfo> result = mActivities.queryIntent(
3296                        intent, resolvedType, flags, userId);
3297                if (resolveInfo != null) {
3298                    result.add(resolveInfo);
3299                }
3300                return result;
3301            }
3302            final PackageParser.Package pkg = mPackages.get(pkgName);
3303            if (pkg != null) {
3304                if (queryCrossProfile) {
3305                    ArrayList<ResolveInfo> crossProfileResult =
3306                            queryIntentActivitiesCrossProfilePackage(
3307                                    intent, resolvedType, flags, userId, pkg, pkgName);
3308                    if (!crossProfileResult.isEmpty()) {
3309                        // Skip the current profile
3310                        return crossProfileResult;
3311                    }
3312                }
3313                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3314                        pkg.activities, userId);
3315            }
3316            return new ArrayList<ResolveInfo>();
3317        }
3318    }
3319
3320    private ResolveInfo querySkipCurrentProfileIntents(
3321            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3322            int flags, int sourceUserId) {
3323        if (matchingFilters != null) {
3324            int size = matchingFilters.size();
3325            for (int i = 0; i < size; i ++) {
3326                CrossProfileIntentFilter filter = matchingFilters.get(i);
3327                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3328                    // Checking if there are activities in the target user that can handle the
3329                    // intent.
3330                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3331                            flags, sourceUserId);
3332                    if (resolveInfo != null) {
3333                        return resolveInfo;
3334                    }
3335                }
3336            }
3337        }
3338        return null;
3339    }
3340
3341    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3342            Intent intent, String resolvedType, int flags, int userId) {
3343        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3344        SparseArray<ArrayList<String>> sourceForwardingInfo =
3345                mSettings.mCrossProfilePackageInfo.get(userId);
3346        if (sourceForwardingInfo != null) {
3347            int NI = sourceForwardingInfo.size();
3348            for (int i = 0; i < NI; i++) {
3349                int targetUserId = sourceForwardingInfo.keyAt(i);
3350                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3351                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3352                        intent, resolvedType, flags, targetUserId);
3353                int NJ = resolveInfos.size();
3354                for (int j = 0; j < NJ; j++) {
3355                    ResolveInfo resolveInfo = resolveInfos.get(j);
3356                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3357                        matchingResolveInfos.add(createForwardingResolveInfo(
3358                                resolveInfo.filter, userId, targetUserId));
3359                    }
3360                }
3361            }
3362        }
3363        return matchingResolveInfos;
3364    }
3365
3366    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3367            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3368            String packageName) {
3369        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3370        SparseArray<ArrayList<String>> sourceForwardingInfo =
3371                mSettings.mCrossProfilePackageInfo.get(userId);
3372        if (sourceForwardingInfo != null) {
3373            int NI = sourceForwardingInfo.size();
3374            for (int i = 0; i < NI; i++) {
3375                int targetUserId = sourceForwardingInfo.keyAt(i);
3376                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3377                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3378                            intent, resolvedType, flags, pkg.activities, targetUserId);
3379                    int NJ = resolveInfos.size();
3380                    for (int j = 0; j < NJ; j++) {
3381                        ResolveInfo resolveInfo = resolveInfos.get(j);
3382                        matchingResolveInfos.add(createForwardingResolveInfo(
3383                                resolveInfo.filter, userId, targetUserId));
3384                    }
3385                }
3386            }
3387        }
3388        return matchingResolveInfos;
3389    }
3390
3391    // Return matching ResolveInfo if any for skip current profile intent filters.
3392    private ResolveInfo queryCrossProfileIntents(
3393            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3394            int flags, int sourceUserId) {
3395        if (matchingFilters != null) {
3396            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3397            // match the same intent. For performance reasons, it is better not to
3398            // run queryIntent twice for the same userId
3399            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3400            int size = matchingFilters.size();
3401            for (int i = 0; i < size; i++) {
3402                CrossProfileIntentFilter filter = matchingFilters.get(i);
3403                int targetUserId = filter.getTargetUserId();
3404                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3405                        && !alreadyTriedUserIds.get(targetUserId)) {
3406                    // Checking if there are activities in the target user that can handle the
3407                    // intent.
3408                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3409                            flags, sourceUserId);
3410                    if (resolveInfo != null) return resolveInfo;
3411                    alreadyTriedUserIds.put(targetUserId, true);
3412                }
3413            }
3414        }
3415        return null;
3416    }
3417
3418    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3419            String resolvedType, int flags, int sourceUserId) {
3420        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3421                resolvedType, flags, filter.getTargetUserId());
3422        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3423            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3424        }
3425        return null;
3426    }
3427
3428    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3429            int sourceUserId, int targetUserId) {
3430        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3431        String className;
3432        if (targetUserId == UserHandle.USER_OWNER) {
3433            className = FORWARD_INTENT_TO_USER_OWNER;
3434        } else {
3435            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3436        }
3437        ComponentName forwardingActivityComponentName = new ComponentName(
3438                mAndroidApplication.packageName, className);
3439        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3440                sourceUserId);
3441        if (targetUserId == UserHandle.USER_OWNER) {
3442            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3443            forwardingResolveInfo.noResourceId = true;
3444        }
3445        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3446        forwardingResolveInfo.priority = 0;
3447        forwardingResolveInfo.preferredOrder = 0;
3448        forwardingResolveInfo.match = 0;
3449        forwardingResolveInfo.isDefault = true;
3450        forwardingResolveInfo.filter = filter;
3451        forwardingResolveInfo.targetUserId = targetUserId;
3452        return forwardingResolveInfo;
3453    }
3454
3455    @Override
3456    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3457            Intent[] specifics, String[] specificTypes, Intent intent,
3458            String resolvedType, int flags, int userId) {
3459        if (!sUserManager.exists(userId)) return Collections.emptyList();
3460        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3461                "query intent activity options");
3462        final String resultsAction = intent.getAction();
3463
3464        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3465                | PackageManager.GET_RESOLVED_FILTER, userId);
3466
3467        if (DEBUG_INTENT_MATCHING) {
3468            Log.v(TAG, "Query " + intent + ": " + results);
3469        }
3470
3471        int specificsPos = 0;
3472        int N;
3473
3474        // todo: note that the algorithm used here is O(N^2).  This
3475        // isn't a problem in our current environment, but if we start running
3476        // into situations where we have more than 5 or 10 matches then this
3477        // should probably be changed to something smarter...
3478
3479        // First we go through and resolve each of the specific items
3480        // that were supplied, taking care of removing any corresponding
3481        // duplicate items in the generic resolve list.
3482        if (specifics != null) {
3483            for (int i=0; i<specifics.length; i++) {
3484                final Intent sintent = specifics[i];
3485                if (sintent == null) {
3486                    continue;
3487                }
3488
3489                if (DEBUG_INTENT_MATCHING) {
3490                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3491                }
3492
3493                String action = sintent.getAction();
3494                if (resultsAction != null && resultsAction.equals(action)) {
3495                    // If this action was explicitly requested, then don't
3496                    // remove things that have it.
3497                    action = null;
3498                }
3499
3500                ResolveInfo ri = null;
3501                ActivityInfo ai = null;
3502
3503                ComponentName comp = sintent.getComponent();
3504                if (comp == null) {
3505                    ri = resolveIntent(
3506                        sintent,
3507                        specificTypes != null ? specificTypes[i] : null,
3508                            flags, userId);
3509                    if (ri == null) {
3510                        continue;
3511                    }
3512                    if (ri == mResolveInfo) {
3513                        // ACK!  Must do something better with this.
3514                    }
3515                    ai = ri.activityInfo;
3516                    comp = new ComponentName(ai.applicationInfo.packageName,
3517                            ai.name);
3518                } else {
3519                    ai = getActivityInfo(comp, flags, userId);
3520                    if (ai == null) {
3521                        continue;
3522                    }
3523                }
3524
3525                // Look for any generic query activities that are duplicates
3526                // of this specific one, and remove them from the results.
3527                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3528                N = results.size();
3529                int j;
3530                for (j=specificsPos; j<N; j++) {
3531                    ResolveInfo sri = results.get(j);
3532                    if ((sri.activityInfo.name.equals(comp.getClassName())
3533                            && sri.activityInfo.applicationInfo.packageName.equals(
3534                                    comp.getPackageName()))
3535                        || (action != null && sri.filter.matchAction(action))) {
3536                        results.remove(j);
3537                        if (DEBUG_INTENT_MATCHING) Log.v(
3538                            TAG, "Removing duplicate item from " + j
3539                            + " due to specific " + specificsPos);
3540                        if (ri == null) {
3541                            ri = sri;
3542                        }
3543                        j--;
3544                        N--;
3545                    }
3546                }
3547
3548                // Add this specific item to its proper place.
3549                if (ri == null) {
3550                    ri = new ResolveInfo();
3551                    ri.activityInfo = ai;
3552                }
3553                results.add(specificsPos, ri);
3554                ri.specificIndex = i;
3555                specificsPos++;
3556            }
3557        }
3558
3559        // Now we go through the remaining generic results and remove any
3560        // duplicate actions that are found here.
3561        N = results.size();
3562        for (int i=specificsPos; i<N-1; i++) {
3563            final ResolveInfo rii = results.get(i);
3564            if (rii.filter == null) {
3565                continue;
3566            }
3567
3568            // Iterate over all of the actions of this result's intent
3569            // filter...  typically this should be just one.
3570            final Iterator<String> it = rii.filter.actionsIterator();
3571            if (it == null) {
3572                continue;
3573            }
3574            while (it.hasNext()) {
3575                final String action = it.next();
3576                if (resultsAction != null && resultsAction.equals(action)) {
3577                    // If this action was explicitly requested, then don't
3578                    // remove things that have it.
3579                    continue;
3580                }
3581                for (int j=i+1; j<N; j++) {
3582                    final ResolveInfo rij = results.get(j);
3583                    if (rij.filter != null && rij.filter.hasAction(action)) {
3584                        results.remove(j);
3585                        if (DEBUG_INTENT_MATCHING) Log.v(
3586                            TAG, "Removing duplicate item from " + j
3587                            + " due to action " + action + " at " + i);
3588                        j--;
3589                        N--;
3590                    }
3591                }
3592            }
3593
3594            // If the caller didn't request filter information, drop it now
3595            // so we don't have to marshall/unmarshall it.
3596            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3597                rii.filter = null;
3598            }
3599        }
3600
3601        // Filter out the caller activity if so requested.
3602        if (caller != null) {
3603            N = results.size();
3604            for (int i=0; i<N; i++) {
3605                ActivityInfo ainfo = results.get(i).activityInfo;
3606                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3607                        && caller.getClassName().equals(ainfo.name)) {
3608                    results.remove(i);
3609                    break;
3610                }
3611            }
3612        }
3613
3614        // If the caller didn't request filter information,
3615        // drop them now so we don't have to
3616        // marshall/unmarshall it.
3617        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3618            N = results.size();
3619            for (int i=0; i<N; i++) {
3620                results.get(i).filter = null;
3621            }
3622        }
3623
3624        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3625        return results;
3626    }
3627
3628    @Override
3629    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3630            int userId) {
3631        if (!sUserManager.exists(userId)) return Collections.emptyList();
3632        ComponentName comp = intent.getComponent();
3633        if (comp == null) {
3634            if (intent.getSelector() != null) {
3635                intent = intent.getSelector();
3636                comp = intent.getComponent();
3637            }
3638        }
3639        if (comp != null) {
3640            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3641            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3642            if (ai != null) {
3643                ResolveInfo ri = new ResolveInfo();
3644                ri.activityInfo = ai;
3645                list.add(ri);
3646            }
3647            return list;
3648        }
3649
3650        // reader
3651        synchronized (mPackages) {
3652            String pkgName = intent.getPackage();
3653            if (pkgName == null) {
3654                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3655            }
3656            final PackageParser.Package pkg = mPackages.get(pkgName);
3657            if (pkg != null) {
3658                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3659                        userId);
3660            }
3661            return null;
3662        }
3663    }
3664
3665    @Override
3666    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3667        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3668        if (!sUserManager.exists(userId)) return null;
3669        if (query != null) {
3670            if (query.size() >= 1) {
3671                // If there is more than one service with the same priority,
3672                // just arbitrarily pick the first one.
3673                return query.get(0);
3674            }
3675        }
3676        return null;
3677    }
3678
3679    @Override
3680    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3681            int userId) {
3682        if (!sUserManager.exists(userId)) return Collections.emptyList();
3683        ComponentName comp = intent.getComponent();
3684        if (comp == null) {
3685            if (intent.getSelector() != null) {
3686                intent = intent.getSelector();
3687                comp = intent.getComponent();
3688            }
3689        }
3690        if (comp != null) {
3691            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3692            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3693            if (si != null) {
3694                final ResolveInfo ri = new ResolveInfo();
3695                ri.serviceInfo = si;
3696                list.add(ri);
3697            }
3698            return list;
3699        }
3700
3701        // reader
3702        synchronized (mPackages) {
3703            String pkgName = intent.getPackage();
3704            if (pkgName == null) {
3705                return mServices.queryIntent(intent, resolvedType, flags, userId);
3706            }
3707            final PackageParser.Package pkg = mPackages.get(pkgName);
3708            if (pkg != null) {
3709                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3710                        userId);
3711            }
3712            return null;
3713        }
3714    }
3715
3716    @Override
3717    public List<ResolveInfo> queryIntentContentProviders(
3718            Intent intent, String resolvedType, int flags, int userId) {
3719        if (!sUserManager.exists(userId)) return Collections.emptyList();
3720        ComponentName comp = intent.getComponent();
3721        if (comp == null) {
3722            if (intent.getSelector() != null) {
3723                intent = intent.getSelector();
3724                comp = intent.getComponent();
3725            }
3726        }
3727        if (comp != null) {
3728            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3729            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3730            if (pi != null) {
3731                final ResolveInfo ri = new ResolveInfo();
3732                ri.providerInfo = pi;
3733                list.add(ri);
3734            }
3735            return list;
3736        }
3737
3738        // reader
3739        synchronized (mPackages) {
3740            String pkgName = intent.getPackage();
3741            if (pkgName == null) {
3742                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3743            }
3744            final PackageParser.Package pkg = mPackages.get(pkgName);
3745            if (pkg != null) {
3746                return mProviders.queryIntentForPackage(
3747                        intent, resolvedType, flags, pkg.providers, userId);
3748            }
3749            return null;
3750        }
3751    }
3752
3753    @Override
3754    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3755        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3756
3757        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3758
3759        // writer
3760        synchronized (mPackages) {
3761            ArrayList<PackageInfo> list;
3762            if (listUninstalled) {
3763                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3764                for (PackageSetting ps : mSettings.mPackages.values()) {
3765                    PackageInfo pi;
3766                    if (ps.pkg != null) {
3767                        pi = generatePackageInfo(ps.pkg, flags, userId);
3768                    } else {
3769                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3770                    }
3771                    if (pi != null) {
3772                        list.add(pi);
3773                    }
3774                }
3775            } else {
3776                list = new ArrayList<PackageInfo>(mPackages.size());
3777                for (PackageParser.Package p : mPackages.values()) {
3778                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3779                    if (pi != null) {
3780                        list.add(pi);
3781                    }
3782                }
3783            }
3784
3785            return new ParceledListSlice<PackageInfo>(list);
3786        }
3787    }
3788
3789    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3790            String[] permissions, boolean[] tmp, int flags, int userId) {
3791        int numMatch = 0;
3792        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3793        for (int i=0; i<permissions.length; i++) {
3794            if (gp.grantedPermissions.contains(permissions[i])) {
3795                tmp[i] = true;
3796                numMatch++;
3797            } else {
3798                tmp[i] = false;
3799            }
3800        }
3801        if (numMatch == 0) {
3802            return;
3803        }
3804        PackageInfo pi;
3805        if (ps.pkg != null) {
3806            pi = generatePackageInfo(ps.pkg, flags, userId);
3807        } else {
3808            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3809        }
3810        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3811            if (numMatch == permissions.length) {
3812                pi.requestedPermissions = permissions;
3813            } else {
3814                pi.requestedPermissions = new String[numMatch];
3815                numMatch = 0;
3816                for (int i=0; i<permissions.length; i++) {
3817                    if (tmp[i]) {
3818                        pi.requestedPermissions[numMatch] = permissions[i];
3819                        numMatch++;
3820                    }
3821                }
3822            }
3823        }
3824        list.add(pi);
3825    }
3826
3827    @Override
3828    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3829            String[] permissions, int flags, int userId) {
3830        if (!sUserManager.exists(userId)) return null;
3831        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3832
3833        // writer
3834        synchronized (mPackages) {
3835            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3836            boolean[] tmpBools = new boolean[permissions.length];
3837            if (listUninstalled) {
3838                for (PackageSetting ps : mSettings.mPackages.values()) {
3839                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3840                }
3841            } else {
3842                for (PackageParser.Package pkg : mPackages.values()) {
3843                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3844                    if (ps != null) {
3845                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3846                                userId);
3847                    }
3848                }
3849            }
3850
3851            return new ParceledListSlice<PackageInfo>(list);
3852        }
3853    }
3854
3855    @Override
3856    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3857        if (!sUserManager.exists(userId)) return null;
3858        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3859
3860        // writer
3861        synchronized (mPackages) {
3862            ArrayList<ApplicationInfo> list;
3863            if (listUninstalled) {
3864                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3865                for (PackageSetting ps : mSettings.mPackages.values()) {
3866                    ApplicationInfo ai;
3867                    if (ps.pkg != null) {
3868                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3869                                ps.readUserState(userId), userId);
3870                    } else {
3871                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3872                    }
3873                    if (ai != null) {
3874                        list.add(ai);
3875                    }
3876                }
3877            } else {
3878                list = new ArrayList<ApplicationInfo>(mPackages.size());
3879                for (PackageParser.Package p : mPackages.values()) {
3880                    if (p.mExtras != null) {
3881                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3882                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3883                        if (ai != null) {
3884                            list.add(ai);
3885                        }
3886                    }
3887                }
3888            }
3889
3890            return new ParceledListSlice<ApplicationInfo>(list);
3891        }
3892    }
3893
3894    public List<ApplicationInfo> getPersistentApplications(int flags) {
3895        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3896
3897        // reader
3898        synchronized (mPackages) {
3899            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3900            final int userId = UserHandle.getCallingUserId();
3901            while (i.hasNext()) {
3902                final PackageParser.Package p = i.next();
3903                if (p.applicationInfo != null
3904                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3905                        && (!mSafeMode || isSystemApp(p))) {
3906                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3907                    if (ps != null) {
3908                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3909                                ps.readUserState(userId), userId);
3910                        if (ai != null) {
3911                            finalList.add(ai);
3912                        }
3913                    }
3914                }
3915            }
3916        }
3917
3918        return finalList;
3919    }
3920
3921    @Override
3922    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3923        if (!sUserManager.exists(userId)) return null;
3924        // reader
3925        synchronized (mPackages) {
3926            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3927            PackageSetting ps = provider != null
3928                    ? mSettings.mPackages.get(provider.owner.packageName)
3929                    : null;
3930            return ps != null
3931                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3932                    && (!mSafeMode || (provider.info.applicationInfo.flags
3933                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3934                    ? PackageParser.generateProviderInfo(provider, flags,
3935                            ps.readUserState(userId), userId)
3936                    : null;
3937        }
3938    }
3939
3940    /**
3941     * @deprecated
3942     */
3943    @Deprecated
3944    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3945        // reader
3946        synchronized (mPackages) {
3947            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3948                    .entrySet().iterator();
3949            final int userId = UserHandle.getCallingUserId();
3950            while (i.hasNext()) {
3951                Map.Entry<String, PackageParser.Provider> entry = i.next();
3952                PackageParser.Provider p = entry.getValue();
3953                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3954
3955                if (ps != null && p.syncable
3956                        && (!mSafeMode || (p.info.applicationInfo.flags
3957                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3958                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3959                            ps.readUserState(userId), userId);
3960                    if (info != null) {
3961                        outNames.add(entry.getKey());
3962                        outInfo.add(info);
3963                    }
3964                }
3965            }
3966        }
3967    }
3968
3969    @Override
3970    public List<ProviderInfo> queryContentProviders(String processName,
3971            int uid, int flags) {
3972        ArrayList<ProviderInfo> finalList = null;
3973        // reader
3974        synchronized (mPackages) {
3975            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3976            final int userId = processName != null ?
3977                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3978            while (i.hasNext()) {
3979                final PackageParser.Provider p = i.next();
3980                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3981                if (ps != null && p.info.authority != null
3982                        && (processName == null
3983                                || (p.info.processName.equals(processName)
3984                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3985                        && mSettings.isEnabledLPr(p.info, flags, userId)
3986                        && (!mSafeMode
3987                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3988                    if (finalList == null) {
3989                        finalList = new ArrayList<ProviderInfo>(3);
3990                    }
3991                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3992                            ps.readUserState(userId), userId);
3993                    if (info != null) {
3994                        finalList.add(info);
3995                    }
3996                }
3997            }
3998        }
3999
4000        if (finalList != null) {
4001            Collections.sort(finalList, mProviderInitOrderSorter);
4002        }
4003
4004        return finalList;
4005    }
4006
4007    @Override
4008    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4009            int flags) {
4010        // reader
4011        synchronized (mPackages) {
4012            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4013            return PackageParser.generateInstrumentationInfo(i, flags);
4014        }
4015    }
4016
4017    @Override
4018    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4019            int flags) {
4020        ArrayList<InstrumentationInfo> finalList =
4021            new ArrayList<InstrumentationInfo>();
4022
4023        // reader
4024        synchronized (mPackages) {
4025            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4026            while (i.hasNext()) {
4027                final PackageParser.Instrumentation p = i.next();
4028                if (targetPackage == null
4029                        || targetPackage.equals(p.info.targetPackage)) {
4030                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4031                            flags);
4032                    if (ii != null) {
4033                        finalList.add(ii);
4034                    }
4035                }
4036            }
4037        }
4038
4039        return finalList;
4040    }
4041
4042    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4043        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4044        if (overlays == null) {
4045            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4046            return;
4047        }
4048        for (PackageParser.Package opkg : overlays.values()) {
4049            // Not much to do if idmap fails: we already logged the error
4050            // and we certainly don't want to abort installation of pkg simply
4051            // because an overlay didn't fit properly. For these reasons,
4052            // ignore the return value of createIdmapForPackagePairLI.
4053            createIdmapForPackagePairLI(pkg, opkg);
4054        }
4055    }
4056
4057    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4058            PackageParser.Package opkg) {
4059        if (!opkg.mTrustedOverlay) {
4060            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4061                    opkg.baseCodePath + ": overlay not trusted");
4062            return false;
4063        }
4064        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4065        if (overlaySet == null) {
4066            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4067                    opkg.baseCodePath + " but target package has no known overlays");
4068            return false;
4069        }
4070        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4071        // TODO: generate idmap for split APKs
4072        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4073            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4074                    + opkg.baseCodePath);
4075            return false;
4076        }
4077        PackageParser.Package[] overlayArray =
4078            overlaySet.values().toArray(new PackageParser.Package[0]);
4079        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4080            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4081                return p1.mOverlayPriority - p2.mOverlayPriority;
4082            }
4083        };
4084        Arrays.sort(overlayArray, cmp);
4085
4086        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4087        int i = 0;
4088        for (PackageParser.Package p : overlayArray) {
4089            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4090        }
4091        return true;
4092    }
4093
4094    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4095        final File[] files = dir.listFiles();
4096        if (ArrayUtils.isEmpty(files)) {
4097            Log.d(TAG, "No files in app dir " + dir);
4098            return;
4099        }
4100
4101        if (DEBUG_PACKAGE_SCANNING) {
4102            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4103                    + " flags=0x" + Integer.toHexString(flags));
4104        }
4105
4106        for (File file : files) {
4107            final boolean isPackage = isApkFile(file) || file.isDirectory();
4108            if (!isPackage) {
4109                // Ignore entries which are not apk's
4110                continue;
4111            }
4112            try {
4113                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime,
4114                        null, null);
4115            } catch (PackageManagerException e) {
4116                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4117
4118                // Don't mess around with apps in system partition.
4119                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4120                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4121                    // Delete the apk
4122                    Slog.w(TAG, "Cleaning up failed install of " + file);
4123                    file.delete();
4124                }
4125            }
4126        }
4127    }
4128
4129    private static File getSettingsProblemFile() {
4130        File dataDir = Environment.getDataDirectory();
4131        File systemDir = new File(dataDir, "system");
4132        File fname = new File(systemDir, "uiderrors.txt");
4133        return fname;
4134    }
4135
4136    static void reportSettingsProblem(int priority, String msg) {
4137        try {
4138            File fname = getSettingsProblemFile();
4139            FileOutputStream out = new FileOutputStream(fname, true);
4140            PrintWriter pw = new FastPrintWriter(out);
4141            SimpleDateFormat formatter = new SimpleDateFormat();
4142            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4143            pw.println(dateString + ": " + msg);
4144            pw.close();
4145            FileUtils.setPermissions(
4146                    fname.toString(),
4147                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4148                    -1, -1);
4149        } catch (java.io.IOException e) {
4150        }
4151        Slog.println(priority, TAG, msg);
4152    }
4153
4154    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4155            PackageParser.Package pkg, File srcFile, int parseFlags)
4156            throws PackageManagerException {
4157        if (ps != null
4158                && ps.codePath.equals(srcFile)
4159                && ps.timeStamp == srcFile.lastModified()
4160                && !isCompatSignatureUpdateNeeded(pkg)) {
4161            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4162            if (ps.signatures.mSignatures != null
4163                    && ps.signatures.mSignatures.length != 0
4164                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4165                // Optimization: reuse the existing cached certificates
4166                // if the package appears to be unchanged.
4167                pkg.mSignatures = ps.signatures.mSignatures;
4168                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4169                synchronized (mPackages) {
4170                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4171                }
4172                return;
4173            }
4174
4175            Slog.w(TAG, "PackageSetting for " + ps.name
4176                    + " is missing signatures.  Collecting certs again to recover them.");
4177        } else {
4178            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4179        }
4180
4181        try {
4182            pp.collectCertificates(pkg, parseFlags);
4183            pp.collectManifestDigest(pkg);
4184        } catch (PackageParserException e) {
4185            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4186                    + pkg.packageName + ": " + e.getMessage());
4187        }
4188    }
4189
4190    /*
4191     *  Scan a package and return the newly parsed package.
4192     *  Returns null in case of errors and the error code is stored in mLastScanError
4193     */
4194    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4195            long currentTime, UserHandle user, String abiOverride) throws PackageManagerException {
4196        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4197        parseFlags |= mDefParseFlags;
4198        PackageParser pp = new PackageParser();
4199        pp.setSeparateProcesses(mSeparateProcesses);
4200        pp.setOnlyCoreApps(mOnlyCore);
4201        pp.setDisplayMetrics(mMetrics);
4202
4203        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4204            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4205        }
4206
4207        final PackageParser.Package pkg;
4208        try {
4209            pkg = pp.parsePackage(scanFile, parseFlags);
4210        } catch (PackageParserException e) {
4211            throw new PackageManagerException(e.error,
4212                    "Failed to scan " + scanFile + ": " + e.getMessage());
4213        }
4214
4215        PackageSetting ps = null;
4216        PackageSetting updatedPkg;
4217        // reader
4218        synchronized (mPackages) {
4219            // Look to see if we already know about this package.
4220            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4221            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4222                // This package has been renamed to its original name.  Let's
4223                // use that.
4224                ps = mSettings.peekPackageLPr(oldName);
4225            }
4226            // If there was no original package, see one for the real package name.
4227            if (ps == null) {
4228                ps = mSettings.peekPackageLPr(pkg.packageName);
4229            }
4230            // Check to see if this package could be hiding/updating a system
4231            // package.  Must look for it either under the original or real
4232            // package name depending on our state.
4233            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4234            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4235        }
4236        boolean updatedPkgBetter = false;
4237        // First check if this is a system package that may involve an update
4238        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4239            if (ps != null && !ps.codePath.equals(scanFile)) {
4240                // The path has changed from what was last scanned...  check the
4241                // version of the new path against what we have stored to determine
4242                // what to do.
4243                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4244                if (pkg.mVersionCode < ps.versionCode) {
4245                    // The system package has been updated and the code path does not match
4246                    // Ignore entry. Skip it.
4247                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4248                            + " ignored: updated version " + ps.versionCode
4249                            + " better than this " + pkg.mVersionCode);
4250                    if (!updatedPkg.codePath.equals(scanFile)) {
4251                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4252                                + ps.name + " changing from " + updatedPkg.codePathString
4253                                + " to " + scanFile);
4254                        updatedPkg.codePath = scanFile;
4255                        updatedPkg.codePathString = scanFile.toString();
4256                        // This is the point at which we know that the system-disk APK
4257                        // for this package has moved during a reboot (e.g. due to an OTA),
4258                        // so we need to reevaluate it for privilege policy.
4259                        if (locationIsPrivileged(scanFile)) {
4260                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4261                        }
4262                    }
4263                    updatedPkg.pkg = pkg;
4264                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4265                } else {
4266                    // The current app on the system partition is better than
4267                    // what we have updated to on the data partition; switch
4268                    // back to the system partition version.
4269                    // At this point, its safely assumed that package installation for
4270                    // apps in system partition will go through. If not there won't be a working
4271                    // version of the app
4272                    // writer
4273                    synchronized (mPackages) {
4274                        // Just remove the loaded entries from package lists.
4275                        mPackages.remove(ps.name);
4276                    }
4277                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4278                            + "reverting from " + ps.codePathString
4279                            + ": new version " + pkg.mVersionCode
4280                            + " better than installed " + ps.versionCode);
4281
4282                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4283                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4284                            getAppDexInstructionSets(ps), isMultiArch(ps));
4285                    synchronized (mInstallLock) {
4286                        args.cleanUpResourcesLI();
4287                    }
4288                    synchronized (mPackages) {
4289                        mSettings.enableSystemPackageLPw(ps.name);
4290                    }
4291                    updatedPkgBetter = true;
4292                }
4293            }
4294        }
4295
4296        if (updatedPkg != null) {
4297            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4298            // initially
4299            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4300
4301            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4302            // flag set initially
4303            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4304                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4305            }
4306        }
4307
4308        // Verify certificates against what was last scanned
4309        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4310
4311        /*
4312         * A new system app appeared, but we already had a non-system one of the
4313         * same name installed earlier.
4314         */
4315        boolean shouldHideSystemApp = false;
4316        if (updatedPkg == null && ps != null
4317                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4318            /*
4319             * Check to make sure the signatures match first. If they don't,
4320             * wipe the installed application and its data.
4321             */
4322            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4323                    != PackageManager.SIGNATURE_MATCH) {
4324                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4325                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4326                ps = null;
4327            } else {
4328                /*
4329                 * If the newly-added system app is an older version than the
4330                 * already installed version, hide it. It will be scanned later
4331                 * and re-added like an update.
4332                 */
4333                if (pkg.mVersionCode < ps.versionCode) {
4334                    shouldHideSystemApp = true;
4335                } else {
4336                    /*
4337                     * The newly found system app is a newer version that the
4338                     * one previously installed. Simply remove the
4339                     * already-installed application and replace it with our own
4340                     * while keeping the application data.
4341                     */
4342                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4343                            + ps.codePathString + ": new version " + pkg.mVersionCode
4344                            + " better than installed " + ps.versionCode);
4345                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4346                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4347                            getAppDexInstructionSets(ps), isMultiArch(ps));
4348                    synchronized (mInstallLock) {
4349                        args.cleanUpResourcesLI();
4350                    }
4351                }
4352            }
4353        }
4354
4355        // The apk is forward locked (not public) if its code and resources
4356        // are kept in different files. (except for app in either system or
4357        // vendor path).
4358        // TODO grab this value from PackageSettings
4359        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4360            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4361                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4362            }
4363        }
4364
4365        // TODO: extend to support forward-locked splits
4366        String resourcePath = null;
4367        String baseResourcePath = null;
4368        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4369            if (ps != null && ps.resourcePathString != null) {
4370                resourcePath = ps.resourcePathString;
4371                baseResourcePath = ps.resourcePathString;
4372            } else {
4373                // Should not happen at all. Just log an error.
4374                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4375            }
4376        } else {
4377            resourcePath = pkg.codePath;
4378            baseResourcePath = pkg.baseCodePath;
4379        }
4380
4381        // Set application objects path explicitly.
4382        pkg.applicationInfo.setCodePath(pkg.codePath);
4383        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4384        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4385        pkg.applicationInfo.setResourcePath(resourcePath);
4386        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4387        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4388
4389        // Note that we invoke the following method only if we are about to unpack an application
4390        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4391                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4392
4393        /*
4394         * If the system app should be overridden by a previously installed
4395         * data, hide the system app now and let the /data/app scan pick it up
4396         * again.
4397         */
4398        if (shouldHideSystemApp) {
4399            synchronized (mPackages) {
4400                /*
4401                 * We have to grant systems permissions before we hide, because
4402                 * grantPermissions will assume the package update is trying to
4403                 * expand its permissions.
4404                 */
4405                grantPermissionsLPw(pkg, true);
4406                mSettings.disableSystemPackageLPw(pkg.packageName);
4407            }
4408        }
4409
4410        return scannedPkg;
4411    }
4412
4413    private static String fixProcessName(String defProcessName,
4414            String processName, int uid) {
4415        if (processName == null) {
4416            return defProcessName;
4417        }
4418        return processName;
4419    }
4420
4421    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4422            throws PackageManagerException {
4423        if (pkgSetting.signatures.mSignatures != null) {
4424            // Already existing package. Make sure signatures match
4425            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4426                    == PackageManager.SIGNATURE_MATCH;
4427            if (!match) {
4428                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4429                        == PackageManager.SIGNATURE_MATCH;
4430            }
4431            if (!match) {
4432                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4433                        + pkg.packageName + " signatures do not match the "
4434                        + "previously installed version; ignoring!");
4435            }
4436        }
4437
4438        // Check for shared user signatures
4439        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4440            // Already existing package. Make sure signatures match
4441            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4442                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4443            if (!match) {
4444                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4445                        == PackageManager.SIGNATURE_MATCH;
4446            }
4447            if (!match) {
4448                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4449                        "Package " + pkg.packageName
4450                        + " has no signatures that match those in shared user "
4451                        + pkgSetting.sharedUser.name + "; ignoring!");
4452            }
4453        }
4454    }
4455
4456    /**
4457     * Enforces that only the system UID or root's UID can call a method exposed
4458     * via Binder.
4459     *
4460     * @param message used as message if SecurityException is thrown
4461     * @throws SecurityException if the caller is not system or root
4462     */
4463    private static final void enforceSystemOrRoot(String message) {
4464        final int uid = Binder.getCallingUid();
4465        if (uid != Process.SYSTEM_UID && uid != 0) {
4466            throw new SecurityException(message);
4467        }
4468    }
4469
4470    @Override
4471    public void performBootDexOpt() {
4472        enforceSystemOrRoot("Only the system can request dexopt be performed");
4473
4474        final HashSet<PackageParser.Package> pkgs;
4475        synchronized (mPackages) {
4476            pkgs = mDeferredDexOpt;
4477            mDeferredDexOpt = null;
4478        }
4479
4480        if (pkgs != null) {
4481            // Filter out packages that aren't recently used.
4482            //
4483            // The exception is first boot of a non-eng device, which
4484            // should do a full dexopt.
4485            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4486            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4487                // TODO: add a property to control this?
4488                long dexOptLRUThresholdInMinutes;
4489                if (eng) {
4490                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4491                } else {
4492                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4493                }
4494                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4495
4496                int total = pkgs.size();
4497                int skipped = 0;
4498                long now = System.currentTimeMillis();
4499                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4500                    PackageParser.Package pkg = i.next();
4501                    long then = pkg.mLastPackageUsageTimeInMills;
4502                    if (then + dexOptLRUThresholdInMills < now) {
4503                        if (DEBUG_DEXOPT) {
4504                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4505                                  ((then == 0) ? "never" : new Date(then)));
4506                        }
4507                        i.remove();
4508                        skipped++;
4509                    }
4510                }
4511                if (DEBUG_DEXOPT) {
4512                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4513                }
4514            }
4515
4516            int i = 0;
4517            for (PackageParser.Package pkg : pkgs) {
4518                i++;
4519                if (DEBUG_DEXOPT) {
4520                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4521                          + ": " + pkg.packageName);
4522                }
4523                if (!isFirstBoot()) {
4524                    try {
4525                        ActivityManagerNative.getDefault().showBootMessage(
4526                                mContext.getResources().getString(
4527                                        R.string.android_upgrading_apk,
4528                                        i, pkgs.size()), true);
4529                    } catch (RemoteException e) {
4530                    }
4531                }
4532                PackageParser.Package p = pkg;
4533                synchronized (mInstallLock) {
4534                    if (p.mDexOptNeeded) {
4535                        performDexOptLI(p, false /* force dex */, false /* defer */,
4536                                true /* include dependencies */);
4537                    }
4538                }
4539            }
4540        }
4541    }
4542
4543    @Override
4544    public boolean performDexOpt(String packageName) {
4545        enforceSystemOrRoot("Only the system can request dexopt be performed");
4546        return performDexOpt(packageName, true);
4547    }
4548
4549    public boolean performDexOpt(String packageName, boolean updateUsage) {
4550
4551        PackageParser.Package p;
4552        synchronized (mPackages) {
4553            p = mPackages.get(packageName);
4554            if (p == null) {
4555                return false;
4556            }
4557            if (updateUsage) {
4558                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4559            }
4560            mPackageUsage.write(false);
4561            if (!p.mDexOptNeeded) {
4562                return false;
4563            }
4564        }
4565
4566        synchronized (mInstallLock) {
4567            return performDexOptLI(p, false /* force dex */, false /* defer */,
4568                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4569        }
4570    }
4571
4572    public HashSet<String> getPackagesThatNeedDexOpt() {
4573        HashSet<String> pkgs = null;
4574        synchronized (mPackages) {
4575            for (PackageParser.Package p : mPackages.values()) {
4576                if (DEBUG_DEXOPT) {
4577                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4578                }
4579                if (!p.mDexOptNeeded) {
4580                    continue;
4581                }
4582                if (pkgs == null) {
4583                    pkgs = new HashSet<String>();
4584                }
4585                pkgs.add(p.packageName);
4586            }
4587        }
4588        return pkgs;
4589    }
4590
4591    public void shutdown() {
4592        mPackageUsage.write(true);
4593    }
4594
4595    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4596             boolean forceDex, boolean defer, HashSet<String> done) {
4597        for (int i=0; i<libs.size(); i++) {
4598            PackageParser.Package libPkg;
4599            String libName;
4600            synchronized (mPackages) {
4601                libName = libs.get(i);
4602                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4603                if (lib != null && lib.apk != null) {
4604                    libPkg = mPackages.get(lib.apk);
4605                } else {
4606                    libPkg = null;
4607                }
4608            }
4609            if (libPkg != null && !done.contains(libName)) {
4610                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4611            }
4612        }
4613    }
4614
4615    static final int DEX_OPT_SKIPPED = 0;
4616    static final int DEX_OPT_PERFORMED = 1;
4617    static final int DEX_OPT_DEFERRED = 2;
4618    static final int DEX_OPT_FAILED = -1;
4619
4620    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4621            boolean forceDex, boolean defer, HashSet<String> done) {
4622        final String[] instructionSets = targetInstructionSets != null ?
4623                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4624
4625        if (done != null) {
4626            done.add(pkg.packageName);
4627            if (pkg.usesLibraries != null) {
4628                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4629            }
4630            if (pkg.usesOptionalLibraries != null) {
4631                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4632            }
4633        }
4634
4635        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4636            return DEX_OPT_SKIPPED;
4637        }
4638
4639        final Collection<String> paths = pkg.getAllCodePaths();
4640        boolean performedDexOpt = false;
4641        // There are three basic cases here:
4642        // 1.) we need to dexopt, either because we are forced or it is needed
4643        // 2.) we are defering a needed dexopt
4644        // 3.) we are skipping an unneeded dexopt
4645        for (String path : paths) {
4646            for (String instructionSet : instructionSets) {
4647                try {
4648                    final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4649                            pkg.packageName, instructionSet, defer);
4650                    if (forceDex || (!defer && isDexOptNeeded)) {
4651                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName + " isa=" + instructionSet);
4652                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4653                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4654                                pkg.packageName, instructionSet);
4655
4656                        if (ret < 0) {
4657                            // Don't bother running dexopt again if we failed, it will probably
4658                            // just result in an error again. Also, don't bother dexopting for other
4659                            // paths & ISAs.
4660                            pkg.mDexOptNeeded = false;
4661                            return DEX_OPT_FAILED;
4662                        } else {
4663                            performedDexOpt = true;
4664                        }
4665                    }
4666
4667                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4668                    // paths and instruction sets. We'll deal with them all together when we process
4669                    // our list of deferred dexopts.
4670                    if (defer && isDexOptNeeded) {
4671                        if (mDeferredDexOpt == null) {
4672                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4673                        }
4674                        mDeferredDexOpt.add(pkg);
4675                        return DEX_OPT_DEFERRED;
4676                    }
4677                } catch (FileNotFoundException e) {
4678                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4679                    return DEX_OPT_FAILED;
4680                } catch (IOException e) {
4681                    Slog.w(TAG, "IOException reading apk: " + path, e);
4682                    return DEX_OPT_FAILED;
4683                } catch (StaleDexCacheError e) {
4684                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4685                    return DEX_OPT_FAILED;
4686                } catch (Exception e) {
4687                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4688                    return DEX_OPT_FAILED;
4689                }
4690            }
4691        }
4692
4693        // If we've gotten here, we're sure that no error occurred and that we haven't
4694        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4695        // we've skipped all of them because they are up to date. In both cases this
4696        // package doesn't need dexopt any longer.
4697        pkg.mDexOptNeeded = false;
4698        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4699    }
4700
4701    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4702        if (info.primaryCpuAbi != null) {
4703            if (info.secondaryCpuAbi != null) {
4704                return new String[] {
4705                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4706                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4707            } else {
4708                return new String[] {
4709                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4710            }
4711        }
4712
4713        return new String[] { getPreferredInstructionSet() };
4714    }
4715
4716    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4717        if (ps.primaryCpuAbiString != null) {
4718            if (ps.secondaryCpuAbiString != null) {
4719                return new String[] {
4720                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4721                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4722            } else {
4723                return new String[] {
4724                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4725            }
4726        }
4727
4728        return new String[] { getPreferredInstructionSet() };
4729    }
4730
4731    private static String getPreferredInstructionSet() {
4732        if (sPreferredInstructionSet == null) {
4733            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4734        }
4735
4736        return sPreferredInstructionSet;
4737    }
4738
4739    private static List<String> getAllInstructionSets() {
4740        final String[] allAbis = Build.SUPPORTED_ABIS;
4741        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4742
4743        for (String abi : allAbis) {
4744            final String instructionSet = VMRuntime.getInstructionSet(abi);
4745            if (!allInstructionSets.contains(instructionSet)) {
4746                allInstructionSets.add(instructionSet);
4747            }
4748        }
4749
4750        return allInstructionSets;
4751    }
4752
4753    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4754            boolean inclDependencies) {
4755        HashSet<String> done;
4756        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4757            done = new HashSet<String>();
4758            done.add(pkg.packageName);
4759        } else {
4760            done = null;
4761        }
4762        return performDexOptLI(pkg, null /* target instruction sets */,  forceDex, defer, done);
4763    }
4764
4765    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4766        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4767            Slog.w(TAG, "Unable to update from " + oldPkg.name
4768                    + " to " + newPkg.packageName
4769                    + ": old package not in system partition");
4770            return false;
4771        } else if (mPackages.get(oldPkg.name) != null) {
4772            Slog.w(TAG, "Unable to update from " + oldPkg.name
4773                    + " to " + newPkg.packageName
4774                    + ": old package still exists");
4775            return false;
4776        }
4777        return true;
4778    }
4779
4780    File getDataPathForUser(int userId) {
4781        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4782    }
4783
4784    private File getDataPathForPackage(String packageName, int userId) {
4785        /*
4786         * Until we fully support multiple users, return the directory we
4787         * previously would have. The PackageManagerTests will need to be
4788         * revised when this is changed back..
4789         */
4790        if (userId == 0) {
4791            return new File(mAppDataDir, packageName);
4792        } else {
4793            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4794                + File.separator + packageName);
4795        }
4796    }
4797
4798    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4799        int[] users = sUserManager.getUserIds();
4800        int res = mInstaller.install(packageName, uid, uid, seinfo);
4801        if (res < 0) {
4802            return res;
4803        }
4804        for (int user : users) {
4805            if (user != 0) {
4806                res = mInstaller.createUserData(packageName,
4807                        UserHandle.getUid(user, uid), user, seinfo);
4808                if (res < 0) {
4809                    return res;
4810                }
4811            }
4812        }
4813        return res;
4814    }
4815
4816    private int removeDataDirsLI(String packageName) {
4817        int[] users = sUserManager.getUserIds();
4818        int res = 0;
4819        for (int user : users) {
4820            int resInner = mInstaller.remove(packageName, user);
4821            if (resInner < 0) {
4822                res = resInner;
4823            }
4824        }
4825
4826        return res;
4827    }
4828
4829    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4830            PackageParser.Package changingLib) {
4831        if (file.path != null) {
4832            usesLibraryFiles.add(file.path);
4833            return;
4834        }
4835        PackageParser.Package p = mPackages.get(file.apk);
4836        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4837            // If we are doing this while in the middle of updating a library apk,
4838            // then we need to make sure to use that new apk for determining the
4839            // dependencies here.  (We haven't yet finished committing the new apk
4840            // to the package manager state.)
4841            if (p == null || p.packageName.equals(changingLib.packageName)) {
4842                p = changingLib;
4843            }
4844        }
4845        if (p != null) {
4846            usesLibraryFiles.addAll(p.getAllCodePaths());
4847        }
4848    }
4849
4850    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4851            PackageParser.Package changingLib) throws PackageManagerException {
4852        // We might be upgrading from a version of the platform that did not
4853        // provide per-package native library directories for system apps.
4854        // Fix that up here.
4855        if (isSystemApp(pkg)) {
4856            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4857            if (!isUpdatedSystemApp(pkg)) {
4858                setBundledAppAbisAndRoots(pkg, ps);
4859            }
4860        }
4861
4862        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4863            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4864            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4865            for (int i=0; i<N; i++) {
4866                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4867                if (file == null) {
4868                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4869                            "Package " + pkg.packageName + " requires unavailable shared library "
4870                            + pkg.usesLibraries.get(i) + "; failing!");
4871                }
4872                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4873            }
4874            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4875            for (int i=0; i<N; i++) {
4876                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4877                if (file == null) {
4878                    Slog.w(TAG, "Package " + pkg.packageName
4879                            + " desires unavailable shared library "
4880                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4881                } else {
4882                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4883                }
4884            }
4885            N = usesLibraryFiles.size();
4886            if (N > 0) {
4887                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4888            } else {
4889                pkg.usesLibraryFiles = null;
4890            }
4891        }
4892    }
4893
4894    private static boolean hasString(List<String> list, List<String> which) {
4895        if (list == null) {
4896            return false;
4897        }
4898        for (int i=list.size()-1; i>=0; i--) {
4899            for (int j=which.size()-1; j>=0; j--) {
4900                if (which.get(j).equals(list.get(i))) {
4901                    return true;
4902                }
4903            }
4904        }
4905        return false;
4906    }
4907
4908    private void updateAllSharedLibrariesLPw() {
4909        for (PackageParser.Package pkg : mPackages.values()) {
4910            try {
4911                updateSharedLibrariesLPw(pkg, null);
4912            } catch (PackageManagerException e) {
4913                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4914            }
4915        }
4916    }
4917
4918    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4919            PackageParser.Package changingPkg) {
4920        ArrayList<PackageParser.Package> res = null;
4921        for (PackageParser.Package pkg : mPackages.values()) {
4922            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4923                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4924                if (res == null) {
4925                    res = new ArrayList<PackageParser.Package>();
4926                }
4927                res.add(pkg);
4928                try {
4929                    updateSharedLibrariesLPw(pkg, changingPkg);
4930                } catch (PackageManagerException e) {
4931                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4932                }
4933            }
4934        }
4935        return res;
4936    }
4937
4938    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4939            int scanMode, long currentTime, UserHandle user, String abiOverride)
4940            throws PackageManagerException {
4941        final File scanFile = new File(pkg.codePath);
4942        if (pkg.applicationInfo.getCodePath() == null ||
4943                pkg.applicationInfo.getResourcePath() == null) {
4944            // Bail out. The resource and code paths haven't been set.
4945            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4946                    "Code and resource paths haven't been set correctly");
4947        }
4948
4949        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4950            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4951        }
4952
4953        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4954            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4955        }
4956
4957        if (mCustomResolverComponentName != null &&
4958                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4959            setUpCustomResolverActivity(pkg);
4960        }
4961
4962        if (pkg.packageName.equals("android")) {
4963            synchronized (mPackages) {
4964                if (mAndroidApplication != null) {
4965                    Slog.w(TAG, "*************************************************");
4966                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4967                    Slog.w(TAG, " file=" + scanFile);
4968                    Slog.w(TAG, "*************************************************");
4969                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
4970                            "Core android package being redefined.  Skipping.");
4971                }
4972
4973                // Set up information for our fall-back user intent resolution activity.
4974                mPlatformPackage = pkg;
4975                pkg.mVersionCode = mSdkVersion;
4976                mAndroidApplication = pkg.applicationInfo;
4977
4978                if (!mResolverReplaced) {
4979                    mResolveActivity.applicationInfo = mAndroidApplication;
4980                    mResolveActivity.name = ResolverActivity.class.getName();
4981                    mResolveActivity.packageName = mAndroidApplication.packageName;
4982                    mResolveActivity.processName = "system:ui";
4983                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4984                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4985                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4986                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4987                    mResolveActivity.exported = true;
4988                    mResolveActivity.enabled = true;
4989                    mResolveInfo.activityInfo = mResolveActivity;
4990                    mResolveInfo.priority = 0;
4991                    mResolveInfo.preferredOrder = 0;
4992                    mResolveInfo.match = 0;
4993                    mResolveComponentName = new ComponentName(
4994                            mAndroidApplication.packageName, mResolveActivity.name);
4995                }
4996            }
4997        }
4998
4999        if (DEBUG_PACKAGE_SCANNING) {
5000            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5001                Log.d(TAG, "Scanning package " + pkg.packageName);
5002        }
5003
5004        if (mPackages.containsKey(pkg.packageName)
5005                || mSharedLibraries.containsKey(pkg.packageName)) {
5006            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5007                    "Application package " + pkg.packageName
5008                    + " already installed.  Skipping duplicate.");
5009        }
5010
5011        // Initialize package source and resource directories
5012        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5013        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5014
5015        SharedUserSetting suid = null;
5016        PackageSetting pkgSetting = null;
5017
5018        if (!isSystemApp(pkg)) {
5019            // Only system apps can use these features.
5020            pkg.mOriginalPackages = null;
5021            pkg.mRealPackage = null;
5022            pkg.mAdoptPermissions = null;
5023        }
5024
5025        // writer
5026        synchronized (mPackages) {
5027            if (pkg.mSharedUserId != null) {
5028                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5029                if (suid == null) {
5030                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5031                            "Creating application package " + pkg.packageName
5032                            + " for shared user failed");
5033                }
5034                if (DEBUG_PACKAGE_SCANNING) {
5035                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5036                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5037                                + "): packages=" + suid.packages);
5038                }
5039            }
5040
5041            // Check if we are renaming from an original package name.
5042            PackageSetting origPackage = null;
5043            String realName = null;
5044            if (pkg.mOriginalPackages != null) {
5045                // This package may need to be renamed to a previously
5046                // installed name.  Let's check on that...
5047                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5048                if (pkg.mOriginalPackages.contains(renamed)) {
5049                    // This package had originally been installed as the
5050                    // original name, and we have already taken care of
5051                    // transitioning to the new one.  Just update the new
5052                    // one to continue using the old name.
5053                    realName = pkg.mRealPackage;
5054                    if (!pkg.packageName.equals(renamed)) {
5055                        // Callers into this function may have already taken
5056                        // care of renaming the package; only do it here if
5057                        // it is not already done.
5058                        pkg.setPackageName(renamed);
5059                    }
5060
5061                } else {
5062                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5063                        if ((origPackage = mSettings.peekPackageLPr(
5064                                pkg.mOriginalPackages.get(i))) != null) {
5065                            // We do have the package already installed under its
5066                            // original name...  should we use it?
5067                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5068                                // New package is not compatible with original.
5069                                origPackage = null;
5070                                continue;
5071                            } else if (origPackage.sharedUser != null) {
5072                                // Make sure uid is compatible between packages.
5073                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5074                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5075                                            + " to " + pkg.packageName + ": old uid "
5076                                            + origPackage.sharedUser.name
5077                                            + " differs from " + pkg.mSharedUserId);
5078                                    origPackage = null;
5079                                    continue;
5080                                }
5081                            } else {
5082                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5083                                        + pkg.packageName + " to old name " + origPackage.name);
5084                            }
5085                            break;
5086                        }
5087                    }
5088                }
5089            }
5090
5091            if (mTransferedPackages.contains(pkg.packageName)) {
5092                Slog.w(TAG, "Package " + pkg.packageName
5093                        + " was transferred to another, but its .apk remains");
5094            }
5095
5096            // Just create the setting, don't add it yet. For already existing packages
5097            // the PkgSetting exists already and doesn't have to be created.
5098            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5099                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5100                    pkg.applicationInfo.primaryCpuAbi,
5101                    pkg.applicationInfo.secondaryCpuAbi,
5102                    pkg.applicationInfo.flags, user, false);
5103            if (pkgSetting == null) {
5104                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5105                        "Creating application package " + pkg.packageName + " failed");
5106            }
5107
5108            if (pkgSetting.origPackage != null) {
5109                // If we are first transitioning from an original package,
5110                // fix up the new package's name now.  We need to do this after
5111                // looking up the package under its new name, so getPackageLP
5112                // can take care of fiddling things correctly.
5113                pkg.setPackageName(origPackage.name);
5114
5115                // File a report about this.
5116                String msg = "New package " + pkgSetting.realName
5117                        + " renamed to replace old package " + pkgSetting.name;
5118                reportSettingsProblem(Log.WARN, msg);
5119
5120                // Make a note of it.
5121                mTransferedPackages.add(origPackage.name);
5122
5123                // No longer need to retain this.
5124                pkgSetting.origPackage = null;
5125            }
5126
5127            if (realName != null) {
5128                // Make a note of it.
5129                mTransferedPackages.add(pkg.packageName);
5130            }
5131
5132            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5133                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5134            }
5135
5136            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5137                // Check all shared libraries and map to their actual file path.
5138                // We only do this here for apps not on a system dir, because those
5139                // are the only ones that can fail an install due to this.  We
5140                // will take care of the system apps by updating all of their
5141                // library paths after the scan is done.
5142                updateSharedLibrariesLPw(pkg, null);
5143            }
5144
5145            if (mFoundPolicyFile) {
5146                SELinuxMMAC.assignSeinfoValue(pkg);
5147            }
5148
5149            pkg.applicationInfo.uid = pkgSetting.appId;
5150            pkg.mExtras = pkgSetting;
5151            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5152                try {
5153                    verifySignaturesLP(pkgSetting, pkg);
5154                } catch (PackageManagerException e) {
5155                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5156                        throw e;
5157                    }
5158                    // The signature has changed, but this package is in the system
5159                    // image...  let's recover!
5160                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5161                    // However...  if this package is part of a shared user, but it
5162                    // doesn't match the signature of the shared user, let's fail.
5163                    // What this means is that you can't change the signatures
5164                    // associated with an overall shared user, which doesn't seem all
5165                    // that unreasonable.
5166                    if (pkgSetting.sharedUser != null) {
5167                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5168                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5169                            throw new PackageManagerException(
5170                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5171                                            "Signature mismatch for shared user : "
5172                                            + pkgSetting.sharedUser);
5173                        }
5174                    }
5175                    // File a report about this.
5176                    String msg = "System package " + pkg.packageName
5177                        + " signature changed; retaining data.";
5178                    reportSettingsProblem(Log.WARN, msg);
5179                }
5180            } else {
5181                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5182                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5183                            + pkg.packageName + " upgrade keys do not match the "
5184                            + "previously installed version");
5185                } else {
5186                    // signatures may have changed as result of upgrade
5187                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5188                }
5189            }
5190            // Verify that this new package doesn't have any content providers
5191            // that conflict with existing packages.  Only do this if the
5192            // package isn't already installed, since we don't want to break
5193            // things that are installed.
5194            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5195                final int N = pkg.providers.size();
5196                int i;
5197                for (i=0; i<N; i++) {
5198                    PackageParser.Provider p = pkg.providers.get(i);
5199                    if (p.info.authority != null) {
5200                        String names[] = p.info.authority.split(";");
5201                        for (int j = 0; j < names.length; j++) {
5202                            if (mProvidersByAuthority.containsKey(names[j])) {
5203                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5204                                final String otherPackageName =
5205                                        ((other != null && other.getComponentName() != null) ?
5206                                                other.getComponentName().getPackageName() : "?");
5207                                throw new PackageManagerException(
5208                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5209                                                "Can't install because provider name " + names[j]
5210                                                + " (in package " + pkg.applicationInfo.packageName
5211                                                + ") is already used by " + otherPackageName);
5212                            }
5213                        }
5214                    }
5215                }
5216            }
5217
5218            if (pkg.mAdoptPermissions != null) {
5219                // This package wants to adopt ownership of permissions from
5220                // another package.
5221                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5222                    final String origName = pkg.mAdoptPermissions.get(i);
5223                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5224                    if (orig != null) {
5225                        if (verifyPackageUpdateLPr(orig, pkg)) {
5226                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5227                                    + pkg.packageName);
5228                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5229                        }
5230                    }
5231                }
5232            }
5233        }
5234
5235        final String pkgName = pkg.packageName;
5236
5237        final long scanFileTime = scanFile.lastModified();
5238        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5239        pkg.applicationInfo.processName = fixProcessName(
5240                pkg.applicationInfo.packageName,
5241                pkg.applicationInfo.processName,
5242                pkg.applicationInfo.uid);
5243
5244        File dataPath;
5245        if (mPlatformPackage == pkg) {
5246            // The system package is special.
5247            dataPath = new File (Environment.getDataDirectory(), "system");
5248            pkg.applicationInfo.dataDir = dataPath.getPath();
5249        } else {
5250            // This is a normal package, need to make its data directory.
5251            dataPath = getDataPathForPackage(pkg.packageName, 0);
5252
5253            boolean uidError = false;
5254
5255            if (dataPath.exists()) {
5256                int currentUid = 0;
5257                try {
5258                    StructStat stat = Os.stat(dataPath.getPath());
5259                    currentUid = stat.st_uid;
5260                } catch (ErrnoException e) {
5261                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5262                }
5263
5264                // If we have mismatched owners for the data path, we have a problem.
5265                if (currentUid != pkg.applicationInfo.uid) {
5266                    boolean recovered = false;
5267                    if (currentUid == 0) {
5268                        // The directory somehow became owned by root.  Wow.
5269                        // This is probably because the system was stopped while
5270                        // installd was in the middle of messing with its libs
5271                        // directory.  Ask installd to fix that.
5272                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5273                                pkg.applicationInfo.uid);
5274                        if (ret >= 0) {
5275                            recovered = true;
5276                            String msg = "Package " + pkg.packageName
5277                                    + " unexpectedly changed to uid 0; recovered to " +
5278                                    + pkg.applicationInfo.uid;
5279                            reportSettingsProblem(Log.WARN, msg);
5280                        }
5281                    }
5282                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5283                            || (scanMode&SCAN_BOOTING) != 0)) {
5284                        // If this is a system app, we can at least delete its
5285                        // current data so the application will still work.
5286                        int ret = removeDataDirsLI(pkgName);
5287                        if (ret >= 0) {
5288                            // TODO: Kill the processes first
5289                            // Old data gone!
5290                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5291                                    ? "System package " : "Third party package ";
5292                            String msg = prefix + pkg.packageName
5293                                    + " has changed from uid: "
5294                                    + currentUid + " to "
5295                                    + pkg.applicationInfo.uid + "; old data erased";
5296                            reportSettingsProblem(Log.WARN, msg);
5297                            recovered = true;
5298
5299                            // And now re-install the app.
5300                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5301                                                   pkg.applicationInfo.seinfo);
5302                            if (ret == -1) {
5303                                // Ack should not happen!
5304                                msg = prefix + pkg.packageName
5305                                        + " could not have data directory re-created after delete.";
5306                                reportSettingsProblem(Log.WARN, msg);
5307                                throw new PackageManagerException(
5308                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5309                            }
5310                        }
5311                        if (!recovered) {
5312                            mHasSystemUidErrors = true;
5313                        }
5314                    } else if (!recovered) {
5315                        // If we allow this install to proceed, we will be broken.
5316                        // Abort, abort!
5317                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5318                                "scanPackageLI");
5319                    }
5320                    if (!recovered) {
5321                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5322                            + pkg.applicationInfo.uid + "/fs_"
5323                            + currentUid;
5324                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5325                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5326                        String msg = "Package " + pkg.packageName
5327                                + " has mismatched uid: "
5328                                + currentUid + " on disk, "
5329                                + pkg.applicationInfo.uid + " in settings";
5330                        // writer
5331                        synchronized (mPackages) {
5332                            mSettings.mReadMessages.append(msg);
5333                            mSettings.mReadMessages.append('\n');
5334                            uidError = true;
5335                            if (!pkgSetting.uidError) {
5336                                reportSettingsProblem(Log.ERROR, msg);
5337                            }
5338                        }
5339                    }
5340                }
5341                pkg.applicationInfo.dataDir = dataPath.getPath();
5342                if (mShouldRestoreconData) {
5343                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5344                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5345                                pkg.applicationInfo.uid);
5346                }
5347            } else {
5348                if (DEBUG_PACKAGE_SCANNING) {
5349                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5350                        Log.v(TAG, "Want this data dir: " + dataPath);
5351                }
5352                //invoke installer to do the actual installation
5353                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5354                                           pkg.applicationInfo.seinfo);
5355                if (ret < 0) {
5356                    // Error from installer
5357                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5358                            "Unable to create data dirs [errorCode=" + ret + "]");
5359                }
5360
5361                if (dataPath.exists()) {
5362                    pkg.applicationInfo.dataDir = dataPath.getPath();
5363                } else {
5364                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5365                    pkg.applicationInfo.dataDir = null;
5366                }
5367            }
5368
5369            pkgSetting.uidError = uidError;
5370        }
5371
5372        final String path = scanFile.getPath();
5373        final String codePath = pkg.applicationInfo.getCodePath();
5374        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5375            // For the case where we had previously uninstalled an update, get rid
5376            // of any native binaries we might have unpackaged. Note that this assumes
5377            // that system app updates were not installed via ASEC.
5378            //
5379            // TODO(multiArch): Is this cleanup really necessary ?
5380            NativeLibraryHelper.removeNativeBinariesFromDirLI(
5381                    new File(codePath, LIB_DIR_NAME), false /* delete dirs */);
5382            setBundledAppAbisAndRoots(pkg, pkgSetting);
5383            setNativeLibraryPaths(pkg);
5384        } else {
5385            // TODO: We can probably be smarter about this stuff. For installed apps,
5386            // we can calculate this information at install time once and for all. For
5387            // system apps, we can probably assume that this information doesn't change
5388            // after the first boot scan. As things stand, we do lots of unnecessary work.
5389
5390            // Give ourselves some initial paths; we'll come back for another
5391            // pass once we've determined ABI below.
5392            setNativeLibraryPaths(pkg);
5393
5394            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5395            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5396            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5397
5398            NativeLibraryHelper.Handle handle = null;
5399            try {
5400                handle = NativeLibraryHelper.Handle.create(scanFile);
5401                // TODO(multiArch): This can be null for apps that didn't go through the
5402                // usual installation process. We can calculate it again, like we
5403                // do during install time.
5404                //
5405                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5406                // unnecessary.
5407                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5408
5409                // Null out the abis so that they can be recalculated.
5410                pkg.applicationInfo.primaryCpuAbi = null;
5411                pkg.applicationInfo.secondaryCpuAbi = null;
5412                if (isMultiArch(pkg.applicationInfo)) {
5413                    // Warn if we've set an abiOverride for multi-lib packages..
5414                    // By definition, we need to copy both 32 and 64 bit libraries for
5415                    // such packages.
5416                    if (abiOverride != null) {
5417                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5418                    }
5419
5420                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5421                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5422                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5423                        if (isAsec) {
5424                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5425                        } else {
5426                            abi32 = copyNativeLibrariesForInternalApp(handle,
5427                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5428                        }
5429                    }
5430
5431                    if (abi32 < 0 && abi32 != PackageManager.NO_NATIVE_LIBRARIES) {
5432                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5433                                "Error unpackaging 32 bit native libs for multiarch app, errorCode="
5434                                + abi32);
5435                    }
5436
5437                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5438                        if (isAsec) {
5439                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5440                        } else {
5441                            abi64 = copyNativeLibrariesForInternalApp(handle,
5442                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5443                        }
5444                    }
5445
5446                    if (abi64 < 0 && abi64 != PackageManager.NO_NATIVE_LIBRARIES) {
5447                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5448                                "Error unpackaging 64 bit native libs for multiarch app, errorCode="
5449                                + abi32);
5450                    }
5451
5452                    if (abi64 >= 0) {
5453                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5454                    }
5455
5456                    if (abi32 >= 0) {
5457                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5458                        if (abi64 >= 0) {
5459                            pkg.applicationInfo.secondaryCpuAbi = abi;
5460                        } else {
5461                            pkg.applicationInfo.primaryCpuAbi = abi;
5462                        }
5463                    }
5464                } else {
5465                    String[] abiList = (abiOverride != null) ?
5466                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
5467
5468                    // Enable gross and lame hacks for apps that are built with old
5469                    // SDK tools. We must scan their APKs for renderscript bitcode and
5470                    // not launch them if it's present. Don't bother checking on devices
5471                    // that don't have 64 bit support.
5472                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
5473                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5474                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5475                    }
5476
5477                    final int copyRet;
5478                    if (isAsec) {
5479                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5480                    } else {
5481                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5482                                useIsaSpecificSubdirs);
5483                    }
5484
5485                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5486                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5487                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5488                    }
5489
5490                    if (copyRet >= 0) {
5491                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5492                    }
5493                }
5494            } catch (IOException ioe) {
5495                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5496            } finally {
5497                IoUtils.closeQuietly(handle);
5498            }
5499
5500            // Now that we've calculated the ABIs and determined if it's an internal app,
5501            // we will go ahead and populate the nativeLibraryPath.
5502            setNativeLibraryPaths(pkg);
5503
5504            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5505            final int[] userIds = sUserManager.getUserIds();
5506            synchronized (mInstallLock) {
5507                // Create a native library symlink only if we have native libraries
5508                // and if the native libraries are 32 bit libraries. We do not provide
5509                // this symlink for 64 bit libraries.
5510                if (pkg.applicationInfo.primaryCpuAbi != null &&
5511                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5512                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5513                    for (int userId : userIds) {
5514                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5515                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5516                                    "Failed linking native library dir (user=" + userId + ")");
5517                        }
5518                    }
5519                }
5520            }
5521
5522            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5523            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5524        }
5525
5526        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5527                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5528                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5529
5530        // Push the derived path down into PackageSettings so we know what to
5531        // clean up at uninstall time.
5532        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5533
5534        if (DEBUG_ABI_SELECTION) {
5535            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5536                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5537                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5538        }
5539
5540        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5541            // We don't do this here during boot because we can do it all
5542            // at once after scanning all existing packages.
5543            //
5544            // We also do this *before* we perform dexopt on this package, so that
5545            // we can avoid redundant dexopts, and also to make sure we've got the
5546            // code and package path correct.
5547            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5548                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5549                throw new PackageManagerException(INSTALL_FAILED_CPU_ABI_INCOMPATIBLE,
5550                        "scanPackageLI");
5551            }
5552        }
5553
5554        if ((scanMode&SCAN_NO_DEX) == 0) {
5555            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5556                    == DEX_OPT_FAILED) {
5557                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5558                    removeDataDirsLI(pkg.packageName);
5559                }
5560
5561                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5562            }
5563        }
5564
5565        if (mFactoryTest && pkg.requestedPermissions.contains(
5566                android.Manifest.permission.FACTORY_TEST)) {
5567            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5568        }
5569
5570        ArrayList<PackageParser.Package> clientLibPkgs = null;
5571
5572        // writer
5573        synchronized (mPackages) {
5574            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5575                // Only system apps can add new shared libraries.
5576                if (pkg.libraryNames != null) {
5577                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5578                        String name = pkg.libraryNames.get(i);
5579                        boolean allowed = false;
5580                        if (isUpdatedSystemApp(pkg)) {
5581                            // New library entries can only be added through the
5582                            // system image.  This is important to get rid of a lot
5583                            // of nasty edge cases: for example if we allowed a non-
5584                            // system update of the app to add a library, then uninstalling
5585                            // the update would make the library go away, and assumptions
5586                            // we made such as through app install filtering would now
5587                            // have allowed apps on the device which aren't compatible
5588                            // with it.  Better to just have the restriction here, be
5589                            // conservative, and create many fewer cases that can negatively
5590                            // impact the user experience.
5591                            final PackageSetting sysPs = mSettings
5592                                    .getDisabledSystemPkgLPr(pkg.packageName);
5593                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5594                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5595                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5596                                        allowed = true;
5597                                        allowed = true;
5598                                        break;
5599                                    }
5600                                }
5601                            }
5602                        } else {
5603                            allowed = true;
5604                        }
5605                        if (allowed) {
5606                            if (!mSharedLibraries.containsKey(name)) {
5607                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5608                            } else if (!name.equals(pkg.packageName)) {
5609                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5610                                        + name + " already exists; skipping");
5611                            }
5612                        } else {
5613                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5614                                    + name + " that is not declared on system image; skipping");
5615                        }
5616                    }
5617                    if ((scanMode&SCAN_BOOTING) == 0) {
5618                        // If we are not booting, we need to update any applications
5619                        // that are clients of our shared library.  If we are booting,
5620                        // this will all be done once the scan is complete.
5621                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5622                    }
5623                }
5624            }
5625        }
5626
5627        // We also need to dexopt any apps that are dependent on this library.  Note that
5628        // if these fail, we should abort the install since installing the library will
5629        // result in some apps being broken.
5630        if (clientLibPkgs != null) {
5631            if ((scanMode&SCAN_NO_DEX) == 0) {
5632                for (int i=0; i<clientLibPkgs.size(); i++) {
5633                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5634                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5635                            == DEX_OPT_FAILED) {
5636                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5637                            removeDataDirsLI(pkg.packageName);
5638                        }
5639
5640                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5641                                "scanPackageLI failed to dexopt clientLibPkgs");
5642                    }
5643                }
5644            }
5645        }
5646
5647        // Request the ActivityManager to kill the process(only for existing packages)
5648        // so that we do not end up in a confused state while the user is still using the older
5649        // version of the application while the new one gets installed.
5650        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5651            // If the package lives in an asec, tell everyone that the container is going
5652            // away so they can clean up any references to its resources (which would prevent
5653            // vold from being able to unmount the asec)
5654            if (isForwardLocked(pkg) || isExternal(pkg)) {
5655                if (DEBUG_INSTALL) {
5656                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5657                }
5658                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5659                final ArrayList<String> pkgList = new ArrayList<String>(1);
5660                pkgList.add(pkg.applicationInfo.packageName);
5661                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5662            }
5663
5664            // Post the request that it be killed now that the going-away broadcast is en route
5665            killApplication(pkg.applicationInfo.packageName,
5666                        pkg.applicationInfo.uid, "update pkg");
5667        }
5668
5669        // Also need to kill any apps that are dependent on the library.
5670        if (clientLibPkgs != null) {
5671            for (int i=0; i<clientLibPkgs.size(); i++) {
5672                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5673                killApplication(clientPkg.applicationInfo.packageName,
5674                        clientPkg.applicationInfo.uid, "update lib");
5675            }
5676        }
5677
5678        // writer
5679        synchronized (mPackages) {
5680            // We don't expect installation to fail beyond this point,
5681            if ((scanMode&SCAN_MONITOR) != 0) {
5682                mAppDirs.put(pkg.codePath, pkg);
5683            }
5684            // Add the new setting to mSettings
5685            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5686            // Add the new setting to mPackages
5687            mPackages.put(pkg.applicationInfo.packageName, pkg);
5688            // Make sure we don't accidentally delete its data.
5689            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5690            while (iter.hasNext()) {
5691                PackageCleanItem item = iter.next();
5692                if (pkgName.equals(item.packageName)) {
5693                    iter.remove();
5694                }
5695            }
5696
5697            // Take care of first install / last update times.
5698            if (currentTime != 0) {
5699                if (pkgSetting.firstInstallTime == 0) {
5700                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5701                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5702                    pkgSetting.lastUpdateTime = currentTime;
5703                }
5704            } else if (pkgSetting.firstInstallTime == 0) {
5705                // We need *something*.  Take time time stamp of the file.
5706                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5707            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5708                if (scanFileTime != pkgSetting.timeStamp) {
5709                    // A package on the system image has changed; consider this
5710                    // to be an update.
5711                    pkgSetting.lastUpdateTime = scanFileTime;
5712                }
5713            }
5714
5715            // Add the package's KeySets to the global KeySetManagerService
5716            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5717            try {
5718                // Old KeySetData no longer valid.
5719                ksms.removeAppKeySetDataLPw(pkg.packageName);
5720                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5721                if (pkg.mKeySetMapping != null) {
5722                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5723                            pkg.mKeySetMapping.entrySet()) {
5724                        if (entry.getValue() != null) {
5725                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5726                                                          entry.getValue(), entry.getKey());
5727                        }
5728                    }
5729                    if (pkg.mUpgradeKeySets != null) {
5730                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5731                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5732                        }
5733                    }
5734                }
5735            } catch (NullPointerException e) {
5736                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5737            } catch (IllegalArgumentException e) {
5738                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5739            }
5740
5741            int N = pkg.providers.size();
5742            StringBuilder r = null;
5743            int i;
5744            for (i=0; i<N; i++) {
5745                PackageParser.Provider p = pkg.providers.get(i);
5746                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5747                        p.info.processName, pkg.applicationInfo.uid);
5748                mProviders.addProvider(p);
5749                p.syncable = p.info.isSyncable;
5750                if (p.info.authority != null) {
5751                    String names[] = p.info.authority.split(";");
5752                    p.info.authority = null;
5753                    for (int j = 0; j < names.length; j++) {
5754                        if (j == 1 && p.syncable) {
5755                            // We only want the first authority for a provider to possibly be
5756                            // syncable, so if we already added this provider using a different
5757                            // authority clear the syncable flag. We copy the provider before
5758                            // changing it because the mProviders object contains a reference
5759                            // to a provider that we don't want to change.
5760                            // Only do this for the second authority since the resulting provider
5761                            // object can be the same for all future authorities for this provider.
5762                            p = new PackageParser.Provider(p);
5763                            p.syncable = false;
5764                        }
5765                        if (!mProvidersByAuthority.containsKey(names[j])) {
5766                            mProvidersByAuthority.put(names[j], p);
5767                            if (p.info.authority == null) {
5768                                p.info.authority = names[j];
5769                            } else {
5770                                p.info.authority = p.info.authority + ";" + names[j];
5771                            }
5772                            if (DEBUG_PACKAGE_SCANNING) {
5773                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5774                                    Log.d(TAG, "Registered content provider: " + names[j]
5775                                            + ", className = " + p.info.name + ", isSyncable = "
5776                                            + p.info.isSyncable);
5777                            }
5778                        } else {
5779                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5780                            Slog.w(TAG, "Skipping provider name " + names[j] +
5781                                    " (in package " + pkg.applicationInfo.packageName +
5782                                    "): name already used by "
5783                                    + ((other != null && other.getComponentName() != null)
5784                                            ? other.getComponentName().getPackageName() : "?"));
5785                        }
5786                    }
5787                }
5788                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5789                    if (r == null) {
5790                        r = new StringBuilder(256);
5791                    } else {
5792                        r.append(' ');
5793                    }
5794                    r.append(p.info.name);
5795                }
5796            }
5797            if (r != null) {
5798                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5799            }
5800
5801            N = pkg.services.size();
5802            r = null;
5803            for (i=0; i<N; i++) {
5804                PackageParser.Service s = pkg.services.get(i);
5805                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5806                        s.info.processName, pkg.applicationInfo.uid);
5807                mServices.addService(s);
5808                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5809                    if (r == null) {
5810                        r = new StringBuilder(256);
5811                    } else {
5812                        r.append(' ');
5813                    }
5814                    r.append(s.info.name);
5815                }
5816            }
5817            if (r != null) {
5818                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5819            }
5820
5821            N = pkg.receivers.size();
5822            r = null;
5823            for (i=0; i<N; i++) {
5824                PackageParser.Activity a = pkg.receivers.get(i);
5825                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5826                        a.info.processName, pkg.applicationInfo.uid);
5827                mReceivers.addActivity(a, "receiver");
5828                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5829                    if (r == null) {
5830                        r = new StringBuilder(256);
5831                    } else {
5832                        r.append(' ');
5833                    }
5834                    r.append(a.info.name);
5835                }
5836            }
5837            if (r != null) {
5838                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5839            }
5840
5841            N = pkg.activities.size();
5842            r = null;
5843            for (i=0; i<N; i++) {
5844                PackageParser.Activity a = pkg.activities.get(i);
5845                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5846                        a.info.processName, pkg.applicationInfo.uid);
5847                mActivities.addActivity(a, "activity");
5848                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5849                    if (r == null) {
5850                        r = new StringBuilder(256);
5851                    } else {
5852                        r.append(' ');
5853                    }
5854                    r.append(a.info.name);
5855                }
5856            }
5857            if (r != null) {
5858                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5859            }
5860
5861            N = pkg.permissionGroups.size();
5862            r = null;
5863            for (i=0; i<N; i++) {
5864                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5865                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5866                if (cur == null) {
5867                    mPermissionGroups.put(pg.info.name, pg);
5868                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5869                        if (r == null) {
5870                            r = new StringBuilder(256);
5871                        } else {
5872                            r.append(' ');
5873                        }
5874                        r.append(pg.info.name);
5875                    }
5876                } else {
5877                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5878                            + pg.info.packageName + " ignored: original from "
5879                            + cur.info.packageName);
5880                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5881                        if (r == null) {
5882                            r = new StringBuilder(256);
5883                        } else {
5884                            r.append(' ');
5885                        }
5886                        r.append("DUP:");
5887                        r.append(pg.info.name);
5888                    }
5889                }
5890            }
5891            if (r != null) {
5892                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5893            }
5894
5895            N = pkg.permissions.size();
5896            r = null;
5897            for (i=0; i<N; i++) {
5898                PackageParser.Permission p = pkg.permissions.get(i);
5899                HashMap<String, BasePermission> permissionMap =
5900                        p.tree ? mSettings.mPermissionTrees
5901                        : mSettings.mPermissions;
5902                p.group = mPermissionGroups.get(p.info.group);
5903                if (p.info.group == null || p.group != null) {
5904                    BasePermission bp = permissionMap.get(p.info.name);
5905                    if (bp == null) {
5906                        bp = new BasePermission(p.info.name, p.info.packageName,
5907                                BasePermission.TYPE_NORMAL);
5908                        permissionMap.put(p.info.name, bp);
5909                    }
5910                    if (bp.perm == null) {
5911                        if (bp.sourcePackage != null
5912                                && !bp.sourcePackage.equals(p.info.packageName)) {
5913                            // If this is a permission that was formerly defined by a non-system
5914                            // app, but is now defined by a system app (following an upgrade),
5915                            // discard the previous declaration and consider the system's to be
5916                            // canonical.
5917                            if (isSystemApp(p.owner)) {
5918                                String msg = "New decl " + p.owner + " of permission  "
5919                                        + p.info.name + " is system";
5920                                reportSettingsProblem(Log.WARN, msg);
5921                                bp.sourcePackage = null;
5922                            }
5923                        }
5924                        if (bp.sourcePackage == null
5925                                || bp.sourcePackage.equals(p.info.packageName)) {
5926                            BasePermission tree = findPermissionTreeLP(p.info.name);
5927                            if (tree == null
5928                                    || tree.sourcePackage.equals(p.info.packageName)) {
5929                                bp.packageSetting = pkgSetting;
5930                                bp.perm = p;
5931                                bp.uid = pkg.applicationInfo.uid;
5932                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5933                                    if (r == null) {
5934                                        r = new StringBuilder(256);
5935                                    } else {
5936                                        r.append(' ');
5937                                    }
5938                                    r.append(p.info.name);
5939                                }
5940                            } else {
5941                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5942                                        + p.info.packageName + " ignored: base tree "
5943                                        + tree.name + " is from package "
5944                                        + tree.sourcePackage);
5945                            }
5946                        } else {
5947                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5948                                    + p.info.packageName + " ignored: original from "
5949                                    + bp.sourcePackage);
5950                        }
5951                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5952                        if (r == null) {
5953                            r = new StringBuilder(256);
5954                        } else {
5955                            r.append(' ');
5956                        }
5957                        r.append("DUP:");
5958                        r.append(p.info.name);
5959                    }
5960                    if (bp.perm == p) {
5961                        bp.protectionLevel = p.info.protectionLevel;
5962                    }
5963                } else {
5964                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5965                            + p.info.packageName + " ignored: no group "
5966                            + p.group);
5967                }
5968            }
5969            if (r != null) {
5970                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5971            }
5972
5973            N = pkg.instrumentation.size();
5974            r = null;
5975            for (i=0; i<N; i++) {
5976                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5977                a.info.packageName = pkg.applicationInfo.packageName;
5978                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5979                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5980                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5981                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5982                a.info.dataDir = pkg.applicationInfo.dataDir;
5983
5984                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
5985                // need other information about the application, like the ABI and what not ?
5986                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5987                mInstrumentation.put(a.getComponentName(), a);
5988                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5989                    if (r == null) {
5990                        r = new StringBuilder(256);
5991                    } else {
5992                        r.append(' ');
5993                    }
5994                    r.append(a.info.name);
5995                }
5996            }
5997            if (r != null) {
5998                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5999            }
6000
6001            if (pkg.protectedBroadcasts != null) {
6002                N = pkg.protectedBroadcasts.size();
6003                for (i=0; i<N; i++) {
6004                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6005                }
6006            }
6007
6008            pkgSetting.setTimeStamp(scanFileTime);
6009
6010            // Create idmap files for pairs of (packages, overlay packages).
6011            // Note: "android", ie framework-res.apk, is handled by native layers.
6012            if (pkg.mOverlayTarget != null) {
6013                // This is an overlay package.
6014                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6015                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6016                        mOverlays.put(pkg.mOverlayTarget,
6017                                new HashMap<String, PackageParser.Package>());
6018                    }
6019                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6020                    map.put(pkg.packageName, pkg);
6021                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6022                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6023                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6024                                "scanPackageLI failed to createIdmap");
6025                    }
6026                }
6027            } else if (mOverlays.containsKey(pkg.packageName) &&
6028                    !pkg.packageName.equals("android")) {
6029                // This is a regular package, with one or more known overlay packages.
6030                createIdmapsForPackageLI(pkg);
6031            }
6032        }
6033
6034        return pkg;
6035    }
6036
6037    /**
6038     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6039     * i.e, so that all packages can be run inside a single process if required.
6040     *
6041     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6042     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6043     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6044     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6045     * updating a package that belongs to a shared user.
6046     *
6047     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6048     * adds unnecessary complexity.
6049     */
6050    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6051            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6052        String requiredInstructionSet = null;
6053        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6054            requiredInstructionSet = VMRuntime.getInstructionSet(
6055                     scannedPackage.applicationInfo.primaryCpuAbi);
6056        }
6057
6058        PackageSetting requirer = null;
6059        for (PackageSetting ps : packagesForUser) {
6060            // If packagesForUser contains scannedPackage, we skip it. This will happen
6061            // when scannedPackage is an update of an existing package. Without this check,
6062            // we will never be able to change the ABI of any package belonging to a shared
6063            // user, even if it's compatible with other packages.
6064            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6065                if (ps.primaryCpuAbiString == null) {
6066                    continue;
6067                }
6068
6069                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6070                if (requiredInstructionSet != null) {
6071                    if (!instructionSet.equals(requiredInstructionSet)) {
6072                        // We have a mismatch between instruction sets (say arm vs arm64).
6073                        // bail out.
6074                        String errorMessage = "Instruction set mismatch, "
6075                                + ((requirer == null) ? "[caller]" : requirer)
6076                                + " requires " + requiredInstructionSet + " whereas " + ps
6077                                + " requires " + instructionSet;
6078                        Slog.e(TAG, errorMessage);
6079
6080                        reportSettingsProblem(Log.WARN, errorMessage);
6081                        // Give up, don't bother making any other changes to the package settings.
6082                        return false;
6083                    }
6084                } else {
6085                    requiredInstructionSet = instructionSet;
6086                    requirer = ps;
6087                }
6088            }
6089        }
6090
6091        if (requiredInstructionSet != null) {
6092            String adjustedAbi;
6093            if (requirer != null) {
6094                // requirer != null implies that either scannedPackage was null or that scannedPackage
6095                // did not require an ABI, in which case we have to adjust scannedPackage to match
6096                // the ABI of the set (which is the same as requirer's ABI)
6097                adjustedAbi = requirer.primaryCpuAbiString;
6098                if (scannedPackage != null) {
6099                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6100                }
6101            } else {
6102                // requirer == null implies that we're updating all ABIs in the set to
6103                // match scannedPackage.
6104                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6105            }
6106
6107            for (PackageSetting ps : packagesForUser) {
6108                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6109                    if (ps.primaryCpuAbiString != null) {
6110                        continue;
6111                    }
6112
6113                    ps.primaryCpuAbiString = adjustedAbi;
6114                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6115                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6116                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6117
6118                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6119                            ps.primaryCpuAbiString = null;
6120                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6121                            return false;
6122                        } else {
6123                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6124                        }
6125                    }
6126                }
6127            }
6128        }
6129
6130        return true;
6131    }
6132
6133    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6134        synchronized (mPackages) {
6135            mResolverReplaced = true;
6136            // Set up information for custom user intent resolution activity.
6137            mResolveActivity.applicationInfo = pkg.applicationInfo;
6138            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6139            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6140            mResolveActivity.processName = null;
6141            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6142            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6143                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6144            mResolveActivity.theme = 0;
6145            mResolveActivity.exported = true;
6146            mResolveActivity.enabled = true;
6147            mResolveInfo.activityInfo = mResolveActivity;
6148            mResolveInfo.priority = 0;
6149            mResolveInfo.preferredOrder = 0;
6150            mResolveInfo.match = 0;
6151            mResolveComponentName = mCustomResolverComponentName;
6152            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6153                    mResolveComponentName);
6154        }
6155    }
6156
6157    private static String calculateApkRoot(final String codePathString) {
6158        final File codePath = new File(codePathString);
6159        final File codeRoot;
6160        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6161            codeRoot = Environment.getRootDirectory();
6162        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6163            codeRoot = Environment.getOemDirectory();
6164        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6165            codeRoot = Environment.getVendorDirectory();
6166        } else {
6167            // Unrecognized code path; take its top real segment as the apk root:
6168            // e.g. /something/app/blah.apk => /something
6169            try {
6170                File f = codePath.getCanonicalFile();
6171                File parent = f.getParentFile();    // non-null because codePath is a file
6172                File tmp;
6173                while ((tmp = parent.getParentFile()) != null) {
6174                    f = parent;
6175                    parent = tmp;
6176                }
6177                codeRoot = f;
6178                Slog.w(TAG, "Unrecognized code path "
6179                        + codePath + " - using " + codeRoot);
6180            } catch (IOException e) {
6181                // Can't canonicalize the code path -- shenanigans?
6182                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6183                return Environment.getRootDirectory().getPath();
6184            }
6185        }
6186        return codeRoot.getPath();
6187    }
6188
6189    /**
6190     * Derive and set the location of native libraries for the given package,
6191     * which varies depending on where and how the package was installed.
6192     */
6193    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6194        final ApplicationInfo info = pkg.applicationInfo;
6195        final String codePath = pkg.codePath;
6196        final File codeFile = new File(codePath);
6197
6198        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6199        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6200
6201        info.nativeLibraryRootDir = null;
6202        info.nativeLibraryRootRequiresIsa = false;
6203        info.nativeLibraryDir = null;
6204
6205        if (bundledApp) {
6206            // Monolithic bundled install
6207            // TODO: support cluster bundled installs?
6208
6209            final boolean is64Bit = (info.primaryCpuAbi != null)
6210                    && VMRuntime.is64BitAbi(info.primaryCpuAbi);
6211
6212            // This is a bundled system app so choose the path based on the ABI.
6213            // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6214            // is just the default path.
6215            final String apkName = deriveCodePathName(codePath);
6216            final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6217            info.nativeLibraryRootDir = Environment.buildPath(new File(info.apkRoot), libDir,
6218                    apkName).getAbsolutePath();
6219            info.nativeLibraryRootRequiresIsa = false;
6220
6221        } else if (isApkFile(codeFile)) {
6222            // Monolithic install
6223            if (asecApp) {
6224                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6225                        .getAbsolutePath();
6226                info.nativeLibraryRootRequiresIsa = false;
6227            } else {
6228                final String apkName = deriveCodePathName(codePath);
6229                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6230                        .getAbsolutePath();
6231                info.nativeLibraryRootRequiresIsa = false;
6232            }
6233        } else {
6234            // Cluster install
6235            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6236            info.nativeLibraryRootRequiresIsa = true;
6237        }
6238
6239        if (info.nativeLibraryRootRequiresIsa) {
6240            if (info.primaryCpuAbi != null) {
6241                info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6242                        VMRuntime.getInstructionSet(info.primaryCpuAbi)).getAbsolutePath();
6243            } else {
6244                Slog.w(TAG, "Package " + info.packageName
6245                        + " missing ABI; unable to derive nativeLibraryDir");
6246            }
6247        } else {
6248            info.nativeLibraryDir = info.nativeLibraryRootDir;
6249        }
6250    }
6251
6252    /**
6253     * Calculate the abis and roots for a bundled app. These can uniquely
6254     * be determined from the contents of the system partition, i.e whether
6255     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6256     * of this information, and instead assume that the system was built
6257     * sensibly.
6258     */
6259    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6260                                           PackageSetting pkgSetting) {
6261        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6262
6263        // If "/system/lib64/apkname" exists, assume that is the per-package
6264        // native library directory to use; otherwise use "/system/lib/apkname".
6265        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6266        pkg.applicationInfo.apkRoot = apkRoot;
6267        setBundledAppAbi(pkg, apkRoot, apkName);
6268        // pkgSetting might be null during rescan following uninstall of updates
6269        // to a bundled app, so accommodate that possibility.  The settings in
6270        // that case will be established later from the parsed package.
6271        //
6272        // If the settings aren't null, sync them up with what we've just derived.
6273        // note that apkRoot isn't stored in the package settings.
6274        if (pkgSetting != null) {
6275            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6276            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6277        }
6278    }
6279
6280    /**
6281     * Deduces the ABI of a bundled app and sets the relevant fields on the
6282     * parsed pkg object.
6283     *
6284     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6285     *        under which system libraries are installed.
6286     * @param apkName the name of the installed package.
6287     */
6288    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6289        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6290        // or similar.
6291        final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6292        final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6293
6294        if (has64BitLibs && !has32BitLibs) {
6295            // The package has 64 bit libs, but not 32 bit libs. Its primary
6296            // ABI should be 64 bit. We can safely assume here that the bundled
6297            // native libraries correspond to the most preferred ABI in the list.
6298
6299            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6300            pkg.applicationInfo.secondaryCpuAbi = null;
6301        } else if (has32BitLibs && !has64BitLibs) {
6302            // The package has 32 bit libs but not 64 bit libs. Its primary
6303            // ABI should be 32 bit.
6304
6305            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6306            pkg.applicationInfo.secondaryCpuAbi = null;
6307        } else if (has32BitLibs && has64BitLibs) {
6308            // The application has both 64 and 32 bit bundled libraries. We check
6309            // here that the app declares multiArch support, and warn if it doesn't.
6310            //
6311            // We will be lenient here and record both ABIs. The primary will be the
6312            // ABI that's higher on the list, i.e, a device that's configured to prefer
6313            // 64 bit apps will see a 64 bit primary ABI,
6314
6315            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6316                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6317            }
6318
6319            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6320                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6321                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6322            } else {
6323                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6324                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6325            }
6326        } else {
6327            pkg.applicationInfo.primaryCpuAbi = null;
6328            pkg.applicationInfo.secondaryCpuAbi = null;
6329        }
6330    }
6331
6332    private static void createNativeLibrarySubdir(File path) throws IOException {
6333        if (!path.isDirectory()) {
6334            path.delete();
6335
6336            if (!path.mkdir()) {
6337                throw new IOException("Cannot create " + path.getPath());
6338            }
6339
6340            try {
6341                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6342            } catch (ErrnoException e) {
6343                throw new IOException("Cannot chmod native library directory "
6344                        + path.getPath(), e);
6345            }
6346        } else if (!SELinux.restorecon(path)) {
6347            throw new IOException("Cannot set SELinux context for " + path.getPath());
6348        }
6349    }
6350
6351    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6352            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6353        createNativeLibrarySubdir(nativeLibraryRoot);
6354
6355        /*
6356         * If this is an internal application or our nativeLibraryPath points to
6357         * the app-lib directory, unpack the libraries if necessary.
6358         */
6359        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6360        if (abi >= 0) {
6361            /*
6362             * If we have a matching instruction set, construct a subdir under the native
6363             * library root that corresponds to this instruction set.
6364             */
6365            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6366            final File subDir;
6367            if (useIsaSubdir) {
6368                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6369                createNativeLibrarySubdir(isaSubdir);
6370                subDir = isaSubdir;
6371            } else {
6372                subDir = nativeLibraryRoot;
6373            }
6374
6375            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6376            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6377                return copyRet;
6378            }
6379        }
6380
6381        return abi;
6382    }
6383
6384    private void killApplication(String pkgName, int appId, String reason) {
6385        // Request the ActivityManager to kill the process(only for existing packages)
6386        // so that we do not end up in a confused state while the user is still using the older
6387        // version of the application while the new one gets installed.
6388        IActivityManager am = ActivityManagerNative.getDefault();
6389        if (am != null) {
6390            try {
6391                am.killApplicationWithAppId(pkgName, appId, reason);
6392            } catch (RemoteException e) {
6393            }
6394        }
6395    }
6396
6397    void removePackageLI(PackageSetting ps, boolean chatty) {
6398        if (DEBUG_INSTALL) {
6399            if (chatty)
6400                Log.d(TAG, "Removing package " + ps.name);
6401        }
6402
6403        // writer
6404        synchronized (mPackages) {
6405            mPackages.remove(ps.name);
6406            if (ps.codePathString != null) {
6407                mAppDirs.remove(ps.codePathString);
6408            }
6409
6410            final PackageParser.Package pkg = ps.pkg;
6411            if (pkg != null) {
6412                cleanPackageDataStructuresLILPw(pkg, chatty);
6413            }
6414        }
6415    }
6416
6417    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6418        if (DEBUG_INSTALL) {
6419            if (chatty)
6420                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6421        }
6422
6423        // writer
6424        synchronized (mPackages) {
6425            mPackages.remove(pkg.applicationInfo.packageName);
6426            if (pkg.codePath != null) {
6427                mAppDirs.remove(pkg.codePath);
6428            }
6429            cleanPackageDataStructuresLILPw(pkg, chatty);
6430        }
6431    }
6432
6433    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6434        int N = pkg.providers.size();
6435        StringBuilder r = null;
6436        int i;
6437        for (i=0; i<N; i++) {
6438            PackageParser.Provider p = pkg.providers.get(i);
6439            mProviders.removeProvider(p);
6440            if (p.info.authority == null) {
6441
6442                /* There was another ContentProvider with this authority when
6443                 * this app was installed so this authority is null,
6444                 * Ignore it as we don't have to unregister the provider.
6445                 */
6446                continue;
6447            }
6448            String names[] = p.info.authority.split(";");
6449            for (int j = 0; j < names.length; j++) {
6450                if (mProvidersByAuthority.get(names[j]) == p) {
6451                    mProvidersByAuthority.remove(names[j]);
6452                    if (DEBUG_REMOVE) {
6453                        if (chatty)
6454                            Log.d(TAG, "Unregistered content provider: " + names[j]
6455                                    + ", className = " + p.info.name + ", isSyncable = "
6456                                    + p.info.isSyncable);
6457                    }
6458                }
6459            }
6460            if (DEBUG_REMOVE && chatty) {
6461                if (r == null) {
6462                    r = new StringBuilder(256);
6463                } else {
6464                    r.append(' ');
6465                }
6466                r.append(p.info.name);
6467            }
6468        }
6469        if (r != null) {
6470            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6471        }
6472
6473        N = pkg.services.size();
6474        r = null;
6475        for (i=0; i<N; i++) {
6476            PackageParser.Service s = pkg.services.get(i);
6477            mServices.removeService(s);
6478            if (chatty) {
6479                if (r == null) {
6480                    r = new StringBuilder(256);
6481                } else {
6482                    r.append(' ');
6483                }
6484                r.append(s.info.name);
6485            }
6486        }
6487        if (r != null) {
6488            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6489        }
6490
6491        N = pkg.receivers.size();
6492        r = null;
6493        for (i=0; i<N; i++) {
6494            PackageParser.Activity a = pkg.receivers.get(i);
6495            mReceivers.removeActivity(a, "receiver");
6496            if (DEBUG_REMOVE && chatty) {
6497                if (r == null) {
6498                    r = new StringBuilder(256);
6499                } else {
6500                    r.append(' ');
6501                }
6502                r.append(a.info.name);
6503            }
6504        }
6505        if (r != null) {
6506            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6507        }
6508
6509        N = pkg.activities.size();
6510        r = null;
6511        for (i=0; i<N; i++) {
6512            PackageParser.Activity a = pkg.activities.get(i);
6513            mActivities.removeActivity(a, "activity");
6514            if (DEBUG_REMOVE && chatty) {
6515                if (r == null) {
6516                    r = new StringBuilder(256);
6517                } else {
6518                    r.append(' ');
6519                }
6520                r.append(a.info.name);
6521            }
6522        }
6523        if (r != null) {
6524            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6525        }
6526
6527        N = pkg.permissions.size();
6528        r = null;
6529        for (i=0; i<N; i++) {
6530            PackageParser.Permission p = pkg.permissions.get(i);
6531            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6532            if (bp == null) {
6533                bp = mSettings.mPermissionTrees.get(p.info.name);
6534            }
6535            if (bp != null && bp.perm == p) {
6536                bp.perm = null;
6537                if (DEBUG_REMOVE && chatty) {
6538                    if (r == null) {
6539                        r = new StringBuilder(256);
6540                    } else {
6541                        r.append(' ');
6542                    }
6543                    r.append(p.info.name);
6544                }
6545            }
6546        }
6547        if (r != null) {
6548            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6549        }
6550
6551        N = pkg.instrumentation.size();
6552        r = null;
6553        for (i=0; i<N; i++) {
6554            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6555            mInstrumentation.remove(a.getComponentName());
6556            if (DEBUG_REMOVE && chatty) {
6557                if (r == null) {
6558                    r = new StringBuilder(256);
6559                } else {
6560                    r.append(' ');
6561                }
6562                r.append(a.info.name);
6563            }
6564        }
6565        if (r != null) {
6566            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6567        }
6568
6569        r = null;
6570        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6571            // Only system apps can hold shared libraries.
6572            if (pkg.libraryNames != null) {
6573                for (i=0; i<pkg.libraryNames.size(); i++) {
6574                    String name = pkg.libraryNames.get(i);
6575                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6576                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6577                        mSharedLibraries.remove(name);
6578                        if (DEBUG_REMOVE && chatty) {
6579                            if (r == null) {
6580                                r = new StringBuilder(256);
6581                            } else {
6582                                r.append(' ');
6583                            }
6584                            r.append(name);
6585                        }
6586                    }
6587                }
6588            }
6589        }
6590        if (r != null) {
6591            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6592        }
6593    }
6594
6595    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6596        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6597            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6598                return true;
6599            }
6600        }
6601        return false;
6602    }
6603
6604    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6605    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6606    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6607
6608    private void updatePermissionsLPw(String changingPkg,
6609            PackageParser.Package pkgInfo, int flags) {
6610        // Make sure there are no dangling permission trees.
6611        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6612        while (it.hasNext()) {
6613            final BasePermission bp = it.next();
6614            if (bp.packageSetting == null) {
6615                // We may not yet have parsed the package, so just see if
6616                // we still know about its settings.
6617                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6618            }
6619            if (bp.packageSetting == null) {
6620                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6621                        + " from package " + bp.sourcePackage);
6622                it.remove();
6623            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6624                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6625                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6626                            + " from package " + bp.sourcePackage);
6627                    flags |= UPDATE_PERMISSIONS_ALL;
6628                    it.remove();
6629                }
6630            }
6631        }
6632
6633        // Make sure all dynamic permissions have been assigned to a package,
6634        // and make sure there are no dangling permissions.
6635        it = mSettings.mPermissions.values().iterator();
6636        while (it.hasNext()) {
6637            final BasePermission bp = it.next();
6638            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6639                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6640                        + bp.name + " pkg=" + bp.sourcePackage
6641                        + " info=" + bp.pendingInfo);
6642                if (bp.packageSetting == null && bp.pendingInfo != null) {
6643                    final BasePermission tree = findPermissionTreeLP(bp.name);
6644                    if (tree != null && tree.perm != null) {
6645                        bp.packageSetting = tree.packageSetting;
6646                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6647                                new PermissionInfo(bp.pendingInfo));
6648                        bp.perm.info.packageName = tree.perm.info.packageName;
6649                        bp.perm.info.name = bp.name;
6650                        bp.uid = tree.uid;
6651                    }
6652                }
6653            }
6654            if (bp.packageSetting == null) {
6655                // We may not yet have parsed the package, so just see if
6656                // we still know about its settings.
6657                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6658            }
6659            if (bp.packageSetting == null) {
6660                Slog.w(TAG, "Removing dangling permission: " + bp.name
6661                        + " from package " + bp.sourcePackage);
6662                it.remove();
6663            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6664                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6665                    Slog.i(TAG, "Removing old permission: " + bp.name
6666                            + " from package " + bp.sourcePackage);
6667                    flags |= UPDATE_PERMISSIONS_ALL;
6668                    it.remove();
6669                }
6670            }
6671        }
6672
6673        // Now update the permissions for all packages, in particular
6674        // replace the granted permissions of the system packages.
6675        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6676            for (PackageParser.Package pkg : mPackages.values()) {
6677                if (pkg != pkgInfo) {
6678                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6679                }
6680            }
6681        }
6682
6683        if (pkgInfo != null) {
6684            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6685        }
6686    }
6687
6688    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6689        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6690        if (ps == null) {
6691            return;
6692        }
6693        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6694        HashSet<String> origPermissions = gp.grantedPermissions;
6695        boolean changedPermission = false;
6696
6697        if (replace) {
6698            ps.permissionsFixed = false;
6699            if (gp == ps) {
6700                origPermissions = new HashSet<String>(gp.grantedPermissions);
6701                gp.grantedPermissions.clear();
6702                gp.gids = mGlobalGids;
6703            }
6704        }
6705
6706        if (gp.gids == null) {
6707            gp.gids = mGlobalGids;
6708        }
6709
6710        final int N = pkg.requestedPermissions.size();
6711        for (int i=0; i<N; i++) {
6712            final String name = pkg.requestedPermissions.get(i);
6713            final boolean required = pkg.requestedPermissionsRequired.get(i);
6714            final BasePermission bp = mSettings.mPermissions.get(name);
6715            if (DEBUG_INSTALL) {
6716                if (gp != ps) {
6717                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6718                }
6719            }
6720
6721            if (bp == null || bp.packageSetting == null) {
6722                Slog.w(TAG, "Unknown permission " + name
6723                        + " in package " + pkg.packageName);
6724                continue;
6725            }
6726
6727            final String perm = bp.name;
6728            boolean allowed;
6729            boolean allowedSig = false;
6730            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6731            if (level == PermissionInfo.PROTECTION_NORMAL
6732                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6733                // We grant a normal or dangerous permission if any of the following
6734                // are true:
6735                // 1) The permission is required
6736                // 2) The permission is optional, but was granted in the past
6737                // 3) The permission is optional, but was requested by an
6738                //    app in /system (not /data)
6739                //
6740                // Otherwise, reject the permission.
6741                allowed = (required || origPermissions.contains(perm)
6742                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6743            } else if (bp.packageSetting == null) {
6744                // This permission is invalid; skip it.
6745                allowed = false;
6746            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6747                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6748                if (allowed) {
6749                    allowedSig = true;
6750                }
6751            } else {
6752                allowed = false;
6753            }
6754            if (DEBUG_INSTALL) {
6755                if (gp != ps) {
6756                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6757                }
6758            }
6759            if (allowed) {
6760                if (!isSystemApp(ps) && ps.permissionsFixed) {
6761                    // If this is an existing, non-system package, then
6762                    // we can't add any new permissions to it.
6763                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6764                        // Except...  if this is a permission that was added
6765                        // to the platform (note: need to only do this when
6766                        // updating the platform).
6767                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6768                    }
6769                }
6770                if (allowed) {
6771                    if (!gp.grantedPermissions.contains(perm)) {
6772                        changedPermission = true;
6773                        gp.grantedPermissions.add(perm);
6774                        gp.gids = appendInts(gp.gids, bp.gids);
6775                    } else if (!ps.haveGids) {
6776                        gp.gids = appendInts(gp.gids, bp.gids);
6777                    }
6778                } else {
6779                    Slog.w(TAG, "Not granting permission " + perm
6780                            + " to package " + pkg.packageName
6781                            + " because it was previously installed without");
6782                }
6783            } else {
6784                if (gp.grantedPermissions.remove(perm)) {
6785                    changedPermission = true;
6786                    gp.gids = removeInts(gp.gids, bp.gids);
6787                    Slog.i(TAG, "Un-granting permission " + perm
6788                            + " from package " + pkg.packageName
6789                            + " (protectionLevel=" + bp.protectionLevel
6790                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6791                            + ")");
6792                } else {
6793                    Slog.w(TAG, "Not granting permission " + perm
6794                            + " to package " + pkg.packageName
6795                            + " (protectionLevel=" + bp.protectionLevel
6796                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6797                            + ")");
6798                }
6799            }
6800        }
6801
6802        if ((changedPermission || replace) && !ps.permissionsFixed &&
6803                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6804            // This is the first that we have heard about this package, so the
6805            // permissions we have now selected are fixed until explicitly
6806            // changed.
6807            ps.permissionsFixed = true;
6808        }
6809        ps.haveGids = true;
6810    }
6811
6812    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6813        boolean allowed = false;
6814        final int NP = PackageParser.NEW_PERMISSIONS.length;
6815        for (int ip=0; ip<NP; ip++) {
6816            final PackageParser.NewPermissionInfo npi
6817                    = PackageParser.NEW_PERMISSIONS[ip];
6818            if (npi.name.equals(perm)
6819                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6820                allowed = true;
6821                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6822                        + pkg.packageName);
6823                break;
6824            }
6825        }
6826        return allowed;
6827    }
6828
6829    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6830                                          BasePermission bp, HashSet<String> origPermissions) {
6831        boolean allowed;
6832        allowed = (compareSignatures(
6833                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6834                        == PackageManager.SIGNATURE_MATCH)
6835                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6836                        == PackageManager.SIGNATURE_MATCH);
6837        if (!allowed && (bp.protectionLevel
6838                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6839            if (isSystemApp(pkg)) {
6840                // For updated system applications, a system permission
6841                // is granted only if it had been defined by the original application.
6842                if (isUpdatedSystemApp(pkg)) {
6843                    final PackageSetting sysPs = mSettings
6844                            .getDisabledSystemPkgLPr(pkg.packageName);
6845                    final GrantedPermissions origGp = sysPs.sharedUser != null
6846                            ? sysPs.sharedUser : sysPs;
6847
6848                    if (origGp.grantedPermissions.contains(perm)) {
6849                        // If the original was granted this permission, we take
6850                        // that grant decision as read and propagate it to the
6851                        // update.
6852                        allowed = true;
6853                    } else {
6854                        // The system apk may have been updated with an older
6855                        // version of the one on the data partition, but which
6856                        // granted a new system permission that it didn't have
6857                        // before.  In this case we do want to allow the app to
6858                        // now get the new permission if the ancestral apk is
6859                        // privileged to get it.
6860                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6861                            for (int j=0;
6862                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6863                                if (perm.equals(
6864                                        sysPs.pkg.requestedPermissions.get(j))) {
6865                                    allowed = true;
6866                                    break;
6867                                }
6868                            }
6869                        }
6870                    }
6871                } else {
6872                    allowed = isPrivilegedApp(pkg);
6873                }
6874            }
6875        }
6876        if (!allowed && (bp.protectionLevel
6877                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6878            // For development permissions, a development permission
6879            // is granted only if it was already granted.
6880            allowed = origPermissions.contains(perm);
6881        }
6882        return allowed;
6883    }
6884
6885    final class ActivityIntentResolver
6886            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6887        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6888                boolean defaultOnly, int userId) {
6889            if (!sUserManager.exists(userId)) return null;
6890            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6891            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6892        }
6893
6894        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6895                int userId) {
6896            if (!sUserManager.exists(userId)) return null;
6897            mFlags = flags;
6898            return super.queryIntent(intent, resolvedType,
6899                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6900        }
6901
6902        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6903                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6904            if (!sUserManager.exists(userId)) return null;
6905            if (packageActivities == null) {
6906                return null;
6907            }
6908            mFlags = flags;
6909            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6910            final int N = packageActivities.size();
6911            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6912                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6913
6914            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6915            for (int i = 0; i < N; ++i) {
6916                intentFilters = packageActivities.get(i).intents;
6917                if (intentFilters != null && intentFilters.size() > 0) {
6918                    PackageParser.ActivityIntentInfo[] array =
6919                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6920                    intentFilters.toArray(array);
6921                    listCut.add(array);
6922                }
6923            }
6924            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6925        }
6926
6927        public final void addActivity(PackageParser.Activity a, String type) {
6928            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6929            mActivities.put(a.getComponentName(), a);
6930            if (DEBUG_SHOW_INFO)
6931                Log.v(
6932                TAG, "  " + type + " " +
6933                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6934            if (DEBUG_SHOW_INFO)
6935                Log.v(TAG, "    Class=" + a.info.name);
6936            final int NI = a.intents.size();
6937            for (int j=0; j<NI; j++) {
6938                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6939                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6940                    intent.setPriority(0);
6941                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6942                            + a.className + " with priority > 0, forcing to 0");
6943                }
6944                if (DEBUG_SHOW_INFO) {
6945                    Log.v(TAG, "    IntentFilter:");
6946                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6947                }
6948                if (!intent.debugCheck()) {
6949                    Log.w(TAG, "==> For Activity " + a.info.name);
6950                }
6951                addFilter(intent);
6952            }
6953        }
6954
6955        public final void removeActivity(PackageParser.Activity a, String type) {
6956            mActivities.remove(a.getComponentName());
6957            if (DEBUG_SHOW_INFO) {
6958                Log.v(TAG, "  " + type + " "
6959                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6960                                : a.info.name) + ":");
6961                Log.v(TAG, "    Class=" + a.info.name);
6962            }
6963            final int NI = a.intents.size();
6964            for (int j=0; j<NI; j++) {
6965                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6966                if (DEBUG_SHOW_INFO) {
6967                    Log.v(TAG, "    IntentFilter:");
6968                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6969                }
6970                removeFilter(intent);
6971            }
6972        }
6973
6974        @Override
6975        protected boolean allowFilterResult(
6976                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6977            ActivityInfo filterAi = filter.activity.info;
6978            for (int i=dest.size()-1; i>=0; i--) {
6979                ActivityInfo destAi = dest.get(i).activityInfo;
6980                if (destAi.name == filterAi.name
6981                        && destAi.packageName == filterAi.packageName) {
6982                    return false;
6983                }
6984            }
6985            return true;
6986        }
6987
6988        @Override
6989        protected ActivityIntentInfo[] newArray(int size) {
6990            return new ActivityIntentInfo[size];
6991        }
6992
6993        @Override
6994        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6995            if (!sUserManager.exists(userId)) return true;
6996            PackageParser.Package p = filter.activity.owner;
6997            if (p != null) {
6998                PackageSetting ps = (PackageSetting)p.mExtras;
6999                if (ps != null) {
7000                    // System apps are never considered stopped for purposes of
7001                    // filtering, because there may be no way for the user to
7002                    // actually re-launch them.
7003                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7004                            && ps.getStopped(userId);
7005                }
7006            }
7007            return false;
7008        }
7009
7010        @Override
7011        protected boolean isPackageForFilter(String packageName,
7012                PackageParser.ActivityIntentInfo info) {
7013            return packageName.equals(info.activity.owner.packageName);
7014        }
7015
7016        @Override
7017        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7018                int match, int userId) {
7019            if (!sUserManager.exists(userId)) return null;
7020            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7021                return null;
7022            }
7023            final PackageParser.Activity activity = info.activity;
7024            if (mSafeMode && (activity.info.applicationInfo.flags
7025                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7026                return null;
7027            }
7028            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7029            if (ps == null) {
7030                return null;
7031            }
7032            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7033                    ps.readUserState(userId), userId);
7034            if (ai == null) {
7035                return null;
7036            }
7037            final ResolveInfo res = new ResolveInfo();
7038            res.activityInfo = ai;
7039            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7040                res.filter = info;
7041            }
7042            res.priority = info.getPriority();
7043            res.preferredOrder = activity.owner.mPreferredOrder;
7044            //System.out.println("Result: " + res.activityInfo.className +
7045            //                   " = " + res.priority);
7046            res.match = match;
7047            res.isDefault = info.hasDefault;
7048            res.labelRes = info.labelRes;
7049            res.nonLocalizedLabel = info.nonLocalizedLabel;
7050            if (userNeedsBadging(userId)) {
7051                res.noResourceId = true;
7052            } else {
7053                res.icon = info.icon;
7054            }
7055            res.system = isSystemApp(res.activityInfo.applicationInfo);
7056            return res;
7057        }
7058
7059        @Override
7060        protected void sortResults(List<ResolveInfo> results) {
7061            Collections.sort(results, mResolvePrioritySorter);
7062        }
7063
7064        @Override
7065        protected void dumpFilter(PrintWriter out, String prefix,
7066                PackageParser.ActivityIntentInfo filter) {
7067            out.print(prefix); out.print(
7068                    Integer.toHexString(System.identityHashCode(filter.activity)));
7069                    out.print(' ');
7070                    filter.activity.printComponentShortName(out);
7071                    out.print(" filter ");
7072                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7073        }
7074
7075//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7076//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7077//            final List<ResolveInfo> retList = Lists.newArrayList();
7078//            while (i.hasNext()) {
7079//                final ResolveInfo resolveInfo = i.next();
7080//                if (isEnabledLP(resolveInfo.activityInfo)) {
7081//                    retList.add(resolveInfo);
7082//                }
7083//            }
7084//            return retList;
7085//        }
7086
7087        // Keys are String (activity class name), values are Activity.
7088        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7089                = new HashMap<ComponentName, PackageParser.Activity>();
7090        private int mFlags;
7091    }
7092
7093    private final class ServiceIntentResolver
7094            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7096                boolean defaultOnly, int userId) {
7097            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7098            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7099        }
7100
7101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7102                int userId) {
7103            if (!sUserManager.exists(userId)) return null;
7104            mFlags = flags;
7105            return super.queryIntent(intent, resolvedType,
7106                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7107        }
7108
7109        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7110                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7111            if (!sUserManager.exists(userId)) return null;
7112            if (packageServices == null) {
7113                return null;
7114            }
7115            mFlags = flags;
7116            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7117            final int N = packageServices.size();
7118            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7119                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7120
7121            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7122            for (int i = 0; i < N; ++i) {
7123                intentFilters = packageServices.get(i).intents;
7124                if (intentFilters != null && intentFilters.size() > 0) {
7125                    PackageParser.ServiceIntentInfo[] array =
7126                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7127                    intentFilters.toArray(array);
7128                    listCut.add(array);
7129                }
7130            }
7131            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7132        }
7133
7134        public final void addService(PackageParser.Service s) {
7135            mServices.put(s.getComponentName(), s);
7136            if (DEBUG_SHOW_INFO) {
7137                Log.v(TAG, "  "
7138                        + (s.info.nonLocalizedLabel != null
7139                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7140                Log.v(TAG, "    Class=" + s.info.name);
7141            }
7142            final int NI = s.intents.size();
7143            int j;
7144            for (j=0; j<NI; j++) {
7145                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7146                if (DEBUG_SHOW_INFO) {
7147                    Log.v(TAG, "    IntentFilter:");
7148                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7149                }
7150                if (!intent.debugCheck()) {
7151                    Log.w(TAG, "==> For Service " + s.info.name);
7152                }
7153                addFilter(intent);
7154            }
7155        }
7156
7157        public final void removeService(PackageParser.Service s) {
7158            mServices.remove(s.getComponentName());
7159            if (DEBUG_SHOW_INFO) {
7160                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7161                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7162                Log.v(TAG, "    Class=" + s.info.name);
7163            }
7164            final int NI = s.intents.size();
7165            int j;
7166            for (j=0; j<NI; j++) {
7167                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7168                if (DEBUG_SHOW_INFO) {
7169                    Log.v(TAG, "    IntentFilter:");
7170                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7171                }
7172                removeFilter(intent);
7173            }
7174        }
7175
7176        @Override
7177        protected boolean allowFilterResult(
7178                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7179            ServiceInfo filterSi = filter.service.info;
7180            for (int i=dest.size()-1; i>=0; i--) {
7181                ServiceInfo destAi = dest.get(i).serviceInfo;
7182                if (destAi.name == filterSi.name
7183                        && destAi.packageName == filterSi.packageName) {
7184                    return false;
7185                }
7186            }
7187            return true;
7188        }
7189
7190        @Override
7191        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7192            return new PackageParser.ServiceIntentInfo[size];
7193        }
7194
7195        @Override
7196        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7197            if (!sUserManager.exists(userId)) return true;
7198            PackageParser.Package p = filter.service.owner;
7199            if (p != null) {
7200                PackageSetting ps = (PackageSetting)p.mExtras;
7201                if (ps != null) {
7202                    // System apps are never considered stopped for purposes of
7203                    // filtering, because there may be no way for the user to
7204                    // actually re-launch them.
7205                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7206                            && ps.getStopped(userId);
7207                }
7208            }
7209            return false;
7210        }
7211
7212        @Override
7213        protected boolean isPackageForFilter(String packageName,
7214                PackageParser.ServiceIntentInfo info) {
7215            return packageName.equals(info.service.owner.packageName);
7216        }
7217
7218        @Override
7219        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7220                int match, int userId) {
7221            if (!sUserManager.exists(userId)) return null;
7222            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7223            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7224                return null;
7225            }
7226            final PackageParser.Service service = info.service;
7227            if (mSafeMode && (service.info.applicationInfo.flags
7228                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7229                return null;
7230            }
7231            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7232            if (ps == null) {
7233                return null;
7234            }
7235            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7236                    ps.readUserState(userId), userId);
7237            if (si == null) {
7238                return null;
7239            }
7240            final ResolveInfo res = new ResolveInfo();
7241            res.serviceInfo = si;
7242            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7243                res.filter = filter;
7244            }
7245            res.priority = info.getPriority();
7246            res.preferredOrder = service.owner.mPreferredOrder;
7247            //System.out.println("Result: " + res.activityInfo.className +
7248            //                   " = " + res.priority);
7249            res.match = match;
7250            res.isDefault = info.hasDefault;
7251            res.labelRes = info.labelRes;
7252            res.nonLocalizedLabel = info.nonLocalizedLabel;
7253            res.icon = info.icon;
7254            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7255            return res;
7256        }
7257
7258        @Override
7259        protected void sortResults(List<ResolveInfo> results) {
7260            Collections.sort(results, mResolvePrioritySorter);
7261        }
7262
7263        @Override
7264        protected void dumpFilter(PrintWriter out, String prefix,
7265                PackageParser.ServiceIntentInfo filter) {
7266            out.print(prefix); out.print(
7267                    Integer.toHexString(System.identityHashCode(filter.service)));
7268                    out.print(' ');
7269                    filter.service.printComponentShortName(out);
7270                    out.print(" filter ");
7271                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7272        }
7273
7274//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7275//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7276//            final List<ResolveInfo> retList = Lists.newArrayList();
7277//            while (i.hasNext()) {
7278//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7279//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7280//                    retList.add(resolveInfo);
7281//                }
7282//            }
7283//            return retList;
7284//        }
7285
7286        // Keys are String (activity class name), values are Activity.
7287        private final HashMap<ComponentName, PackageParser.Service> mServices
7288                = new HashMap<ComponentName, PackageParser.Service>();
7289        private int mFlags;
7290    };
7291
7292    private final class ProviderIntentResolver
7293            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7294        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7295                boolean defaultOnly, int userId) {
7296            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7297            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7298        }
7299
7300        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7301                int userId) {
7302            if (!sUserManager.exists(userId))
7303                return null;
7304            mFlags = flags;
7305            return super.queryIntent(intent, resolvedType,
7306                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7307        }
7308
7309        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7310                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7311            if (!sUserManager.exists(userId))
7312                return null;
7313            if (packageProviders == null) {
7314                return null;
7315            }
7316            mFlags = flags;
7317            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7318            final int N = packageProviders.size();
7319            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7320                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7321
7322            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7323            for (int i = 0; i < N; ++i) {
7324                intentFilters = packageProviders.get(i).intents;
7325                if (intentFilters != null && intentFilters.size() > 0) {
7326                    PackageParser.ProviderIntentInfo[] array =
7327                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7328                    intentFilters.toArray(array);
7329                    listCut.add(array);
7330                }
7331            }
7332            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7333        }
7334
7335        public final void addProvider(PackageParser.Provider p) {
7336            if (mProviders.containsKey(p.getComponentName())) {
7337                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7338                return;
7339            }
7340
7341            mProviders.put(p.getComponentName(), p);
7342            if (DEBUG_SHOW_INFO) {
7343                Log.v(TAG, "  "
7344                        + (p.info.nonLocalizedLabel != null
7345                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7346                Log.v(TAG, "    Class=" + p.info.name);
7347            }
7348            final int NI = p.intents.size();
7349            int j;
7350            for (j = 0; j < NI; j++) {
7351                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7352                if (DEBUG_SHOW_INFO) {
7353                    Log.v(TAG, "    IntentFilter:");
7354                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7355                }
7356                if (!intent.debugCheck()) {
7357                    Log.w(TAG, "==> For Provider " + p.info.name);
7358                }
7359                addFilter(intent);
7360            }
7361        }
7362
7363        public final void removeProvider(PackageParser.Provider p) {
7364            mProviders.remove(p.getComponentName());
7365            if (DEBUG_SHOW_INFO) {
7366                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7367                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7368                Log.v(TAG, "    Class=" + p.info.name);
7369            }
7370            final int NI = p.intents.size();
7371            int j;
7372            for (j = 0; j < NI; j++) {
7373                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7374                if (DEBUG_SHOW_INFO) {
7375                    Log.v(TAG, "    IntentFilter:");
7376                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7377                }
7378                removeFilter(intent);
7379            }
7380        }
7381
7382        @Override
7383        protected boolean allowFilterResult(
7384                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7385            ProviderInfo filterPi = filter.provider.info;
7386            for (int i = dest.size() - 1; i >= 0; i--) {
7387                ProviderInfo destPi = dest.get(i).providerInfo;
7388                if (destPi.name == filterPi.name
7389                        && destPi.packageName == filterPi.packageName) {
7390                    return false;
7391                }
7392            }
7393            return true;
7394        }
7395
7396        @Override
7397        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7398            return new PackageParser.ProviderIntentInfo[size];
7399        }
7400
7401        @Override
7402        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7403            if (!sUserManager.exists(userId))
7404                return true;
7405            PackageParser.Package p = filter.provider.owner;
7406            if (p != null) {
7407                PackageSetting ps = (PackageSetting) p.mExtras;
7408                if (ps != null) {
7409                    // System apps are never considered stopped for purposes of
7410                    // filtering, because there may be no way for the user to
7411                    // actually re-launch them.
7412                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7413                            && ps.getStopped(userId);
7414                }
7415            }
7416            return false;
7417        }
7418
7419        @Override
7420        protected boolean isPackageForFilter(String packageName,
7421                PackageParser.ProviderIntentInfo info) {
7422            return packageName.equals(info.provider.owner.packageName);
7423        }
7424
7425        @Override
7426        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7427                int match, int userId) {
7428            if (!sUserManager.exists(userId))
7429                return null;
7430            final PackageParser.ProviderIntentInfo info = filter;
7431            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7432                return null;
7433            }
7434            final PackageParser.Provider provider = info.provider;
7435            if (mSafeMode && (provider.info.applicationInfo.flags
7436                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7437                return null;
7438            }
7439            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7440            if (ps == null) {
7441                return null;
7442            }
7443            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7444                    ps.readUserState(userId), userId);
7445            if (pi == null) {
7446                return null;
7447            }
7448            final ResolveInfo res = new ResolveInfo();
7449            res.providerInfo = pi;
7450            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7451                res.filter = filter;
7452            }
7453            res.priority = info.getPriority();
7454            res.preferredOrder = provider.owner.mPreferredOrder;
7455            res.match = match;
7456            res.isDefault = info.hasDefault;
7457            res.labelRes = info.labelRes;
7458            res.nonLocalizedLabel = info.nonLocalizedLabel;
7459            res.icon = info.icon;
7460            res.system = isSystemApp(res.providerInfo.applicationInfo);
7461            return res;
7462        }
7463
7464        @Override
7465        protected void sortResults(List<ResolveInfo> results) {
7466            Collections.sort(results, mResolvePrioritySorter);
7467        }
7468
7469        @Override
7470        protected void dumpFilter(PrintWriter out, String prefix,
7471                PackageParser.ProviderIntentInfo filter) {
7472            out.print(prefix);
7473            out.print(
7474                    Integer.toHexString(System.identityHashCode(filter.provider)));
7475            out.print(' ');
7476            filter.provider.printComponentShortName(out);
7477            out.print(" filter ");
7478            out.println(Integer.toHexString(System.identityHashCode(filter)));
7479        }
7480
7481        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7482                = new HashMap<ComponentName, PackageParser.Provider>();
7483        private int mFlags;
7484    };
7485
7486    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7487            new Comparator<ResolveInfo>() {
7488        public int compare(ResolveInfo r1, ResolveInfo r2) {
7489            int v1 = r1.priority;
7490            int v2 = r2.priority;
7491            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7492            if (v1 != v2) {
7493                return (v1 > v2) ? -1 : 1;
7494            }
7495            v1 = r1.preferredOrder;
7496            v2 = r2.preferredOrder;
7497            if (v1 != v2) {
7498                return (v1 > v2) ? -1 : 1;
7499            }
7500            if (r1.isDefault != r2.isDefault) {
7501                return r1.isDefault ? -1 : 1;
7502            }
7503            v1 = r1.match;
7504            v2 = r2.match;
7505            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7506            if (v1 != v2) {
7507                return (v1 > v2) ? -1 : 1;
7508            }
7509            if (r1.system != r2.system) {
7510                return r1.system ? -1 : 1;
7511            }
7512            return 0;
7513        }
7514    };
7515
7516    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7517            new Comparator<ProviderInfo>() {
7518        public int compare(ProviderInfo p1, ProviderInfo p2) {
7519            final int v1 = p1.initOrder;
7520            final int v2 = p2.initOrder;
7521            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7522        }
7523    };
7524
7525    static final void sendPackageBroadcast(String action, String pkg,
7526            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7527            int[] userIds) {
7528        IActivityManager am = ActivityManagerNative.getDefault();
7529        if (am != null) {
7530            try {
7531                if (userIds == null) {
7532                    userIds = am.getRunningUserIds();
7533                }
7534                for (int id : userIds) {
7535                    final Intent intent = new Intent(action,
7536                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7537                    if (extras != null) {
7538                        intent.putExtras(extras);
7539                    }
7540                    if (targetPkg != null) {
7541                        intent.setPackage(targetPkg);
7542                    }
7543                    // Modify the UID when posting to other users
7544                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7545                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7546                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7547                        intent.putExtra(Intent.EXTRA_UID, uid);
7548                    }
7549                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7550                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7551                    if (DEBUG_BROADCASTS) {
7552                        RuntimeException here = new RuntimeException("here");
7553                        here.fillInStackTrace();
7554                        Slog.d(TAG, "Sending to user " + id + ": "
7555                                + intent.toShortString(false, true, false, false)
7556                                + " " + intent.getExtras(), here);
7557                    }
7558                    am.broadcastIntent(null, intent, null, finishedReceiver,
7559                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7560                            finishedReceiver != null, false, id);
7561                }
7562            } catch (RemoteException ex) {
7563            }
7564        }
7565    }
7566
7567    /**
7568     * Check if the external storage media is available. This is true if there
7569     * is a mounted external storage medium or if the external storage is
7570     * emulated.
7571     */
7572    private boolean isExternalMediaAvailable() {
7573        return mMediaMounted || Environment.isExternalStorageEmulated();
7574    }
7575
7576    @Override
7577    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7578        // writer
7579        synchronized (mPackages) {
7580            if (!isExternalMediaAvailable()) {
7581                // If the external storage is no longer mounted at this point,
7582                // the caller may not have been able to delete all of this
7583                // packages files and can not delete any more.  Bail.
7584                return null;
7585            }
7586            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7587            if (lastPackage != null) {
7588                pkgs.remove(lastPackage);
7589            }
7590            if (pkgs.size() > 0) {
7591                return pkgs.get(0);
7592            }
7593        }
7594        return null;
7595    }
7596
7597    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7598        if (false) {
7599            RuntimeException here = new RuntimeException("here");
7600            here.fillInStackTrace();
7601            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7602                    + " andCode=" + andCode, here);
7603        }
7604        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7605                userId, andCode ? 1 : 0, packageName));
7606    }
7607
7608    void startCleaningPackages() {
7609        // reader
7610        synchronized (mPackages) {
7611            if (!isExternalMediaAvailable()) {
7612                return;
7613            }
7614            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7615                return;
7616            }
7617        }
7618        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7619        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7620        IActivityManager am = ActivityManagerNative.getDefault();
7621        if (am != null) {
7622            try {
7623                am.startService(null, intent, null, UserHandle.USER_OWNER);
7624            } catch (RemoteException e) {
7625            }
7626        }
7627    }
7628
7629    private final class AppDirObserver extends FileObserver {
7630        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7631            super(path, mask);
7632            mRootDir = path;
7633            mIsRom = isrom;
7634            mIsPrivileged = isPrivileged;
7635        }
7636
7637        public void onEvent(int event, String path) {
7638            String removedPackage = null;
7639            int removedAppId = -1;
7640            int[] removedUsers = null;
7641            String addedPackage = null;
7642            int addedAppId = -1;
7643            int[] addedUsers = null;
7644
7645            // TODO post a message to the handler to obtain serial ordering
7646            synchronized (mInstallLock) {
7647                String fullPathStr = null;
7648                File fullPath = null;
7649                if (path != null) {
7650                    fullPath = new File(mRootDir, path);
7651                    fullPathStr = fullPath.getPath();
7652                }
7653
7654                if (DEBUG_APP_DIR_OBSERVER)
7655                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7656
7657                if (!isApkFile(fullPath)) {
7658                    if (DEBUG_APP_DIR_OBSERVER)
7659                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7660                    return;
7661                }
7662
7663                // Ignore packages that are being installed or
7664                // have just been installed.
7665                if (ignoreCodePath(fullPathStr)) {
7666                    return;
7667                }
7668                PackageParser.Package p = null;
7669                PackageSetting ps = null;
7670                // reader
7671                synchronized (mPackages) {
7672                    p = mAppDirs.get(fullPathStr);
7673                    if (p != null) {
7674                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7675                        if (ps != null) {
7676                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7677                        } else {
7678                            removedUsers = sUserManager.getUserIds();
7679                        }
7680                    }
7681                    addedUsers = sUserManager.getUserIds();
7682                }
7683                if ((event&REMOVE_EVENTS) != 0) {
7684                    if (ps != null) {
7685                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7686                        removePackageLI(ps, true);
7687                        removedPackage = ps.name;
7688                        removedAppId = ps.appId;
7689                    }
7690                }
7691
7692                if ((event&ADD_EVENTS) != 0) {
7693                    if (p == null) {
7694                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7695                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7696                        if (mIsRom) {
7697                            flags |= PackageParser.PARSE_IS_SYSTEM
7698                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7699                            if (mIsPrivileged) {
7700                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7701                            }
7702                        }
7703                        try {
7704                            p = scanPackageLI(fullPath, flags,
7705                                    SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7706                                    System.currentTimeMillis(), UserHandle.ALL, null);
7707                        } catch (PackageManagerException e) {
7708                            Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage());
7709                            p = null;
7710                        }
7711                        if (p != null) {
7712                            /*
7713                             * TODO this seems dangerous as the package may have
7714                             * changed since we last acquired the mPackages
7715                             * lock.
7716                             */
7717                            // writer
7718                            synchronized (mPackages) {
7719                                updatePermissionsLPw(p.packageName, p,
7720                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7721                            }
7722                            addedPackage = p.applicationInfo.packageName;
7723                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7724                        }
7725                    }
7726                }
7727
7728                // reader
7729                synchronized (mPackages) {
7730                    mSettings.writeLPr();
7731                }
7732            }
7733
7734            if (removedPackage != null) {
7735                Bundle extras = new Bundle(1);
7736                extras.putInt(Intent.EXTRA_UID, removedAppId);
7737                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7738                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7739                        extras, null, null, removedUsers);
7740            }
7741            if (addedPackage != null) {
7742                Bundle extras = new Bundle(1);
7743                extras.putInt(Intent.EXTRA_UID, addedAppId);
7744                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7745                        extras, null, null, addedUsers);
7746            }
7747        }
7748
7749        private final String mRootDir;
7750        private final boolean mIsRom;
7751        private final boolean mIsPrivileged;
7752    }
7753
7754    @Override
7755    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7756            String installerPackageName, VerificationParams verificationParams,
7757            String packageAbiOverride) {
7758        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7759                null);
7760
7761        final File originFile = new File(originPath);
7762        final int uid = Binder.getCallingUid();
7763        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7764            try {
7765                if (observer != null) {
7766                    observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null);
7767                }
7768            } catch (RemoteException re) {
7769            }
7770            return;
7771        }
7772
7773        UserHandle user;
7774        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7775            user = UserHandle.ALL;
7776        } else {
7777            user = new UserHandle(UserHandle.getUserId(uid));
7778        }
7779
7780        final int filteredFlags;
7781        if (uid == Process.SHELL_UID || uid == 0) {
7782            if (DEBUG_INSTALL) {
7783                Slog.v(TAG, "Install from ADB");
7784            }
7785            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7786        } else {
7787            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7788        }
7789
7790        verificationParams.setInstallerUid(uid);
7791
7792        final Message msg = mHandler.obtainMessage(INIT_COPY);
7793        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7794                installerPackageName, verificationParams, user, packageAbiOverride);
7795        mHandler.sendMessage(msg);
7796    }
7797
7798    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7799            InstallSessionParams params, String installerPackageName, int installerUid,
7800            UserHandle user) {
7801        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7802                params.referrerUri, installerUid, null);
7803
7804        final Message msg = mHandler.obtainMessage(INIT_COPY);
7805        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7806                installerPackageName, verifParams, user, params.abiOverride);
7807        mHandler.sendMessage(msg);
7808    }
7809
7810    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7811        Bundle extras = new Bundle(1);
7812        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7813
7814        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7815                packageName, extras, null, null, new int[] {userId});
7816        try {
7817            IActivityManager am = ActivityManagerNative.getDefault();
7818            final boolean isSystem =
7819                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7820            if (isSystem && am.isUserRunning(userId, false)) {
7821                // The just-installed/enabled app is bundled on the system, so presumed
7822                // to be able to run automatically without needing an explicit launch.
7823                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7824                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7825                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7826                        .setPackage(packageName);
7827                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7828                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7829            }
7830        } catch (RemoteException e) {
7831            // shouldn't happen
7832            Slog.w(TAG, "Unable to bootstrap installed package", e);
7833        }
7834    }
7835
7836    @Override
7837    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7838            int userId) {
7839        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7840        PackageSetting pkgSetting;
7841        final int uid = Binder.getCallingUid();
7842        if (UserHandle.getUserId(uid) != userId) {
7843            mContext.enforceCallingOrSelfPermission(
7844                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7845                    "setApplicationBlockedSetting for user " + userId);
7846        }
7847
7848        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7849            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7850            return false;
7851        }
7852
7853        long callingId = Binder.clearCallingIdentity();
7854        try {
7855            boolean sendAdded = false;
7856            boolean sendRemoved = false;
7857            // writer
7858            synchronized (mPackages) {
7859                pkgSetting = mSettings.mPackages.get(packageName);
7860                if (pkgSetting == null) {
7861                    return false;
7862                }
7863                if (pkgSetting.getBlocked(userId) != blocked) {
7864                    pkgSetting.setBlocked(blocked, userId);
7865                    mSettings.writePackageRestrictionsLPr(userId);
7866                    if (blocked) {
7867                        sendRemoved = true;
7868                    } else {
7869                        sendAdded = true;
7870                    }
7871                }
7872            }
7873            if (sendAdded) {
7874                sendPackageAddedForUser(packageName, pkgSetting, userId);
7875                return true;
7876            }
7877            if (sendRemoved) {
7878                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7879                        "blocking pkg");
7880                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7881            }
7882        } finally {
7883            Binder.restoreCallingIdentity(callingId);
7884        }
7885        return false;
7886    }
7887
7888    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7889            int userId) {
7890        final PackageRemovedInfo info = new PackageRemovedInfo();
7891        info.removedPackage = packageName;
7892        info.removedUsers = new int[] {userId};
7893        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7894        info.sendBroadcast(false, false, false);
7895    }
7896
7897    /**
7898     * Returns true if application is not found or there was an error. Otherwise it returns
7899     * the blocked state of the package for the given user.
7900     */
7901    @Override
7902    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7903        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7904        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7905                "getApplicationBlocked for user " + userId);
7906        PackageSetting pkgSetting;
7907        long callingId = Binder.clearCallingIdentity();
7908        try {
7909            // writer
7910            synchronized (mPackages) {
7911                pkgSetting = mSettings.mPackages.get(packageName);
7912                if (pkgSetting == null) {
7913                    return true;
7914                }
7915                return pkgSetting.getBlocked(userId);
7916            }
7917        } finally {
7918            Binder.restoreCallingIdentity(callingId);
7919        }
7920    }
7921
7922    /**
7923     * @hide
7924     */
7925    @Override
7926    public int installExistingPackageAsUser(String packageName, int userId) {
7927        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7928                null);
7929        PackageSetting pkgSetting;
7930        final int uid = Binder.getCallingUid();
7931        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7932        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7933            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7934        }
7935
7936        long callingId = Binder.clearCallingIdentity();
7937        try {
7938            boolean sendAdded = false;
7939            Bundle extras = new Bundle(1);
7940
7941            // writer
7942            synchronized (mPackages) {
7943                pkgSetting = mSettings.mPackages.get(packageName);
7944                if (pkgSetting == null) {
7945                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7946                }
7947                if (!pkgSetting.getInstalled(userId)) {
7948                    pkgSetting.setInstalled(true, userId);
7949                    pkgSetting.setBlocked(false, userId);
7950                    mSettings.writePackageRestrictionsLPr(userId);
7951                    sendAdded = true;
7952                }
7953            }
7954
7955            if (sendAdded) {
7956                sendPackageAddedForUser(packageName, pkgSetting, userId);
7957            }
7958        } finally {
7959            Binder.restoreCallingIdentity(callingId);
7960        }
7961
7962        return PackageManager.INSTALL_SUCCEEDED;
7963    }
7964
7965    boolean isUserRestricted(int userId, String restrictionKey) {
7966        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7967        if (restrictions.getBoolean(restrictionKey, false)) {
7968            Log.w(TAG, "User is restricted: " + restrictionKey);
7969            return true;
7970        }
7971        return false;
7972    }
7973
7974    @Override
7975    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7976        mContext.enforceCallingOrSelfPermission(
7977                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7978                "Only package verification agents can verify applications");
7979
7980        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7981        final PackageVerificationResponse response = new PackageVerificationResponse(
7982                verificationCode, Binder.getCallingUid());
7983        msg.arg1 = id;
7984        msg.obj = response;
7985        mHandler.sendMessage(msg);
7986    }
7987
7988    @Override
7989    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7990            long millisecondsToDelay) {
7991        mContext.enforceCallingOrSelfPermission(
7992                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7993                "Only package verification agents can extend verification timeouts");
7994
7995        final PackageVerificationState state = mPendingVerification.get(id);
7996        final PackageVerificationResponse response = new PackageVerificationResponse(
7997                verificationCodeAtTimeout, Binder.getCallingUid());
7998
7999        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8000            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8001        }
8002        if (millisecondsToDelay < 0) {
8003            millisecondsToDelay = 0;
8004        }
8005        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8006                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8007            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8008        }
8009
8010        if ((state != null) && !state.timeoutExtended()) {
8011            state.extendTimeout();
8012
8013            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8014            msg.arg1 = id;
8015            msg.obj = response;
8016            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8017        }
8018    }
8019
8020    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8021            int verificationCode, UserHandle user) {
8022        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8023        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8024        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8025        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8026        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8027
8028        mContext.sendBroadcastAsUser(intent, user,
8029                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8030    }
8031
8032    private ComponentName matchComponentForVerifier(String packageName,
8033            List<ResolveInfo> receivers) {
8034        ActivityInfo targetReceiver = null;
8035
8036        final int NR = receivers.size();
8037        for (int i = 0; i < NR; i++) {
8038            final ResolveInfo info = receivers.get(i);
8039            if (info.activityInfo == null) {
8040                continue;
8041            }
8042
8043            if (packageName.equals(info.activityInfo.packageName)) {
8044                targetReceiver = info.activityInfo;
8045                break;
8046            }
8047        }
8048
8049        if (targetReceiver == null) {
8050            return null;
8051        }
8052
8053        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8054    }
8055
8056    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8057            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8058        if (pkgInfo.verifiers.length == 0) {
8059            return null;
8060        }
8061
8062        final int N = pkgInfo.verifiers.length;
8063        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8064        for (int i = 0; i < N; i++) {
8065            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8066
8067            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8068                    receivers);
8069            if (comp == null) {
8070                continue;
8071            }
8072
8073            final int verifierUid = getUidForVerifier(verifierInfo);
8074            if (verifierUid == -1) {
8075                continue;
8076            }
8077
8078            if (DEBUG_VERIFY) {
8079                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8080                        + " with the correct signature");
8081            }
8082            sufficientVerifiers.add(comp);
8083            verificationState.addSufficientVerifier(verifierUid);
8084        }
8085
8086        return sufficientVerifiers;
8087    }
8088
8089    private int getUidForVerifier(VerifierInfo verifierInfo) {
8090        synchronized (mPackages) {
8091            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8092            if (pkg == null) {
8093                return -1;
8094            } else if (pkg.mSignatures.length != 1) {
8095                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8096                        + " has more than one signature; ignoring");
8097                return -1;
8098            }
8099
8100            /*
8101             * If the public key of the package's signature does not match
8102             * our expected public key, then this is a different package and
8103             * we should skip.
8104             */
8105
8106            final byte[] expectedPublicKey;
8107            try {
8108                final Signature verifierSig = pkg.mSignatures[0];
8109                final PublicKey publicKey = verifierSig.getPublicKey();
8110                expectedPublicKey = publicKey.getEncoded();
8111            } catch (CertificateException e) {
8112                return -1;
8113            }
8114
8115            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8116
8117            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8118                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8119                        + " does not have the expected public key; ignoring");
8120                return -1;
8121            }
8122
8123            return pkg.applicationInfo.uid;
8124        }
8125    }
8126
8127    @Override
8128    public void finishPackageInstall(int token) {
8129        enforceSystemOrRoot("Only the system is allowed to finish installs");
8130
8131        if (DEBUG_INSTALL) {
8132            Slog.v(TAG, "BM finishing package install for " + token);
8133        }
8134
8135        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8136        mHandler.sendMessage(msg);
8137    }
8138
8139    /**
8140     * Get the verification agent timeout.
8141     *
8142     * @return verification timeout in milliseconds
8143     */
8144    private long getVerificationTimeout() {
8145        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8146                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8147                DEFAULT_VERIFICATION_TIMEOUT);
8148    }
8149
8150    /**
8151     * Get the default verification agent response code.
8152     *
8153     * @return default verification response code
8154     */
8155    private int getDefaultVerificationResponse() {
8156        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8157                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8158                DEFAULT_VERIFICATION_RESPONSE);
8159    }
8160
8161    /**
8162     * Check whether or not package verification has been enabled.
8163     *
8164     * @return true if verification should be performed
8165     */
8166    private boolean isVerificationEnabled(int userId, int flags) {
8167        if (!DEFAULT_VERIFY_ENABLE) {
8168            return false;
8169        }
8170
8171        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8172
8173        // Check if installing from ADB
8174        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8175            // Do not run verification in a test harness environment
8176            if (ActivityManager.isRunningInTestHarness()) {
8177                return false;
8178            }
8179            if (ensureVerifyAppsEnabled) {
8180                return true;
8181            }
8182            // Check if the developer does not want package verification for ADB installs
8183            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8184                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8185                return false;
8186            }
8187        }
8188
8189        if (ensureVerifyAppsEnabled) {
8190            return true;
8191        }
8192
8193        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8194                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8195    }
8196
8197    /**
8198     * Get the "allow unknown sources" setting.
8199     *
8200     * @return the current "allow unknown sources" setting
8201     */
8202    private int getUnknownSourcesSettings() {
8203        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8204                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8205                -1);
8206    }
8207
8208    @Override
8209    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8210        final int uid = Binder.getCallingUid();
8211        // writer
8212        synchronized (mPackages) {
8213            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8214            if (targetPackageSetting == null) {
8215                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8216            }
8217
8218            PackageSetting installerPackageSetting;
8219            if (installerPackageName != null) {
8220                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8221                if (installerPackageSetting == null) {
8222                    throw new IllegalArgumentException("Unknown installer package: "
8223                            + installerPackageName);
8224                }
8225            } else {
8226                installerPackageSetting = null;
8227            }
8228
8229            Signature[] callerSignature;
8230            Object obj = mSettings.getUserIdLPr(uid);
8231            if (obj != null) {
8232                if (obj instanceof SharedUserSetting) {
8233                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8234                } else if (obj instanceof PackageSetting) {
8235                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8236                } else {
8237                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8238                }
8239            } else {
8240                throw new SecurityException("Unknown calling uid " + uid);
8241            }
8242
8243            // Verify: can't set installerPackageName to a package that is
8244            // not signed with the same cert as the caller.
8245            if (installerPackageSetting != null) {
8246                if (compareSignatures(callerSignature,
8247                        installerPackageSetting.signatures.mSignatures)
8248                        != PackageManager.SIGNATURE_MATCH) {
8249                    throw new SecurityException(
8250                            "Caller does not have same cert as new installer package "
8251                            + installerPackageName);
8252                }
8253            }
8254
8255            // Verify: if target already has an installer package, it must
8256            // be signed with the same cert as the caller.
8257            if (targetPackageSetting.installerPackageName != null) {
8258                PackageSetting setting = mSettings.mPackages.get(
8259                        targetPackageSetting.installerPackageName);
8260                // If the currently set package isn't valid, then it's always
8261                // okay to change it.
8262                if (setting != null) {
8263                    if (compareSignatures(callerSignature,
8264                            setting.signatures.mSignatures)
8265                            != PackageManager.SIGNATURE_MATCH) {
8266                        throw new SecurityException(
8267                                "Caller does not have same cert as old installer package "
8268                                + targetPackageSetting.installerPackageName);
8269                    }
8270                }
8271            }
8272
8273            // Okay!
8274            targetPackageSetting.installerPackageName = installerPackageName;
8275            scheduleWriteSettingsLocked();
8276        }
8277    }
8278
8279    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8280        // Queue up an async operation since the package installation may take a little while.
8281        mHandler.post(new Runnable() {
8282            public void run() {
8283                mHandler.removeCallbacks(this);
8284                 // Result object to be returned
8285                PackageInstalledInfo res = new PackageInstalledInfo();
8286                res.returnCode = currentStatus;
8287                res.uid = -1;
8288                res.pkg = null;
8289                res.removedInfo = new PackageRemovedInfo();
8290                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8291                    args.doPreInstall(res.returnCode);
8292                    synchronized (mInstallLock) {
8293                        installPackageLI(args, true, res);
8294                    }
8295                    args.doPostInstall(res.returnCode, res.uid);
8296                }
8297
8298                // A restore should be performed at this point if (a) the install
8299                // succeeded, (b) the operation is not an update, and (c) the new
8300                // package has a backupAgent defined.
8301                final boolean update = res.removedInfo.removedPackage != null;
8302                boolean doRestore = (!update
8303                        && res.pkg != null
8304                        && res.pkg.applicationInfo.backupAgentName != null);
8305
8306                // Set up the post-install work request bookkeeping.  This will be used
8307                // and cleaned up by the post-install event handling regardless of whether
8308                // there's a restore pass performed.  Token values are >= 1.
8309                int token;
8310                if (mNextInstallToken < 0) mNextInstallToken = 1;
8311                token = mNextInstallToken++;
8312
8313                PostInstallData data = new PostInstallData(args, res);
8314                mRunningInstalls.put(token, data);
8315                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8316
8317                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8318                    // Pass responsibility to the Backup Manager.  It will perform a
8319                    // restore if appropriate, then pass responsibility back to the
8320                    // Package Manager to run the post-install observer callbacks
8321                    // and broadcasts.
8322                    IBackupManager bm = IBackupManager.Stub.asInterface(
8323                            ServiceManager.getService(Context.BACKUP_SERVICE));
8324                    if (bm != null) {
8325                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8326                                + " to BM for possible restore");
8327                        try {
8328                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8329                        } catch (RemoteException e) {
8330                            // can't happen; the backup manager is local
8331                        } catch (Exception e) {
8332                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8333                            doRestore = false;
8334                        }
8335                    } else {
8336                        Slog.e(TAG, "Backup Manager not found!");
8337                        doRestore = false;
8338                    }
8339                }
8340
8341                if (!doRestore) {
8342                    // No restore possible, or the Backup Manager was mysteriously not
8343                    // available -- just fire the post-install work request directly.
8344                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8345                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8346                    mHandler.sendMessage(msg);
8347                }
8348            }
8349        });
8350    }
8351
8352    private abstract class HandlerParams {
8353        private static final int MAX_RETRIES = 4;
8354
8355        /**
8356         * Number of times startCopy() has been attempted and had a non-fatal
8357         * error.
8358         */
8359        private int mRetries = 0;
8360
8361        /** User handle for the user requesting the information or installation. */
8362        private final UserHandle mUser;
8363
8364        HandlerParams(UserHandle user) {
8365            mUser = user;
8366        }
8367
8368        UserHandle getUser() {
8369            return mUser;
8370        }
8371
8372        final boolean startCopy() {
8373            boolean res;
8374            try {
8375                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8376
8377                if (++mRetries > MAX_RETRIES) {
8378                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8379                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8380                    handleServiceError();
8381                    return false;
8382                } else {
8383                    handleStartCopy();
8384                    res = true;
8385                }
8386            } catch (RemoteException e) {
8387                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8388                mHandler.sendEmptyMessage(MCS_RECONNECT);
8389                res = false;
8390            }
8391            handleReturnCode();
8392            return res;
8393        }
8394
8395        final void serviceError() {
8396            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8397            handleServiceError();
8398            handleReturnCode();
8399        }
8400
8401        abstract void handleStartCopy() throws RemoteException;
8402        abstract void handleServiceError();
8403        abstract void handleReturnCode();
8404    }
8405
8406    class MeasureParams extends HandlerParams {
8407        private final PackageStats mStats;
8408        private boolean mSuccess;
8409
8410        private final IPackageStatsObserver mObserver;
8411
8412        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8413            super(new UserHandle(stats.userHandle));
8414            mObserver = observer;
8415            mStats = stats;
8416        }
8417
8418        @Override
8419        public String toString() {
8420            return "MeasureParams{"
8421                + Integer.toHexString(System.identityHashCode(this))
8422                + " " + mStats.packageName + "}";
8423        }
8424
8425        @Override
8426        void handleStartCopy() throws RemoteException {
8427            synchronized (mInstallLock) {
8428                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8429            }
8430
8431            if (mSuccess) {
8432                final boolean mounted;
8433                if (Environment.isExternalStorageEmulated()) {
8434                    mounted = true;
8435                } else {
8436                    final String status = Environment.getExternalStorageState();
8437                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8438                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8439                }
8440
8441                if (mounted) {
8442                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8443
8444                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8445                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8446
8447                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8448                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8449
8450                    // Always subtract cache size, since it's a subdirectory
8451                    mStats.externalDataSize -= mStats.externalCacheSize;
8452
8453                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8454                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8455
8456                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8457                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8458                }
8459            }
8460        }
8461
8462        @Override
8463        void handleReturnCode() {
8464            if (mObserver != null) {
8465                try {
8466                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8467                } catch (RemoteException e) {
8468                    Slog.i(TAG, "Observer no longer exists.");
8469                }
8470            }
8471        }
8472
8473        @Override
8474        void handleServiceError() {
8475            Slog.e(TAG, "Could not measure application " + mStats.packageName
8476                            + " external storage");
8477        }
8478    }
8479
8480    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8481            throws RemoteException {
8482        long result = 0;
8483        for (File path : paths) {
8484            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8485        }
8486        return result;
8487    }
8488
8489    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8490        for (File path : paths) {
8491            try {
8492                mcs.clearDirectory(path.getAbsolutePath());
8493            } catch (RemoteException e) {
8494            }
8495        }
8496    }
8497
8498    class InstallParams extends HandlerParams {
8499        /**
8500         * Location where install is coming from, before it has been
8501         * copied/renamed into place. This could be a single monolithic APK
8502         * file, or a cluster directory. This location may be untrusted.
8503         */
8504        final File originFile;
8505
8506        /**
8507         * Flag indicating that {@link #originFile} has already been staged,
8508         * meaning downstream users don't need to defensively copy the contents.
8509         */
8510        boolean originStaged;
8511
8512        final IPackageInstallObserver2 observer;
8513        int flags;
8514        final String installerPackageName;
8515        final VerificationParams verificationParams;
8516        private InstallArgs mArgs;
8517        private int mRet;
8518        final String packageAbiOverride;
8519        boolean multiArch;
8520
8521        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8522                int flags, String installerPackageName, VerificationParams verificationParams,
8523                UserHandle user, String packageAbiOverride) {
8524            super(user);
8525            this.originFile = Preconditions.checkNotNull(originFile);
8526            this.originStaged = originStaged;
8527            this.observer = observer;
8528            this.flags = flags;
8529            this.installerPackageName = installerPackageName;
8530            this.verificationParams = verificationParams;
8531            this.packageAbiOverride = packageAbiOverride;
8532        }
8533
8534        @Override
8535        public String toString() {
8536            return "InstallParams{"
8537                + Integer.toHexString(System.identityHashCode(this))
8538                + " " + originFile + "}";
8539        }
8540
8541        public ManifestDigest getManifestDigest() {
8542            if (verificationParams == null) {
8543                return null;
8544            }
8545            return verificationParams.getManifestDigest();
8546        }
8547
8548        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8549            String packageName = pkgLite.packageName;
8550            int installLocation = pkgLite.installLocation;
8551            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8552            // reader
8553            synchronized (mPackages) {
8554                PackageParser.Package pkg = mPackages.get(packageName);
8555                if (pkg != null) {
8556                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8557                        // Check for downgrading.
8558                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8559                            if (pkgLite.versionCode < pkg.mVersionCode) {
8560                                Slog.w(TAG, "Can't install update of " + packageName
8561                                        + " update version " + pkgLite.versionCode
8562                                        + " is older than installed version "
8563                                        + pkg.mVersionCode);
8564                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8565                            }
8566                        }
8567                        // Check for updated system application.
8568                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8569                            if (onSd) {
8570                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8571                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8572                            }
8573                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8574                        } else {
8575                            if (onSd) {
8576                                // Install flag overrides everything.
8577                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8578                            }
8579                            // If current upgrade specifies particular preference
8580                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8581                                // Application explicitly specified internal.
8582                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8583                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8584                                // App explictly prefers external. Let policy decide
8585                            } else {
8586                                // Prefer previous location
8587                                if (isExternal(pkg)) {
8588                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8589                                }
8590                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8591                            }
8592                        }
8593                    } else {
8594                        // Invalid install. Return error code
8595                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8596                    }
8597                }
8598            }
8599            // All the special cases have been taken care of.
8600            // Return result based on recommended install location.
8601            if (onSd) {
8602                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8603            }
8604            return pkgLite.recommendedInstallLocation;
8605        }
8606
8607        private long getMemoryLowThreshold() {
8608            final DeviceStorageMonitorInternal
8609                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8610            if (dsm == null) {
8611                return 0L;
8612            }
8613            return dsm.getMemoryLowThreshold();
8614        }
8615
8616        /*
8617         * Invoke remote method to get package information and install
8618         * location values. Override install location based on default
8619         * policy if needed and then create install arguments based
8620         * on the install location.
8621         */
8622        public void handleStartCopy() throws RemoteException {
8623            int ret = PackageManager.INSTALL_SUCCEEDED;
8624            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8625            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8626            PackageInfoLite pkgLite = null;
8627
8628            if (onInt && onSd) {
8629                // Check if both bits are set.
8630                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8631                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8632            } else {
8633                final long lowThreshold = getMemoryLowThreshold();
8634                if (lowThreshold == 0L) {
8635                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8636                }
8637
8638                // Remote call to find out default install location
8639                final String originPath = originFile.getAbsolutePath();
8640                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8641                        packageAbiOverride);
8642                // Keep track of whether this package is a multiArch package until
8643                // we perform a full scan of it. We need to do this because we might
8644                // end up extracting the package shared libraries before we perform
8645                // a full scan.
8646                multiArch = pkgLite.multiArch;
8647
8648                /*
8649                 * If we have too little free space, try to free cache
8650                 * before giving up.
8651                 */
8652                if (pkgLite.recommendedInstallLocation
8653                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8654                    final long size = mContainerService.calculateInstalledSize(
8655                            originPath, isForwardLocked(), packageAbiOverride);
8656                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8657                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8658                                lowThreshold, packageAbiOverride);
8659                    }
8660                    /*
8661                     * The cache free must have deleted the file we
8662                     * downloaded to install.
8663                     *
8664                     * TODO: fix the "freeCache" call to not delete
8665                     *       the file we care about.
8666                     */
8667                    if (pkgLite.recommendedInstallLocation
8668                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8669                        pkgLite.recommendedInstallLocation
8670                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8671                    }
8672                }
8673            }
8674
8675            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8676                int loc = pkgLite.recommendedInstallLocation;
8677                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8678                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8679                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8680                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8681                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8682                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8683                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8684                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8685                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8686                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8687                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8688                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8689                } else {
8690                    // Override with defaults if needed.
8691                    loc = installLocationPolicy(pkgLite, flags);
8692                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8693                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8694                    } else if (!onSd && !onInt) {
8695                        // Override install location with flags
8696                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8697                            // Set the flag to install on external media.
8698                            flags |= PackageManager.INSTALL_EXTERNAL;
8699                            flags &= ~PackageManager.INSTALL_INTERNAL;
8700                        } else {
8701                            // Make sure the flag for installing on external
8702                            // media is unset
8703                            flags |= PackageManager.INSTALL_INTERNAL;
8704                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8705                        }
8706                    }
8707                }
8708            }
8709
8710            final InstallArgs args = createInstallArgs(this);
8711            mArgs = args;
8712
8713            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8714                 /*
8715                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8716                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8717                 */
8718                int userIdentifier = getUser().getIdentifier();
8719                if (userIdentifier == UserHandle.USER_ALL
8720                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8721                    userIdentifier = UserHandle.USER_OWNER;
8722                }
8723
8724                /*
8725                 * Determine if we have any installed package verifiers. If we
8726                 * do, then we'll defer to them to verify the packages.
8727                 */
8728                final int requiredUid = mRequiredVerifierPackage == null ? -1
8729                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8730                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8731                    // TODO: send verifier the install session instead of uri
8732                    final Intent verification = new Intent(
8733                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8734                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8735                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8736
8737                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8738                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8739                            0 /* TODO: Which userId? */);
8740
8741                    if (DEBUG_VERIFY) {
8742                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8743                                + verification.toString() + " with " + pkgLite.verifiers.length
8744                                + " optional verifiers");
8745                    }
8746
8747                    final int verificationId = mPendingVerificationToken++;
8748
8749                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8750
8751                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8752                            installerPackageName);
8753
8754                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8755
8756                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8757                            pkgLite.packageName);
8758
8759                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8760                            pkgLite.versionCode);
8761
8762                    if (verificationParams != null) {
8763                        if (verificationParams.getVerificationURI() != null) {
8764                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8765                                 verificationParams.getVerificationURI());
8766                        }
8767                        if (verificationParams.getOriginatingURI() != null) {
8768                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8769                                  verificationParams.getOriginatingURI());
8770                        }
8771                        if (verificationParams.getReferrer() != null) {
8772                            verification.putExtra(Intent.EXTRA_REFERRER,
8773                                  verificationParams.getReferrer());
8774                        }
8775                        if (verificationParams.getOriginatingUid() >= 0) {
8776                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8777                                  verificationParams.getOriginatingUid());
8778                        }
8779                        if (verificationParams.getInstallerUid() >= 0) {
8780                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8781                                  verificationParams.getInstallerUid());
8782                        }
8783                    }
8784
8785                    final PackageVerificationState verificationState = new PackageVerificationState(
8786                            requiredUid, args);
8787
8788                    mPendingVerification.append(verificationId, verificationState);
8789
8790                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8791                            receivers, verificationState);
8792
8793                    /*
8794                     * If any sufficient verifiers were listed in the package
8795                     * manifest, attempt to ask them.
8796                     */
8797                    if (sufficientVerifiers != null) {
8798                        final int N = sufficientVerifiers.size();
8799                        if (N == 0) {
8800                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8802                        } else {
8803                            for (int i = 0; i < N; i++) {
8804                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8805
8806                                final Intent sufficientIntent = new Intent(verification);
8807                                sufficientIntent.setComponent(verifierComponent);
8808
8809                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8810                            }
8811                        }
8812                    }
8813
8814                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8815                            mRequiredVerifierPackage, receivers);
8816                    if (ret == PackageManager.INSTALL_SUCCEEDED
8817                            && mRequiredVerifierPackage != null) {
8818                        /*
8819                         * Send the intent to the required verification agent,
8820                         * but only start the verification timeout after the
8821                         * target BroadcastReceivers have run.
8822                         */
8823                        verification.setComponent(requiredVerifierComponent);
8824                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8825                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8826                                new BroadcastReceiver() {
8827                                    @Override
8828                                    public void onReceive(Context context, Intent intent) {
8829                                        final Message msg = mHandler
8830                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8831                                        msg.arg1 = verificationId;
8832                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8833                                    }
8834                                }, null, 0, null, null);
8835
8836                        /*
8837                         * We don't want the copy to proceed until verification
8838                         * succeeds, so null out this field.
8839                         */
8840                        mArgs = null;
8841                    }
8842                } else {
8843                    /*
8844                     * No package verification is enabled, so immediately start
8845                     * the remote call to initiate copy using temporary file.
8846                     */
8847                    ret = args.copyApk(mContainerService, true);
8848                }
8849            }
8850
8851            mRet = ret;
8852        }
8853
8854        @Override
8855        void handleReturnCode() {
8856            // If mArgs is null, then MCS couldn't be reached. When it
8857            // reconnects, it will try again to install. At that point, this
8858            // will succeed.
8859            if (mArgs != null) {
8860                processPendingInstall(mArgs, mRet);
8861            }
8862        }
8863
8864        @Override
8865        void handleServiceError() {
8866            mArgs = createInstallArgs(this);
8867            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8868        }
8869
8870        public boolean isForwardLocked() {
8871            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8872        }
8873    }
8874
8875    /*
8876     * Utility class used in movePackage api.
8877     * srcArgs and targetArgs are not set for invalid flags and make
8878     * sure to do null checks when invoking methods on them.
8879     * We probably want to return ErrorPrams for both failed installs
8880     * and moves.
8881     */
8882    class MoveParams extends HandlerParams {
8883        final IPackageMoveObserver observer;
8884        final int flags;
8885        final String packageName;
8886        final InstallArgs srcArgs;
8887        final InstallArgs targetArgs;
8888        int uid;
8889        int mRet;
8890
8891        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8892                String packageName, String[] instructionSets, int uid, UserHandle user,
8893                boolean isMultiArch) {
8894            super(user);
8895            this.srcArgs = srcArgs;
8896            this.observer = observer;
8897            this.flags = flags;
8898            this.packageName = packageName;
8899            this.uid = uid;
8900            if (srcArgs != null) {
8901                final String codePath = srcArgs.getCodePath();
8902                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8903                        instructionSets, isMultiArch);
8904            } else {
8905                targetArgs = null;
8906            }
8907        }
8908
8909        @Override
8910        public String toString() {
8911            return "MoveParams{"
8912                + Integer.toHexString(System.identityHashCode(this))
8913                + " " + packageName + "}";
8914        }
8915
8916        public void handleStartCopy() throws RemoteException {
8917            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8918            // Check for storage space on target medium
8919            if (!targetArgs.checkFreeStorage(mContainerService)) {
8920                Log.w(TAG, "Insufficient storage to install");
8921                return;
8922            }
8923
8924            mRet = srcArgs.doPreCopy();
8925            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8926                return;
8927            }
8928
8929            mRet = targetArgs.copyApk(mContainerService, false);
8930            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8931                srcArgs.doPostCopy(uid);
8932                return;
8933            }
8934
8935            mRet = srcArgs.doPostCopy(uid);
8936            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8937                return;
8938            }
8939
8940            mRet = targetArgs.doPreInstall(mRet);
8941            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8942                return;
8943            }
8944
8945            if (DEBUG_SD_INSTALL) {
8946                StringBuilder builder = new StringBuilder();
8947                if (srcArgs != null) {
8948                    builder.append("src: ");
8949                    builder.append(srcArgs.getCodePath());
8950                }
8951                if (targetArgs != null) {
8952                    builder.append(" target : ");
8953                    builder.append(targetArgs.getCodePath());
8954                }
8955                Log.i(TAG, builder.toString());
8956            }
8957        }
8958
8959        @Override
8960        void handleReturnCode() {
8961            targetArgs.doPostInstall(mRet, uid);
8962            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8963            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8964                currentStatus = PackageManager.MOVE_SUCCEEDED;
8965            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8966                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8967            }
8968            processPendingMove(this, currentStatus);
8969        }
8970
8971        @Override
8972        void handleServiceError() {
8973            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8974        }
8975    }
8976
8977    /**
8978     * Used during creation of InstallArgs
8979     *
8980     * @param flags package installation flags
8981     * @return true if should be installed on external storage
8982     */
8983    private static boolean installOnSd(int flags) {
8984        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8985            return false;
8986        }
8987        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8988            return true;
8989        }
8990        return false;
8991    }
8992
8993    /**
8994     * Used during creation of InstallArgs
8995     *
8996     * @param flags package installation flags
8997     * @return true if should be installed as forward locked
8998     */
8999    private static boolean installForwardLocked(int flags) {
9000        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9001    }
9002
9003    private InstallArgs createInstallArgs(InstallParams params) {
9004        // TODO: extend to support incoming zero-copy locations
9005
9006        if (installOnSd(params.flags) || params.isForwardLocked()) {
9007            return new AsecInstallArgs(params);
9008        } else {
9009            return new FileInstallArgs(params);
9010        }
9011    }
9012
9013    /**
9014     * Create args that describe an existing installed package. Typically used
9015     * when cleaning up old installs, or used as a move source.
9016     */
9017    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9018            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9019            boolean isMultiArch) {
9020        final boolean isInAsec;
9021        if (installOnSd(flags)) {
9022            /* Apps on SD card are always in ASEC containers. */
9023            isInAsec = true;
9024        } else if (installForwardLocked(flags)
9025                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9026            /*
9027             * Forward-locked apps are only in ASEC containers if they're the
9028             * new style
9029             */
9030            isInAsec = true;
9031        } else {
9032            isInAsec = false;
9033        }
9034
9035        if (isInAsec) {
9036            return new AsecInstallArgs(codePath, instructionSets,
9037                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9038        } else {
9039            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9040                    instructionSets, isMultiArch);
9041        }
9042    }
9043
9044    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9045            String[] instructionSets, boolean isMultiArch) {
9046        final File codeFile = new File(codePath);
9047        if (installOnSd(flags) || installForwardLocked(flags)) {
9048            String cid = getNextCodePath(codePath, pkgName, "/"
9049                    + AsecInstallArgs.RES_FILE_NAME);
9050            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9051                    installForwardLocked(flags), isMultiArch);
9052        } else {
9053            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9054        }
9055    }
9056
9057    static abstract class InstallArgs {
9058        /** @see InstallParams#originFile */
9059        final File originFile;
9060        /** @see InstallParams#originStaged */
9061        final boolean originStaged;
9062
9063        // TODO: define inherit location
9064
9065        final IPackageInstallObserver2 observer;
9066        // Always refers to PackageManager flags only
9067        final int flags;
9068        final String installerPackageName;
9069        final ManifestDigest manifestDigest;
9070        final UserHandle user;
9071        final String abiOverride;
9072        final boolean multiArch;
9073
9074        // The list of instruction sets supported by this app. This is currently
9075        // only used during the rmdex() phase to clean up resources. We can get rid of this
9076        // if we move dex files under the common app path.
9077        /* nullable */ String[] instructionSets;
9078
9079        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9080                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9081                    UserHandle user, String[] instructionSets,
9082                    String abiOverride, boolean multiArch) {
9083            this.originFile = originFile;
9084            this.originStaged = originStaged;
9085            this.flags = flags;
9086            this.observer = observer;
9087            this.installerPackageName = installerPackageName;
9088            this.manifestDigest = manifestDigest;
9089            this.user = user;
9090            this.instructionSets = instructionSets;
9091            this.abiOverride = abiOverride;
9092            this.multiArch = multiArch;
9093        }
9094
9095        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9096        abstract int doPreInstall(int status);
9097
9098        /**
9099         * Rename package into final resting place. All paths on the given
9100         * scanned package should be updated to reflect the rename.
9101         */
9102        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9103        abstract int doPostInstall(int status, int uid);
9104
9105        /** @see PackageSettingBase#codePathString */
9106        abstract String getCodePath();
9107        /** @see PackageSettingBase#resourcePathString */
9108        abstract String getResourcePath();
9109        abstract String getLegacyNativeLibraryPath();
9110
9111        // Need installer lock especially for dex file removal.
9112        abstract void cleanUpResourcesLI();
9113        abstract boolean doPostDeleteLI(boolean delete);
9114        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9115
9116        /**
9117         * Called before the source arguments are copied. This is used mostly
9118         * for MoveParams when it needs to read the source file to put it in the
9119         * destination.
9120         */
9121        int doPreCopy() {
9122            return PackageManager.INSTALL_SUCCEEDED;
9123        }
9124
9125        /**
9126         * Called after the source arguments are copied. This is used mostly for
9127         * MoveParams when it needs to read the source file to put it in the
9128         * destination.
9129         *
9130         * @return
9131         */
9132        int doPostCopy(int uid) {
9133            return PackageManager.INSTALL_SUCCEEDED;
9134        }
9135
9136        protected boolean isFwdLocked() {
9137            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9138        }
9139
9140        UserHandle getUser() {
9141            return user;
9142        }
9143    }
9144
9145    /**
9146     * Logic to handle installation of non-ASEC applications, including copying
9147     * and renaming logic.
9148     */
9149    class FileInstallArgs extends InstallArgs {
9150        private File codeFile;
9151        private File resourceFile;
9152        private File legacyNativeLibraryPath;
9153
9154        // Example topology:
9155        // /data/app/com.example/base.apk
9156        // /data/app/com.example/split_foo.apk
9157        // /data/app/com.example/lib/arm/libfoo.so
9158        // /data/app/com.example/lib/arm64/libfoo.so
9159        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9160
9161        /** New install */
9162        FileInstallArgs(InstallParams params) {
9163            super(params.originFile, params.originStaged, params.observer, params.flags,
9164                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9165                    null /* instruction sets */, params.packageAbiOverride,
9166                    params.multiArch);
9167            if (isFwdLocked()) {
9168                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9169            }
9170        }
9171
9172        /** Existing install */
9173        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9174                String[] instructionSets, boolean isMultiArch) {
9175            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9176            this.codeFile = (codePath != null) ? new File(codePath) : null;
9177            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9178            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9179                    new File(legacyNativeLibraryPath) : null;
9180        }
9181
9182        /** New install from existing */
9183        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9184            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9185                    isMultiArch);
9186        }
9187
9188        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9189            final long lowThreshold;
9190
9191            final DeviceStorageMonitorInternal
9192                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9193            if (dsm == null) {
9194                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9195                lowThreshold = 0L;
9196            } else {
9197                if (dsm.isMemoryLow()) {
9198                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9199                    return false;
9200                }
9201
9202                lowThreshold = dsm.getMemoryLowThreshold();
9203            }
9204
9205            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9206                    lowThreshold);
9207        }
9208
9209        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9210            int ret = PackageManager.INSTALL_SUCCEEDED;
9211
9212            if (originStaged) {
9213                Slog.d(TAG, originFile + " already staged; skipping copy");
9214                codeFile = originFile;
9215                resourceFile = originFile;
9216            } else {
9217                try {
9218                    final File tempDir = mInstallerService.allocateSessionDir();
9219                    codeFile = tempDir;
9220                    resourceFile = tempDir;
9221                } catch (IOException e) {
9222                    Slog.w(TAG, "Failed to create copy file: " + e);
9223                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9224                }
9225
9226                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9227                    @Override
9228                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9229                        if (!FileUtils.isValidExtFilename(name)) {
9230                            throw new IllegalArgumentException("Invalid filename: " + name);
9231                        }
9232                        try {
9233                            final File file = new File(codeFile, name);
9234                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9235                                    O_RDWR | O_CREAT, 0644);
9236                            Os.chmod(file.getAbsolutePath(), 0644);
9237                            return new ParcelFileDescriptor(fd);
9238                        } catch (ErrnoException e) {
9239                            throw new RemoteException("Failed to open: " + e.getMessage());
9240                        }
9241                    }
9242                };
9243
9244                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9245                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9246                    Slog.e(TAG, "Failed to copy package");
9247                    return ret;
9248                }
9249            }
9250
9251            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9252            NativeLibraryHelper.Handle handle = null;
9253            try {
9254                handle = NativeLibraryHelper.Handle.create(codeFile);
9255                if (multiArch) {
9256                    // Warn if we've set an abiOverride for multi-lib packages..
9257                    // By definition, we need to copy both 32 and 64 bit libraries for
9258                    // such packages.
9259                    if (abiOverride != null) {
9260                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9261                    }
9262
9263                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9264                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9265                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9266                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9267                        if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9268                            Slog.w(TAG, "Failure copying 32 bit native libraries [errorCode=" + copyRet + "]");
9269                            return copyRet;
9270                        }
9271                    }
9272
9273                    if (DEBUG_ABI_SELECTION && copyRet >= 0) {
9274                        Log.d(TAG, "Installed 32 bit libraries under: " + codeFile + " abi=" +
9275                                Build.SUPPORTED_32_BIT_ABIS[copyRet]);
9276                    }
9277
9278                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9279                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9280                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9281                        if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9282                            Slog.w(TAG, "Failure copying 64 bit native libraries [errorCode=" + copyRet + "]");
9283                            return copyRet;
9284                        }
9285                    }
9286
9287                    if (DEBUG_ABI_SELECTION && copyRet >= 0) {
9288                        Log.d(TAG, "Installed 64 bit libraries under: " + codeFile + " abi=" +
9289                                Build.SUPPORTED_64_BIT_ABIS[copyRet]);
9290                    }
9291                } else {
9292                    String[] abiList = (abiOverride != null) ?
9293                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9294
9295                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
9296                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9297                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9298                    }
9299
9300                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9301                            true /* use isa specific subdirs */);
9302                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9303                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9304                        return copyRet;
9305                    }
9306
9307                    if (DEBUG_ABI_SELECTION && copyRet >= 0) {
9308                        Log.d(TAG, "Installed libraries under: " + codeFile + " abi=" + abiList[copyRet]);
9309                    }
9310                }
9311            } catch (IOException e) {
9312                Slog.e(TAG, "Copying native libraries failed", e);
9313                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9314            } finally {
9315                IoUtils.closeQuietly(handle);
9316            }
9317
9318            return ret;
9319        }
9320
9321        int doPreInstall(int status) {
9322            if (status != PackageManager.INSTALL_SUCCEEDED) {
9323                cleanUp();
9324            }
9325            return status;
9326        }
9327
9328        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9329            if (status != PackageManager.INSTALL_SUCCEEDED) {
9330                cleanUp();
9331                return false;
9332            } else {
9333                final File beforeCodeFile = codeFile;
9334                final File afterCodeFile = new File(mAppInstallDir,
9335                        getNextCodePath(oldCodePath, pkg.packageName, null));
9336
9337                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9338                if (!beforeCodeFile.renameTo(afterCodeFile)) {
9339                    return false;
9340                }
9341                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9342                    return false;
9343                }
9344
9345                // Reflect the rename internally
9346                codeFile = afterCodeFile;
9347                resourceFile = afterCodeFile;
9348
9349                // Reflect the rename in scanned details
9350                pkg.codePath = afterCodeFile.getAbsolutePath();
9351                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9352                        pkg.baseCodePath);
9353                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9354                        pkg.splitCodePaths);
9355
9356                // Reflect the rename in app info
9357                pkg.applicationInfo.setCodePath(pkg.codePath);
9358                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9359                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9360                pkg.applicationInfo.setResourcePath(pkg.codePath);
9361                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9362                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9363
9364                return true;
9365            }
9366        }
9367
9368        int doPostInstall(int status, int uid) {
9369            if (status != PackageManager.INSTALL_SUCCEEDED) {
9370                cleanUp();
9371            }
9372            return status;
9373        }
9374
9375        @Override
9376        String getCodePath() {
9377            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9378        }
9379
9380        @Override
9381        String getResourcePath() {
9382            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9383        }
9384
9385        @Override
9386        String getLegacyNativeLibraryPath() {
9387            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9388        }
9389
9390        private boolean cleanUp() {
9391            if (codeFile == null || !codeFile.exists()) {
9392                return false;
9393            }
9394
9395            if (codeFile.isDirectory()) {
9396                FileUtils.deleteContents(codeFile);
9397            }
9398            codeFile.delete();
9399
9400            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9401                resourceFile.delete();
9402            }
9403
9404            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9405                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9406                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9407                }
9408                legacyNativeLibraryPath.delete();
9409            }
9410
9411            return true;
9412        }
9413
9414        void cleanUpResourcesLI() {
9415            // Try enumerating all code paths before deleting
9416            List<String> allCodePaths = Collections.EMPTY_LIST;
9417            if (codeFile != null && codeFile.exists()) {
9418                try {
9419                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9420                    allCodePaths = pkg.getAllCodePaths();
9421                } catch (PackageParserException e) {
9422                    // Ignored; we tried our best
9423                }
9424            }
9425
9426            cleanUp();
9427
9428            if (!allCodePaths.isEmpty()) {
9429                if (instructionSets == null) {
9430                    throw new IllegalStateException("instructionSet == null");
9431                }
9432
9433                for (String codePath : allCodePaths) {
9434                    for (String instructionSet : instructionSets) {
9435                        int retCode = mInstaller.rmdex(codePath, instructionSet);
9436                        if (retCode < 0) {
9437                            Slog.w(TAG, "Couldn't remove dex file for package: "
9438                                    + " at location " + codePath + ", retcode=" + retCode);
9439                            // we don't consider this to be a failure of the core package deletion
9440                        }
9441                    }
9442                }
9443            }
9444        }
9445
9446        boolean doPostDeleteLI(boolean delete) {
9447            // XXX err, shouldn't we respect the delete flag?
9448            cleanUpResourcesLI();
9449            return true;
9450        }
9451    }
9452
9453    private boolean isAsecExternal(String cid) {
9454        final String asecPath = PackageHelper.getSdFilesystem(cid);
9455        return !asecPath.startsWith(mAsecInternalPath);
9456    }
9457
9458    /**
9459     * Extract the MountService "container ID" from the full code path of an
9460     * .apk.
9461     */
9462    static String cidFromCodePath(String fullCodePath) {
9463        int eidx = fullCodePath.lastIndexOf("/");
9464        String subStr1 = fullCodePath.substring(0, eidx);
9465        int sidx = subStr1.lastIndexOf("/");
9466        return subStr1.substring(sidx+1, eidx);
9467    }
9468
9469    /**
9470     * Logic to handle installation of ASEC applications, including copying and
9471     * renaming logic.
9472     */
9473    class AsecInstallArgs extends InstallArgs {
9474        // TODO: teach about handling cluster directories
9475
9476        static final String RES_FILE_NAME = "pkg.apk";
9477        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9478
9479        String cid;
9480        String packagePath;
9481        String resourcePath;
9482        String legacyNativeLibraryDir;
9483
9484        /** New install */
9485        AsecInstallArgs(InstallParams params) {
9486            super(params.originFile, params.originStaged, params.observer, params.flags,
9487                    params.installerPackageName, params.getManifestDigest(),
9488                    params.getUser(), null /* instruction sets */,
9489                    params.packageAbiOverride, params.multiArch);
9490        }
9491
9492        /** Existing install */
9493        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9494                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9495            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9496                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9497                    instructionSets, null, isMultiArch);
9498            // Extract cid from fullCodePath
9499            int eidx = fullCodePath.lastIndexOf("/");
9500            String subStr1 = fullCodePath.substring(0, eidx);
9501            int sidx = subStr1.lastIndexOf("/");
9502            cid = subStr1.substring(sidx+1, eidx);
9503            setCachePath(subStr1);
9504        }
9505
9506        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9507                        boolean isMultiArch) {
9508            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9509                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9510                    instructionSets, null, isMultiArch);
9511            this.cid = cid;
9512            setCachePath(PackageHelper.getSdDir(cid));
9513        }
9514
9515        /** New install from existing */
9516        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9517                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9518            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9519                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9520                    instructionSets, null, isMultiArch);
9521            this.cid = cid;
9522        }
9523
9524        void createCopyFile() {
9525            cid = getTempContainerId();
9526        }
9527
9528        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9529            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9530                    abiOverride);
9531        }
9532
9533        private final boolean isExternal() {
9534            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9535        }
9536
9537        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9538            if (temp) {
9539                createCopyFile();
9540            } else {
9541                /*
9542                 * Pre-emptively destroy the container since it's destroyed if
9543                 * copying fails due to it existing anyway.
9544                 */
9545                PackageHelper.destroySdDir(cid);
9546            }
9547
9548            final String newCachePath = imcs.copyPackageToContainer(
9549                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9550                    isFwdLocked(), abiOverride);
9551
9552            if (newCachePath != null) {
9553                setCachePath(newCachePath);
9554                return PackageManager.INSTALL_SUCCEEDED;
9555            } else {
9556                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9557            }
9558        }
9559
9560        @Override
9561        String getCodePath() {
9562            return packagePath;
9563        }
9564
9565        @Override
9566        String getResourcePath() {
9567            return resourcePath;
9568        }
9569
9570        @Override
9571        String getLegacyNativeLibraryPath() {
9572            return legacyNativeLibraryDir;
9573        }
9574
9575        int doPreInstall(int status) {
9576            if (status != PackageManager.INSTALL_SUCCEEDED) {
9577                // Destroy container
9578                PackageHelper.destroySdDir(cid);
9579            } else {
9580                boolean mounted = PackageHelper.isContainerMounted(cid);
9581                if (!mounted) {
9582                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9583                            Process.SYSTEM_UID);
9584                    if (newCachePath != null) {
9585                        setCachePath(newCachePath);
9586                    } else {
9587                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9588                    }
9589                }
9590            }
9591            return status;
9592        }
9593
9594        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9595            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9596            String newCachePath = null;
9597            if (PackageHelper.isContainerMounted(cid)) {
9598                // Unmount the container
9599                if (!PackageHelper.unMountSdDir(cid)) {
9600                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9601                    return false;
9602                }
9603            }
9604            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9605                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9606                        " which might be stale. Will try to clean up.");
9607                // Clean up the stale container and proceed to recreate.
9608                if (!PackageHelper.destroySdDir(newCacheId)) {
9609                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9610                    return false;
9611                }
9612                // Successfully cleaned up stale container. Try to rename again.
9613                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9614                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9615                            + " inspite of cleaning it up.");
9616                    return false;
9617                }
9618            }
9619            if (!PackageHelper.isContainerMounted(newCacheId)) {
9620                Slog.w(TAG, "Mounting container " + newCacheId);
9621                newCachePath = PackageHelper.mountSdDir(newCacheId,
9622                        getEncryptKey(), Process.SYSTEM_UID);
9623            } else {
9624                newCachePath = PackageHelper.getSdDir(newCacheId);
9625            }
9626            if (newCachePath == null) {
9627                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9628                return false;
9629            }
9630            Log.i(TAG, "Succesfully renamed " + cid +
9631                    " to " + newCacheId +
9632                    " at new path: " + newCachePath);
9633            cid = newCacheId;
9634            setCachePath(newCachePath);
9635
9636            // TODO: extend to support split APKs
9637            pkg.codePath = getCodePath();
9638            pkg.baseCodePath = getCodePath();
9639            pkg.splitCodePaths = null;
9640
9641            pkg.applicationInfo.setCodePath(getCodePath());
9642            pkg.applicationInfo.setBaseCodePath(getCodePath());
9643            pkg.applicationInfo.setSplitCodePaths(null);
9644            pkg.applicationInfo.setResourcePath(getResourcePath());
9645            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9646            pkg.applicationInfo.setSplitResourcePaths(null);
9647
9648            return true;
9649        }
9650
9651        private void setCachePath(String newCachePath) {
9652            File cachePath = new File(newCachePath);
9653            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9654            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9655
9656            if (isFwdLocked()) {
9657                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9658            } else {
9659                resourcePath = packagePath;
9660            }
9661        }
9662
9663        int doPostInstall(int status, int uid) {
9664            if (status != PackageManager.INSTALL_SUCCEEDED) {
9665                cleanUp();
9666            } else {
9667                final int groupOwner;
9668                final String protectedFile;
9669                if (isFwdLocked()) {
9670                    groupOwner = UserHandle.getSharedAppGid(uid);
9671                    protectedFile = RES_FILE_NAME;
9672                } else {
9673                    groupOwner = -1;
9674                    protectedFile = null;
9675                }
9676
9677                if (uid < Process.FIRST_APPLICATION_UID
9678                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9679                    Slog.e(TAG, "Failed to finalize " + cid);
9680                    PackageHelper.destroySdDir(cid);
9681                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9682                }
9683
9684                boolean mounted = PackageHelper.isContainerMounted(cid);
9685                if (!mounted) {
9686                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9687                }
9688            }
9689            return status;
9690        }
9691
9692        private void cleanUp() {
9693            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9694
9695            // Destroy secure container
9696            PackageHelper.destroySdDir(cid);
9697        }
9698
9699        void cleanUpResourcesLI() {
9700            String sourceFile = getCodePath();
9701            // Remove dex file
9702            if (instructionSets == null) {
9703                throw new IllegalStateException("instructionSet == null");
9704            }
9705            for (String instructionSet : instructionSets) {
9706                int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9707                if (retCode < 0) {
9708                    Slog.w(TAG, "Couldn't remove dex file for package: "
9709                            + " at location "
9710                            + sourceFile.toString() + ", retcode=" + retCode);
9711                    // we don't consider this to be a failure of the core package deletion
9712                }
9713            }
9714            cleanUp();
9715        }
9716
9717        boolean matchContainer(String app) {
9718            if (cid.startsWith(app)) {
9719                return true;
9720            }
9721            return false;
9722        }
9723
9724        String getPackageName() {
9725            return getAsecPackageName(cid);
9726        }
9727
9728        boolean doPostDeleteLI(boolean delete) {
9729            boolean ret = false;
9730            boolean mounted = PackageHelper.isContainerMounted(cid);
9731            if (mounted) {
9732                // Unmount first
9733                ret = PackageHelper.unMountSdDir(cid);
9734            }
9735            if (ret && delete) {
9736                cleanUpResourcesLI();
9737            }
9738            return ret;
9739        }
9740
9741        @Override
9742        int doPreCopy() {
9743            if (isFwdLocked()) {
9744                if (!PackageHelper.fixSdPermissions(cid,
9745                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9746                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9747                }
9748            }
9749
9750            return PackageManager.INSTALL_SUCCEEDED;
9751        }
9752
9753        @Override
9754        int doPostCopy(int uid) {
9755            if (isFwdLocked()) {
9756                if (uid < Process.FIRST_APPLICATION_UID
9757                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9758                                RES_FILE_NAME)) {
9759                    Slog.e(TAG, "Failed to finalize " + cid);
9760                    PackageHelper.destroySdDir(cid);
9761                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9762                }
9763            }
9764
9765            return PackageManager.INSTALL_SUCCEEDED;
9766        }
9767    }
9768
9769    static String getAsecPackageName(String packageCid) {
9770        int idx = packageCid.lastIndexOf("-");
9771        if (idx == -1) {
9772            return packageCid;
9773        }
9774        return packageCid.substring(0, idx);
9775    }
9776
9777    // Utility method used to create code paths based on package name and available index.
9778    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9779        String idxStr = "";
9780        int idx = 1;
9781        // Fall back to default value of idx=1 if prefix is not
9782        // part of oldCodePath
9783        if (oldCodePath != null) {
9784            String subStr = oldCodePath;
9785            // Drop the suffix right away
9786            if (suffix != null && subStr.endsWith(suffix)) {
9787                subStr = subStr.substring(0, subStr.length() - suffix.length());
9788            }
9789            // If oldCodePath already contains prefix find out the
9790            // ending index to either increment or decrement.
9791            int sidx = subStr.lastIndexOf(prefix);
9792            if (sidx != -1) {
9793                subStr = subStr.substring(sidx + prefix.length());
9794                if (subStr != null) {
9795                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9796                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9797                    }
9798                    try {
9799                        idx = Integer.parseInt(subStr);
9800                        if (idx <= 1) {
9801                            idx++;
9802                        } else {
9803                            idx--;
9804                        }
9805                    } catch(NumberFormatException e) {
9806                    }
9807                }
9808            }
9809        }
9810        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9811        return prefix + idxStr;
9812    }
9813
9814    // Utility method used to ignore ADD/REMOVE events
9815    // by directory observer.
9816    private static boolean ignoreCodePath(String fullPathStr) {
9817        String apkName = deriveCodePathName(fullPathStr);
9818        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9819        if (idx != -1 && ((idx+1) < apkName.length())) {
9820            // Make sure the package ends with a numeral
9821            String version = apkName.substring(idx+1);
9822            try {
9823                Integer.parseInt(version);
9824                return true;
9825            } catch (NumberFormatException e) {}
9826        }
9827        return false;
9828    }
9829
9830    // Utility method that returns the relative package path with respect
9831    // to the installation directory. Like say for /data/data/com.test-1.apk
9832    // string com.test-1 is returned.
9833    static String deriveCodePathName(String codePath) {
9834        if (codePath == null) {
9835            return null;
9836        }
9837        final File codeFile = new File(codePath);
9838        final String name = codeFile.getName();
9839        if (codeFile.isDirectory()) {
9840            return name;
9841        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9842            final int lastDot = name.lastIndexOf('.');
9843            return name.substring(0, lastDot);
9844        } else {
9845            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9846            return null;
9847        }
9848    }
9849
9850    class PackageInstalledInfo {
9851        String name;
9852        int uid;
9853        // The set of users that originally had this package installed.
9854        int[] origUsers;
9855        // The set of users that now have this package installed.
9856        int[] newUsers;
9857        PackageParser.Package pkg;
9858        int returnCode;
9859        String returnMsg;
9860        PackageRemovedInfo removedInfo;
9861
9862        public void setError(int code, String msg) {
9863            returnCode = code;
9864            returnMsg = msg;
9865            Slog.w(TAG, msg);
9866        }
9867
9868        // In some error cases we want to convey more info back to the observer
9869        String origPackage;
9870        String origPermission;
9871    }
9872
9873    /*
9874     * Install a non-existing package.
9875     */
9876    private void installNewPackageLI(PackageParser.Package pkg,
9877            int parseFlags, int scanMode, UserHandle user,
9878            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9879        // Remember this for later, in case we need to rollback this install
9880        String pkgName = pkg.packageName;
9881
9882        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9883        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9884        synchronized(mPackages) {
9885            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9886                // A package with the same name is already installed, though
9887                // it has been renamed to an older name.  The package we
9888                // are trying to install should be installed as an update to
9889                // the existing one, but that has not been requested, so bail.
9890                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9891                        + " without first uninstalling package running as "
9892                        + mSettings.mRenamedPackages.get(pkgName));
9893                return;
9894            }
9895            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9896                // Don't allow installation over an existing package with the same name.
9897                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9898                        + " without first uninstalling.");
9899                return;
9900            }
9901        }
9902
9903        try {
9904            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9905                    System.currentTimeMillis(), user, abiOverride);
9906
9907            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9908            // delete the partially installed application. the data directory will have to be
9909            // restored if it was already existing
9910            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9911                // remove package from internal structures.  Note that we want deletePackageX to
9912                // delete the package data and cache directories that it created in
9913                // scanPackageLocked, unless those directories existed before we even tried to
9914                // install.
9915                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9916                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9917                                res.removedInfo, true);
9918            }
9919
9920        } catch (PackageManagerException e) {
9921            res.setError(e.error,
9922                    "Package couldn't be installed in " + pkg.codePath + ": " + e.getMessage());
9923        }
9924    }
9925
9926    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9927        // Upgrade keysets are being used.  Determine if new package has a superset of the
9928        // required keys.
9929        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9930        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9931        for (int i = 0; i < upgradeKeySets.length; i++) {
9932            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9933            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9934                return true;
9935            }
9936        }
9937        return false;
9938    }
9939
9940    private void replacePackageLI(PackageParser.Package pkg,
9941            int parseFlags, int scanMode, UserHandle user,
9942            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9943        PackageParser.Package oldPackage;
9944        String pkgName = pkg.packageName;
9945        int[] allUsers;
9946        boolean[] perUserInstalled;
9947
9948        // First find the old package info and check signatures
9949        synchronized(mPackages) {
9950            oldPackage = mPackages.get(pkgName);
9951            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9952            PackageSetting ps = mSettings.mPackages.get(pkgName);
9953            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9954                // default to original signature matching
9955                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9956                    != PackageManager.SIGNATURE_MATCH) {
9957                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9958                            "New package has a different signature: " + pkgName);
9959                    return;
9960                }
9961            } else {
9962                if(!checkUpgradeKeySetLP(ps, pkg)) {
9963                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9964                            "New package not signed by keys specified by upgrade-keysets: "
9965                            + pkgName);
9966                    return;
9967                }
9968            }
9969
9970            // In case of rollback, remember per-user/profile install state
9971            allUsers = sUserManager.getUserIds();
9972            perUserInstalled = new boolean[allUsers.length];
9973            for (int i = 0; i < allUsers.length; i++) {
9974                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9975            }
9976        }
9977        boolean sysPkg = (isSystemApp(oldPackage));
9978        if (sysPkg) {
9979            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9980                    user, allUsers, perUserInstalled, installerPackageName, res,
9981                    abiOverride);
9982        } else {
9983            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9984                    user, allUsers, perUserInstalled, installerPackageName, res,
9985                    abiOverride);
9986        }
9987    }
9988
9989    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9990            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9991            int[] allUsers, boolean[] perUserInstalled,
9992            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9993        String pkgName = deletedPackage.packageName;
9994        boolean deletedPkg = true;
9995        boolean updatedSettings = false;
9996
9997        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9998                + deletedPackage);
9999        long origUpdateTime;
10000        if (pkg.mExtras != null) {
10001            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10002        } else {
10003            origUpdateTime = 0;
10004        }
10005
10006        // First delete the existing package while retaining the data directory
10007        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10008                res.removedInfo, true)) {
10009            // If the existing package wasn't successfully deleted
10010            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10011            deletedPkg = false;
10012        } else {
10013            // Successfully deleted the old package. Now proceed with re-installation
10014            try {
10015                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10016                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride);
10017                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10018                updatedSettings = true;
10019            } catch (PackageManagerException e) {
10020                res.setError(e.error,
10021                        "Package couldn't be installed in " + pkg.codePath + ": " + e.getMessage());
10022            }
10023        }
10024
10025        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10026            // remove package from internal structures.  Note that we want deletePackageX to
10027            // delete the package data and cache directories that it created in
10028            // scanPackageLocked, unless those directories existed before we even tried to
10029            // install.
10030            if(updatedSettings) {
10031                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10032                deletePackageLI(
10033                        pkgName, null, true, allUsers, perUserInstalled,
10034                        PackageManager.DELETE_KEEP_DATA,
10035                                res.removedInfo, true);
10036            }
10037            // Since we failed to install the new package we need to restore the old
10038            // package that we deleted.
10039            if (deletedPkg) {
10040                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10041                File restoreFile = new File(deletedPackage.codePath);
10042                // Parse old package
10043                boolean oldOnSd = isExternal(deletedPackage);
10044                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10045                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10046                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10047                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10048                        | SCAN_UPDATE_TIME;
10049                try {
10050                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null,
10051                            null);
10052                } catch (PackageManagerException e) {
10053                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10054                            + e.getMessage());
10055                    return;
10056                }
10057                // Restore of old package succeeded. Update permissions.
10058                // writer
10059                synchronized (mPackages) {
10060                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10061                            UPDATE_PERMISSIONS_ALL);
10062                    // can downgrade to reader
10063                    mSettings.writeLPr();
10064                }
10065                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10066            }
10067        }
10068    }
10069
10070    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10071            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10072            int[] allUsers, boolean[] perUserInstalled,
10073            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10074        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10075                + ", old=" + deletedPackage);
10076        boolean updatedSettings = false;
10077        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10078                PackageParser.PARSE_IS_SYSTEM;
10079        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10080            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10081        }
10082        String packageName = deletedPackage.packageName;
10083        if (packageName == null) {
10084            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10085                    "Attempt to delete null packageName.");
10086            return;
10087        }
10088        PackageParser.Package oldPkg;
10089        PackageSetting oldPkgSetting;
10090        // reader
10091        synchronized (mPackages) {
10092            oldPkg = mPackages.get(packageName);
10093            oldPkgSetting = mSettings.mPackages.get(packageName);
10094            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10095                    (oldPkgSetting == null)) {
10096                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10097                        "Couldn't find package:" + packageName + " information");
10098                return;
10099            }
10100        }
10101
10102        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10103
10104        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10105        res.removedInfo.removedPackage = packageName;
10106        // Remove existing system package
10107        removePackageLI(oldPkgSetting, true);
10108        // writer
10109        synchronized (mPackages) {
10110            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10111                // We didn't need to disable the .apk as a current system package,
10112                // which means we are replacing another update that is already
10113                // installed.  We need to make sure to delete the older one's .apk.
10114                res.removedInfo.args = createInstallArgsForExisting(0,
10115                        deletedPackage.applicationInfo.getCodePath(),
10116                        deletedPackage.applicationInfo.getResourcePath(),
10117                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10118                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10119                        isMultiArch(deletedPackage.applicationInfo));
10120            } else {
10121                res.removedInfo.args = null;
10122            }
10123        }
10124
10125        // Successfully disabled the old package. Now proceed with re-installation
10126        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10127        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10128
10129        PackageParser.Package newPackage = null;
10130        try {
10131            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10132            if (newPackage.mExtras != null) {
10133                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10134                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10135                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10136
10137                // is the update attempting to change shared user? that isn't going to work...
10138                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10139                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10140                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10141                            + " to " + newPkgSetting.sharedUser);
10142                    updatedSettings = true;
10143                }
10144            }
10145
10146            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10147                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10148                updatedSettings = true;
10149            }
10150
10151        } catch (PackageManagerException e) {
10152            res.setError(e.error,
10153                    "Package couldn't be installed in " + pkg.codePath + ": " + e.getMessage());
10154        }
10155
10156        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10157            // Re installation failed. Restore old information
10158            // Remove new pkg information
10159            if (newPackage != null) {
10160                removeInstalledPackageLI(newPackage, true);
10161            }
10162            // Add back the old system package
10163            try {
10164                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user,
10165                        null);
10166            } catch (PackageManagerException e) {
10167                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10168            }
10169            // Restore the old system information in Settings
10170            synchronized(mPackages) {
10171                if (updatedSettings) {
10172                    mSettings.enableSystemPackageLPw(packageName);
10173                    mSettings.setInstallerPackageName(packageName,
10174                            oldPkgSetting.installerPackageName);
10175                }
10176                mSettings.writeLPr();
10177            }
10178        }
10179    }
10180
10181    // Utility method used to move dex files during install.
10182    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10183        // TODO: extend to move split APK dex files
10184        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10185            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10186            for (String instructionSet : instructionSets) {
10187                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10188                        instructionSet);
10189                if (retCode != 0) {
10190                /*
10191                 * Programs may be lazily run through dexopt, so the
10192                 * source may not exist. However, something seems to
10193                 * have gone wrong, so note that dexopt needs to be
10194                 * run again and remove the source file. In addition,
10195                 * remove the target to make sure there isn't a stale
10196                 * file from a previous version of the package.
10197                 */
10198                    newPackage.mDexOptNeeded = true;
10199                    mInstaller.rmdex(oldCodePath, instructionSet);
10200                    mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10201                }
10202            }
10203        }
10204        return PackageManager.INSTALL_SUCCEEDED;
10205    }
10206
10207    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10208            int[] allUsers, boolean[] perUserInstalled,
10209            PackageInstalledInfo res) {
10210        String pkgName = newPackage.packageName;
10211        synchronized (mPackages) {
10212            //write settings. the installStatus will be incomplete at this stage.
10213            //note that the new package setting would have already been
10214            //added to mPackages. It hasn't been persisted yet.
10215            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10216            mSettings.writeLPr();
10217        }
10218
10219        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10220
10221        synchronized (mPackages) {
10222            updatePermissionsLPw(newPackage.packageName, newPackage,
10223                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10224                            ? UPDATE_PERMISSIONS_ALL : 0));
10225            // For system-bundled packages, we assume that installing an upgraded version
10226            // of the package implies that the user actually wants to run that new code,
10227            // so we enable the package.
10228            if (isSystemApp(newPackage)) {
10229                // NB: implicit assumption that system package upgrades apply to all users
10230                if (DEBUG_INSTALL) {
10231                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10232                }
10233                PackageSetting ps = mSettings.mPackages.get(pkgName);
10234                if (ps != null) {
10235                    if (res.origUsers != null) {
10236                        for (int userHandle : res.origUsers) {
10237                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10238                                    userHandle, installerPackageName);
10239                        }
10240                    }
10241                    // Also convey the prior install/uninstall state
10242                    if (allUsers != null && perUserInstalled != null) {
10243                        for (int i = 0; i < allUsers.length; i++) {
10244                            if (DEBUG_INSTALL) {
10245                                Slog.d(TAG, "    user " + allUsers[i]
10246                                        + " => " + perUserInstalled[i]);
10247                            }
10248                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10249                        }
10250                        // these install state changes will be persisted in the
10251                        // upcoming call to mSettings.writeLPr().
10252                    }
10253                }
10254            }
10255            res.name = pkgName;
10256            res.uid = newPackage.applicationInfo.uid;
10257            res.pkg = newPackage;
10258            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10259            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10260            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10261            //to update install status
10262            mSettings.writeLPr();
10263        }
10264    }
10265
10266    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10267        int pFlags = args.flags;
10268        String installerPackageName = args.installerPackageName;
10269        File tmpPackageFile = new File(args.getCodePath());
10270        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10271        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10272        boolean replace = false;
10273        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10274                | (newInstall ? SCAN_NEW_INSTALL : 0);
10275        // Result object to be returned
10276        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10277
10278        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10279        // Retrieve PackageSettings and parse package
10280        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10281                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10282                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10283        PackageParser pp = new PackageParser();
10284        pp.setSeparateProcesses(mSeparateProcesses);
10285        pp.setDisplayMetrics(mMetrics);
10286
10287        final PackageParser.Package pkg;
10288        try {
10289            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10290        } catch (PackageParserException e) {
10291            res.setError(e.error, "Failed parse during installPackageLI: " + e.getMessage());
10292            return;
10293        }
10294
10295        String pkgName = res.name = pkg.packageName;
10296        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10297            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10298                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10299                return;
10300            }
10301        }
10302
10303        try {
10304            pp.collectCertificates(pkg, parseFlags);
10305            pp.collectManifestDigest(pkg);
10306        } catch (PackageParserException e) {
10307            res.setError(e.error, "Failed collect during installPackageLI: " + e.getMessage());
10308            return;
10309        }
10310
10311        /* If the installer passed in a manifest digest, compare it now. */
10312        if (args.manifestDigest != null) {
10313            if (DEBUG_INSTALL) {
10314                final String parsedManifest = pkg.manifestDigest == null ? "null"
10315                        : pkg.manifestDigest.toString();
10316                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10317                        + parsedManifest);
10318            }
10319
10320            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10321                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10322                return;
10323            }
10324        } else if (DEBUG_INSTALL) {
10325            final String parsedManifest = pkg.manifestDigest == null
10326                    ? "null" : pkg.manifestDigest.toString();
10327            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10328        }
10329
10330        // Get rid of all references to package scan path via parser.
10331        pp = null;
10332        String oldCodePath = null;
10333        boolean systemApp = false;
10334        synchronized (mPackages) {
10335            // Check whether the newly-scanned package wants to define an already-defined perm
10336            int N = pkg.permissions.size();
10337            for (int i = N-1; i >= 0; i--) {
10338                PackageParser.Permission perm = pkg.permissions.get(i);
10339                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10340                if (bp != null) {
10341                    // If the defining package is signed with our cert, it's okay.  This
10342                    // also includes the "updating the same package" case, of course.
10343                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10344                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10345                        // If the owning package is the system itself, we log but allow
10346                        // install to proceed; we fail the install on all other permission
10347                        // redefinitions.
10348                        if (!bp.sourcePackage.equals("android")) {
10349                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10350                                    + pkg.packageName + " attempting to redeclare permission "
10351                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10352                            res.origPermission = perm.info.name;
10353                            res.origPackage = bp.sourcePackage;
10354                            return;
10355                        } else {
10356                            Slog.w(TAG, "Package " + pkg.packageName
10357                                    + " attempting to redeclare system permission "
10358                                    + perm.info.name + "; ignoring new declaration");
10359                            pkg.permissions.remove(i);
10360                        }
10361                    }
10362                }
10363            }
10364
10365            // Check if installing already existing package
10366            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10367                String oldName = mSettings.mRenamedPackages.get(pkgName);
10368                if (pkg.mOriginalPackages != null
10369                        && pkg.mOriginalPackages.contains(oldName)
10370                        && mPackages.containsKey(oldName)) {
10371                    // This package is derived from an original package,
10372                    // and this device has been updating from that original
10373                    // name.  We must continue using the original name, so
10374                    // rename the new package here.
10375                    pkg.setPackageName(oldName);
10376                    pkgName = pkg.packageName;
10377                    replace = true;
10378                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10379                            + oldName + " pkgName=" + pkgName);
10380                } else if (mPackages.containsKey(pkgName)) {
10381                    // This package, under its official name, already exists
10382                    // on the device; we should replace it.
10383                    replace = true;
10384                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10385                }
10386            }
10387            PackageSetting ps = mSettings.mPackages.get(pkgName);
10388            if (ps != null) {
10389                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10390                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10391                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10392                    systemApp = (ps.pkg.applicationInfo.flags &
10393                            ApplicationInfo.FLAG_SYSTEM) != 0;
10394                }
10395                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10396            }
10397        }
10398
10399        if (systemApp && onSd) {
10400            // Disable updates to system apps on sdcard
10401            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10402                    "Cannot install updates to system apps on sdcard");
10403            return;
10404        }
10405
10406        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10407            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10408            return;
10409        }
10410
10411        if (replace) {
10412            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10413                    installerPackageName, res, args.abiOverride);
10414        } else {
10415            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10416                    installerPackageName, res, args.abiOverride);
10417        }
10418        synchronized (mPackages) {
10419            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10420            if (ps != null) {
10421                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10422            }
10423        }
10424    }
10425
10426    private static boolean isForwardLocked(PackageParser.Package pkg) {
10427        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10428    }
10429
10430    private static boolean isForwardLocked(ApplicationInfo info) {
10431        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10432    }
10433
10434    private boolean isForwardLocked(PackageSetting ps) {
10435        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10436    }
10437
10438    private static boolean isMultiArch(PackageSetting ps) {
10439        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10440    }
10441
10442    private static boolean isMultiArch(ApplicationInfo info) {
10443        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10444    }
10445
10446    private static boolean isExternal(PackageParser.Package pkg) {
10447        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10448    }
10449
10450    private static boolean isExternal(PackageSetting ps) {
10451        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10452    }
10453
10454    private static boolean isExternal(ApplicationInfo info) {
10455        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10456    }
10457
10458    private static boolean isSystemApp(PackageParser.Package pkg) {
10459        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10460    }
10461
10462    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10463        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10464    }
10465
10466    private static boolean isSystemApp(ApplicationInfo info) {
10467        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10468    }
10469
10470    private static boolean isSystemApp(PackageSetting ps) {
10471        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10472    }
10473
10474    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10475        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10476    }
10477
10478    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10479        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10480    }
10481
10482    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10483        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10484    }
10485
10486    private int packageFlagsToInstallFlags(PackageSetting ps) {
10487        int installFlags = 0;
10488        if (isExternal(ps)) {
10489            installFlags |= PackageManager.INSTALL_EXTERNAL;
10490        }
10491        if (isForwardLocked(ps)) {
10492            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10493        }
10494        return installFlags;
10495    }
10496
10497    private void deleteTempPackageFiles() {
10498        final FilenameFilter filter = new FilenameFilter() {
10499            public boolean accept(File dir, String name) {
10500                return name.startsWith("vmdl") && name.endsWith(".tmp");
10501            }
10502        };
10503        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10504            file.delete();
10505        }
10506    }
10507
10508    @Override
10509    public void deletePackageAsUser(final String packageName,
10510                                    final IPackageDeleteObserver observer,
10511                                    final int userId, final int flags) {
10512        mContext.enforceCallingOrSelfPermission(
10513                android.Manifest.permission.DELETE_PACKAGES, null);
10514        final int uid = Binder.getCallingUid();
10515        if (UserHandle.getUserId(uid) != userId) {
10516            mContext.enforceCallingPermission(
10517                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10518                    "deletePackage for user " + userId);
10519        }
10520        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10521            try {
10522                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10523            } catch (RemoteException re) {
10524            }
10525            return;
10526        }
10527
10528        boolean blocked = false;
10529        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10530            int[] users = sUserManager.getUserIds();
10531            for (int i = 0; i < users.length; ++i) {
10532                if (getBlockUninstallForUser(packageName, users[i])) {
10533                    blocked = true;
10534                    break;
10535                }
10536            }
10537        } else {
10538            blocked = getBlockUninstallForUser(packageName, userId);
10539        }
10540        if (blocked) {
10541            try {
10542                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED);
10543            } catch (RemoteException re) {
10544            }
10545            return;
10546        }
10547
10548        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10549        // Queue up an async operation since the package deletion may take a little while.
10550        mHandler.post(new Runnable() {
10551            public void run() {
10552                mHandler.removeCallbacks(this);
10553                final int returnCode = deletePackageX(packageName, userId, flags);
10554                if (observer != null) {
10555                    try {
10556                        observer.packageDeleted(packageName, returnCode);
10557                    } catch (RemoteException e) {
10558                        Log.i(TAG, "Observer no longer exists.");
10559                    } //end catch
10560                } //end if
10561            } //end run
10562        });
10563    }
10564
10565    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10566        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10567                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10568        try {
10569            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10570                    || dpm.isDeviceOwner(packageName))) {
10571                return true;
10572            }
10573        } catch (RemoteException e) {
10574        }
10575        return false;
10576    }
10577
10578    /**
10579     *  This method is an internal method that could be get invoked either
10580     *  to delete an installed package or to clean up a failed installation.
10581     *  After deleting an installed package, a broadcast is sent to notify any
10582     *  listeners that the package has been installed. For cleaning up a failed
10583     *  installation, the broadcast is not necessary since the package's
10584     *  installation wouldn't have sent the initial broadcast either
10585     *  The key steps in deleting a package are
10586     *  deleting the package information in internal structures like mPackages,
10587     *  deleting the packages base directories through installd
10588     *  updating mSettings to reflect current status
10589     *  persisting settings for later use
10590     *  sending a broadcast if necessary
10591     */
10592    private int deletePackageX(String packageName, int userId, int flags) {
10593        final PackageRemovedInfo info = new PackageRemovedInfo();
10594        final boolean res;
10595
10596        if (isPackageDeviceAdmin(packageName, userId)) {
10597            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10598            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10599        }
10600
10601        boolean removedForAllUsers = false;
10602        boolean systemUpdate = false;
10603
10604        // for the uninstall-updates case and restricted profiles, remember the per-
10605        // userhandle installed state
10606        int[] allUsers;
10607        boolean[] perUserInstalled;
10608        synchronized (mPackages) {
10609            PackageSetting ps = mSettings.mPackages.get(packageName);
10610            allUsers = sUserManager.getUserIds();
10611            perUserInstalled = new boolean[allUsers.length];
10612            for (int i = 0; i < allUsers.length; i++) {
10613                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10614            }
10615        }
10616
10617        synchronized (mInstallLock) {
10618            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10619            res = deletePackageLI(packageName,
10620                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10621                            ? UserHandle.ALL : new UserHandle(userId),
10622                    true, allUsers, perUserInstalled,
10623                    flags | REMOVE_CHATTY, info, true);
10624            systemUpdate = info.isRemovedPackageSystemUpdate;
10625            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10626                removedForAllUsers = true;
10627            }
10628            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10629                    + " removedForAllUsers=" + removedForAllUsers);
10630        }
10631
10632        if (res) {
10633            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10634
10635            // If the removed package was a system update, the old system package
10636            // was re-enabled; we need to broadcast this information
10637            if (systemUpdate) {
10638                Bundle extras = new Bundle(1);
10639                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10640                        ? info.removedAppId : info.uid);
10641                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10642
10643                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10644                        extras, null, null, null);
10645                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10646                        extras, null, null, null);
10647                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10648                        null, packageName, null, null);
10649            }
10650        }
10651        // Force a gc here.
10652        Runtime.getRuntime().gc();
10653        // Delete the resources here after sending the broadcast to let
10654        // other processes clean up before deleting resources.
10655        if (info.args != null) {
10656            synchronized (mInstallLock) {
10657                info.args.doPostDeleteLI(true);
10658            }
10659        }
10660
10661        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10662    }
10663
10664    static class PackageRemovedInfo {
10665        String removedPackage;
10666        int uid = -1;
10667        int removedAppId = -1;
10668        int[] removedUsers = null;
10669        boolean isRemovedPackageSystemUpdate = false;
10670        // Clean up resources deleted packages.
10671        InstallArgs args = null;
10672
10673        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10674            Bundle extras = new Bundle(1);
10675            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10676            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10677            if (replacing) {
10678                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10679            }
10680            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10681            if (removedPackage != null) {
10682                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10683                        extras, null, null, removedUsers);
10684                if (fullRemove && !replacing) {
10685                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10686                            extras, null, null, removedUsers);
10687                }
10688            }
10689            if (removedAppId >= 0) {
10690                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10691                        removedUsers);
10692            }
10693        }
10694    }
10695
10696    /*
10697     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10698     * flag is not set, the data directory is removed as well.
10699     * make sure this flag is set for partially installed apps. If not its meaningless to
10700     * delete a partially installed application.
10701     */
10702    private void removePackageDataLI(PackageSetting ps,
10703            int[] allUserHandles, boolean[] perUserInstalled,
10704            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10705        String packageName = ps.name;
10706        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10707        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10708        // Retrieve object to delete permissions for shared user later on
10709        final PackageSetting deletedPs;
10710        // reader
10711        synchronized (mPackages) {
10712            deletedPs = mSettings.mPackages.get(packageName);
10713            if (outInfo != null) {
10714                outInfo.removedPackage = packageName;
10715                outInfo.removedUsers = deletedPs != null
10716                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10717                        : null;
10718            }
10719        }
10720        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10721            removeDataDirsLI(packageName);
10722            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10723        }
10724        // writer
10725        synchronized (mPackages) {
10726            if (deletedPs != null) {
10727                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10728                    if (outInfo != null) {
10729                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10730                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10731                    }
10732                    if (deletedPs != null) {
10733                        updatePermissionsLPw(deletedPs.name, null, 0);
10734                        if (deletedPs.sharedUser != null) {
10735                            // remove permissions associated with package
10736                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10737                        }
10738                    }
10739                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10740                }
10741                // make sure to preserve per-user disabled state if this removal was just
10742                // a downgrade of a system app to the factory package
10743                if (allUserHandles != null && perUserInstalled != null) {
10744                    if (DEBUG_REMOVE) {
10745                        Slog.d(TAG, "Propagating install state across downgrade");
10746                    }
10747                    for (int i = 0; i < allUserHandles.length; i++) {
10748                        if (DEBUG_REMOVE) {
10749                            Slog.d(TAG, "    user " + allUserHandles[i]
10750                                    + " => " + perUserInstalled[i]);
10751                        }
10752                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10753                    }
10754                }
10755            }
10756            // can downgrade to reader
10757            if (writeSettings) {
10758                // Save settings now
10759                mSettings.writeLPr();
10760            }
10761        }
10762        if (outInfo != null) {
10763            // A user ID was deleted here. Go through all users and remove it
10764            // from KeyStore.
10765            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10766        }
10767    }
10768
10769    static boolean locationIsPrivileged(File path) {
10770        try {
10771            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10772                    .getCanonicalPath();
10773            return path.getCanonicalPath().startsWith(privilegedAppDir);
10774        } catch (IOException e) {
10775            Slog.e(TAG, "Unable to access code path " + path);
10776        }
10777        return false;
10778    }
10779
10780    /*
10781     * Tries to delete system package.
10782     */
10783    private boolean deleteSystemPackageLI(PackageSetting newPs,
10784            int[] allUserHandles, boolean[] perUserInstalled,
10785            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10786        final boolean applyUserRestrictions
10787                = (allUserHandles != null) && (perUserInstalled != null);
10788        PackageSetting disabledPs = null;
10789        // Confirm if the system package has been updated
10790        // An updated system app can be deleted. This will also have to restore
10791        // the system pkg from system partition
10792        // reader
10793        synchronized (mPackages) {
10794            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10795        }
10796        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10797                + " disabledPs=" + disabledPs);
10798        if (disabledPs == null) {
10799            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10800            return false;
10801        } else if (DEBUG_REMOVE) {
10802            Slog.d(TAG, "Deleting system pkg from data partition");
10803        }
10804        if (DEBUG_REMOVE) {
10805            if (applyUserRestrictions) {
10806                Slog.d(TAG, "Remembering install states:");
10807                for (int i = 0; i < allUserHandles.length; i++) {
10808                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10809                }
10810            }
10811        }
10812        // Delete the updated package
10813        outInfo.isRemovedPackageSystemUpdate = true;
10814        if (disabledPs.versionCode < newPs.versionCode) {
10815            // Delete data for downgrades
10816            flags &= ~PackageManager.DELETE_KEEP_DATA;
10817        } else {
10818            // Preserve data by setting flag
10819            flags |= PackageManager.DELETE_KEEP_DATA;
10820        }
10821        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10822                allUserHandles, perUserInstalled, outInfo, writeSettings);
10823        if (!ret) {
10824            return false;
10825        }
10826        // writer
10827        synchronized (mPackages) {
10828            // Reinstate the old system package
10829            mSettings.enableSystemPackageLPw(newPs.name);
10830            // Remove any native libraries from the upgraded package.
10831            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10832        }
10833        // Install the system package
10834        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10835        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10836        if (locationIsPrivileged(disabledPs.codePath)) {
10837            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10838        }
10839
10840        final PackageParser.Package newPkg;
10841        try {
10842            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0,
10843                    null, null);
10844        } catch (PackageManagerException e) {
10845            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10846            return false;
10847        }
10848
10849        // writer
10850        synchronized (mPackages) {
10851            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10852            setBundledAppAbisAndRoots(newPkg, ps);
10853            updatePermissionsLPw(newPkg.packageName, newPkg,
10854                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10855            if (applyUserRestrictions) {
10856                if (DEBUG_REMOVE) {
10857                    Slog.d(TAG, "Propagating install state across reinstall");
10858                }
10859                for (int i = 0; i < allUserHandles.length; i++) {
10860                    if (DEBUG_REMOVE) {
10861                        Slog.d(TAG, "    user " + allUserHandles[i]
10862                                + " => " + perUserInstalled[i]);
10863                    }
10864                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10865                }
10866                // Regardless of writeSettings we need to ensure that this restriction
10867                // state propagation is persisted
10868                mSettings.writeAllUsersPackageRestrictionsLPr();
10869            }
10870            // can downgrade to reader here
10871            if (writeSettings) {
10872                mSettings.writeLPr();
10873            }
10874        }
10875        return true;
10876    }
10877
10878    private boolean deleteInstalledPackageLI(PackageSetting ps,
10879            boolean deleteCodeAndResources, int flags,
10880            int[] allUserHandles, boolean[] perUserInstalled,
10881            PackageRemovedInfo outInfo, boolean writeSettings) {
10882        if (outInfo != null) {
10883            outInfo.uid = ps.appId;
10884        }
10885
10886        // Delete package data from internal structures and also remove data if flag is set
10887        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10888
10889        // Delete application code and resources
10890        if (deleteCodeAndResources && (outInfo != null)) {
10891            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10892                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10893                    getAppDexInstructionSets(ps), isMultiArch(ps));
10894        }
10895        return true;
10896    }
10897
10898    @Override
10899    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10900            int userId) {
10901        mContext.enforceCallingOrSelfPermission(
10902                android.Manifest.permission.DELETE_PACKAGES, null);
10903        synchronized (mPackages) {
10904            PackageSetting ps = mSettings.mPackages.get(packageName);
10905            if (ps == null) {
10906                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10907                return false;
10908            }
10909            if (!ps.getInstalled(userId)) {
10910                // Can't block uninstall for an app that is not installed or enabled.
10911                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10912                return false;
10913            }
10914            ps.setBlockUninstall(blockUninstall, userId);
10915            mSettings.writePackageRestrictionsLPr(userId);
10916        }
10917        return true;
10918    }
10919
10920    @Override
10921    public boolean getBlockUninstallForUser(String packageName, int userId) {
10922        synchronized (mPackages) {
10923            PackageSetting ps = mSettings.mPackages.get(packageName);
10924            if (ps == null) {
10925                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10926                return false;
10927            }
10928            return ps.getBlockUninstall(userId);
10929        }
10930    }
10931
10932    /*
10933     * This method handles package deletion in general
10934     */
10935    private boolean deletePackageLI(String packageName, UserHandle user,
10936            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10937            int flags, PackageRemovedInfo outInfo,
10938            boolean writeSettings) {
10939        if (packageName == null) {
10940            Slog.w(TAG, "Attempt to delete null packageName.");
10941            return false;
10942        }
10943        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10944        PackageSetting ps;
10945        boolean dataOnly = false;
10946        int removeUser = -1;
10947        int appId = -1;
10948        synchronized (mPackages) {
10949            ps = mSettings.mPackages.get(packageName);
10950            if (ps == null) {
10951                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10952                return false;
10953            }
10954            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10955                    && user.getIdentifier() != UserHandle.USER_ALL) {
10956                // The caller is asking that the package only be deleted for a single
10957                // user.  To do this, we just mark its uninstalled state and delete
10958                // its data.  If this is a system app, we only allow this to happen if
10959                // they have set the special DELETE_SYSTEM_APP which requests different
10960                // semantics than normal for uninstalling system apps.
10961                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10962                ps.setUserState(user.getIdentifier(),
10963                        COMPONENT_ENABLED_STATE_DEFAULT,
10964                        false, //installed
10965                        true,  //stopped
10966                        true,  //notLaunched
10967                        false, //blocked
10968                        null, null, null,
10969                        false // blockUninstall
10970                        );
10971                if (!isSystemApp(ps)) {
10972                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10973                        // Other user still have this package installed, so all
10974                        // we need to do is clear this user's data and save that
10975                        // it is uninstalled.
10976                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10977                        removeUser = user.getIdentifier();
10978                        appId = ps.appId;
10979                        mSettings.writePackageRestrictionsLPr(removeUser);
10980                    } else {
10981                        // We need to set it back to 'installed' so the uninstall
10982                        // broadcasts will be sent correctly.
10983                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10984                        ps.setInstalled(true, user.getIdentifier());
10985                    }
10986                } else {
10987                    // This is a system app, so we assume that the
10988                    // other users still have this package installed, so all
10989                    // we need to do is clear this user's data and save that
10990                    // it is uninstalled.
10991                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10992                    removeUser = user.getIdentifier();
10993                    appId = ps.appId;
10994                    mSettings.writePackageRestrictionsLPr(removeUser);
10995                }
10996            }
10997        }
10998
10999        if (removeUser >= 0) {
11000            // From above, we determined that we are deleting this only
11001            // for a single user.  Continue the work here.
11002            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11003            if (outInfo != null) {
11004                outInfo.removedPackage = packageName;
11005                outInfo.removedAppId = appId;
11006                outInfo.removedUsers = new int[] {removeUser};
11007            }
11008            mInstaller.clearUserData(packageName, removeUser);
11009            removeKeystoreDataIfNeeded(removeUser, appId);
11010            schedulePackageCleaning(packageName, removeUser, false);
11011            return true;
11012        }
11013
11014        if (dataOnly) {
11015            // Delete application data first
11016            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11017            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11018            return true;
11019        }
11020
11021        boolean ret = false;
11022        if (isSystemApp(ps)) {
11023            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11024            // When an updated system application is deleted we delete the existing resources as well and
11025            // fall back to existing code in system partition
11026            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11027                    flags, outInfo, writeSettings);
11028        } else {
11029            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11030            // Kill application pre-emptively especially for apps on sd.
11031            killApplication(packageName, ps.appId, "uninstall pkg");
11032            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11033                    allUserHandles, perUserInstalled,
11034                    outInfo, writeSettings);
11035        }
11036
11037        return ret;
11038    }
11039
11040    private final class ClearStorageConnection implements ServiceConnection {
11041        IMediaContainerService mContainerService;
11042
11043        @Override
11044        public void onServiceConnected(ComponentName name, IBinder service) {
11045            synchronized (this) {
11046                mContainerService = IMediaContainerService.Stub.asInterface(service);
11047                notifyAll();
11048            }
11049        }
11050
11051        @Override
11052        public void onServiceDisconnected(ComponentName name) {
11053        }
11054    }
11055
11056    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11057        final boolean mounted;
11058        if (Environment.isExternalStorageEmulated()) {
11059            mounted = true;
11060        } else {
11061            final String status = Environment.getExternalStorageState();
11062
11063            mounted = status.equals(Environment.MEDIA_MOUNTED)
11064                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11065        }
11066
11067        if (!mounted) {
11068            return;
11069        }
11070
11071        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11072        int[] users;
11073        if (userId == UserHandle.USER_ALL) {
11074            users = sUserManager.getUserIds();
11075        } else {
11076            users = new int[] { userId };
11077        }
11078        final ClearStorageConnection conn = new ClearStorageConnection();
11079        if (mContext.bindServiceAsUser(
11080                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11081            try {
11082                for (int curUser : users) {
11083                    long timeout = SystemClock.uptimeMillis() + 5000;
11084                    synchronized (conn) {
11085                        long now = SystemClock.uptimeMillis();
11086                        while (conn.mContainerService == null && now < timeout) {
11087                            try {
11088                                conn.wait(timeout - now);
11089                            } catch (InterruptedException e) {
11090                            }
11091                        }
11092                    }
11093                    if (conn.mContainerService == null) {
11094                        return;
11095                    }
11096
11097                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11098                    clearDirectory(conn.mContainerService,
11099                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11100                    if (allData) {
11101                        clearDirectory(conn.mContainerService,
11102                                userEnv.buildExternalStorageAppDataDirs(packageName));
11103                        clearDirectory(conn.mContainerService,
11104                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11105                    }
11106                }
11107            } finally {
11108                mContext.unbindService(conn);
11109            }
11110        }
11111    }
11112
11113    @Override
11114    public void clearApplicationUserData(final String packageName,
11115            final IPackageDataObserver observer, final int userId) {
11116        mContext.enforceCallingOrSelfPermission(
11117                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11118        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11119        // Queue up an async operation since the package deletion may take a little while.
11120        mHandler.post(new Runnable() {
11121            public void run() {
11122                mHandler.removeCallbacks(this);
11123                final boolean succeeded;
11124                synchronized (mInstallLock) {
11125                    succeeded = clearApplicationUserDataLI(packageName, userId);
11126                }
11127                clearExternalStorageDataSync(packageName, userId, true);
11128                if (succeeded) {
11129                    // invoke DeviceStorageMonitor's update method to clear any notifications
11130                    DeviceStorageMonitorInternal
11131                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11132                    if (dsm != null) {
11133                        dsm.checkMemory();
11134                    }
11135                }
11136                if(observer != null) {
11137                    try {
11138                        observer.onRemoveCompleted(packageName, succeeded);
11139                    } catch (RemoteException e) {
11140                        Log.i(TAG, "Observer no longer exists.");
11141                    }
11142                } //end if observer
11143            } //end run
11144        });
11145    }
11146
11147    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11148        if (packageName == null) {
11149            Slog.w(TAG, "Attempt to delete null packageName.");
11150            return false;
11151        }
11152        PackageParser.Package p;
11153        boolean dataOnly = false;
11154        final int appId;
11155        synchronized (mPackages) {
11156            p = mPackages.get(packageName);
11157            if (p == null) {
11158                dataOnly = true;
11159                PackageSetting ps = mSettings.mPackages.get(packageName);
11160                if ((ps == null) || (ps.pkg == null)) {
11161                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11162                    return false;
11163                }
11164                p = ps.pkg;
11165            }
11166            if (!dataOnly) {
11167                // need to check this only for fully installed applications
11168                if (p == null) {
11169                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11170                    return false;
11171                }
11172                final ApplicationInfo applicationInfo = p.applicationInfo;
11173                if (applicationInfo == null) {
11174                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11175                    return false;
11176                }
11177            }
11178            if (p != null && p.applicationInfo != null) {
11179                appId = p.applicationInfo.uid;
11180            } else {
11181                appId = -1;
11182            }
11183        }
11184        int retCode = mInstaller.clearUserData(packageName, userId);
11185        if (retCode < 0) {
11186            Slog.w(TAG, "Couldn't remove cache files for package: "
11187                    + packageName);
11188            return false;
11189        }
11190        removeKeystoreDataIfNeeded(userId, appId);
11191        return true;
11192    }
11193
11194    /**
11195     * Remove entries from the keystore daemon. Will only remove it if the
11196     * {@code appId} is valid.
11197     */
11198    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11199        if (appId < 0) {
11200            return;
11201        }
11202
11203        final KeyStore keyStore = KeyStore.getInstance();
11204        if (keyStore != null) {
11205            if (userId == UserHandle.USER_ALL) {
11206                for (final int individual : sUserManager.getUserIds()) {
11207                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11208                }
11209            } else {
11210                keyStore.clearUid(UserHandle.getUid(userId, appId));
11211            }
11212        } else {
11213            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11214        }
11215    }
11216
11217    @Override
11218    public void deleteApplicationCacheFiles(final String packageName,
11219            final IPackageDataObserver observer) {
11220        mContext.enforceCallingOrSelfPermission(
11221                android.Manifest.permission.DELETE_CACHE_FILES, null);
11222        // Queue up an async operation since the package deletion may take a little while.
11223        final int userId = UserHandle.getCallingUserId();
11224        mHandler.post(new Runnable() {
11225            public void run() {
11226                mHandler.removeCallbacks(this);
11227                final boolean succeded;
11228                synchronized (mInstallLock) {
11229                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11230                }
11231                clearExternalStorageDataSync(packageName, userId, false);
11232                if(observer != null) {
11233                    try {
11234                        observer.onRemoveCompleted(packageName, succeded);
11235                    } catch (RemoteException e) {
11236                        Log.i(TAG, "Observer no longer exists.");
11237                    }
11238                } //end if observer
11239            } //end run
11240        });
11241    }
11242
11243    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11244        if (packageName == null) {
11245            Slog.w(TAG, "Attempt to delete null packageName.");
11246            return false;
11247        }
11248        PackageParser.Package p;
11249        synchronized (mPackages) {
11250            p = mPackages.get(packageName);
11251        }
11252        if (p == null) {
11253            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11254            return false;
11255        }
11256        final ApplicationInfo applicationInfo = p.applicationInfo;
11257        if (applicationInfo == null) {
11258            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11259            return false;
11260        }
11261        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11262        if (retCode < 0) {
11263            Slog.w(TAG, "Couldn't remove cache files for package: "
11264                       + packageName + " u" + userId);
11265            return false;
11266        }
11267        return true;
11268    }
11269
11270    @Override
11271    public void getPackageSizeInfo(final String packageName, int userHandle,
11272            final IPackageStatsObserver observer) {
11273        mContext.enforceCallingOrSelfPermission(
11274                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11275        if (packageName == null) {
11276            throw new IllegalArgumentException("Attempt to get size of null packageName");
11277        }
11278
11279        PackageStats stats = new PackageStats(packageName, userHandle);
11280
11281        /*
11282         * Queue up an async operation since the package measurement may take a
11283         * little while.
11284         */
11285        Message msg = mHandler.obtainMessage(INIT_COPY);
11286        msg.obj = new MeasureParams(stats, observer);
11287        mHandler.sendMessage(msg);
11288    }
11289
11290    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11291            PackageStats pStats) {
11292        if (packageName == null) {
11293            Slog.w(TAG, "Attempt to get size of null packageName.");
11294            return false;
11295        }
11296        PackageParser.Package p;
11297        boolean dataOnly = false;
11298        String libDirRoot = null;
11299        String asecPath = null;
11300        PackageSetting ps = null;
11301        synchronized (mPackages) {
11302            p = mPackages.get(packageName);
11303            ps = mSettings.mPackages.get(packageName);
11304            if(p == null) {
11305                dataOnly = true;
11306                if((ps == null) || (ps.pkg == null)) {
11307                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11308                    return false;
11309                }
11310                p = ps.pkg;
11311            }
11312            if (ps != null) {
11313                libDirRoot = ps.legacyNativeLibraryPathString;
11314            }
11315            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11316                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11317                if (secureContainerId != null) {
11318                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11319                }
11320            }
11321        }
11322        String publicSrcDir = null;
11323        if(!dataOnly) {
11324            final ApplicationInfo applicationInfo = p.applicationInfo;
11325            if (applicationInfo == null) {
11326                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11327                return false;
11328            }
11329            if (isForwardLocked(p)) {
11330                publicSrcDir = applicationInfo.getBaseResourcePath();
11331            }
11332        }
11333        // TODO: extend to measure size of split APKs
11334        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11335        // not just the first level.
11336        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11337        // just the primary.
11338        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11339                publicSrcDir, asecPath, getAppDexInstructionSets(ps),
11340                pStats);
11341        if (res < 0) {
11342            return false;
11343        }
11344
11345        // Fix-up for forward-locked applications in ASEC containers.
11346        if (!isExternal(p)) {
11347            pStats.codeSize += pStats.externalCodeSize;
11348            pStats.externalCodeSize = 0L;
11349        }
11350
11351        return true;
11352    }
11353
11354
11355    @Override
11356    public void addPackageToPreferred(String packageName) {
11357        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11358    }
11359
11360    @Override
11361    public void removePackageFromPreferred(String packageName) {
11362        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11363    }
11364
11365    @Override
11366    public List<PackageInfo> getPreferredPackages(int flags) {
11367        return new ArrayList<PackageInfo>();
11368    }
11369
11370    private int getUidTargetSdkVersionLockedLPr(int uid) {
11371        Object obj = mSettings.getUserIdLPr(uid);
11372        if (obj instanceof SharedUserSetting) {
11373            final SharedUserSetting sus = (SharedUserSetting) obj;
11374            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11375            final Iterator<PackageSetting> it = sus.packages.iterator();
11376            while (it.hasNext()) {
11377                final PackageSetting ps = it.next();
11378                if (ps.pkg != null) {
11379                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11380                    if (v < vers) vers = v;
11381                }
11382            }
11383            return vers;
11384        } else if (obj instanceof PackageSetting) {
11385            final PackageSetting ps = (PackageSetting) obj;
11386            if (ps.pkg != null) {
11387                return ps.pkg.applicationInfo.targetSdkVersion;
11388            }
11389        }
11390        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11391    }
11392
11393    @Override
11394    public void addPreferredActivity(IntentFilter filter, int match,
11395            ComponentName[] set, ComponentName activity, int userId) {
11396        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11397    }
11398
11399    private void addPreferredActivityInternal(IntentFilter filter, int match,
11400            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11401        // writer
11402        int callingUid = Binder.getCallingUid();
11403        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11404        if (filter.countActions() == 0) {
11405            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11406            return;
11407        }
11408        synchronized (mPackages) {
11409            if (mContext.checkCallingOrSelfPermission(
11410                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11411                    != PackageManager.PERMISSION_GRANTED) {
11412                if (getUidTargetSdkVersionLockedLPr(callingUid)
11413                        < Build.VERSION_CODES.FROYO) {
11414                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11415                            + callingUid);
11416                    return;
11417                }
11418                mContext.enforceCallingOrSelfPermission(
11419                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11420            }
11421
11422            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11423            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11424            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11425                    new PreferredActivity(filter, match, set, activity, always));
11426            mSettings.writePackageRestrictionsLPr(userId);
11427        }
11428    }
11429
11430    @Override
11431    public void replacePreferredActivity(IntentFilter filter, int match,
11432            ComponentName[] set, ComponentName activity) {
11433        if (filter.countActions() != 1) {
11434            throw new IllegalArgumentException(
11435                    "replacePreferredActivity expects filter to have only 1 action.");
11436        }
11437        if (filter.countDataAuthorities() != 0
11438                || filter.countDataPaths() != 0
11439                || filter.countDataSchemes() > 1
11440                || filter.countDataTypes() != 0) {
11441            throw new IllegalArgumentException(
11442                    "replacePreferredActivity expects filter to have no data authorities, " +
11443                    "paths, or types; and at most one scheme.");
11444        }
11445        synchronized (mPackages) {
11446            if (mContext.checkCallingOrSelfPermission(
11447                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11448                    != PackageManager.PERMISSION_GRANTED) {
11449                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11450                        < Build.VERSION_CODES.FROYO) {
11451                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11452                            + Binder.getCallingUid());
11453                    return;
11454                }
11455                mContext.enforceCallingOrSelfPermission(
11456                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11457            }
11458
11459            final int callingUserId = UserHandle.getCallingUserId();
11460            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11461            if (pir != null) {
11462                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11463                if (filter.countDataSchemes() == 1) {
11464                    Uri.Builder builder = new Uri.Builder();
11465                    builder.scheme(filter.getDataScheme(0));
11466                    intent.setData(builder.build());
11467                }
11468                List<PreferredActivity> matches = pir.queryIntent(
11469                        intent, null, true, callingUserId);
11470                if (DEBUG_PREFERRED) {
11471                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11472                }
11473                for (int i = 0; i < matches.size(); i++) {
11474                    PreferredActivity pa = matches.get(i);
11475                    if (DEBUG_PREFERRED) {
11476                        Slog.i(TAG, "Removing preferred activity "
11477                                + pa.mPref.mComponent + ":");
11478                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11479                    }
11480                    pir.removeFilter(pa);
11481                }
11482            }
11483            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11484        }
11485    }
11486
11487    @Override
11488    public void clearPackagePreferredActivities(String packageName) {
11489        final int uid = Binder.getCallingUid();
11490        // writer
11491        synchronized (mPackages) {
11492            PackageParser.Package pkg = mPackages.get(packageName);
11493            if (pkg == null || pkg.applicationInfo.uid != uid) {
11494                if (mContext.checkCallingOrSelfPermission(
11495                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11496                        != PackageManager.PERMISSION_GRANTED) {
11497                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11498                            < Build.VERSION_CODES.FROYO) {
11499                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11500                                + Binder.getCallingUid());
11501                        return;
11502                    }
11503                    mContext.enforceCallingOrSelfPermission(
11504                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11505                }
11506            }
11507
11508            int user = UserHandle.getCallingUserId();
11509            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11510                mSettings.writePackageRestrictionsLPr(user);
11511                scheduleWriteSettingsLocked();
11512            }
11513        }
11514    }
11515
11516    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11517    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11518        ArrayList<PreferredActivity> removed = null;
11519        boolean changed = false;
11520        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11521            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11522            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11523            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11524                continue;
11525            }
11526            Iterator<PreferredActivity> it = pir.filterIterator();
11527            while (it.hasNext()) {
11528                PreferredActivity pa = it.next();
11529                // Mark entry for removal only if it matches the package name
11530                // and the entry is of type "always".
11531                if (packageName == null ||
11532                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11533                                && pa.mPref.mAlways)) {
11534                    if (removed == null) {
11535                        removed = new ArrayList<PreferredActivity>();
11536                    }
11537                    removed.add(pa);
11538                }
11539            }
11540            if (removed != null) {
11541                for (int j=0; j<removed.size(); j++) {
11542                    PreferredActivity pa = removed.get(j);
11543                    pir.removeFilter(pa);
11544                }
11545                changed = true;
11546            }
11547        }
11548        return changed;
11549    }
11550
11551    @Override
11552    public void resetPreferredActivities(int userId) {
11553        mContext.enforceCallingOrSelfPermission(
11554                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11555        // writer
11556        synchronized (mPackages) {
11557            int user = UserHandle.getCallingUserId();
11558            clearPackagePreferredActivitiesLPw(null, user);
11559            mSettings.readDefaultPreferredAppsLPw(this, user);
11560            mSettings.writePackageRestrictionsLPr(user);
11561            scheduleWriteSettingsLocked();
11562        }
11563    }
11564
11565    @Override
11566    public int getPreferredActivities(List<IntentFilter> outFilters,
11567            List<ComponentName> outActivities, String packageName) {
11568
11569        int num = 0;
11570        final int userId = UserHandle.getCallingUserId();
11571        // reader
11572        synchronized (mPackages) {
11573            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11574            if (pir != null) {
11575                final Iterator<PreferredActivity> it = pir.filterIterator();
11576                while (it.hasNext()) {
11577                    final PreferredActivity pa = it.next();
11578                    if (packageName == null
11579                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11580                                    && pa.mPref.mAlways)) {
11581                        if (outFilters != null) {
11582                            outFilters.add(new IntentFilter(pa));
11583                        }
11584                        if (outActivities != null) {
11585                            outActivities.add(pa.mPref.mComponent);
11586                        }
11587                    }
11588                }
11589            }
11590        }
11591
11592        return num;
11593    }
11594
11595    @Override
11596    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11597            int userId) {
11598        int callingUid = Binder.getCallingUid();
11599        if (callingUid != Process.SYSTEM_UID) {
11600            throw new SecurityException(
11601                    "addPersistentPreferredActivity can only be run by the system");
11602        }
11603        if (filter.countActions() == 0) {
11604            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11605            return;
11606        }
11607        synchronized (mPackages) {
11608            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11609                    " :");
11610            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11611            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11612                    new PersistentPreferredActivity(filter, activity));
11613            mSettings.writePackageRestrictionsLPr(userId);
11614        }
11615    }
11616
11617    @Override
11618    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11619        int callingUid = Binder.getCallingUid();
11620        if (callingUid != Process.SYSTEM_UID) {
11621            throw new SecurityException(
11622                    "clearPackagePersistentPreferredActivities can only be run by the system");
11623        }
11624        ArrayList<PersistentPreferredActivity> removed = null;
11625        boolean changed = false;
11626        synchronized (mPackages) {
11627            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11628                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11629                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11630                        .valueAt(i);
11631                if (userId != thisUserId) {
11632                    continue;
11633                }
11634                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11635                while (it.hasNext()) {
11636                    PersistentPreferredActivity ppa = it.next();
11637                    // Mark entry for removal only if it matches the package name.
11638                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11639                        if (removed == null) {
11640                            removed = new ArrayList<PersistentPreferredActivity>();
11641                        }
11642                        removed.add(ppa);
11643                    }
11644                }
11645                if (removed != null) {
11646                    for (int j=0; j<removed.size(); j++) {
11647                        PersistentPreferredActivity ppa = removed.get(j);
11648                        ppir.removeFilter(ppa);
11649                    }
11650                    changed = true;
11651                }
11652            }
11653
11654            if (changed) {
11655                mSettings.writePackageRestrictionsLPr(userId);
11656            }
11657        }
11658    }
11659
11660    @Override
11661    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11662            int targetUserId, int flags) {
11663        mContext.enforceCallingOrSelfPermission(
11664                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11665        if (intentFilter.countActions() == 0) {
11666            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11667            return;
11668        }
11669        synchronized (mPackages) {
11670            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11671                    targetUserId, flags);
11672            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11673            mSettings.writePackageRestrictionsLPr(sourceUserId);
11674        }
11675    }
11676
11677    public void addCrossProfileIntentsForPackage(String packageName,
11678            int sourceUserId, int targetUserId) {
11679        mContext.enforceCallingOrSelfPermission(
11680                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11681        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11682        mSettings.writePackageRestrictionsLPr(sourceUserId);
11683    }
11684
11685    public void removeCrossProfileIntentsForPackage(String packageName,
11686            int sourceUserId, int targetUserId) {
11687        mContext.enforceCallingOrSelfPermission(
11688                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11689        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11690        mSettings.writePackageRestrictionsLPr(sourceUserId);
11691    }
11692
11693    @Override
11694    public void clearCrossProfileIntentFilters(int sourceUserId) {
11695        mContext.enforceCallingOrSelfPermission(
11696                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11697        synchronized (mPackages) {
11698            CrossProfileIntentResolver resolver =
11699                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11700            HashSet<CrossProfileIntentFilter> set =
11701                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11702            for (CrossProfileIntentFilter filter : set) {
11703                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11704                    resolver.removeFilter(filter);
11705                }
11706            }
11707            mSettings.writePackageRestrictionsLPr(sourceUserId);
11708        }
11709    }
11710
11711    @Override
11712    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11713        Intent intent = new Intent(Intent.ACTION_MAIN);
11714        intent.addCategory(Intent.CATEGORY_HOME);
11715
11716        final int callingUserId = UserHandle.getCallingUserId();
11717        List<ResolveInfo> list = queryIntentActivities(intent, null,
11718                PackageManager.GET_META_DATA, callingUserId);
11719        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11720                true, false, false, callingUserId);
11721
11722        allHomeCandidates.clear();
11723        if (list != null) {
11724            for (ResolveInfo ri : list) {
11725                allHomeCandidates.add(ri);
11726            }
11727        }
11728        return (preferred == null || preferred.activityInfo == null)
11729                ? null
11730                : new ComponentName(preferred.activityInfo.packageName,
11731                        preferred.activityInfo.name);
11732    }
11733
11734    @Override
11735    public void setApplicationEnabledSetting(String appPackageName,
11736            int newState, int flags, int userId, String callingPackage) {
11737        if (!sUserManager.exists(userId)) return;
11738        if (callingPackage == null) {
11739            callingPackage = Integer.toString(Binder.getCallingUid());
11740        }
11741        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11742    }
11743
11744    @Override
11745    public void setComponentEnabledSetting(ComponentName componentName,
11746            int newState, int flags, int userId) {
11747        if (!sUserManager.exists(userId)) return;
11748        setEnabledSetting(componentName.getPackageName(),
11749                componentName.getClassName(), newState, flags, userId, null);
11750    }
11751
11752    private void setEnabledSetting(final String packageName, String className, int newState,
11753            final int flags, int userId, String callingPackage) {
11754        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11755              || newState == COMPONENT_ENABLED_STATE_ENABLED
11756              || newState == COMPONENT_ENABLED_STATE_DISABLED
11757              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11758              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11759            throw new IllegalArgumentException("Invalid new component state: "
11760                    + newState);
11761        }
11762        PackageSetting pkgSetting;
11763        final int uid = Binder.getCallingUid();
11764        final int permission = mContext.checkCallingOrSelfPermission(
11765                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11766        enforceCrossUserPermission(uid, userId, false, "set enabled");
11767        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11768        boolean sendNow = false;
11769        boolean isApp = (className == null);
11770        String componentName = isApp ? packageName : className;
11771        int packageUid = -1;
11772        ArrayList<String> components;
11773
11774        // writer
11775        synchronized (mPackages) {
11776            pkgSetting = mSettings.mPackages.get(packageName);
11777            if (pkgSetting == null) {
11778                if (className == null) {
11779                    throw new IllegalArgumentException(
11780                            "Unknown package: " + packageName);
11781                }
11782                throw new IllegalArgumentException(
11783                        "Unknown component: " + packageName
11784                        + "/" + className);
11785            }
11786            // Allow root and verify that userId is not being specified by a different user
11787            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11788                throw new SecurityException(
11789                        "Permission Denial: attempt to change component state from pid="
11790                        + Binder.getCallingPid()
11791                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11792            }
11793            if (className == null) {
11794                // We're dealing with an application/package level state change
11795                if (pkgSetting.getEnabled(userId) == newState) {
11796                    // Nothing to do
11797                    return;
11798                }
11799                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11800                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11801                    // Don't care about who enables an app.
11802                    callingPackage = null;
11803                }
11804                pkgSetting.setEnabled(newState, userId, callingPackage);
11805                // pkgSetting.pkg.mSetEnabled = newState;
11806            } else {
11807                // We're dealing with a component level state change
11808                // First, verify that this is a valid class name.
11809                PackageParser.Package pkg = pkgSetting.pkg;
11810                if (pkg == null || !pkg.hasComponentClassName(className)) {
11811                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11812                        throw new IllegalArgumentException("Component class " + className
11813                                + " does not exist in " + packageName);
11814                    } else {
11815                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11816                                + className + " does not exist in " + packageName);
11817                    }
11818                }
11819                switch (newState) {
11820                case COMPONENT_ENABLED_STATE_ENABLED:
11821                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11822                        return;
11823                    }
11824                    break;
11825                case COMPONENT_ENABLED_STATE_DISABLED:
11826                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11827                        return;
11828                    }
11829                    break;
11830                case COMPONENT_ENABLED_STATE_DEFAULT:
11831                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11832                        return;
11833                    }
11834                    break;
11835                default:
11836                    Slog.e(TAG, "Invalid new component state: " + newState);
11837                    return;
11838                }
11839            }
11840            mSettings.writePackageRestrictionsLPr(userId);
11841            components = mPendingBroadcasts.get(userId, packageName);
11842            final boolean newPackage = components == null;
11843            if (newPackage) {
11844                components = new ArrayList<String>();
11845            }
11846            if (!components.contains(componentName)) {
11847                components.add(componentName);
11848            }
11849            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11850                sendNow = true;
11851                // Purge entry from pending broadcast list if another one exists already
11852                // since we are sending one right away.
11853                mPendingBroadcasts.remove(userId, packageName);
11854            } else {
11855                if (newPackage) {
11856                    mPendingBroadcasts.put(userId, packageName, components);
11857                }
11858                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11859                    // Schedule a message
11860                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11861                }
11862            }
11863        }
11864
11865        long callingId = Binder.clearCallingIdentity();
11866        try {
11867            if (sendNow) {
11868                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11869                sendPackageChangedBroadcast(packageName,
11870                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11871            }
11872        } finally {
11873            Binder.restoreCallingIdentity(callingId);
11874        }
11875    }
11876
11877    private void sendPackageChangedBroadcast(String packageName,
11878            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11879        if (DEBUG_INSTALL)
11880            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11881                    + componentNames);
11882        Bundle extras = new Bundle(4);
11883        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11884        String nameList[] = new String[componentNames.size()];
11885        componentNames.toArray(nameList);
11886        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11887        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11888        extras.putInt(Intent.EXTRA_UID, packageUid);
11889        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11890                new int[] {UserHandle.getUserId(packageUid)});
11891    }
11892
11893    @Override
11894    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11895        if (!sUserManager.exists(userId)) return;
11896        final int uid = Binder.getCallingUid();
11897        final int permission = mContext.checkCallingOrSelfPermission(
11898                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11899        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11900        enforceCrossUserPermission(uid, userId, true, "stop package");
11901        // writer
11902        synchronized (mPackages) {
11903            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11904                    uid, userId)) {
11905                scheduleWritePackageRestrictionsLocked(userId);
11906            }
11907        }
11908    }
11909
11910    @Override
11911    public String getInstallerPackageName(String packageName) {
11912        // reader
11913        synchronized (mPackages) {
11914            return mSettings.getInstallerPackageNameLPr(packageName);
11915        }
11916    }
11917
11918    @Override
11919    public int getApplicationEnabledSetting(String packageName, int userId) {
11920        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11921        int uid = Binder.getCallingUid();
11922        enforceCrossUserPermission(uid, userId, false, "get enabled");
11923        // reader
11924        synchronized (mPackages) {
11925            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11926        }
11927    }
11928
11929    @Override
11930    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11931        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11932        int uid = Binder.getCallingUid();
11933        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11934        // reader
11935        synchronized (mPackages) {
11936            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11937        }
11938    }
11939
11940    @Override
11941    public void enterSafeMode() {
11942        enforceSystemOrRoot("Only the system can request entering safe mode");
11943
11944        if (!mSystemReady) {
11945            mSafeMode = true;
11946        }
11947    }
11948
11949    @Override
11950    public void systemReady() {
11951        mSystemReady = true;
11952
11953        // Read the compatibilty setting when the system is ready.
11954        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11955                mContext.getContentResolver(),
11956                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11957        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11958        if (DEBUG_SETTINGS) {
11959            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11960        }
11961
11962        synchronized (mPackages) {
11963            // Verify that all of the preferred activity components actually
11964            // exist.  It is possible for applications to be updated and at
11965            // that point remove a previously declared activity component that
11966            // had been set as a preferred activity.  We try to clean this up
11967            // the next time we encounter that preferred activity, but it is
11968            // possible for the user flow to never be able to return to that
11969            // situation so here we do a sanity check to make sure we haven't
11970            // left any junk around.
11971            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11972            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11973                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11974                removed.clear();
11975                for (PreferredActivity pa : pir.filterSet()) {
11976                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11977                        removed.add(pa);
11978                    }
11979                }
11980                if (removed.size() > 0) {
11981                    for (int r=0; r<removed.size(); r++) {
11982                        PreferredActivity pa = removed.get(r);
11983                        Slog.w(TAG, "Removing dangling preferred activity: "
11984                                + pa.mPref.mComponent);
11985                        pir.removeFilter(pa);
11986                    }
11987                    mSettings.writePackageRestrictionsLPr(
11988                            mSettings.mPreferredActivities.keyAt(i));
11989                }
11990            }
11991        }
11992        sUserManager.systemReady();
11993    }
11994
11995    @Override
11996    public boolean isSafeMode() {
11997        return mSafeMode;
11998    }
11999
12000    @Override
12001    public boolean hasSystemUidErrors() {
12002        return mHasSystemUidErrors;
12003    }
12004
12005    static String arrayToString(int[] array) {
12006        StringBuffer buf = new StringBuffer(128);
12007        buf.append('[');
12008        if (array != null) {
12009            for (int i=0; i<array.length; i++) {
12010                if (i > 0) buf.append(", ");
12011                buf.append(array[i]);
12012            }
12013        }
12014        buf.append(']');
12015        return buf.toString();
12016    }
12017
12018    static class DumpState {
12019        public static final int DUMP_LIBS = 1 << 0;
12020        public static final int DUMP_FEATURES = 1 << 1;
12021        public static final int DUMP_RESOLVERS = 1 << 2;
12022        public static final int DUMP_PERMISSIONS = 1 << 3;
12023        public static final int DUMP_PACKAGES = 1 << 4;
12024        public static final int DUMP_SHARED_USERS = 1 << 5;
12025        public static final int DUMP_MESSAGES = 1 << 6;
12026        public static final int DUMP_PROVIDERS = 1 << 7;
12027        public static final int DUMP_VERIFIERS = 1 << 8;
12028        public static final int DUMP_PREFERRED = 1 << 9;
12029        public static final int DUMP_PREFERRED_XML = 1 << 10;
12030        public static final int DUMP_KEYSETS = 1 << 11;
12031        public static final int DUMP_VERSION = 1 << 12;
12032        public static final int DUMP_INSTALLS = 1 << 13;
12033
12034        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12035
12036        private int mTypes;
12037
12038        private int mOptions;
12039
12040        private boolean mTitlePrinted;
12041
12042        private SharedUserSetting mSharedUser;
12043
12044        public boolean isDumping(int type) {
12045            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12046                return true;
12047            }
12048
12049            return (mTypes & type) != 0;
12050        }
12051
12052        public void setDump(int type) {
12053            mTypes |= type;
12054        }
12055
12056        public boolean isOptionEnabled(int option) {
12057            return (mOptions & option) != 0;
12058        }
12059
12060        public void setOptionEnabled(int option) {
12061            mOptions |= option;
12062        }
12063
12064        public boolean onTitlePrinted() {
12065            final boolean printed = mTitlePrinted;
12066            mTitlePrinted = true;
12067            return printed;
12068        }
12069
12070        public boolean getTitlePrinted() {
12071            return mTitlePrinted;
12072        }
12073
12074        public void setTitlePrinted(boolean enabled) {
12075            mTitlePrinted = enabled;
12076        }
12077
12078        public SharedUserSetting getSharedUser() {
12079            return mSharedUser;
12080        }
12081
12082        public void setSharedUser(SharedUserSetting user) {
12083            mSharedUser = user;
12084        }
12085    }
12086
12087    @Override
12088    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12089        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12090                != PackageManager.PERMISSION_GRANTED) {
12091            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12092                    + Binder.getCallingPid()
12093                    + ", uid=" + Binder.getCallingUid()
12094                    + " without permission "
12095                    + android.Manifest.permission.DUMP);
12096            return;
12097        }
12098
12099        DumpState dumpState = new DumpState();
12100        boolean fullPreferred = false;
12101        boolean checkin = false;
12102
12103        String packageName = null;
12104
12105        int opti = 0;
12106        while (opti < args.length) {
12107            String opt = args[opti];
12108            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12109                break;
12110            }
12111            opti++;
12112            if ("-a".equals(opt)) {
12113                // Right now we only know how to print all.
12114            } else if ("-h".equals(opt)) {
12115                pw.println("Package manager dump options:");
12116                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12117                pw.println("    --checkin: dump for a checkin");
12118                pw.println("    -f: print details of intent filters");
12119                pw.println("    -h: print this help");
12120                pw.println("  cmd may be one of:");
12121                pw.println("    l[ibraries]: list known shared libraries");
12122                pw.println("    f[ibraries]: list device features");
12123                pw.println("    k[eysets]: print known keysets");
12124                pw.println("    r[esolvers]: dump intent resolvers");
12125                pw.println("    perm[issions]: dump permissions");
12126                pw.println("    pref[erred]: print preferred package settings");
12127                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12128                pw.println("    prov[iders]: dump content providers");
12129                pw.println("    p[ackages]: dump installed packages");
12130                pw.println("    s[hared-users]: dump shared user IDs");
12131                pw.println("    m[essages]: print collected runtime messages");
12132                pw.println("    v[erifiers]: print package verifier info");
12133                pw.println("    version: print database version info");
12134                pw.println("    write: write current settings now");
12135                pw.println("    <package.name>: info about given package");
12136                pw.println("    installs: details about install sessions");
12137                return;
12138            } else if ("--checkin".equals(opt)) {
12139                checkin = true;
12140            } else if ("-f".equals(opt)) {
12141                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12142            } else {
12143                pw.println("Unknown argument: " + opt + "; use -h for help");
12144            }
12145        }
12146
12147        // Is the caller requesting to dump a particular piece of data?
12148        if (opti < args.length) {
12149            String cmd = args[opti];
12150            opti++;
12151            // Is this a package name?
12152            if ("android".equals(cmd) || cmd.contains(".")) {
12153                packageName = cmd;
12154                // When dumping a single package, we always dump all of its
12155                // filter information since the amount of data will be reasonable.
12156                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12157            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12158                dumpState.setDump(DumpState.DUMP_LIBS);
12159            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12160                dumpState.setDump(DumpState.DUMP_FEATURES);
12161            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12162                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12163            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12164                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12165            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12166                dumpState.setDump(DumpState.DUMP_PREFERRED);
12167            } else if ("preferred-xml".equals(cmd)) {
12168                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12169                if (opti < args.length && "--full".equals(args[opti])) {
12170                    fullPreferred = true;
12171                    opti++;
12172                }
12173            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12174                dumpState.setDump(DumpState.DUMP_PACKAGES);
12175            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12176                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12177            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12178                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12179            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12180                dumpState.setDump(DumpState.DUMP_MESSAGES);
12181            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12182                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12183            } else if ("version".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_VERSION);
12185            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12186                dumpState.setDump(DumpState.DUMP_KEYSETS);
12187            } else if ("write".equals(cmd)) {
12188                synchronized (mPackages) {
12189                    mSettings.writeLPr();
12190                    pw.println("Settings written.");
12191                    return;
12192                }
12193            } else if ("installs".equals(cmd)) {
12194                dumpState.setDump(DumpState.DUMP_INSTALLS);
12195            }
12196        }
12197
12198        if (checkin) {
12199            pw.println("vers,1");
12200        }
12201
12202        // reader
12203        synchronized (mPackages) {
12204            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12205                if (!checkin) {
12206                    if (dumpState.onTitlePrinted())
12207                        pw.println();
12208                    pw.println("Database versions:");
12209                    pw.print("  SDK Version:");
12210                    pw.print(" internal=");
12211                    pw.print(mSettings.mInternalSdkPlatform);
12212                    pw.print(" external=");
12213                    pw.println(mSettings.mExternalSdkPlatform);
12214                    pw.print("  DB Version:");
12215                    pw.print(" internal=");
12216                    pw.print(mSettings.mInternalDatabaseVersion);
12217                    pw.print(" external=");
12218                    pw.println(mSettings.mExternalDatabaseVersion);
12219                }
12220            }
12221
12222            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12223                if (!checkin) {
12224                    if (dumpState.onTitlePrinted())
12225                        pw.println();
12226                    pw.println("Verifiers:");
12227                    pw.print("  Required: ");
12228                    pw.print(mRequiredVerifierPackage);
12229                    pw.print(" (uid=");
12230                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12231                    pw.println(")");
12232                } else if (mRequiredVerifierPackage != null) {
12233                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12234                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12235                }
12236            }
12237
12238            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12239                boolean printedHeader = false;
12240                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12241                while (it.hasNext()) {
12242                    String name = it.next();
12243                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12244                    if (!checkin) {
12245                        if (!printedHeader) {
12246                            if (dumpState.onTitlePrinted())
12247                                pw.println();
12248                            pw.println("Libraries:");
12249                            printedHeader = true;
12250                        }
12251                        pw.print("  ");
12252                    } else {
12253                        pw.print("lib,");
12254                    }
12255                    pw.print(name);
12256                    if (!checkin) {
12257                        pw.print(" -> ");
12258                    }
12259                    if (ent.path != null) {
12260                        if (!checkin) {
12261                            pw.print("(jar) ");
12262                            pw.print(ent.path);
12263                        } else {
12264                            pw.print(",jar,");
12265                            pw.print(ent.path);
12266                        }
12267                    } else {
12268                        if (!checkin) {
12269                            pw.print("(apk) ");
12270                            pw.print(ent.apk);
12271                        } else {
12272                            pw.print(",apk,");
12273                            pw.print(ent.apk);
12274                        }
12275                    }
12276                    pw.println();
12277                }
12278            }
12279
12280            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12281                if (dumpState.onTitlePrinted())
12282                    pw.println();
12283                if (!checkin) {
12284                    pw.println("Features:");
12285                }
12286                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12287                while (it.hasNext()) {
12288                    String name = it.next();
12289                    if (!checkin) {
12290                        pw.print("  ");
12291                    } else {
12292                        pw.print("feat,");
12293                    }
12294                    pw.println(name);
12295                }
12296            }
12297
12298            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12299                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12300                        : "Activity Resolver Table:", "  ", packageName,
12301                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12302                    dumpState.setTitlePrinted(true);
12303                }
12304                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12305                        : "Receiver Resolver Table:", "  ", packageName,
12306                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12307                    dumpState.setTitlePrinted(true);
12308                }
12309                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12310                        : "Service Resolver Table:", "  ", packageName,
12311                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12312                    dumpState.setTitlePrinted(true);
12313                }
12314                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12315                        : "Provider Resolver Table:", "  ", packageName,
12316                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12317                    dumpState.setTitlePrinted(true);
12318                }
12319            }
12320
12321            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12322                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12323                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12324                    int user = mSettings.mPreferredActivities.keyAt(i);
12325                    if (pir.dump(pw,
12326                            dumpState.getTitlePrinted()
12327                                ? "\nPreferred Activities User " + user + ":"
12328                                : "Preferred Activities User " + user + ":", "  ",
12329                            packageName, true)) {
12330                        dumpState.setTitlePrinted(true);
12331                    }
12332                }
12333            }
12334
12335            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12336                pw.flush();
12337                FileOutputStream fout = new FileOutputStream(fd);
12338                BufferedOutputStream str = new BufferedOutputStream(fout);
12339                XmlSerializer serializer = new FastXmlSerializer();
12340                try {
12341                    serializer.setOutput(str, "utf-8");
12342                    serializer.startDocument(null, true);
12343                    serializer.setFeature(
12344                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12345                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12346                    serializer.endDocument();
12347                    serializer.flush();
12348                } catch (IllegalArgumentException e) {
12349                    pw.println("Failed writing: " + e);
12350                } catch (IllegalStateException e) {
12351                    pw.println("Failed writing: " + e);
12352                } catch (IOException e) {
12353                    pw.println("Failed writing: " + e);
12354                }
12355            }
12356
12357            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12358                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12359            }
12360
12361            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12362                boolean printedSomething = false;
12363                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12364                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12365                        continue;
12366                    }
12367                    if (!printedSomething) {
12368                        if (dumpState.onTitlePrinted())
12369                            pw.println();
12370                        pw.println("Registered ContentProviders:");
12371                        printedSomething = true;
12372                    }
12373                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12374                    pw.print("    "); pw.println(p.toString());
12375                }
12376                printedSomething = false;
12377                for (Map.Entry<String, PackageParser.Provider> entry :
12378                        mProvidersByAuthority.entrySet()) {
12379                    PackageParser.Provider p = entry.getValue();
12380                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12381                        continue;
12382                    }
12383                    if (!printedSomething) {
12384                        if (dumpState.onTitlePrinted())
12385                            pw.println();
12386                        pw.println("ContentProvider Authorities:");
12387                        printedSomething = true;
12388                    }
12389                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12390                    pw.print("    "); pw.println(p.toString());
12391                    if (p.info != null && p.info.applicationInfo != null) {
12392                        final String appInfo = p.info.applicationInfo.toString();
12393                        pw.print("      applicationInfo="); pw.println(appInfo);
12394                    }
12395                }
12396            }
12397
12398            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12399                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12400            }
12401
12402            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12403                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12404            }
12405
12406            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12407                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12408            }
12409
12410            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12411                if (dumpState.onTitlePrinted()) pw.println();
12412                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12413            }
12414
12415            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12416                if (dumpState.onTitlePrinted()) pw.println();
12417                mSettings.dumpReadMessagesLPr(pw, dumpState);
12418
12419                pw.println();
12420                pw.println("Package warning messages:");
12421                final File fname = getSettingsProblemFile();
12422                FileInputStream in = null;
12423                try {
12424                    in = new FileInputStream(fname);
12425                    final int avail = in.available();
12426                    final byte[] data = new byte[avail];
12427                    in.read(data);
12428                    pw.print(new String(data));
12429                } catch (FileNotFoundException e) {
12430                } catch (IOException e) {
12431                } finally {
12432                    if (in != null) {
12433                        try {
12434                            in.close();
12435                        } catch (IOException e) {
12436                        }
12437                    }
12438                }
12439            }
12440        }
12441    }
12442
12443    // ------- apps on sdcard specific code -------
12444    static final boolean DEBUG_SD_INSTALL = false;
12445
12446    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12447
12448    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12449
12450    private boolean mMediaMounted = false;
12451
12452    private String getEncryptKey() {
12453        try {
12454            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12455                    SD_ENCRYPTION_KEYSTORE_NAME);
12456            if (sdEncKey == null) {
12457                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12458                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12459                if (sdEncKey == null) {
12460                    Slog.e(TAG, "Failed to create encryption keys");
12461                    return null;
12462                }
12463            }
12464            return sdEncKey;
12465        } catch (NoSuchAlgorithmException nsae) {
12466            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12467            return null;
12468        } catch (IOException ioe) {
12469            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12470            return null;
12471        }
12472
12473    }
12474
12475    /* package */static String getTempContainerId() {
12476        int tmpIdx = 1;
12477        String list[] = PackageHelper.getSecureContainerList();
12478        if (list != null) {
12479            for (final String name : list) {
12480                // Ignore null and non-temporary container entries
12481                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12482                    continue;
12483                }
12484
12485                String subStr = name.substring(mTempContainerPrefix.length());
12486                try {
12487                    int cid = Integer.parseInt(subStr);
12488                    if (cid >= tmpIdx) {
12489                        tmpIdx = cid + 1;
12490                    }
12491                } catch (NumberFormatException e) {
12492                }
12493            }
12494        }
12495        return mTempContainerPrefix + tmpIdx;
12496    }
12497
12498    /*
12499     * Update media status on PackageManager.
12500     */
12501    @Override
12502    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12503        int callingUid = Binder.getCallingUid();
12504        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12505            throw new SecurityException("Media status can only be updated by the system");
12506        }
12507        // reader; this apparently protects mMediaMounted, but should probably
12508        // be a different lock in that case.
12509        synchronized (mPackages) {
12510            Log.i(TAG, "Updating external media status from "
12511                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12512                    + (mediaStatus ? "mounted" : "unmounted"));
12513            if (DEBUG_SD_INSTALL)
12514                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12515                        + ", mMediaMounted=" + mMediaMounted);
12516            if (mediaStatus == mMediaMounted) {
12517                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12518                        : 0, -1);
12519                mHandler.sendMessage(msg);
12520                return;
12521            }
12522            mMediaMounted = mediaStatus;
12523        }
12524        // Queue up an async operation since the package installation may take a
12525        // little while.
12526        mHandler.post(new Runnable() {
12527            public void run() {
12528                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12529            }
12530        });
12531    }
12532
12533    /**
12534     * Called by MountService when the initial ASECs to scan are available.
12535     * Should block until all the ASEC containers are finished being scanned.
12536     */
12537    public void scanAvailableAsecs() {
12538        updateExternalMediaStatusInner(true, false, false);
12539        if (mShouldRestoreconData) {
12540            SELinuxMMAC.setRestoreconDone();
12541            mShouldRestoreconData = false;
12542        }
12543    }
12544
12545    /*
12546     * Collect information of applications on external media, map them against
12547     * existing containers and update information based on current mount status.
12548     * Please note that we always have to report status if reportStatus has been
12549     * set to true especially when unloading packages.
12550     */
12551    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12552            boolean externalStorage) {
12553        // Collection of uids
12554        int uidArr[] = null;
12555        // Collection of stale containers
12556        HashSet<String> removeCids = new HashSet<String>();
12557        // Collection of packages on external media with valid containers.
12558        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12559        // Get list of secure containers.
12560        final String list[] = PackageHelper.getSecureContainerList();
12561        if (list == null || list.length == 0) {
12562            Log.i(TAG, "No secure containers on sdcard");
12563        } else {
12564            // Process list of secure containers and categorize them
12565            // as active or stale based on their package internal state.
12566            int uidList[] = new int[list.length];
12567            int num = 0;
12568            // reader
12569            synchronized (mPackages) {
12570                for (String cid : list) {
12571                    if (DEBUG_SD_INSTALL)
12572                        Log.i(TAG, "Processing container " + cid);
12573                    String pkgName = getAsecPackageName(cid);
12574                    if (pkgName == null) {
12575                        if (DEBUG_SD_INSTALL)
12576                            Log.i(TAG, "Container : " + cid + " stale");
12577                        removeCids.add(cid);
12578                        continue;
12579                    }
12580                    if (DEBUG_SD_INSTALL)
12581                        Log.i(TAG, "Looking for pkg : " + pkgName);
12582
12583                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12584                    if (ps == null) {
12585                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12586                        removeCids.add(cid);
12587                        continue;
12588                    }
12589
12590                    /*
12591                     * Skip packages that are not external if we're unmounting
12592                     * external storage.
12593                     */
12594                    if (externalStorage && !isMounted && !isExternal(ps)) {
12595                        continue;
12596                    }
12597
12598                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12599                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12600                    // The package status is changed only if the code path
12601                    // matches between settings and the container id.
12602                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12603                        if (DEBUG_SD_INSTALL) {
12604                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12605                                    + " at code path: " + ps.codePathString);
12606                        }
12607
12608                        // We do have a valid package installed on sdcard
12609                        processCids.put(args, ps.codePathString);
12610                        final int uid = ps.appId;
12611                        if (uid != -1) {
12612                            uidList[num++] = uid;
12613                        }
12614                    } else {
12615                        Log.i(TAG, "Deleting stale container for " + cid);
12616                        removeCids.add(cid);
12617                    }
12618                }
12619            }
12620
12621            if (num > 0) {
12622                // Sort uid list
12623                Arrays.sort(uidList, 0, num);
12624                // Throw away duplicates
12625                uidArr = new int[num];
12626                uidArr[0] = uidList[0];
12627                int di = 0;
12628                for (int i = 1; i < num; i++) {
12629                    if (uidList[i - 1] != uidList[i]) {
12630                        uidArr[di++] = uidList[i];
12631                    }
12632                }
12633            }
12634        }
12635        // Process packages with valid entries.
12636        if (isMounted) {
12637            if (DEBUG_SD_INSTALL)
12638                Log.i(TAG, "Loading packages");
12639            loadMediaPackages(processCids, uidArr, removeCids);
12640            startCleaningPackages();
12641        } else {
12642            if (DEBUG_SD_INSTALL)
12643                Log.i(TAG, "Unloading packages");
12644            unloadMediaPackages(processCids, uidArr, reportStatus);
12645        }
12646    }
12647
12648   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12649           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12650        int size = pkgList.size();
12651        if (size > 0) {
12652            // Send broadcasts here
12653            Bundle extras = new Bundle();
12654            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12655                    .toArray(new String[size]));
12656            if (uidArr != null) {
12657                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12658            }
12659            if (replacing) {
12660                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12661            }
12662            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12663                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12664            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12665        }
12666    }
12667
12668   /*
12669     * Look at potentially valid container ids from processCids If package
12670     * information doesn't match the one on record or package scanning fails,
12671     * the cid is added to list of removeCids. We currently don't delete stale
12672     * containers.
12673     */
12674   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12675            HashSet<String> removeCids) {
12676        ArrayList<String> pkgList = new ArrayList<String>();
12677        Set<AsecInstallArgs> keys = processCids.keySet();
12678        boolean doGc = false;
12679        for (AsecInstallArgs args : keys) {
12680            String codePath = processCids.get(args);
12681            if (DEBUG_SD_INSTALL)
12682                Log.i(TAG, "Loading container : " + args.cid);
12683            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12684            try {
12685                // Make sure there are no container errors first.
12686                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12687                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12688                            + " when installing from sdcard");
12689                    continue;
12690                }
12691                // Check code path here.
12692                if (codePath == null || !codePath.equals(args.getCodePath())) {
12693                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12694                            + " does not match one in settings " + codePath);
12695                    continue;
12696                }
12697                // Parse package
12698                int parseFlags = mDefParseFlags;
12699                if (args.isExternal()) {
12700                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12701                }
12702                if (args.isFwdLocked()) {
12703                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12704                }
12705
12706                doGc = true;
12707                synchronized (mInstallLock) {
12708                    PackageParser.Package pkg = null;
12709                    try {
12710                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null);
12711                    } catch (PackageManagerException e) {
12712                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12713                    }
12714                    // Scan the package
12715                    if (pkg != null) {
12716                        /*
12717                         * TODO why is the lock being held? doPostInstall is
12718                         * called in other places without the lock. This needs
12719                         * to be straightened out.
12720                         */
12721                        // writer
12722                        synchronized (mPackages) {
12723                            retCode = PackageManager.INSTALL_SUCCEEDED;
12724                            pkgList.add(pkg.packageName);
12725                            // Post process args
12726                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12727                                    pkg.applicationInfo.uid);
12728                        }
12729                    } else {
12730                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12731                    }
12732                }
12733
12734            } finally {
12735                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12736                    // Don't destroy container here. Wait till gc clears things
12737                    // up.
12738                    removeCids.add(args.cid);
12739                }
12740            }
12741        }
12742        // writer
12743        synchronized (mPackages) {
12744            // If the platform SDK has changed since the last time we booted,
12745            // we need to re-grant app permission to catch any new ones that
12746            // appear. This is really a hack, and means that apps can in some
12747            // cases get permissions that the user didn't initially explicitly
12748            // allow... it would be nice to have some better way to handle
12749            // this situation.
12750            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12751            if (regrantPermissions)
12752                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12753                        + mSdkVersion + "; regranting permissions for external storage");
12754            mSettings.mExternalSdkPlatform = mSdkVersion;
12755
12756            // Make sure group IDs have been assigned, and any permission
12757            // changes in other apps are accounted for
12758            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12759                    | (regrantPermissions
12760                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12761                            : 0));
12762
12763            mSettings.updateExternalDatabaseVersion();
12764
12765            // can downgrade to reader
12766            // Persist settings
12767            mSettings.writeLPr();
12768        }
12769        // Send a broadcast to let everyone know we are done processing
12770        if (pkgList.size() > 0) {
12771            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12772        }
12773        // Force gc to avoid any stale parser references that we might have.
12774        if (doGc) {
12775            Runtime.getRuntime().gc();
12776        }
12777        // List stale containers and destroy stale temporary containers.
12778        if (removeCids != null) {
12779            for (String cid : removeCids) {
12780                if (cid.startsWith(mTempContainerPrefix)) {
12781                    Log.i(TAG, "Destroying stale temporary container " + cid);
12782                    PackageHelper.destroySdDir(cid);
12783                } else {
12784                    Log.w(TAG, "Container " + cid + " is stale");
12785               }
12786           }
12787        }
12788    }
12789
12790   /*
12791     * Utility method to unload a list of specified containers
12792     */
12793    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12794        // Just unmount all valid containers.
12795        for (AsecInstallArgs arg : cidArgs) {
12796            synchronized (mInstallLock) {
12797                arg.doPostDeleteLI(false);
12798           }
12799       }
12800   }
12801
12802    /*
12803     * Unload packages mounted on external media. This involves deleting package
12804     * data from internal structures, sending broadcasts about diabled packages,
12805     * gc'ing to free up references, unmounting all secure containers
12806     * corresponding to packages on external media, and posting a
12807     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12808     * that we always have to post this message if status has been requested no
12809     * matter what.
12810     */
12811    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12812            final boolean reportStatus) {
12813        if (DEBUG_SD_INSTALL)
12814            Log.i(TAG, "unloading media packages");
12815        ArrayList<String> pkgList = new ArrayList<String>();
12816        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12817        final Set<AsecInstallArgs> keys = processCids.keySet();
12818        for (AsecInstallArgs args : keys) {
12819            String pkgName = args.getPackageName();
12820            if (DEBUG_SD_INSTALL)
12821                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12822            // Delete package internally
12823            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12824            synchronized (mInstallLock) {
12825                boolean res = deletePackageLI(pkgName, null, false, null, null,
12826                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12827                if (res) {
12828                    pkgList.add(pkgName);
12829                } else {
12830                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12831                    failedList.add(args);
12832                }
12833            }
12834        }
12835
12836        // reader
12837        synchronized (mPackages) {
12838            // We didn't update the settings after removing each package;
12839            // write them now for all packages.
12840            mSettings.writeLPr();
12841        }
12842
12843        // We have to absolutely send UPDATED_MEDIA_STATUS only
12844        // after confirming that all the receivers processed the ordered
12845        // broadcast when packages get disabled, force a gc to clean things up.
12846        // and unload all the containers.
12847        if (pkgList.size() > 0) {
12848            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12849                    new IIntentReceiver.Stub() {
12850                public void performReceive(Intent intent, int resultCode, String data,
12851                        Bundle extras, boolean ordered, boolean sticky,
12852                        int sendingUser) throws RemoteException {
12853                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12854                            reportStatus ? 1 : 0, 1, keys);
12855                    mHandler.sendMessage(msg);
12856                }
12857            });
12858        } else {
12859            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12860                    keys);
12861            mHandler.sendMessage(msg);
12862        }
12863    }
12864
12865    /** Binder call */
12866    @Override
12867    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12868            final int flags) {
12869        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12870        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12871        int returnCode = PackageManager.MOVE_SUCCEEDED;
12872        int currFlags = 0;
12873        int newFlags = 0;
12874        // reader
12875        synchronized (mPackages) {
12876            PackageParser.Package pkg = mPackages.get(packageName);
12877            if (pkg == null) {
12878                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12879            } else {
12880                // Disable moving fwd locked apps and system packages
12881                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12882                    Slog.w(TAG, "Cannot move system application");
12883                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12884                } else if (pkg.mOperationPending) {
12885                    Slog.w(TAG, "Attempt to move package which has pending operations");
12886                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12887                } else {
12888                    // Find install location first
12889                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12890                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12891                        Slog.w(TAG, "Ambigous flags specified for move location.");
12892                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12893                    } else {
12894                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12895                                : PackageManager.INSTALL_INTERNAL;
12896                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12897                                : PackageManager.INSTALL_INTERNAL;
12898
12899                        if (newFlags == currFlags) {
12900                            Slog.w(TAG, "No move required. Trying to move to same location");
12901                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12902                        } else {
12903                            if (isForwardLocked(pkg)) {
12904                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12905                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12906                            }
12907                        }
12908                    }
12909                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12910                        pkg.mOperationPending = true;
12911                    }
12912                }
12913            }
12914
12915            /*
12916             * TODO this next block probably shouldn't be inside the lock. We
12917             * can't guarantee these won't change after this is fired off
12918             * anyway.
12919             */
12920            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12921                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
12922                        returnCode);
12923            } else {
12924                Message msg = mHandler.obtainMessage(INIT_COPY);
12925                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
12926                final boolean multiArch = isMultiArch(pkg.applicationInfo);
12927                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12928                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
12929                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
12930                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12931                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
12932                msg.obj = mp;
12933                mHandler.sendMessage(msg);
12934            }
12935        }
12936    }
12937
12938    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12939        // Queue up an async operation since the package deletion may take a
12940        // little while.
12941        mHandler.post(new Runnable() {
12942            public void run() {
12943                // TODO fix this; this does nothing.
12944                mHandler.removeCallbacks(this);
12945                int returnCode = currentStatus;
12946                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12947                    int uidArr[] = null;
12948                    ArrayList<String> pkgList = null;
12949                    synchronized (mPackages) {
12950                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12951                        if (pkg == null) {
12952                            Slog.w(TAG, " Package " + mp.packageName
12953                                    + " doesn't exist. Aborting move");
12954                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12955                        } else if (!mp.srcArgs.getCodePath().equals(
12956                                pkg.applicationInfo.getCodePath())) {
12957                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12958                                    + mp.srcArgs.getCodePath() + " to "
12959                                    + pkg.applicationInfo.getCodePath()
12960                                    + " Aborting move and returning error");
12961                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12962                        } else {
12963                            uidArr = new int[] {
12964                                pkg.applicationInfo.uid
12965                            };
12966                            pkgList = new ArrayList<String>();
12967                            pkgList.add(mp.packageName);
12968                        }
12969                    }
12970                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12971                        // Send resources unavailable broadcast
12972                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12973                        // Update package code and resource paths
12974                        synchronized (mInstallLock) {
12975                            synchronized (mPackages) {
12976                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12977                                // Recheck for package again.
12978                                if (pkg == null) {
12979                                    Slog.w(TAG, " Package " + mp.packageName
12980                                            + " doesn't exist. Aborting move");
12981                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12982                                } else if (!mp.srcArgs.getCodePath().equals(
12983                                        pkg.applicationInfo.getCodePath())) {
12984                                    Slog.w(TAG, "Package " + mp.packageName
12985                                            + " code path changed from " + mp.srcArgs.getCodePath()
12986                                            + " to " + pkg.applicationInfo.getCodePath()
12987                                            + " Aborting move and returning error");
12988                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12989                                } else {
12990                                    final String oldCodePath = pkg.codePath;
12991                                    final String newCodePath = mp.targetArgs.getCodePath();
12992                                    final String newResPath = mp.targetArgs.getResourcePath();
12993                                    // TODO: This assumes the new style of installation.
12994                                    // should we look at legacyNativeLibraryPath ?
12995                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
12996                                    final File newNativeDir = new File(newNativeRoot);
12997
12998                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12999                                        // TODO(multiArch): Fix this so that it looks at the existing
13000                                        // recorded CPU abis from the package. There's no need for a separate
13001                                        // round of ABI scanning here.
13002                                        NativeLibraryHelper.Handle handle = null;
13003                                        try {
13004                                            handle = NativeLibraryHelper.Handle.create(
13005                                                    new File(newCodePath));
13006                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13007                                                    handle, Build.SUPPORTED_ABIS);
13008                                            if (abi >= 0) {
13009                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13010                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13011                                            }
13012                                        } catch (IOException ioe) {
13013                                            Slog.w(TAG, "Unable to extract native libs for package :"
13014                                                    + mp.packageName, ioe);
13015                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13016                                        } finally {
13017                                            IoUtils.closeQuietly(handle);
13018                                        }
13019                                    }
13020
13021                                    final int[] users = sUserManager.getUserIds();
13022                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13023                                        for (int user : users) {
13024                                            // TODO(multiArch): Fix this so that it links to the
13025                                            // correct directory. We're currently pointing to root. but we
13026                                            // must point to the arch specific subdirectory (if applicable).
13027                                            //
13028                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13029                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13030                                                    newNativeRoot, user) < 0) {
13031                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13032                                            }
13033                                        }
13034                                    }
13035
13036                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13037                                        pkg.codePath = newCodePath;
13038                                        pkg.baseCodePath = newCodePath;
13039                                        // Move dex files around
13040                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13041                                            // Moving of dex files failed. Set
13042                                            // error code and abort move.
13043                                            pkg.codePath = oldCodePath;
13044                                            pkg.baseCodePath = oldCodePath;
13045                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13046                                        }
13047                                    }
13048
13049                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13050                                        pkg.applicationInfo.setCodePath(newCodePath);
13051                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13052                                        pkg.applicationInfo.setSplitCodePaths(null);
13053                                        pkg.applicationInfo.setResourcePath(newResPath);
13054                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13055                                        pkg.applicationInfo.setSplitResourcePaths(null);
13056
13057                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13058                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13059                                        ps.codePathString = ps.codePath.getPath();
13060                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13061                                        ps.resourcePathString = ps.resourcePath.getPath();
13062
13063                                        // Note that we don't have to recalculate the primary and secondary
13064                                        // CPU ABIs because they must already have been calculated during the
13065                                        // initial install of the app.
13066                                        ps.legacyNativeLibraryPathString = null;
13067
13068                                        // Set the application info flag
13069                                        // correctly.
13070                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13071                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13072                                        } else {
13073                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13074                                        }
13075                                        ps.setFlags(pkg.applicationInfo.flags);
13076                                        mAppDirs.remove(oldCodePath);
13077                                        mAppDirs.put(newCodePath, pkg);
13078                                        // Persist settings
13079                                        mSettings.writeLPr();
13080                                    }
13081                                }
13082                            }
13083                        }
13084                        // Send resources available broadcast
13085                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13086                    }
13087                }
13088                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13089                    // Clean up failed installation
13090                    if (mp.targetArgs != null) {
13091                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13092                                -1);
13093                    }
13094                } else {
13095                    // Force a gc to clear things up.
13096                    Runtime.getRuntime().gc();
13097                    // Delete older code
13098                    synchronized (mInstallLock) {
13099                        mp.srcArgs.doPostDeleteLI(true);
13100                    }
13101                }
13102
13103                // Allow more operations on this file if we didn't fail because
13104                // an operation was already pending for this package.
13105                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13106                    synchronized (mPackages) {
13107                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13108                        if (pkg != null) {
13109                            pkg.mOperationPending = false;
13110                       }
13111                   }
13112                }
13113
13114                IPackageMoveObserver observer = mp.observer;
13115                if (observer != null) {
13116                    try {
13117                        observer.packageMoved(mp.packageName, returnCode);
13118                    } catch (RemoteException e) {
13119                        Log.i(TAG, "Observer no longer exists.");
13120                    }
13121                }
13122            }
13123        });
13124    }
13125
13126    @Override
13127    public boolean setInstallLocation(int loc) {
13128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13129                null);
13130        if (getInstallLocation() == loc) {
13131            return true;
13132        }
13133        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13134                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13135            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13136                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13137            return true;
13138        }
13139        return false;
13140   }
13141
13142    @Override
13143    public int getInstallLocation() {
13144        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13145                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13146                PackageHelper.APP_INSTALL_AUTO);
13147    }
13148
13149    /** Called by UserManagerService */
13150    void cleanUpUserLILPw(int userHandle) {
13151        mDirtyUsers.remove(userHandle);
13152        mSettings.removeUserLPw(userHandle);
13153        mPendingBroadcasts.remove(userHandle);
13154        if (mInstaller != null) {
13155            // Technically, we shouldn't be doing this with the package lock
13156            // held.  However, this is very rare, and there is already so much
13157            // other disk I/O going on, that we'll let it slide for now.
13158            mInstaller.removeUserDataDirs(userHandle);
13159        }
13160        mUserNeedsBadging.delete(userHandle);
13161    }
13162
13163    /** Called by UserManagerService */
13164    void createNewUserLILPw(int userHandle, File path) {
13165        if (mInstaller != null) {
13166            mInstaller.createUserConfig(userHandle);
13167            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13168        }
13169    }
13170
13171    @Override
13172    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13173        mContext.enforceCallingOrSelfPermission(
13174                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13175                "Only package verification agents can read the verifier device identity");
13176
13177        synchronized (mPackages) {
13178            return mSettings.getVerifierDeviceIdentityLPw();
13179        }
13180    }
13181
13182    @Override
13183    public void setPermissionEnforced(String permission, boolean enforced) {
13184        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13185        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13186            synchronized (mPackages) {
13187                if (mSettings.mReadExternalStorageEnforced == null
13188                        || mSettings.mReadExternalStorageEnforced != enforced) {
13189                    mSettings.mReadExternalStorageEnforced = enforced;
13190                    mSettings.writeLPr();
13191                }
13192            }
13193            // kill any non-foreground processes so we restart them and
13194            // grant/revoke the GID.
13195            final IActivityManager am = ActivityManagerNative.getDefault();
13196            if (am != null) {
13197                final long token = Binder.clearCallingIdentity();
13198                try {
13199                    am.killProcessesBelowForeground("setPermissionEnforcement");
13200                } catch (RemoteException e) {
13201                } finally {
13202                    Binder.restoreCallingIdentity(token);
13203                }
13204            }
13205        } else {
13206            throw new IllegalArgumentException("No selective enforcement for " + permission);
13207        }
13208    }
13209
13210    @Override
13211    @Deprecated
13212    public boolean isPermissionEnforced(String permission) {
13213        return true;
13214    }
13215
13216    @Override
13217    public boolean isStorageLow() {
13218        final long token = Binder.clearCallingIdentity();
13219        try {
13220            final DeviceStorageMonitorInternal
13221                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13222            if (dsm != null) {
13223                return dsm.isMemoryLow();
13224            } else {
13225                return false;
13226            }
13227        } finally {
13228            Binder.restoreCallingIdentity(token);
13229        }
13230    }
13231
13232    @Override
13233    public IPackageInstaller getPackageInstaller() {
13234        return mInstallerService;
13235    }
13236
13237    private boolean userNeedsBadging(int userId) {
13238        int index = mUserNeedsBadging.indexOfKey(userId);
13239        if (index < 0) {
13240            final UserInfo userInfo;
13241            final long token = Binder.clearCallingIdentity();
13242            try {
13243                userInfo = sUserManager.getUserInfo(userId);
13244            } finally {
13245                Binder.restoreCallingIdentity(token);
13246            }
13247            final boolean b;
13248            if (userInfo != null && userInfo.isManagedProfile()) {
13249                b = true;
13250            } else {
13251                b = false;
13252            }
13253            mUserNeedsBadging.put(userId, b);
13254            return b;
13255        }
13256        return mUserNeedsBadging.valueAt(index);
13257    }
13258
13259    @Override
13260    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13261        if (packageName == null || alias == null) {
13262            return null;
13263        }
13264        synchronized(mPackages) {
13265            final PackageParser.Package pkg = mPackages.get(packageName);
13266            if (pkg == null) {
13267                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13268                throw new IllegalArgumentException("Unknown package: " + packageName);
13269            }
13270            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13271                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13272                throw new SecurityException("May not access KeySets defined by"
13273                        + " aliases in other applications.");
13274            }
13275            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13276            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13277        }
13278    }
13279
13280    @Override
13281    public KeySetHandle getSigningKeySet(String packageName) {
13282        if (packageName == null) {
13283            return null;
13284        }
13285        synchronized(mPackages) {
13286            final PackageParser.Package pkg = mPackages.get(packageName);
13287            if (pkg == null) {
13288                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13289                throw new IllegalArgumentException("Unknown package: " + packageName);
13290            }
13291            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13292                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13293                throw new SecurityException("May not access signing KeySet of other apps.");
13294            }
13295            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13296            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13297        }
13298    }
13299
13300    @Override
13301    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13302        if (packageName == null || ks == null) {
13303            return false;
13304        }
13305        synchronized(mPackages) {
13306            final PackageParser.Package pkg = mPackages.get(packageName);
13307            if (pkg == null) {
13308                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13309                throw new IllegalArgumentException("Unknown package: " + packageName);
13310            }
13311            if (ks instanceof KeySetHandle) {
13312                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13313                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13314            }
13315            return false;
13316        }
13317    }
13318
13319    @Override
13320    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13321        if (packageName == null || ks == null) {
13322            return false;
13323        }
13324        synchronized(mPackages) {
13325            final PackageParser.Package pkg = mPackages.get(packageName);
13326            if (pkg == null) {
13327                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13328                throw new IllegalArgumentException("Unknown package: " + packageName);
13329            }
13330            if (ks instanceof KeySetHandle) {
13331                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13332                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13333            }
13334            return false;
13335        }
13336    }
13337}
13338