PackageManagerService.java revision fbd0e9fa37fc17ccd25e4c1f16195bbd27de3c4c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static android.system.OsConstants.S_IRGRP;
52import static android.system.OsConstants.S_IROTH;
53import static android.system.OsConstants.S_IRWXU;
54import static android.system.OsConstants.S_IXGRP;
55import static android.system.OsConstants.S_IXOTH;
56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
58import static com.android.internal.util.ArrayUtils.appendInt;
59import static com.android.internal.util.ArrayUtils.removeInt;
60
61import android.util.ArrayMap;
62
63import com.android.internal.R;
64import com.android.internal.app.IMediaContainerService;
65import com.android.internal.app.ResolverActivity;
66import com.android.internal.content.NativeLibraryHelper;
67import com.android.internal.content.PackageHelper;
68import com.android.internal.os.IParcelFileDescriptorFactory;
69import com.android.internal.util.ArrayUtils;
70import com.android.internal.util.FastPrintWriter;
71import com.android.internal.util.FastXmlSerializer;
72import com.android.internal.util.IndentingPrintWriter;
73import com.android.internal.util.Preconditions;
74import com.android.server.EventLogTags;
75import com.android.server.IntentResolver;
76import com.android.server.LocalServices;
77import com.android.server.ServiceThread;
78import com.android.server.SystemConfig;
79import com.android.server.Watchdog;
80import com.android.server.pm.Settings.DatabaseVersion;
81import com.android.server.storage.DeviceStorageMonitorInternal;
82
83import org.xmlpull.v1.XmlSerializer;
84
85import android.app.ActivityManager;
86import android.app.ActivityManagerNative;
87import android.app.IActivityManager;
88import android.app.PackageDeleteObserver;
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.IPackageDeleteObserver2;
106import android.content.pm.IPackageInstallObserver2;
107import android.content.pm.IPackageInstaller;
108import android.content.pm.IPackageManager;
109import android.content.pm.IPackageMoveObserver;
110import android.content.pm.IPackageStatsObserver;
111import android.content.pm.InstallSessionParams;
112import android.content.pm.InstrumentationInfo;
113import android.content.pm.ManifestDigest;
114import android.content.pm.PackageCleanItem;
115import android.content.pm.PackageInfo;
116import android.content.pm.PackageInfoLite;
117import android.content.pm.PackageManager;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageParser;
122import android.content.pm.PackageStats;
123import android.content.pm.PackageUserState;
124import android.content.pm.ParceledListSlice;
125import android.content.pm.PermissionGroupInfo;
126import android.content.pm.PermissionInfo;
127import android.content.pm.ProviderInfo;
128import android.content.pm.ResolveInfo;
129import android.content.pm.ServiceInfo;
130import android.content.pm.Signature;
131import android.content.pm.UserInfo;
132import android.content.pm.VerificationParams;
133import android.content.pm.VerifierDeviceIdentity;
134import android.content.pm.VerifierInfo;
135import android.content.res.Resources;
136import android.hardware.display.DisplayManager;
137import android.net.Uri;
138import android.os.Binder;
139import android.os.Build;
140import android.os.Bundle;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.util.ArraySet;
165import android.util.AtomicFile;
166import android.util.DisplayMetrics;
167import android.util.EventLog;
168import android.util.ExceptionUtils;
169import android.util.Log;
170import android.util.LogPrinter;
171import android.util.PrintStreamPrinter;
172import android.util.Slog;
173import android.util.SparseArray;
174import android.util.SparseBooleanArray;
175import android.view.Display;
176
177import java.io.BufferedInputStream;
178import java.io.BufferedOutputStream;
179import java.io.File;
180import java.io.FileDescriptor;
181import java.io.FileInputStream;
182import java.io.FileNotFoundException;
183import java.io.FileOutputStream;
184import java.io.FilenameFilter;
185import java.io.IOException;
186import java.io.InputStream;
187import java.io.PrintWriter;
188import java.nio.charset.StandardCharsets;
189import java.security.NoSuchAlgorithmException;
190import java.security.PublicKey;
191import java.security.cert.CertificateEncodingException;
192import java.security.cert.CertificateException;
193import java.text.SimpleDateFormat;
194import java.util.ArrayList;
195import java.util.Arrays;
196import java.util.Collection;
197import java.util.Collections;
198import java.util.Comparator;
199import java.util.Date;
200import java.util.HashMap;
201import java.util.HashSet;
202import java.util.Iterator;
203import java.util.List;
204import java.util.Map;
205import java.util.Set;
206import java.util.concurrent.atomic.AtomicBoolean;
207import java.util.concurrent.atomic.AtomicLong;
208
209import dalvik.system.DexFile;
210import dalvik.system.StaleDexCacheError;
211import dalvik.system.VMRuntime;
212
213import libcore.io.IoUtils;
214
215/**
216 * Keep track of all those .apks everywhere.
217 *
218 * This is very central to the platform's security; please run the unit
219 * tests whenever making modifications here:
220 *
221mmm frameworks/base/tests/AndroidTests
222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
224 *
225 * {@hide}
226 */
227public class PackageManagerService extends IPackageManager.Stub {
228    static final String TAG = "PackageManager";
229    static final boolean DEBUG_SETTINGS = false;
230    static final boolean DEBUG_PREFERRED = false;
231    static final boolean DEBUG_UPGRADE = false;
232    private static final boolean DEBUG_INSTALL = false;
233    private static final boolean DEBUG_REMOVE = false;
234    private static final boolean DEBUG_BROADCASTS = false;
235    private static final boolean DEBUG_SHOW_INFO = false;
236    private static final boolean DEBUG_PACKAGE_INFO = false;
237    private static final boolean DEBUG_INTENT_MATCHING = false;
238    private static final boolean DEBUG_PACKAGE_SCANNING = false;
239    private static final boolean DEBUG_VERIFY = false;
240    private static final boolean DEBUG_DEXOPT = false;
241    private static final boolean DEBUG_ABI_SELECTION = false;
242
243    private static final int RADIO_UID = Process.PHONE_UID;
244    private static final int LOG_UID = Process.LOG_UID;
245    private static final int NFC_UID = Process.NFC_UID;
246    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
247    private static final int SHELL_UID = Process.SHELL_UID;
248
249    // Cap the size of permission trees that 3rd party apps can define
250    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
251
252    // Suffix used during package installation when copying/moving
253    // package apks to install directory.
254    private static final String INSTALL_PACKAGE_SUFFIX = "-";
255
256    static final int SCAN_MONITOR = 1<<0;
257    static final int SCAN_NO_DEX = 1<<1;
258    static final int SCAN_FORCE_DEX = 1<<2;
259    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
260    static final int SCAN_NEW_INSTALL = 1<<4;
261    static final int SCAN_NO_PATHS = 1<<5;
262    static final int SCAN_UPDATE_TIME = 1<<6;
263    static final int SCAN_DEFER_DEX = 1<<7;
264    static final int SCAN_BOOTING = 1<<8;
265    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
266    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
267
268    static final int REMOVE_CHATTY = 1<<16;
269
270    /**
271     * Timeout (in milliseconds) after which the watchdog should declare that
272     * our handler thread is wedged.  The usual default for such things is one
273     * minute but we sometimes do very lengthy I/O operations on this thread,
274     * such as installing multi-gigabyte applications, so ours needs to be longer.
275     */
276    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
277
278    /**
279     * Whether verification is enabled by default.
280     */
281    private static final boolean DEFAULT_VERIFY_ENABLE = true;
282
283    /**
284     * The default maximum time to wait for the verification agent to return in
285     * milliseconds.
286     */
287    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
288
289    /**
290     * The default response for package verification timeout.
291     *
292     * This can be either PackageManager.VERIFICATION_ALLOW or
293     * PackageManager.VERIFICATION_REJECT.
294     */
295    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
296
297    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
298
299    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
300            DEFAULT_CONTAINER_PACKAGE,
301            "com.android.defcontainer.DefaultContainerService");
302
303    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
304
305    private static final String LIB_DIR_NAME = "lib";
306    private static final String LIB64_DIR_NAME = "lib64";
307
308    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
309
310    static final String mTempContainerPrefix = "smdl2tmp";
311
312    private static String sPreferredInstructionSet;
313
314    final ServiceThread mHandlerThread;
315
316    private static final String IDMAP_PREFIX = "/data/resource-cache/";
317    private static final String IDMAP_SUFFIX = "@idmap";
318
319    final PackageHandler mHandler;
320
321    final int mSdkVersion = Build.VERSION.SDK_INT;
322
323    final Context mContext;
324    final boolean mFactoryTest;
325    final boolean mOnlyCore;
326    final DisplayMetrics mMetrics;
327    final int mDefParseFlags;
328    final String[] mSeparateProcesses;
329
330    // This is where all application persistent data goes.
331    final File mAppDataDir;
332
333    // This is where all application persistent data goes for secondary users.
334    final File mUserAppDataDir;
335
336    /** The location for ASEC container files on internal storage. */
337    final String mAsecInternalPath;
338
339    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
340    // LOCK HELD.  Can be called with mInstallLock held.
341    final Installer mInstaller;
342
343    /** Directory where installed third-party apps stored */
344    final File mAppInstallDir;
345
346    /**
347     * Directory to which applications installed internally have their
348     * 32 bit native libraries copied.
349     */
350    private File mAppLib32InstallDir;
351
352    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
353    // apps.
354    final File mDrmAppPrivateInstallDir;
355
356    // ----------------------------------------------------------------
357
358    // Lock for state used when installing and doing other long running
359    // operations.  Methods that must be called with this lock held have
360    // the suffix "LI".
361    final Object mInstallLock = new Object();
362
363    // These are the directories in the 3rd party applications installed dir
364    // that we have currently loaded packages from.  Keys are the application's
365    // installed zip file (absolute codePath), and values are Package.
366    final HashMap<String, PackageParser.Package> mAppDirs =
367            new HashMap<String, PackageParser.Package>();
368
369    // ----------------------------------------------------------------
370
371    // Keys are String (package name), values are Package.  This also serves
372    // as the lock for the global state.  Methods that must be called with
373    // this lock held have the prefix "LP".
374    final HashMap<String, PackageParser.Package> mPackages =
375            new HashMap<String, PackageParser.Package>();
376
377    // Tracks available target package names -> overlay package paths.
378    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
379        new HashMap<String, HashMap<String, PackageParser.Package>>();
380
381    final Settings mSettings;
382    boolean mRestoredSettings;
383
384    // System configuration read by SystemConfig.
385    final int[] mGlobalGids;
386    final SparseArray<HashSet<String>> mSystemPermissions;
387    final HashMap<String, FeatureInfo> mAvailableFeatures;
388
389    // If mac_permissions.xml was found for seinfo labeling.
390    boolean mFoundPolicyFile;
391
392    // If a recursive restorecon of /data/data/<pkg> is needed.
393    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
394
395    public static final class SharedLibraryEntry {
396        public final String path;
397        public final String apk;
398
399        SharedLibraryEntry(String _path, String _apk) {
400            path = _path;
401            apk = _apk;
402        }
403    }
404
405    // Currently known shared libraries.
406    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
407            new HashMap<String, SharedLibraryEntry>();
408
409    // All available activities, for your resolving pleasure.
410    final ActivityIntentResolver mActivities =
411            new ActivityIntentResolver();
412
413    // All available receivers, for your resolving pleasure.
414    final ActivityIntentResolver mReceivers =
415            new ActivityIntentResolver();
416
417    // All available services, for your resolving pleasure.
418    final ServiceIntentResolver mServices = new ServiceIntentResolver();
419
420    // All available providers, for your resolving pleasure.
421    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
422
423    // Mapping from provider base names (first directory in content URI codePath)
424    // to the provider information.
425    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
426            new HashMap<String, PackageParser.Provider>();
427
428    // Mapping from instrumentation class names to info about them.
429    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
430            new HashMap<ComponentName, PackageParser.Instrumentation>();
431
432    // Mapping from permission names to info about them.
433    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
434            new HashMap<String, PackageParser.PermissionGroup>();
435
436    // Packages whose data we have transfered into another package, thus
437    // should no longer exist.
438    final HashSet<String> mTransferedPackages = new HashSet<String>();
439
440    // Broadcast actions that are only available to the system.
441    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
442
443    /** List of packages waiting for verification. */
444    final SparseArray<PackageVerificationState> mPendingVerification
445            = new SparseArray<PackageVerificationState>();
446
447    /** Set of packages associated with each app op permission. */
448    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
449
450    final PackageInstallerService mInstallerService;
451
452    HashSet<PackageParser.Package> mDeferredDexOpt = null;
453
454    // Cache of users who need badging.
455    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
456
457    /** Token for keys in mPendingVerification. */
458    private int mPendingVerificationToken = 0;
459
460    boolean mSystemReady;
461    boolean mSafeMode;
462    boolean mHasSystemUidErrors;
463
464    ApplicationInfo mAndroidApplication;
465    final ActivityInfo mResolveActivity = new ActivityInfo();
466    final ResolveInfo mResolveInfo = new ResolveInfo();
467    ComponentName mResolveComponentName;
468    PackageParser.Package mPlatformPackage;
469    ComponentName mCustomResolverComponentName;
470
471    boolean mResolverReplaced = false;
472
473    // Set of pending broadcasts for aggregating enable/disable of components.
474    static class PendingPackageBroadcasts {
475        // for each user id, a map of <package name -> components within that package>
476        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
477
478        public PendingPackageBroadcasts() {
479            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
480        }
481
482        public ArrayList<String> get(int userId, String packageName) {
483            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
484            return packages.get(packageName);
485        }
486
487        public void put(int userId, String packageName, ArrayList<String> components) {
488            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
489            packages.put(packageName, components);
490        }
491
492        public void remove(int userId, String packageName) {
493            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
494            if (packages != null) {
495                packages.remove(packageName);
496            }
497        }
498
499        public void remove(int userId) {
500            mUidMap.remove(userId);
501        }
502
503        public int userIdCount() {
504            return mUidMap.size();
505        }
506
507        public int userIdAt(int n) {
508            return mUidMap.keyAt(n);
509        }
510
511        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
512            return mUidMap.get(userId);
513        }
514
515        public int size() {
516            // total number of pending broadcast entries across all userIds
517            int num = 0;
518            for (int i = 0; i< mUidMap.size(); i++) {
519                num += mUidMap.valueAt(i).size();
520            }
521            return num;
522        }
523
524        public void clear() {
525            mUidMap.clear();
526        }
527
528        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
529            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
530            if (map == null) {
531                map = new HashMap<String, ArrayList<String>>();
532                mUidMap.put(userId, map);
533            }
534            return map;
535        }
536    }
537    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
538
539    // Service Connection to remote media container service to copy
540    // package uri's from external media onto secure containers
541    // or internal storage.
542    private IMediaContainerService mContainerService = null;
543
544    static final int SEND_PENDING_BROADCAST = 1;
545    static final int MCS_BOUND = 3;
546    static final int END_COPY = 4;
547    static final int INIT_COPY = 5;
548    static final int MCS_UNBIND = 6;
549    static final int START_CLEANING_PACKAGE = 7;
550    static final int FIND_INSTALL_LOC = 8;
551    static final int POST_INSTALL = 9;
552    static final int MCS_RECONNECT = 10;
553    static final int MCS_GIVE_UP = 11;
554    static final int UPDATED_MEDIA_STATUS = 12;
555    static final int WRITE_SETTINGS = 13;
556    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
557    static final int PACKAGE_VERIFIED = 15;
558    static final int CHECK_PENDING_VERIFICATION = 16;
559
560    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
561
562    // Delay time in millisecs
563    static final int BROADCAST_DELAY = 10 * 1000;
564
565    static UserManagerService sUserManager;
566
567    // Stores a list of users whose package restrictions file needs to be updated
568    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
569
570    final private DefaultContainerConnection mDefContainerConn =
571            new DefaultContainerConnection();
572    class DefaultContainerConnection implements ServiceConnection {
573        public void onServiceConnected(ComponentName name, IBinder service) {
574            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
575            IMediaContainerService imcs =
576                IMediaContainerService.Stub.asInterface(service);
577            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
578        }
579
580        public void onServiceDisconnected(ComponentName name) {
581            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
582        }
583    };
584
585    // Recordkeeping of restore-after-install operations that are currently in flight
586    // between the Package Manager and the Backup Manager
587    class PostInstallData {
588        public InstallArgs args;
589        public PackageInstalledInfo res;
590
591        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
592            args = _a;
593            res = _r;
594        }
595    };
596    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
597    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
598
599    private final String mRequiredVerifierPackage;
600
601    private final PackageUsage mPackageUsage = new PackageUsage();
602
603    private class PackageUsage {
604        private static final int WRITE_INTERVAL
605            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
606
607        private final Object mFileLock = new Object();
608        private final AtomicLong mLastWritten = new AtomicLong(0);
609        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
610
611        private boolean mIsHistoricalPackageUsageAvailable = true;
612
613        boolean isHistoricalPackageUsageAvailable() {
614            return mIsHistoricalPackageUsageAvailable;
615        }
616
617        void write(boolean force) {
618            if (force) {
619                writeInternal();
620                return;
621            }
622            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
623                && !DEBUG_DEXOPT) {
624                return;
625            }
626            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
627                new Thread("PackageUsage_DiskWriter") {
628                    @Override
629                    public void run() {
630                        try {
631                            writeInternal();
632                        } finally {
633                            mBackgroundWriteRunning.set(false);
634                        }
635                    }
636                }.start();
637            }
638        }
639
640        private void writeInternal() {
641            synchronized (mPackages) {
642                synchronized (mFileLock) {
643                    AtomicFile file = getFile();
644                    FileOutputStream f = null;
645                    try {
646                        f = file.startWrite();
647                        BufferedOutputStream out = new BufferedOutputStream(f);
648                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
649                        StringBuilder sb = new StringBuilder();
650                        for (PackageParser.Package pkg : mPackages.values()) {
651                            if (pkg.mLastPackageUsageTimeInMills == 0) {
652                                continue;
653                            }
654                            sb.setLength(0);
655                            sb.append(pkg.packageName);
656                            sb.append(' ');
657                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
658                            sb.append('\n');
659                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
660                        }
661                        out.flush();
662                        file.finishWrite(f);
663                    } catch (IOException e) {
664                        if (f != null) {
665                            file.failWrite(f);
666                        }
667                        Log.e(TAG, "Failed to write package usage times", e);
668                    }
669                }
670            }
671            mLastWritten.set(SystemClock.elapsedRealtime());
672        }
673
674        void readLP() {
675            synchronized (mFileLock) {
676                AtomicFile file = getFile();
677                BufferedInputStream in = null;
678                try {
679                    in = new BufferedInputStream(file.openRead());
680                    StringBuffer sb = new StringBuffer();
681                    while (true) {
682                        String packageName = readToken(in, sb, ' ');
683                        if (packageName == null) {
684                            break;
685                        }
686                        String timeInMillisString = readToken(in, sb, '\n');
687                        if (timeInMillisString == null) {
688                            throw new IOException("Failed to find last usage time for package "
689                                                  + packageName);
690                        }
691                        PackageParser.Package pkg = mPackages.get(packageName);
692                        if (pkg == null) {
693                            continue;
694                        }
695                        long timeInMillis;
696                        try {
697                            timeInMillis = Long.parseLong(timeInMillisString.toString());
698                        } catch (NumberFormatException e) {
699                            throw new IOException("Failed to parse " + timeInMillisString
700                                                  + " as a long.", e);
701                        }
702                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
703                    }
704                } catch (FileNotFoundException expected) {
705                    mIsHistoricalPackageUsageAvailable = false;
706                } catch (IOException e) {
707                    Log.w(TAG, "Failed to read package usage times", e);
708                } finally {
709                    IoUtils.closeQuietly(in);
710                }
711            }
712            mLastWritten.set(SystemClock.elapsedRealtime());
713        }
714
715        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
716                throws IOException {
717            sb.setLength(0);
718            while (true) {
719                int ch = in.read();
720                if (ch == -1) {
721                    if (sb.length() == 0) {
722                        return null;
723                    }
724                    throw new IOException("Unexpected EOF");
725                }
726                if (ch == endOfToken) {
727                    return sb.toString();
728                }
729                sb.append((char)ch);
730            }
731        }
732
733        private AtomicFile getFile() {
734            File dataDir = Environment.getDataDirectory();
735            File systemDir = new File(dataDir, "system");
736            File fname = new File(systemDir, "package-usage.list");
737            return new AtomicFile(fname);
738        }
739    }
740
741    class PackageHandler extends Handler {
742        private boolean mBound = false;
743        final ArrayList<HandlerParams> mPendingInstalls =
744            new ArrayList<HandlerParams>();
745
746        private boolean connectToService() {
747            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
748                    " DefaultContainerService");
749            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
750            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
751            if (mContext.bindServiceAsUser(service, mDefContainerConn,
752                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
753                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754                mBound = true;
755                return true;
756            }
757            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
758            return false;
759        }
760
761        private void disconnectService() {
762            mContainerService = null;
763            mBound = false;
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            mContext.unbindService(mDefContainerConn);
766            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767        }
768
769        PackageHandler(Looper looper) {
770            super(looper);
771        }
772
773        public void handleMessage(Message msg) {
774            try {
775                doHandleMessage(msg);
776            } finally {
777                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
778            }
779        }
780
781        void doHandleMessage(Message msg) {
782            switch (msg.what) {
783                case INIT_COPY: {
784                    HandlerParams params = (HandlerParams) msg.obj;
785                    int idx = mPendingInstalls.size();
786                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
787                    // If a bind was already initiated we dont really
788                    // need to do anything. The pending install
789                    // will be processed later on.
790                    if (!mBound) {
791                        // If this is the only one pending we might
792                        // have to bind to the service again.
793                        if (!connectToService()) {
794                            Slog.e(TAG, "Failed to bind to media container service");
795                            params.serviceError();
796                            return;
797                        } else {
798                            // Once we bind to the service, the first
799                            // pending request will be processed.
800                            mPendingInstalls.add(idx, params);
801                        }
802                    } else {
803                        mPendingInstalls.add(idx, params);
804                        // Already bound to the service. Just make
805                        // sure we trigger off processing the first request.
806                        if (idx == 0) {
807                            mHandler.sendEmptyMessage(MCS_BOUND);
808                        }
809                    }
810                    break;
811                }
812                case MCS_BOUND: {
813                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
814                    if (msg.obj != null) {
815                        mContainerService = (IMediaContainerService) msg.obj;
816                    }
817                    if (mContainerService == null) {
818                        // Something seriously wrong. Bail out
819                        Slog.e(TAG, "Cannot bind to media container service");
820                        for (HandlerParams params : mPendingInstalls) {
821                            // Indicate service bind error
822                            params.serviceError();
823                        }
824                        mPendingInstalls.clear();
825                    } else if (mPendingInstalls.size() > 0) {
826                        HandlerParams params = mPendingInstalls.get(0);
827                        if (params != null) {
828                            if (params.startCopy()) {
829                                // We are done...  look for more work or to
830                                // go idle.
831                                if (DEBUG_SD_INSTALL) Log.i(TAG,
832                                        "Checking for more work or unbind...");
833                                // Delete pending install
834                                if (mPendingInstalls.size() > 0) {
835                                    mPendingInstalls.remove(0);
836                                }
837                                if (mPendingInstalls.size() == 0) {
838                                    if (mBound) {
839                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
840                                                "Posting delayed MCS_UNBIND");
841                                        removeMessages(MCS_UNBIND);
842                                        Message ubmsg = obtainMessage(MCS_UNBIND);
843                                        // Unbind after a little delay, to avoid
844                                        // continual thrashing.
845                                        sendMessageDelayed(ubmsg, 10000);
846                                    }
847                                } else {
848                                    // There are more pending requests in queue.
849                                    // Just post MCS_BOUND message to trigger processing
850                                    // of next pending install.
851                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
852                                            "Posting MCS_BOUND for next work");
853                                    mHandler.sendEmptyMessage(MCS_BOUND);
854                                }
855                            }
856                        }
857                    } else {
858                        // Should never happen ideally.
859                        Slog.w(TAG, "Empty queue");
860                    }
861                    break;
862                }
863                case MCS_RECONNECT: {
864                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
865                    if (mPendingInstalls.size() > 0) {
866                        if (mBound) {
867                            disconnectService();
868                        }
869                        if (!connectToService()) {
870                            Slog.e(TAG, "Failed to bind to media container service");
871                            for (HandlerParams params : mPendingInstalls) {
872                                // Indicate service bind error
873                                params.serviceError();
874                            }
875                            mPendingInstalls.clear();
876                        }
877                    }
878                    break;
879                }
880                case MCS_UNBIND: {
881                    // If there is no actual work left, then time to unbind.
882                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
883
884                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
885                        if (mBound) {
886                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
887
888                            disconnectService();
889                        }
890                    } else if (mPendingInstalls.size() > 0) {
891                        // There are more pending requests in queue.
892                        // Just post MCS_BOUND message to trigger processing
893                        // of next pending install.
894                        mHandler.sendEmptyMessage(MCS_BOUND);
895                    }
896
897                    break;
898                }
899                case MCS_GIVE_UP: {
900                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
901                    mPendingInstalls.remove(0);
902                    break;
903                }
904                case SEND_PENDING_BROADCAST: {
905                    String packages[];
906                    ArrayList<String> components[];
907                    int size = 0;
908                    int uids[];
909                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
910                    synchronized (mPackages) {
911                        if (mPendingBroadcasts == null) {
912                            return;
913                        }
914                        size = mPendingBroadcasts.size();
915                        if (size <= 0) {
916                            // Nothing to be done. Just return
917                            return;
918                        }
919                        packages = new String[size];
920                        components = new ArrayList[size];
921                        uids = new int[size];
922                        int i = 0;  // filling out the above arrays
923
924                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
925                            int packageUserId = mPendingBroadcasts.userIdAt(n);
926                            Iterator<Map.Entry<String, ArrayList<String>>> it
927                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
928                                            .entrySet().iterator();
929                            while (it.hasNext() && i < size) {
930                                Map.Entry<String, ArrayList<String>> ent = it.next();
931                                packages[i] = ent.getKey();
932                                components[i] = ent.getValue();
933                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
934                                uids[i] = (ps != null)
935                                        ? UserHandle.getUid(packageUserId, ps.appId)
936                                        : -1;
937                                i++;
938                            }
939                        }
940                        size = i;
941                        mPendingBroadcasts.clear();
942                    }
943                    // Send broadcasts
944                    for (int i = 0; i < size; i++) {
945                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
946                    }
947                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
948                    break;
949                }
950                case START_CLEANING_PACKAGE: {
951                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
952                    final String packageName = (String)msg.obj;
953                    final int userId = msg.arg1;
954                    final boolean andCode = msg.arg2 != 0;
955                    synchronized (mPackages) {
956                        if (userId == UserHandle.USER_ALL) {
957                            int[] users = sUserManager.getUserIds();
958                            for (int user : users) {
959                                mSettings.addPackageToCleanLPw(
960                                        new PackageCleanItem(user, packageName, andCode));
961                            }
962                        } else {
963                            mSettings.addPackageToCleanLPw(
964                                    new PackageCleanItem(userId, packageName, andCode));
965                        }
966                    }
967                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
968                    startCleaningPackages();
969                } break;
970                case POST_INSTALL: {
971                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
972                    PostInstallData data = mRunningInstalls.get(msg.arg1);
973                    mRunningInstalls.delete(msg.arg1);
974                    boolean deleteOld = false;
975
976                    if (data != null) {
977                        InstallArgs args = data.args;
978                        PackageInstalledInfo res = data.res;
979
980                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
981                            res.removedInfo.sendBroadcast(false, true, false);
982                            Bundle extras = new Bundle(1);
983                            extras.putInt(Intent.EXTRA_UID, res.uid);
984                            // Determine the set of users who are adding this
985                            // package for the first time vs. those who are seeing
986                            // an update.
987                            int[] firstUsers;
988                            int[] updateUsers = new int[0];
989                            if (res.origUsers == null || res.origUsers.length == 0) {
990                                firstUsers = res.newUsers;
991                            } else {
992                                firstUsers = new int[0];
993                                for (int i=0; i<res.newUsers.length; i++) {
994                                    int user = res.newUsers[i];
995                                    boolean isNew = true;
996                                    for (int j=0; j<res.origUsers.length; j++) {
997                                        if (res.origUsers[j] == user) {
998                                            isNew = false;
999                                            break;
1000                                        }
1001                                    }
1002                                    if (isNew) {
1003                                        int[] newFirst = new int[firstUsers.length+1];
1004                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1005                                                firstUsers.length);
1006                                        newFirst[firstUsers.length] = user;
1007                                        firstUsers = newFirst;
1008                                    } else {
1009                                        int[] newUpdate = new int[updateUsers.length+1];
1010                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1011                                                updateUsers.length);
1012                                        newUpdate[updateUsers.length] = user;
1013                                        updateUsers = newUpdate;
1014                                    }
1015                                }
1016                            }
1017                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1018                                    res.pkg.applicationInfo.packageName,
1019                                    extras, null, null, firstUsers);
1020                            final boolean update = res.removedInfo.removedPackage != null;
1021                            if (update) {
1022                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1023                            }
1024                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1025                                    res.pkg.applicationInfo.packageName,
1026                                    extras, null, null, updateUsers);
1027                            if (update) {
1028                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1029                                        res.pkg.applicationInfo.packageName,
1030                                        extras, null, null, updateUsers);
1031                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1032                                        null, null,
1033                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1034
1035                                // treat asec-hosted packages like removable media on upgrade
1036                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1037                                    if (DEBUG_INSTALL) {
1038                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1039                                                + " is ASEC-hosted -> AVAILABLE");
1040                                    }
1041                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1042                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1043                                    pkgList.add(res.pkg.applicationInfo.packageName);
1044                                    sendResourcesChangedBroadcast(true, true,
1045                                            pkgList,uidArray, null);
1046                                }
1047                            }
1048                            if (res.removedInfo.args != null) {
1049                                // Remove the replaced package's older resources safely now
1050                                deleteOld = true;
1051                            }
1052
1053                            // Log current value of "unknown sources" setting
1054                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1055                                getUnknownSourcesSettings());
1056                        }
1057                        // Force a gc to clear up things
1058                        Runtime.getRuntime().gc();
1059                        // We delete after a gc for applications  on sdcard.
1060                        if (deleteOld) {
1061                            synchronized (mInstallLock) {
1062                                res.removedInfo.args.doPostDeleteLI(true);
1063                            }
1064                        }
1065                        if (args.observer != null) {
1066                            try {
1067                                Bundle extras = extrasForInstallResult(res);
1068                                args.observer.onPackageInstalled(res.name, res.returnCode,
1069                                        res.returnMsg, extras);
1070                            } catch (RemoteException e) {
1071                                Slog.i(TAG, "Observer no longer exists.");
1072                            }
1073                        }
1074                    } else {
1075                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1076                    }
1077                } break;
1078                case UPDATED_MEDIA_STATUS: {
1079                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1080                    boolean reportStatus = msg.arg1 == 1;
1081                    boolean doGc = msg.arg2 == 1;
1082                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1083                    if (doGc) {
1084                        // Force a gc to clear up stale containers.
1085                        Runtime.getRuntime().gc();
1086                    }
1087                    if (msg.obj != null) {
1088                        @SuppressWarnings("unchecked")
1089                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1090                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1091                        // Unload containers
1092                        unloadAllContainers(args);
1093                    }
1094                    if (reportStatus) {
1095                        try {
1096                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1097                            PackageHelper.getMountService().finishMediaUpdate();
1098                        } catch (RemoteException e) {
1099                            Log.e(TAG, "MountService not running?");
1100                        }
1101                    }
1102                } break;
1103                case WRITE_SETTINGS: {
1104                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1105                    synchronized (mPackages) {
1106                        removeMessages(WRITE_SETTINGS);
1107                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1108                        mSettings.writeLPr();
1109                        mDirtyUsers.clear();
1110                    }
1111                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                } break;
1113                case WRITE_PACKAGE_RESTRICTIONS: {
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1115                    synchronized (mPackages) {
1116                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1117                        for (int userId : mDirtyUsers) {
1118                            mSettings.writePackageRestrictionsLPr(userId);
1119                        }
1120                        mDirtyUsers.clear();
1121                    }
1122                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1123                } break;
1124                case CHECK_PENDING_VERIFICATION: {
1125                    final int verificationId = msg.arg1;
1126                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1127
1128                    if ((state != null) && !state.timeoutExtended()) {
1129                        final InstallArgs args = state.getInstallArgs();
1130                        final Uri originUri = Uri.fromFile(args.originFile);
1131
1132                        Slog.i(TAG, "Verification timed out for " + originUri);
1133                        mPendingVerification.remove(verificationId);
1134
1135                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1136
1137                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1138                            Slog.i(TAG, "Continuing with installation of " + originUri);
1139                            state.setVerifierResponse(Binder.getCallingUid(),
1140                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1141                            broadcastPackageVerified(verificationId, originUri,
1142                                    PackageManager.VERIFICATION_ALLOW,
1143                                    state.getInstallArgs().getUser());
1144                            try {
1145                                ret = args.copyApk(mContainerService, true);
1146                            } catch (RemoteException e) {
1147                                Slog.e(TAG, "Could not contact the ContainerService");
1148                            }
1149                        } else {
1150                            broadcastPackageVerified(verificationId, originUri,
1151                                    PackageManager.VERIFICATION_REJECT,
1152                                    state.getInstallArgs().getUser());
1153                        }
1154
1155                        processPendingInstall(args, ret);
1156                        mHandler.sendEmptyMessage(MCS_UNBIND);
1157                    }
1158                    break;
1159                }
1160                case PACKAGE_VERIFIED: {
1161                    final int verificationId = msg.arg1;
1162
1163                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1164                    if (state == null) {
1165                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1166                        break;
1167                    }
1168
1169                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1170
1171                    state.setVerifierResponse(response.callerUid, response.code);
1172
1173                    if (state.isVerificationComplete()) {
1174                        mPendingVerification.remove(verificationId);
1175
1176                        final InstallArgs args = state.getInstallArgs();
1177                        final Uri originUri = Uri.fromFile(args.originFile);
1178
1179                        int ret;
1180                        if (state.isInstallAllowed()) {
1181                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1182                            broadcastPackageVerified(verificationId, originUri,
1183                                    response.code, state.getInstallArgs().getUser());
1184                            try {
1185                                ret = args.copyApk(mContainerService, true);
1186                            } catch (RemoteException e) {
1187                                Slog.e(TAG, "Could not contact the ContainerService");
1188                            }
1189                        } else {
1190                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1191                        }
1192
1193                        processPendingInstall(args, ret);
1194
1195                        mHandler.sendEmptyMessage(MCS_UNBIND);
1196                    }
1197
1198                    break;
1199                }
1200            }
1201        }
1202    }
1203
1204    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1205        Bundle extras = null;
1206        switch (res.returnCode) {
1207            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1208                extras = new Bundle();
1209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1210                        res.origPermission);
1211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1212                        res.origPackage);
1213                break;
1214            }
1215        }
1216        return extras;
1217    }
1218
1219    void scheduleWriteSettingsLocked() {
1220        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1221            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1222        }
1223    }
1224
1225    void scheduleWritePackageRestrictionsLocked(int userId) {
1226        if (!sUserManager.exists(userId)) return;
1227        mDirtyUsers.add(userId);
1228        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1229            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1230        }
1231    }
1232
1233    public static final PackageManagerService main(Context context, Installer installer,
1234            boolean factoryTest, boolean onlyCore) {
1235        PackageManagerService m = new PackageManagerService(context, installer,
1236                factoryTest, onlyCore);
1237        ServiceManager.addService("package", m);
1238        return m;
1239    }
1240
1241    static String[] splitString(String str, char sep) {
1242        int count = 1;
1243        int i = 0;
1244        while ((i=str.indexOf(sep, i)) >= 0) {
1245            count++;
1246            i++;
1247        }
1248
1249        String[] res = new String[count];
1250        i=0;
1251        count = 0;
1252        int lastI=0;
1253        while ((i=str.indexOf(sep, i)) >= 0) {
1254            res[count] = str.substring(lastI, i);
1255            count++;
1256            i++;
1257            lastI = i;
1258        }
1259        res[count] = str.substring(lastI, str.length());
1260        return res;
1261    }
1262
1263    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1264        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1265                Context.DISPLAY_SERVICE);
1266        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1267    }
1268
1269    public PackageManagerService(Context context, Installer installer,
1270            boolean factoryTest, boolean onlyCore) {
1271        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1272                SystemClock.uptimeMillis());
1273
1274        if (mSdkVersion <= 0) {
1275            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1276        }
1277
1278        mContext = context;
1279        mFactoryTest = factoryTest;
1280        mOnlyCore = onlyCore;
1281        mMetrics = new DisplayMetrics();
1282        mSettings = new Settings(context);
1283        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295
1296        String separateProcesses = SystemProperties.get("debug.separate_processes");
1297        if (separateProcesses != null && separateProcesses.length() > 0) {
1298            if ("*".equals(separateProcesses)) {
1299                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1300                mSeparateProcesses = null;
1301                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1302            } else {
1303                mDefParseFlags = 0;
1304                mSeparateProcesses = separateProcesses.split(",");
1305                Slog.w(TAG, "Running with debug.separate_processes: "
1306                        + separateProcesses);
1307            }
1308        } else {
1309            mDefParseFlags = 0;
1310            mSeparateProcesses = null;
1311        }
1312
1313        mInstaller = installer;
1314
1315        getDefaultDisplayMetrics(context, mMetrics);
1316
1317        SystemConfig systemConfig = SystemConfig.getInstance();
1318        mGlobalGids = systemConfig.getGlobalGids();
1319        mSystemPermissions = systemConfig.getSystemPermissions();
1320        mAvailableFeatures = systemConfig.getAvailableFeatures();
1321
1322        synchronized (mInstallLock) {
1323        // writer
1324        synchronized (mPackages) {
1325            mHandlerThread = new ServiceThread(TAG,
1326                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1327            mHandlerThread.start();
1328            mHandler = new PackageHandler(mHandlerThread.getLooper());
1329            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1330
1331            File dataDir = Environment.getDataDirectory();
1332            mAppDataDir = new File(dataDir, "data");
1333            mAppInstallDir = new File(dataDir, "app");
1334            mAppLib32InstallDir = new File(dataDir, "app-lib");
1335            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1336            mUserAppDataDir = new File(dataDir, "user");
1337            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1338
1339            sUserManager = new UserManagerService(context, this,
1340                    mInstallLock, mPackages);
1341
1342            // Propagate permission configuration in to package manager.
1343            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1344                    = systemConfig.getPermissions();
1345            for (int i=0; i<permConfig.size(); i++) {
1346                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1347                BasePermission bp = mSettings.mPermissions.get(perm.name);
1348                if (bp == null) {
1349                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1350                    mSettings.mPermissions.put(perm.name, bp);
1351                }
1352                if (perm.gids != null) {
1353                    bp.gids = appendInts(bp.gids, perm.gids);
1354                }
1355            }
1356
1357            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1358            for (int i=0; i<libConfig.size(); i++) {
1359                mSharedLibraries.put(libConfig.keyAt(i),
1360                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1361            }
1362
1363            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1364
1365            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1366                    mSdkVersion, mOnlyCore);
1367
1368            String customResolverActivity = Resources.getSystem().getString(
1369                    R.string.config_customResolverActivity);
1370            if (TextUtils.isEmpty(customResolverActivity)) {
1371                customResolverActivity = null;
1372            } else {
1373                mCustomResolverComponentName = ComponentName.unflattenFromString(
1374                        customResolverActivity);
1375            }
1376
1377            long startTime = SystemClock.uptimeMillis();
1378
1379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1380                    startTime);
1381
1382            // Set flag to monitor and not change apk file paths when
1383            // scanning install directories.
1384            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1385
1386            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1387
1388            /**
1389             * Add everything in the in the boot class path to the
1390             * list of process files because dexopt will have been run
1391             * if necessary during zygote startup.
1392             */
1393            String bootClassPath = System.getProperty("java.boot.class.path");
1394            if (bootClassPath != null) {
1395                String[] paths = splitString(bootClassPath, ':');
1396                for (int i=0; i<paths.length; i++) {
1397                    alreadyDexOpted.add(paths[i]);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            boolean didDexOptLibraryOrTool = false;
1404
1405            final List<String> instructionSets = getAllInstructionSets();
1406
1407            /**
1408             * Ensure all external libraries have had dexopt run on them.
1409             */
1410            if (mSharedLibraries.size() > 0) {
1411                // NOTE: For now, we're compiling these system "shared libraries"
1412                // (and framework jars) into all available architectures. It's possible
1413                // to compile them only when we come across an app that uses them (there's
1414                // already logic for that in scanPackageLI) but that adds some complexity.
1415                for (String instructionSet : instructionSets) {
1416                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1417                        final String lib = libEntry.path;
1418                        if (lib == null) {
1419                            continue;
1420                        }
1421
1422                        try {
1423                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1424                                alreadyDexOpted.add(lib);
1425
1426                                // The list of "shared libraries" we have at this point is
1427                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1428                                didDexOptLibraryOrTool = true;
1429                            }
1430                        } catch (FileNotFoundException e) {
1431                            Slog.w(TAG, "Library not found: " + lib);
1432                        } catch (IOException e) {
1433                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1434                                    + e.getMessage());
1435                        }
1436                    }
1437                }
1438            }
1439
1440            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1441
1442            // Gross hack for now: we know this file doesn't contain any
1443            // code, so don't dexopt it to avoid the resulting log spew.
1444            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1445
1446            // Gross hack for now: we know this file is only part of
1447            // the boot class path for art, so don't dexopt it to
1448            // avoid the resulting log spew.
1449            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1450
1451            /**
1452             * And there are a number of commands implemented in Java, which
1453             * we currently need to do the dexopt on so that they can be
1454             * run from a non-root shell.
1455             */
1456            String[] frameworkFiles = frameworkDir.list();
1457            if (frameworkFiles != null) {
1458                // TODO: We could compile these only for the most preferred ABI. We should
1459                // first double check that the dex files for these commands are not referenced
1460                // by other system apps.
1461                for (String instructionSet : instructionSets) {
1462                    for (int i=0; i<frameworkFiles.length; i++) {
1463                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1464                        String path = libPath.getPath();
1465                        // Skip the file if we already did it.
1466                        if (alreadyDexOpted.contains(path)) {
1467                            continue;
1468                        }
1469                        // Skip the file if it is not a type we want to dexopt.
1470                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1471                            continue;
1472                        }
1473                        try {
1474                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1475                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1476                                didDexOptLibraryOrTool = true;
1477                            }
1478                        } catch (FileNotFoundException e) {
1479                            Slog.w(TAG, "Jar not found: " + path);
1480                        } catch (IOException e) {
1481                            Slog.w(TAG, "Exception reading jar: " + path, e);
1482                        }
1483                    }
1484                }
1485            }
1486
1487            if (didDexOptLibraryOrTool) {
1488                // If we dexopted a library or tool, then something on the system has
1489                // changed. Consider this significant, and wipe away all other
1490                // existing dexopt files to ensure we don't leave any dangling around.
1491                //
1492                // TODO: This should be revisited because it isn't as good an indicator
1493                // as it used to be. It used to include the boot classpath but at some point
1494                // DexFile.isDexOptNeeded started returning false for the boot
1495                // class path files in all cases. It is very possible in a
1496                // small maintenance release update that the library and tool
1497                // jars may be unchanged but APK could be removed resulting in
1498                // unused dalvik-cache files.
1499                for (String instructionSet : instructionSets) {
1500                    mInstaller.pruneDexCache(instructionSet);
1501                }
1502
1503                // Additionally, delete all dex files from the root directory
1504                // since there shouldn't be any there anyway, unless we're upgrading
1505                // from an older OS version or a build that contained the "old" style
1506                // flat scheme.
1507                mInstaller.pruneDexCache(".");
1508            }
1509
1510            // Collect vendor overlay packages.
1511            // (Do this before scanning any apps.)
1512            // For security and version matching reason, only consider
1513            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1514            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1515            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1516                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1517
1518            // Find base frameworks (resource packages without code).
1519            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1520                    | PackageParser.PARSE_IS_SYSTEM_DIR
1521                    | PackageParser.PARSE_IS_PRIVILEGED,
1522                    scanMode | SCAN_NO_DEX, 0);
1523
1524            // Collected privileged system packages.
1525            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1526            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1527                    | PackageParser.PARSE_IS_SYSTEM_DIR
1528                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1529
1530            // Collect ordinary system packages.
1531            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1532            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1533                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1534
1535            // Collect all vendor packages.
1536            File vendorAppDir = new File("/vendor/app");
1537            try {
1538                vendorAppDir = vendorAppDir.getCanonicalFile();
1539            } catch (IOException e) {
1540                // failed to look up canonical path, continue with original one
1541            }
1542            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1543                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1544
1545            // Collect all OEM packages.
1546            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1547            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1548                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1549
1550            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1551            mInstaller.moveFiles();
1552
1553            // Prune any system packages that no longer exist.
1554            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1555            if (!mOnlyCore) {
1556                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1557                while (psit.hasNext()) {
1558                    PackageSetting ps = psit.next();
1559
1560                    /*
1561                     * If this is not a system app, it can't be a
1562                     * disable system app.
1563                     */
1564                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1565                        continue;
1566                    }
1567
1568                    /*
1569                     * If the package is scanned, it's not erased.
1570                     */
1571                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1572                    if (scannedPkg != null) {
1573                        /*
1574                         * If the system app is both scanned and in the
1575                         * disabled packages list, then it must have been
1576                         * added via OTA. Remove it from the currently
1577                         * scanned package so the previously user-installed
1578                         * application can be scanned.
1579                         */
1580                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1581                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1582                                    + "; removing system app");
1583                            removePackageLI(ps, true);
1584                        }
1585
1586                        continue;
1587                    }
1588
1589                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1590                        psit.remove();
1591                        String msg = "System package " + ps.name
1592                                + " no longer exists; wiping its data";
1593                        reportSettingsProblem(Log.WARN, msg);
1594                        removeDataDirsLI(ps.name);
1595                    } else {
1596                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1597                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1598                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1599                        }
1600                    }
1601                }
1602            }
1603
1604            //look for any incomplete package installations
1605            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1606            //clean up list
1607            for(int i = 0; i < deletePkgsList.size(); i++) {
1608                //clean up here
1609                cleanupInstallFailedPackage(deletePkgsList.get(i));
1610            }
1611            //delete tmp files
1612            deleteTempPackageFiles();
1613
1614            // Remove any shared userIDs that have no associated packages
1615            mSettings.pruneSharedUsersLPw();
1616
1617            if (!mOnlyCore) {
1618                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1619                        SystemClock.uptimeMillis());
1620                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1621
1622                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1623                        scanMode, 0);
1624
1625                /**
1626                 * Remove disable package settings for any updated system
1627                 * apps that were removed via an OTA. If they're not a
1628                 * previously-updated app, remove them completely.
1629                 * Otherwise, just revoke their system-level permissions.
1630                 */
1631                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1632                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1633                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1634
1635                    String msg;
1636                    if (deletedPkg == null) {
1637                        msg = "Updated system package " + deletedAppName
1638                                + " no longer exists; wiping its data";
1639                        removeDataDirsLI(deletedAppName);
1640                    } else {
1641                        msg = "Updated system app + " + deletedAppName
1642                                + " no longer present; removing system privileges for "
1643                                + deletedAppName;
1644
1645                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1646
1647                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1648                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1649                    }
1650                    reportSettingsProblem(Log.WARN, msg);
1651                }
1652            }
1653
1654            // Now that we know all of the shared libraries, update all clients to have
1655            // the correct library paths.
1656            updateAllSharedLibrariesLPw();
1657
1658            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1659                // NOTE: We ignore potential failures here during a system scan (like
1660                // the rest of the commands above) because there's precious little we
1661                // can do about it. A settings error is reported, though.
1662                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1663                        false /* force dexopt */, false /* defer dexopt */);
1664            }
1665
1666            // Now that we know all the packages we are keeping,
1667            // read and update their last usage times.
1668            mPackageUsage.readLP();
1669
1670            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1671                    SystemClock.uptimeMillis());
1672            Slog.i(TAG, "Time to scan packages: "
1673                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1674                    + " seconds");
1675
1676            // If the platform SDK has changed since the last time we booted,
1677            // we need to re-grant app permission to catch any new ones that
1678            // appear.  This is really a hack, and means that apps can in some
1679            // cases get permissions that the user didn't initially explicitly
1680            // allow...  it would be nice to have some better way to handle
1681            // this situation.
1682            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1683                    != mSdkVersion;
1684            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1685                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1686                    + "; regranting permissions for internal storage");
1687            mSettings.mInternalSdkPlatform = mSdkVersion;
1688
1689            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1690                    | (regrantPermissions
1691                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1692                            : 0));
1693
1694            // If this is the first boot, and it is a normal boot, then
1695            // we need to initialize the default preferred apps.
1696            if (!mRestoredSettings && !onlyCore) {
1697                mSettings.readDefaultPreferredAppsLPw(this, 0);
1698            }
1699
1700            // If this is first boot after an OTA, and a normal boot, then
1701            // we need to clear code cache directories.
1702            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1703                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1704                for (String pkgName : mSettings.mPackages.keySet()) {
1705                    deleteCodeCacheDirsLI(pkgName);
1706                }
1707                mSettings.mFingerprint = Build.FINGERPRINT;
1708            }
1709
1710            // All the changes are done during package scanning.
1711            mSettings.updateInternalDatabaseVersion();
1712
1713            // can downgrade to reader
1714            mSettings.writeLPr();
1715
1716            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1717                    SystemClock.uptimeMillis());
1718
1719
1720            mRequiredVerifierPackage = getRequiredVerifierLPr();
1721        } // synchronized (mPackages)
1722        } // synchronized (mInstallLock)
1723
1724        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1725
1726        // Now after opening every single application zip, make sure they
1727        // are all flushed.  Not really needed, but keeps things nice and
1728        // tidy.
1729        Runtime.getRuntime().gc();
1730    }
1731
1732    @Override
1733    public boolean isFirstBoot() {
1734        return !mRestoredSettings;
1735    }
1736
1737    @Override
1738    public boolean isOnlyCoreApps() {
1739        return mOnlyCore;
1740    }
1741
1742    private String getRequiredVerifierLPr() {
1743        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1744        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1745                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1746
1747        String requiredVerifier = null;
1748
1749        final int N = receivers.size();
1750        for (int i = 0; i < N; i++) {
1751            final ResolveInfo info = receivers.get(i);
1752
1753            if (info.activityInfo == null) {
1754                continue;
1755            }
1756
1757            final String packageName = info.activityInfo.packageName;
1758
1759            final PackageSetting ps = mSettings.mPackages.get(packageName);
1760            if (ps == null) {
1761                continue;
1762            }
1763
1764            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1765            if (!gp.grantedPermissions
1766                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1767                continue;
1768            }
1769
1770            if (requiredVerifier != null) {
1771                throw new RuntimeException("There can be only one required verifier");
1772            }
1773
1774            requiredVerifier = packageName;
1775        }
1776
1777        return requiredVerifier;
1778    }
1779
1780    @Override
1781    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1782            throws RemoteException {
1783        try {
1784            return super.onTransact(code, data, reply, flags);
1785        } catch (RuntimeException e) {
1786            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1787                Slog.wtf(TAG, "Package Manager Crash", e);
1788            }
1789            throw e;
1790        }
1791    }
1792
1793    void cleanupInstallFailedPackage(PackageSetting ps) {
1794        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1795        removeDataDirsLI(ps.name);
1796
1797        // TODO: try cleaning up codePath directory contents first, since it
1798        // might be a cluster
1799
1800        if (ps.codePath != null) {
1801            if (!ps.codePath.delete()) {
1802                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1803            }
1804        }
1805        if (ps.resourcePath != null) {
1806            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1807                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1808            }
1809        }
1810        mSettings.removePackageLPw(ps.name);
1811    }
1812
1813    static int[] appendInts(int[] cur, int[] add) {
1814        if (add == null) return cur;
1815        if (cur == null) return add;
1816        final int N = add.length;
1817        for (int i=0; i<N; i++) {
1818            cur = appendInt(cur, add[i]);
1819        }
1820        return cur;
1821    }
1822
1823    static int[] removeInts(int[] cur, int[] rem) {
1824        if (rem == null) return cur;
1825        if (cur == null) return cur;
1826        final int N = rem.length;
1827        for (int i=0; i<N; i++) {
1828            cur = removeInt(cur, rem[i]);
1829        }
1830        return cur;
1831    }
1832
1833    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1834        if (!sUserManager.exists(userId)) return null;
1835        final PackageSetting ps = (PackageSetting) p.mExtras;
1836        if (ps == null) {
1837            return null;
1838        }
1839        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1840        final PackageUserState state = ps.readUserState(userId);
1841        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1842                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1843                state, userId);
1844    }
1845
1846    @Override
1847    public boolean isPackageAvailable(String packageName, int userId) {
1848        if (!sUserManager.exists(userId)) return false;
1849        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1850        synchronized (mPackages) {
1851            PackageParser.Package p = mPackages.get(packageName);
1852            if (p != null) {
1853                final PackageSetting ps = (PackageSetting) p.mExtras;
1854                if (ps != null) {
1855                    final PackageUserState state = ps.readUserState(userId);
1856                    if (state != null) {
1857                        return PackageParser.isAvailable(state);
1858                    }
1859                }
1860            }
1861        }
1862        return false;
1863    }
1864
1865    @Override
1866    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1867        if (!sUserManager.exists(userId)) return null;
1868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1869        // reader
1870        synchronized (mPackages) {
1871            PackageParser.Package p = mPackages.get(packageName);
1872            if (DEBUG_PACKAGE_INFO)
1873                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1874            if (p != null) {
1875                return generatePackageInfo(p, flags, userId);
1876            }
1877            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1878                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1879            }
1880        }
1881        return null;
1882    }
1883
1884    @Override
1885    public String[] currentToCanonicalPackageNames(String[] names) {
1886        String[] out = new String[names.length];
1887        // reader
1888        synchronized (mPackages) {
1889            for (int i=names.length-1; i>=0; i--) {
1890                PackageSetting ps = mSettings.mPackages.get(names[i]);
1891                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1892            }
1893        }
1894        return out;
1895    }
1896
1897    @Override
1898    public String[] canonicalToCurrentPackageNames(String[] names) {
1899        String[] out = new String[names.length];
1900        // reader
1901        synchronized (mPackages) {
1902            for (int i=names.length-1; i>=0; i--) {
1903                String cur = mSettings.mRenamedPackages.get(names[i]);
1904                out[i] = cur != null ? cur : names[i];
1905            }
1906        }
1907        return out;
1908    }
1909
1910    @Override
1911    public int getPackageUid(String packageName, int userId) {
1912        if (!sUserManager.exists(userId)) return -1;
1913        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1914        // reader
1915        synchronized (mPackages) {
1916            PackageParser.Package p = mPackages.get(packageName);
1917            if(p != null) {
1918                return UserHandle.getUid(userId, p.applicationInfo.uid);
1919            }
1920            PackageSetting ps = mSettings.mPackages.get(packageName);
1921            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1922                return -1;
1923            }
1924            p = ps.pkg;
1925            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1926        }
1927    }
1928
1929    @Override
1930    public int[] getPackageGids(String packageName) {
1931        // reader
1932        synchronized (mPackages) {
1933            PackageParser.Package p = mPackages.get(packageName);
1934            if (DEBUG_PACKAGE_INFO)
1935                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1936            if (p != null) {
1937                final PackageSetting ps = (PackageSetting)p.mExtras;
1938                return ps.getGids();
1939            }
1940        }
1941        // stupid thing to indicate an error.
1942        return new int[0];
1943    }
1944
1945    static final PermissionInfo generatePermissionInfo(
1946            BasePermission bp, int flags) {
1947        if (bp.perm != null) {
1948            return PackageParser.generatePermissionInfo(bp.perm, flags);
1949        }
1950        PermissionInfo pi = new PermissionInfo();
1951        pi.name = bp.name;
1952        pi.packageName = bp.sourcePackage;
1953        pi.nonLocalizedLabel = bp.name;
1954        pi.protectionLevel = bp.protectionLevel;
1955        return pi;
1956    }
1957
1958    @Override
1959    public PermissionInfo getPermissionInfo(String name, int flags) {
1960        // reader
1961        synchronized (mPackages) {
1962            final BasePermission p = mSettings.mPermissions.get(name);
1963            if (p != null) {
1964                return generatePermissionInfo(p, flags);
1965            }
1966            return null;
1967        }
1968    }
1969
1970    @Override
1971    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1972        // reader
1973        synchronized (mPackages) {
1974            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1975            for (BasePermission p : mSettings.mPermissions.values()) {
1976                if (group == null) {
1977                    if (p.perm == null || p.perm.info.group == null) {
1978                        out.add(generatePermissionInfo(p, flags));
1979                    }
1980                } else {
1981                    if (p.perm != null && group.equals(p.perm.info.group)) {
1982                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1983                    }
1984                }
1985            }
1986
1987            if (out.size() > 0) {
1988                return out;
1989            }
1990            return mPermissionGroups.containsKey(group) ? out : null;
1991        }
1992    }
1993
1994    @Override
1995    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1996        // reader
1997        synchronized (mPackages) {
1998            return PackageParser.generatePermissionGroupInfo(
1999                    mPermissionGroups.get(name), flags);
2000        }
2001    }
2002
2003    @Override
2004    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2005        // reader
2006        synchronized (mPackages) {
2007            final int N = mPermissionGroups.size();
2008            ArrayList<PermissionGroupInfo> out
2009                    = new ArrayList<PermissionGroupInfo>(N);
2010            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2011                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2012            }
2013            return out;
2014        }
2015    }
2016
2017    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2018            int userId) {
2019        if (!sUserManager.exists(userId)) return null;
2020        PackageSetting ps = mSettings.mPackages.get(packageName);
2021        if (ps != null) {
2022            if (ps.pkg == null) {
2023                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2024                        flags, userId);
2025                if (pInfo != null) {
2026                    return pInfo.applicationInfo;
2027                }
2028                return null;
2029            }
2030            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2031                    ps.readUserState(userId), userId);
2032        }
2033        return null;
2034    }
2035
2036    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2037            int userId) {
2038        if (!sUserManager.exists(userId)) return null;
2039        PackageSetting ps = mSettings.mPackages.get(packageName);
2040        if (ps != null) {
2041            PackageParser.Package pkg = ps.pkg;
2042            if (pkg == null) {
2043                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2044                    return null;
2045                }
2046                // Only data remains, so we aren't worried about code paths
2047                pkg = new PackageParser.Package(packageName);
2048                pkg.applicationInfo.packageName = packageName;
2049                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2050                pkg.applicationInfo.dataDir =
2051                        getDataPathForPackage(packageName, 0).getPath();
2052                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2053                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2054            }
2055            return generatePackageInfo(pkg, flags, userId);
2056        }
2057        return null;
2058    }
2059
2060    @Override
2061    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2062        if (!sUserManager.exists(userId)) return null;
2063        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2064        // writer
2065        synchronized (mPackages) {
2066            PackageParser.Package p = mPackages.get(packageName);
2067            if (DEBUG_PACKAGE_INFO) Log.v(
2068                    TAG, "getApplicationInfo " + packageName
2069                    + ": " + p);
2070            if (p != null) {
2071                PackageSetting ps = mSettings.mPackages.get(packageName);
2072                if (ps == null) return null;
2073                // Note: isEnabledLP() does not apply here - always return info
2074                return PackageParser.generateApplicationInfo(
2075                        p, flags, ps.readUserState(userId), userId);
2076            }
2077            if ("android".equals(packageName)||"system".equals(packageName)) {
2078                return mAndroidApplication;
2079            }
2080            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2081                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2082            }
2083        }
2084        return null;
2085    }
2086
2087
2088    @Override
2089    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2090        mContext.enforceCallingOrSelfPermission(
2091                android.Manifest.permission.CLEAR_APP_CACHE, null);
2092        // Queue up an async operation since clearing cache may take a little while.
2093        mHandler.post(new Runnable() {
2094            public void run() {
2095                mHandler.removeCallbacks(this);
2096                int retCode = -1;
2097                synchronized (mInstallLock) {
2098                    retCode = mInstaller.freeCache(freeStorageSize);
2099                    if (retCode < 0) {
2100                        Slog.w(TAG, "Couldn't clear application caches");
2101                    }
2102                }
2103                if (observer != null) {
2104                    try {
2105                        observer.onRemoveCompleted(null, (retCode >= 0));
2106                    } catch (RemoteException e) {
2107                        Slog.w(TAG, "RemoveException when invoking call back");
2108                    }
2109                }
2110            }
2111        });
2112    }
2113
2114    @Override
2115    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2116        mContext.enforceCallingOrSelfPermission(
2117                android.Manifest.permission.CLEAR_APP_CACHE, null);
2118        // Queue up an async operation since clearing cache may take a little while.
2119        mHandler.post(new Runnable() {
2120            public void run() {
2121                mHandler.removeCallbacks(this);
2122                int retCode = -1;
2123                synchronized (mInstallLock) {
2124                    retCode = mInstaller.freeCache(freeStorageSize);
2125                    if (retCode < 0) {
2126                        Slog.w(TAG, "Couldn't clear application caches");
2127                    }
2128                }
2129                if(pi != null) {
2130                    try {
2131                        // Callback via pending intent
2132                        int code = (retCode >= 0) ? 1 : 0;
2133                        pi.sendIntent(null, code, null,
2134                                null, null);
2135                    } catch (SendIntentException e1) {
2136                        Slog.i(TAG, "Failed to send pending intent");
2137                    }
2138                }
2139            }
2140        });
2141    }
2142
2143    void freeStorage(long freeStorageSize) throws IOException {
2144        synchronized (mInstallLock) {
2145            if (mInstaller.freeCache(freeStorageSize) < 0) {
2146                throw new IOException("Failed to free enough space");
2147            }
2148        }
2149    }
2150
2151    @Override
2152    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2153        if (!sUserManager.exists(userId)) return null;
2154        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2155        synchronized (mPackages) {
2156            PackageParser.Activity a = mActivities.mActivities.get(component);
2157
2158            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2159            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2160                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2161                if (ps == null) return null;
2162                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2163                        userId);
2164            }
2165            if (mResolveComponentName.equals(component)) {
2166                return mResolveActivity;
2167            }
2168        }
2169        return null;
2170    }
2171
2172    @Override
2173    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2174            String resolvedType) {
2175        synchronized (mPackages) {
2176            PackageParser.Activity a = mActivities.mActivities.get(component);
2177            if (a == null) {
2178                return false;
2179            }
2180            for (int i=0; i<a.intents.size(); i++) {
2181                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2182                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2183                    return true;
2184                }
2185            }
2186            return false;
2187        }
2188    }
2189
2190    @Override
2191    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2192        if (!sUserManager.exists(userId)) return null;
2193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mReceivers.mActivities.get(component);
2196            if (DEBUG_PACKAGE_INFO) Log.v(
2197                TAG, "getReceiverInfo " + component + ": " + a);
2198            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2199                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2200                if (ps == null) return null;
2201                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2202                        userId);
2203            }
2204        }
2205        return null;
2206    }
2207
2208    @Override
2209    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2210        if (!sUserManager.exists(userId)) return null;
2211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2212        synchronized (mPackages) {
2213            PackageParser.Service s = mServices.mServices.get(component);
2214            if (DEBUG_PACKAGE_INFO) Log.v(
2215                TAG, "getServiceInfo " + component + ": " + s);
2216            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2218                if (ps == null) return null;
2219                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2220                        userId);
2221            }
2222        }
2223        return null;
2224    }
2225
2226    @Override
2227    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2228        if (!sUserManager.exists(userId)) return null;
2229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2230        synchronized (mPackages) {
2231            PackageParser.Provider p = mProviders.mProviders.get(component);
2232            if (DEBUG_PACKAGE_INFO) Log.v(
2233                TAG, "getProviderInfo " + component + ": " + p);
2234            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2235                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2236                if (ps == null) return null;
2237                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2238                        userId);
2239            }
2240        }
2241        return null;
2242    }
2243
2244    @Override
2245    public String[] getSystemSharedLibraryNames() {
2246        Set<String> libSet;
2247        synchronized (mPackages) {
2248            libSet = mSharedLibraries.keySet();
2249            int size = libSet.size();
2250            if (size > 0) {
2251                String[] libs = new String[size];
2252                libSet.toArray(libs);
2253                return libs;
2254            }
2255        }
2256        return null;
2257    }
2258
2259    @Override
2260    public FeatureInfo[] getSystemAvailableFeatures() {
2261        Collection<FeatureInfo> featSet;
2262        synchronized (mPackages) {
2263            featSet = mAvailableFeatures.values();
2264            int size = featSet.size();
2265            if (size > 0) {
2266                FeatureInfo[] features = new FeatureInfo[size+1];
2267                featSet.toArray(features);
2268                FeatureInfo fi = new FeatureInfo();
2269                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2270                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2271                features[size] = fi;
2272                return features;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public boolean hasSystemFeature(String name) {
2280        synchronized (mPackages) {
2281            return mAvailableFeatures.containsKey(name);
2282        }
2283    }
2284
2285    private void checkValidCaller(int uid, int userId) {
2286        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2287            return;
2288
2289        throw new SecurityException("Caller uid=" + uid
2290                + " is not privileged to communicate with user=" + userId);
2291    }
2292
2293    @Override
2294    public int checkPermission(String permName, String pkgName) {
2295        synchronized (mPackages) {
2296            PackageParser.Package p = mPackages.get(pkgName);
2297            if (p != null && p.mExtras != null) {
2298                PackageSetting ps = (PackageSetting)p.mExtras;
2299                if (ps.sharedUser != null) {
2300                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2301                        return PackageManager.PERMISSION_GRANTED;
2302                    }
2303                } else if (ps.grantedPermissions.contains(permName)) {
2304                    return PackageManager.PERMISSION_GRANTED;
2305                }
2306            }
2307        }
2308        return PackageManager.PERMISSION_DENIED;
2309    }
2310
2311    @Override
2312    public int checkUidPermission(String permName, int uid) {
2313        synchronized (mPackages) {
2314            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2315            if (obj != null) {
2316                GrantedPermissions gp = (GrantedPermissions)obj;
2317                if (gp.grantedPermissions.contains(permName)) {
2318                    return PackageManager.PERMISSION_GRANTED;
2319                }
2320            } else {
2321                HashSet<String> perms = mSystemPermissions.get(uid);
2322                if (perms != null && perms.contains(permName)) {
2323                    return PackageManager.PERMISSION_GRANTED;
2324                }
2325            }
2326        }
2327        return PackageManager.PERMISSION_DENIED;
2328    }
2329
2330    /**
2331     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2332     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2333     * @param message the message to log on security exception
2334     */
2335    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2336            String message) {
2337        if (userId < 0) {
2338            throw new IllegalArgumentException("Invalid userId " + userId);
2339        }
2340        if (userId == UserHandle.getUserId(callingUid)) return;
2341        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2342            if (requireFullPermission) {
2343                mContext.enforceCallingOrSelfPermission(
2344                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2345            } else {
2346                try {
2347                    mContext.enforceCallingOrSelfPermission(
2348                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2349                } catch (SecurityException se) {
2350                    mContext.enforceCallingOrSelfPermission(
2351                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2352                }
2353            }
2354        }
2355    }
2356
2357    private BasePermission findPermissionTreeLP(String permName) {
2358        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2359            if (permName.startsWith(bp.name) &&
2360                    permName.length() > bp.name.length() &&
2361                    permName.charAt(bp.name.length()) == '.') {
2362                return bp;
2363            }
2364        }
2365        return null;
2366    }
2367
2368    private BasePermission checkPermissionTreeLP(String permName) {
2369        if (permName != null) {
2370            BasePermission bp = findPermissionTreeLP(permName);
2371            if (bp != null) {
2372                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2373                    return bp;
2374                }
2375                throw new SecurityException("Calling uid "
2376                        + Binder.getCallingUid()
2377                        + " is not allowed to add to permission tree "
2378                        + bp.name + " owned by uid " + bp.uid);
2379            }
2380        }
2381        throw new SecurityException("No permission tree found for " + permName);
2382    }
2383
2384    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2385        if (s1 == null) {
2386            return s2 == null;
2387        }
2388        if (s2 == null) {
2389            return false;
2390        }
2391        if (s1.getClass() != s2.getClass()) {
2392            return false;
2393        }
2394        return s1.equals(s2);
2395    }
2396
2397    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2398        if (pi1.icon != pi2.icon) return false;
2399        if (pi1.logo != pi2.logo) return false;
2400        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2401        if (!compareStrings(pi1.name, pi2.name)) return false;
2402        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2403        // We'll take care of setting this one.
2404        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2405        // These are not currently stored in settings.
2406        //if (!compareStrings(pi1.group, pi2.group)) return false;
2407        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2408        //if (pi1.labelRes != pi2.labelRes) return false;
2409        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2410        return true;
2411    }
2412
2413    int permissionInfoFootprint(PermissionInfo info) {
2414        int size = info.name.length();
2415        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2416        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2417        return size;
2418    }
2419
2420    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2421        int size = 0;
2422        for (BasePermission perm : mSettings.mPermissions.values()) {
2423            if (perm.uid == tree.uid) {
2424                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2425            }
2426        }
2427        return size;
2428    }
2429
2430    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2431        // We calculate the max size of permissions defined by this uid and throw
2432        // if that plus the size of 'info' would exceed our stated maximum.
2433        if (tree.uid != Process.SYSTEM_UID) {
2434            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2435            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2436                throw new SecurityException("Permission tree size cap exceeded");
2437            }
2438        }
2439    }
2440
2441    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2442        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2443            throw new SecurityException("Label must be specified in permission");
2444        }
2445        BasePermission tree = checkPermissionTreeLP(info.name);
2446        BasePermission bp = mSettings.mPermissions.get(info.name);
2447        boolean added = bp == null;
2448        boolean changed = true;
2449        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2450        if (added) {
2451            enforcePermissionCapLocked(info, tree);
2452            bp = new BasePermission(info.name, tree.sourcePackage,
2453                    BasePermission.TYPE_DYNAMIC);
2454        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2455            throw new SecurityException(
2456                    "Not allowed to modify non-dynamic permission "
2457                    + info.name);
2458        } else {
2459            if (bp.protectionLevel == fixedLevel
2460                    && bp.perm.owner.equals(tree.perm.owner)
2461                    && bp.uid == tree.uid
2462                    && comparePermissionInfos(bp.perm.info, info)) {
2463                changed = false;
2464            }
2465        }
2466        bp.protectionLevel = fixedLevel;
2467        info = new PermissionInfo(info);
2468        info.protectionLevel = fixedLevel;
2469        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2470        bp.perm.info.packageName = tree.perm.info.packageName;
2471        bp.uid = tree.uid;
2472        if (added) {
2473            mSettings.mPermissions.put(info.name, bp);
2474        }
2475        if (changed) {
2476            if (!async) {
2477                mSettings.writeLPr();
2478            } else {
2479                scheduleWriteSettingsLocked();
2480            }
2481        }
2482        return added;
2483    }
2484
2485    @Override
2486    public boolean addPermission(PermissionInfo info) {
2487        synchronized (mPackages) {
2488            return addPermissionLocked(info, false);
2489        }
2490    }
2491
2492    @Override
2493    public boolean addPermissionAsync(PermissionInfo info) {
2494        synchronized (mPackages) {
2495            return addPermissionLocked(info, true);
2496        }
2497    }
2498
2499    @Override
2500    public void removePermission(String name) {
2501        synchronized (mPackages) {
2502            checkPermissionTreeLP(name);
2503            BasePermission bp = mSettings.mPermissions.get(name);
2504            if (bp != null) {
2505                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2506                    throw new SecurityException(
2507                            "Not allowed to modify non-dynamic permission "
2508                            + name);
2509                }
2510                mSettings.mPermissions.remove(name);
2511                mSettings.writeLPr();
2512            }
2513        }
2514    }
2515
2516    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2517        int index = pkg.requestedPermissions.indexOf(bp.name);
2518        if (index == -1) {
2519            throw new SecurityException("Package " + pkg.packageName
2520                    + " has not requested permission " + bp.name);
2521        }
2522        boolean isNormal =
2523                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2524                        == PermissionInfo.PROTECTION_NORMAL);
2525        boolean isDangerous =
2526                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2527                        == PermissionInfo.PROTECTION_DANGEROUS);
2528        boolean isDevelopment =
2529                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2530
2531        if (!isNormal && !isDangerous && !isDevelopment) {
2532            throw new SecurityException("Permission " + bp.name
2533                    + " is not a changeable permission type");
2534        }
2535
2536        if (isNormal || isDangerous) {
2537            if (pkg.requestedPermissionsRequired.get(index)) {
2538                throw new SecurityException("Can't change " + bp.name
2539                        + ". It is required by the application");
2540            }
2541        }
2542    }
2543
2544    @Override
2545    public void grantPermission(String packageName, String permissionName) {
2546        mContext.enforceCallingOrSelfPermission(
2547                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2548        synchronized (mPackages) {
2549            final PackageParser.Package pkg = mPackages.get(packageName);
2550            if (pkg == null) {
2551                throw new IllegalArgumentException("Unknown package: " + packageName);
2552            }
2553            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2554            if (bp == null) {
2555                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2556            }
2557
2558            checkGrantRevokePermissions(pkg, bp);
2559
2560            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2561            if (ps == null) {
2562                return;
2563            }
2564            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2565            if (gp.grantedPermissions.add(permissionName)) {
2566                if (ps.haveGids) {
2567                    gp.gids = appendInts(gp.gids, bp.gids);
2568                }
2569                mSettings.writeLPr();
2570            }
2571        }
2572    }
2573
2574    @Override
2575    public void revokePermission(String packageName, String permissionName) {
2576        int changedAppId = -1;
2577
2578        synchronized (mPackages) {
2579            final PackageParser.Package pkg = mPackages.get(packageName);
2580            if (pkg == null) {
2581                throw new IllegalArgumentException("Unknown package: " + packageName);
2582            }
2583            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2584                mContext.enforceCallingOrSelfPermission(
2585                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2586            }
2587            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2588            if (bp == null) {
2589                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2590            }
2591
2592            checkGrantRevokePermissions(pkg, bp);
2593
2594            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2595            if (ps == null) {
2596                return;
2597            }
2598            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2599            if (gp.grantedPermissions.remove(permissionName)) {
2600                gp.grantedPermissions.remove(permissionName);
2601                if (ps.haveGids) {
2602                    gp.gids = removeInts(gp.gids, bp.gids);
2603                }
2604                mSettings.writeLPr();
2605                changedAppId = ps.appId;
2606            }
2607        }
2608
2609        if (changedAppId >= 0) {
2610            // We changed the perm on someone, kill its processes.
2611            IActivityManager am = ActivityManagerNative.getDefault();
2612            if (am != null) {
2613                final int callingUserId = UserHandle.getCallingUserId();
2614                final long ident = Binder.clearCallingIdentity();
2615                try {
2616                    //XXX we should only revoke for the calling user's app permissions,
2617                    // but for now we impact all users.
2618                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2619                    //        "revoke " + permissionName);
2620                    int[] users = sUserManager.getUserIds();
2621                    for (int user : users) {
2622                        am.killUid(UserHandle.getUid(user, changedAppId),
2623                                "revoke " + permissionName);
2624                    }
2625                } catch (RemoteException e) {
2626                } finally {
2627                    Binder.restoreCallingIdentity(ident);
2628                }
2629            }
2630        }
2631    }
2632
2633    @Override
2634    public boolean isProtectedBroadcast(String actionName) {
2635        synchronized (mPackages) {
2636            return mProtectedBroadcasts.contains(actionName);
2637        }
2638    }
2639
2640    @Override
2641    public int checkSignatures(String pkg1, String pkg2) {
2642        synchronized (mPackages) {
2643            final PackageParser.Package p1 = mPackages.get(pkg1);
2644            final PackageParser.Package p2 = mPackages.get(pkg2);
2645            if (p1 == null || p1.mExtras == null
2646                    || p2 == null || p2.mExtras == null) {
2647                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2648            }
2649            return compareSignatures(p1.mSignatures, p2.mSignatures);
2650        }
2651    }
2652
2653    @Override
2654    public int checkUidSignatures(int uid1, int uid2) {
2655        // Map to base uids.
2656        uid1 = UserHandle.getAppId(uid1);
2657        uid2 = UserHandle.getAppId(uid2);
2658        // reader
2659        synchronized (mPackages) {
2660            Signature[] s1;
2661            Signature[] s2;
2662            Object obj = mSettings.getUserIdLPr(uid1);
2663            if (obj != null) {
2664                if (obj instanceof SharedUserSetting) {
2665                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2666                } else if (obj instanceof PackageSetting) {
2667                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2668                } else {
2669                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2670                }
2671            } else {
2672                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2673            }
2674            obj = mSettings.getUserIdLPr(uid2);
2675            if (obj != null) {
2676                if (obj instanceof SharedUserSetting) {
2677                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2678                } else if (obj instanceof PackageSetting) {
2679                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2680                } else {
2681                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2682                }
2683            } else {
2684                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2685            }
2686            return compareSignatures(s1, s2);
2687        }
2688    }
2689
2690    /**
2691     * Compares two sets of signatures. Returns:
2692     * <br />
2693     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2694     * <br />
2695     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2696     * <br />
2697     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2698     * <br />
2699     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2700     * <br />
2701     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2702     */
2703    static int compareSignatures(Signature[] s1, Signature[] s2) {
2704        if (s1 == null) {
2705            return s2 == null
2706                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2707                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2708        }
2709
2710        if (s2 == null) {
2711            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2712        }
2713
2714        if (s1.length != s2.length) {
2715            return PackageManager.SIGNATURE_NO_MATCH;
2716        }
2717
2718        // Since both signature sets are of size 1, we can compare without HashSets.
2719        if (s1.length == 1) {
2720            return s1[0].equals(s2[0]) ?
2721                    PackageManager.SIGNATURE_MATCH :
2722                    PackageManager.SIGNATURE_NO_MATCH;
2723        }
2724
2725        HashSet<Signature> set1 = new HashSet<Signature>();
2726        for (Signature sig : s1) {
2727            set1.add(sig);
2728        }
2729        HashSet<Signature> set2 = new HashSet<Signature>();
2730        for (Signature sig : s2) {
2731            set2.add(sig);
2732        }
2733        // Make sure s2 contains all signatures in s1.
2734        if (set1.equals(set2)) {
2735            return PackageManager.SIGNATURE_MATCH;
2736        }
2737        return PackageManager.SIGNATURE_NO_MATCH;
2738    }
2739
2740    /**
2741     * If the database version for this type of package (internal storage or
2742     * external storage) is less than the version where package signatures
2743     * were updated, return true.
2744     */
2745    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2746        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2747                DatabaseVersion.SIGNATURE_END_ENTITY))
2748                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2749                        DatabaseVersion.SIGNATURE_END_ENTITY));
2750    }
2751
2752    /**
2753     * Used for backward compatibility to make sure any packages with
2754     * certificate chains get upgraded to the new style. {@code existingSigs}
2755     * will be in the old format (since they were stored on disk from before the
2756     * system upgrade) and {@code scannedSigs} will be in the newer format.
2757     */
2758    private int compareSignaturesCompat(PackageSignatures existingSigs,
2759            PackageParser.Package scannedPkg) {
2760        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2761            return PackageManager.SIGNATURE_NO_MATCH;
2762        }
2763
2764        HashSet<Signature> existingSet = new HashSet<Signature>();
2765        for (Signature sig : existingSigs.mSignatures) {
2766            existingSet.add(sig);
2767        }
2768        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2769        for (Signature sig : scannedPkg.mSignatures) {
2770            try {
2771                Signature[] chainSignatures = sig.getChainSignatures();
2772                for (Signature chainSig : chainSignatures) {
2773                    scannedCompatSet.add(chainSig);
2774                }
2775            } catch (CertificateEncodingException e) {
2776                scannedCompatSet.add(sig);
2777            }
2778        }
2779        /*
2780         * Make sure the expanded scanned set contains all signatures in the
2781         * existing one.
2782         */
2783        if (scannedCompatSet.equals(existingSet)) {
2784            // Migrate the old signatures to the new scheme.
2785            existingSigs.assignSignatures(scannedPkg.mSignatures);
2786            // The new KeySets will be re-added later in the scanning process.
2787            synchronized (mPackages) {
2788                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2789            }
2790            return PackageManager.SIGNATURE_MATCH;
2791        }
2792        return PackageManager.SIGNATURE_NO_MATCH;
2793    }
2794
2795    @Override
2796    public String[] getPackagesForUid(int uid) {
2797        uid = UserHandle.getAppId(uid);
2798        // reader
2799        synchronized (mPackages) {
2800            Object obj = mSettings.getUserIdLPr(uid);
2801            if (obj instanceof SharedUserSetting) {
2802                final SharedUserSetting sus = (SharedUserSetting) obj;
2803                final int N = sus.packages.size();
2804                final String[] res = new String[N];
2805                final Iterator<PackageSetting> it = sus.packages.iterator();
2806                int i = 0;
2807                while (it.hasNext()) {
2808                    res[i++] = it.next().name;
2809                }
2810                return res;
2811            } else if (obj instanceof PackageSetting) {
2812                final PackageSetting ps = (PackageSetting) obj;
2813                return new String[] { ps.name };
2814            }
2815        }
2816        return null;
2817    }
2818
2819    @Override
2820    public String getNameForUid(int uid) {
2821        // reader
2822        synchronized (mPackages) {
2823            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2824            if (obj instanceof SharedUserSetting) {
2825                final SharedUserSetting sus = (SharedUserSetting) obj;
2826                return sus.name + ":" + sus.userId;
2827            } else if (obj instanceof PackageSetting) {
2828                final PackageSetting ps = (PackageSetting) obj;
2829                return ps.name;
2830            }
2831        }
2832        return null;
2833    }
2834
2835    @Override
2836    public int getUidForSharedUser(String sharedUserName) {
2837        if(sharedUserName == null) {
2838            return -1;
2839        }
2840        // reader
2841        synchronized (mPackages) {
2842            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2843            if (suid == null) {
2844                return -1;
2845            }
2846            return suid.userId;
2847        }
2848    }
2849
2850    @Override
2851    public int getFlagsForUid(int uid) {
2852        synchronized (mPackages) {
2853            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2854            if (obj instanceof SharedUserSetting) {
2855                final SharedUserSetting sus = (SharedUserSetting) obj;
2856                return sus.pkgFlags;
2857            } else if (obj instanceof PackageSetting) {
2858                final PackageSetting ps = (PackageSetting) obj;
2859                return ps.pkgFlags;
2860            }
2861        }
2862        return 0;
2863    }
2864
2865    @Override
2866    public String[] getAppOpPermissionPackages(String permissionName) {
2867        synchronized (mPackages) {
2868            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2869            if (pkgs == null) {
2870                return null;
2871            }
2872            return pkgs.toArray(new String[pkgs.size()]);
2873        }
2874    }
2875
2876    @Override
2877    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2878            int flags, int userId) {
2879        if (!sUserManager.exists(userId)) return null;
2880        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2881        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2882        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2883    }
2884
2885    @Override
2886    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2887            IntentFilter filter, int match, ComponentName activity) {
2888        final int userId = UserHandle.getCallingUserId();
2889        if (DEBUG_PREFERRED) {
2890            Log.v(TAG, "setLastChosenActivity intent=" + intent
2891                + " resolvedType=" + resolvedType
2892                + " flags=" + flags
2893                + " filter=" + filter
2894                + " match=" + match
2895                + " activity=" + activity);
2896            filter.dump(new PrintStreamPrinter(System.out), "    ");
2897        }
2898        intent.setComponent(null);
2899        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2900        // Find any earlier preferred or last chosen entries and nuke them
2901        findPreferredActivity(intent, resolvedType,
2902                flags, query, 0, false, true, false, userId);
2903        // Add the new activity as the last chosen for this filter
2904        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2905    }
2906
2907    @Override
2908    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2909        final int userId = UserHandle.getCallingUserId();
2910        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2911        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2912        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2913                false, false, false, userId);
2914    }
2915
2916    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2917            int flags, List<ResolveInfo> query, int userId) {
2918        if (query != null) {
2919            final int N = query.size();
2920            if (N == 1) {
2921                return query.get(0);
2922            } else if (N > 1) {
2923                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2924                // If there is more than one activity with the same priority,
2925                // then let the user decide between them.
2926                ResolveInfo r0 = query.get(0);
2927                ResolveInfo r1 = query.get(1);
2928                if (DEBUG_INTENT_MATCHING || debug) {
2929                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2930                            + r1.activityInfo.name + "=" + r1.priority);
2931                }
2932                // If the first activity has a higher priority, or a different
2933                // default, then it is always desireable to pick it.
2934                if (r0.priority != r1.priority
2935                        || r0.preferredOrder != r1.preferredOrder
2936                        || r0.isDefault != r1.isDefault) {
2937                    return query.get(0);
2938                }
2939                // If we have saved a preference for a preferred activity for
2940                // this Intent, use that.
2941                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2942                        flags, query, r0.priority, true, false, debug, userId);
2943                if (ri != null) {
2944                    return ri;
2945                }
2946                if (userId != 0) {
2947                    ri = new ResolveInfo(mResolveInfo);
2948                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2949                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2950                            ri.activityInfo.applicationInfo);
2951                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2952                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2953                    return ri;
2954                }
2955                return mResolveInfo;
2956            }
2957        }
2958        return null;
2959    }
2960
2961    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2962            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2963        final int N = query.size();
2964        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2965                .get(userId);
2966        // Get the list of persistent preferred activities that handle the intent
2967        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2968        List<PersistentPreferredActivity> pprefs = ppir != null
2969                ? ppir.queryIntent(intent, resolvedType,
2970                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2971                : null;
2972        if (pprefs != null && pprefs.size() > 0) {
2973            final int M = pprefs.size();
2974            for (int i=0; i<M; i++) {
2975                final PersistentPreferredActivity ppa = pprefs.get(i);
2976                if (DEBUG_PREFERRED || debug) {
2977                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2978                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2979                            + "\n  component=" + ppa.mComponent);
2980                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2981                }
2982                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2983                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2984                if (DEBUG_PREFERRED || debug) {
2985                    Slog.v(TAG, "Found persistent preferred activity:");
2986                    if (ai != null) {
2987                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2988                    } else {
2989                        Slog.v(TAG, "  null");
2990                    }
2991                }
2992                if (ai == null) {
2993                    // This previously registered persistent preferred activity
2994                    // component is no longer known. Ignore it and do NOT remove it.
2995                    continue;
2996                }
2997                for (int j=0; j<N; j++) {
2998                    final ResolveInfo ri = query.get(j);
2999                    if (!ri.activityInfo.applicationInfo.packageName
3000                            .equals(ai.applicationInfo.packageName)) {
3001                        continue;
3002                    }
3003                    if (!ri.activityInfo.name.equals(ai.name)) {
3004                        continue;
3005                    }
3006                    //  Found a persistent preference that can handle the intent.
3007                    if (DEBUG_PREFERRED || debug) {
3008                        Slog.v(TAG, "Returning persistent preferred activity: " +
3009                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3010                    }
3011                    return ri;
3012                }
3013            }
3014        }
3015        return null;
3016    }
3017
3018    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3019            List<ResolveInfo> query, int priority, boolean always,
3020            boolean removeMatches, boolean debug, int userId) {
3021        if (!sUserManager.exists(userId)) return null;
3022        // writer
3023        synchronized (mPackages) {
3024            if (intent.getSelector() != null) {
3025                intent = intent.getSelector();
3026            }
3027            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3028
3029            // Try to find a matching persistent preferred activity.
3030            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3031                    debug, userId);
3032
3033            // If a persistent preferred activity matched, use it.
3034            if (pri != null) {
3035                return pri;
3036            }
3037
3038            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3039            // Get the list of preferred activities that handle the intent
3040            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3041            List<PreferredActivity> prefs = pir != null
3042                    ? pir.queryIntent(intent, resolvedType,
3043                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3044                    : null;
3045            if (prefs != null && prefs.size() > 0) {
3046                // First figure out how good the original match set is.
3047                // We will only allow preferred activities that came
3048                // from the same match quality.
3049                int match = 0;
3050
3051                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3052
3053                final int N = query.size();
3054                for (int j=0; j<N; j++) {
3055                    final ResolveInfo ri = query.get(j);
3056                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3057                            + ": 0x" + Integer.toHexString(match));
3058                    if (ri.match > match) {
3059                        match = ri.match;
3060                    }
3061                }
3062
3063                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3064                        + Integer.toHexString(match));
3065
3066                match &= IntentFilter.MATCH_CATEGORY_MASK;
3067                final int M = prefs.size();
3068                for (int i=0; i<M; i++) {
3069                    final PreferredActivity pa = prefs.get(i);
3070                    if (DEBUG_PREFERRED || debug) {
3071                        Slog.v(TAG, "Checking PreferredActivity ds="
3072                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3073                                + "\n  component=" + pa.mPref.mComponent);
3074                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3075                    }
3076                    if (pa.mPref.mMatch != match) {
3077                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3078                                + Integer.toHexString(pa.mPref.mMatch));
3079                        continue;
3080                    }
3081                    // If it's not an "always" type preferred activity and that's what we're
3082                    // looking for, skip it.
3083                    if (always && !pa.mPref.mAlways) {
3084                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3085                        continue;
3086                    }
3087                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3088                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3089                    if (DEBUG_PREFERRED || debug) {
3090                        Slog.v(TAG, "Found preferred activity:");
3091                        if (ai != null) {
3092                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3093                        } else {
3094                            Slog.v(TAG, "  null");
3095                        }
3096                    }
3097                    if (ai == null) {
3098                        // This previously registered preferred activity
3099                        // component is no longer known.  Most likely an update
3100                        // to the app was installed and in the new version this
3101                        // component no longer exists.  Clean it up by removing
3102                        // it from the preferred activities list, and skip it.
3103                        Slog.w(TAG, "Removing dangling preferred activity: "
3104                                + pa.mPref.mComponent);
3105                        pir.removeFilter(pa);
3106                        continue;
3107                    }
3108                    for (int j=0; j<N; j++) {
3109                        final ResolveInfo ri = query.get(j);
3110                        if (!ri.activityInfo.applicationInfo.packageName
3111                                .equals(ai.applicationInfo.packageName)) {
3112                            continue;
3113                        }
3114                        if (!ri.activityInfo.name.equals(ai.name)) {
3115                            continue;
3116                        }
3117
3118                        if (removeMatches) {
3119                            pir.removeFilter(pa);
3120                            if (DEBUG_PREFERRED) {
3121                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3122                            }
3123                            break;
3124                        }
3125
3126                        // Okay we found a previously set preferred or last chosen app.
3127                        // If the result set is different from when this
3128                        // was created, we need to clear it and re-ask the
3129                        // user their preference, if we're looking for an "always" type entry.
3130                        if (always && !pa.mPref.sameSet(query, priority)) {
3131                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3132                                    + intent + " type " + resolvedType);
3133                            if (DEBUG_PREFERRED) {
3134                                Slog.v(TAG, "Removing preferred activity since set changed "
3135                                        + pa.mPref.mComponent);
3136                            }
3137                            pir.removeFilter(pa);
3138                            // Re-add the filter as a "last chosen" entry (!always)
3139                            PreferredActivity lastChosen = new PreferredActivity(
3140                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3141                            pir.addFilter(lastChosen);
3142                            mSettings.writePackageRestrictionsLPr(userId);
3143                            return null;
3144                        }
3145
3146                        // Yay! Either the set matched or we're looking for the last chosen
3147                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3148                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3149                        mSettings.writePackageRestrictionsLPr(userId);
3150                        return ri;
3151                    }
3152                }
3153            }
3154            mSettings.writePackageRestrictionsLPr(userId);
3155        }
3156        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3157        return null;
3158    }
3159
3160    /*
3161     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3162     */
3163    @Override
3164    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3165            int targetUserId) {
3166        mContext.enforceCallingOrSelfPermission(
3167                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3168        List<CrossProfileIntentFilter> matches =
3169                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3170        if (matches != null) {
3171            int size = matches.size();
3172            for (int i = 0; i < size; i++) {
3173                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3174            }
3175        }
3176
3177        ArrayList<String> packageNames = null;
3178        SparseArray<ArrayList<String>> fromSource =
3179                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3180        if (fromSource != null) {
3181            packageNames = fromSource.get(targetUserId);
3182        }
3183        if (packageNames.contains(intent.getPackage())) {
3184            return true;
3185        }
3186        // We need the package name, so we try to resolve with the loosest flags possible
3187        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3188                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3189        int count = resolveInfos.size();
3190        for (int i = 0; i < count; i++) {
3191            ResolveInfo resolveInfo = resolveInfos.get(i);
3192            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3193                return true;
3194            }
3195        }
3196        return false;
3197    }
3198
3199    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3200            String resolvedType, int userId) {
3201        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3202        if (resolver != null) {
3203            return resolver.queryIntent(intent, resolvedType, false, userId);
3204        }
3205        return null;
3206    }
3207
3208    @Override
3209    public List<ResolveInfo> queryIntentActivities(Intent intent,
3210            String resolvedType, int flags, int userId) {
3211        if (!sUserManager.exists(userId)) return Collections.emptyList();
3212        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3213        ComponentName comp = intent.getComponent();
3214        if (comp == null) {
3215            if (intent.getSelector() != null) {
3216                intent = intent.getSelector();
3217                comp = intent.getComponent();
3218            }
3219        }
3220
3221        if (comp != null) {
3222            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3223            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3224            if (ai != null) {
3225                final ResolveInfo ri = new ResolveInfo();
3226                ri.activityInfo = ai;
3227                list.add(ri);
3228            }
3229            return list;
3230        }
3231
3232        // reader
3233        synchronized (mPackages) {
3234            final String pkgName = intent.getPackage();
3235            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3236            if (pkgName == null) {
3237                ResolveInfo resolveInfo = null;
3238                if (queryCrossProfile) {
3239                    // Check if the intent needs to be forwarded to another user for this package
3240                    ArrayList<ResolveInfo> crossProfileResult =
3241                            queryIntentActivitiesCrossProfilePackage(
3242                                    intent, resolvedType, flags, userId);
3243                    if (!crossProfileResult.isEmpty()) {
3244                        // Skip the current profile
3245                        return crossProfileResult;
3246                    }
3247                    List<CrossProfileIntentFilter> matchingFilters =
3248                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3249                    // Check for results that need to skip the current profile.
3250                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3251                            resolvedType, flags, userId);
3252                    if (resolveInfo != null) {
3253                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3254                        result.add(resolveInfo);
3255                        return result;
3256                    }
3257                    // Check for cross profile results.
3258                    resolveInfo = queryCrossProfileIntents(
3259                            matchingFilters, intent, resolvedType, flags, userId);
3260                }
3261                // Check for results in the current profile.
3262                List<ResolveInfo> result = mActivities.queryIntent(
3263                        intent, resolvedType, flags, userId);
3264                if (resolveInfo != null) {
3265                    result.add(resolveInfo);
3266                }
3267                return result;
3268            }
3269            final PackageParser.Package pkg = mPackages.get(pkgName);
3270            if (pkg != null) {
3271                if (queryCrossProfile) {
3272                    ArrayList<ResolveInfo> crossProfileResult =
3273                            queryIntentActivitiesCrossProfilePackage(
3274                                    intent, resolvedType, flags, userId, pkg, pkgName);
3275                    if (!crossProfileResult.isEmpty()) {
3276                        // Skip the current profile
3277                        return crossProfileResult;
3278                    }
3279                }
3280                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3281                        pkg.activities, userId);
3282            }
3283            return new ArrayList<ResolveInfo>();
3284        }
3285    }
3286
3287    private ResolveInfo querySkipCurrentProfileIntents(
3288            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3289            int flags, int sourceUserId) {
3290        if (matchingFilters != null) {
3291            int size = matchingFilters.size();
3292            for (int i = 0; i < size; i ++) {
3293                CrossProfileIntentFilter filter = matchingFilters.get(i);
3294                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3295                    // Checking if there are activities in the target user that can handle the
3296                    // intent.
3297                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3298                            flags, sourceUserId);
3299                    if (resolveInfo != null) {
3300                        return resolveInfo;
3301                    }
3302                }
3303            }
3304        }
3305        return null;
3306    }
3307
3308    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3309            Intent intent, String resolvedType, int flags, int userId) {
3310        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3311        SparseArray<ArrayList<String>> sourceForwardingInfo =
3312                mSettings.mCrossProfilePackageInfo.get(userId);
3313        if (sourceForwardingInfo != null) {
3314            int NI = sourceForwardingInfo.size();
3315            for (int i = 0; i < NI; i++) {
3316                int targetUserId = sourceForwardingInfo.keyAt(i);
3317                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3318                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3319                        intent, resolvedType, flags, targetUserId);
3320                int NJ = resolveInfos.size();
3321                for (int j = 0; j < NJ; j++) {
3322                    ResolveInfo resolveInfo = resolveInfos.get(j);
3323                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3324                        matchingResolveInfos.add(createForwardingResolveInfo(
3325                                resolveInfo.filter, userId, targetUserId));
3326                    }
3327                }
3328            }
3329        }
3330        return matchingResolveInfos;
3331    }
3332
3333    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3334            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3335            String packageName) {
3336        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3337        SparseArray<ArrayList<String>> sourceForwardingInfo =
3338                mSettings.mCrossProfilePackageInfo.get(userId);
3339        if (sourceForwardingInfo != null) {
3340            int NI = sourceForwardingInfo.size();
3341            for (int i = 0; i < NI; i++) {
3342                int targetUserId = sourceForwardingInfo.keyAt(i);
3343                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3344                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3345                            intent, resolvedType, flags, pkg.activities, targetUserId);
3346                    int NJ = resolveInfos.size();
3347                    for (int j = 0; j < NJ; j++) {
3348                        ResolveInfo resolveInfo = resolveInfos.get(j);
3349                        matchingResolveInfos.add(createForwardingResolveInfo(
3350                                resolveInfo.filter, userId, targetUserId));
3351                    }
3352                }
3353            }
3354        }
3355        return matchingResolveInfos;
3356    }
3357
3358    // Return matching ResolveInfo if any for skip current profile intent filters.
3359    private ResolveInfo queryCrossProfileIntents(
3360            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3361            int flags, int sourceUserId) {
3362        if (matchingFilters != null) {
3363            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3364            // match the same intent. For performance reasons, it is better not to
3365            // run queryIntent twice for the same userId
3366            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3367            int size = matchingFilters.size();
3368            for (int i = 0; i < size; i++) {
3369                CrossProfileIntentFilter filter = matchingFilters.get(i);
3370                int targetUserId = filter.getTargetUserId();
3371                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3372                        && !alreadyTriedUserIds.get(targetUserId)) {
3373                    // Checking if there are activities in the target user that can handle the
3374                    // intent.
3375                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3376                            flags, sourceUserId);
3377                    if (resolveInfo != null) return resolveInfo;
3378                    alreadyTriedUserIds.put(targetUserId, true);
3379                }
3380            }
3381        }
3382        return null;
3383    }
3384
3385    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3386            String resolvedType, int flags, int sourceUserId) {
3387        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3388                resolvedType, flags, filter.getTargetUserId());
3389        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3390            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3391        }
3392        return null;
3393    }
3394
3395    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3396            int sourceUserId, int targetUserId) {
3397        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3398        String className;
3399        if (targetUserId == UserHandle.USER_OWNER) {
3400            className = FORWARD_INTENT_TO_USER_OWNER;
3401        } else {
3402            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3403        }
3404        ComponentName forwardingActivityComponentName = new ComponentName(
3405                mAndroidApplication.packageName, className);
3406        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3407                sourceUserId);
3408        if (targetUserId == UserHandle.USER_OWNER) {
3409            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3410            forwardingResolveInfo.noResourceId = true;
3411        }
3412        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3413        forwardingResolveInfo.priority = 0;
3414        forwardingResolveInfo.preferredOrder = 0;
3415        forwardingResolveInfo.match = 0;
3416        forwardingResolveInfo.isDefault = true;
3417        forwardingResolveInfo.filter = filter;
3418        forwardingResolveInfo.targetUserId = targetUserId;
3419        return forwardingResolveInfo;
3420    }
3421
3422    @Override
3423    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3424            Intent[] specifics, String[] specificTypes, Intent intent,
3425            String resolvedType, int flags, int userId) {
3426        if (!sUserManager.exists(userId)) return Collections.emptyList();
3427        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3428                "query intent activity options");
3429        final String resultsAction = intent.getAction();
3430
3431        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3432                | PackageManager.GET_RESOLVED_FILTER, userId);
3433
3434        if (DEBUG_INTENT_MATCHING) {
3435            Log.v(TAG, "Query " + intent + ": " + results);
3436        }
3437
3438        int specificsPos = 0;
3439        int N;
3440
3441        // todo: note that the algorithm used here is O(N^2).  This
3442        // isn't a problem in our current environment, but if we start running
3443        // into situations where we have more than 5 or 10 matches then this
3444        // should probably be changed to something smarter...
3445
3446        // First we go through and resolve each of the specific items
3447        // that were supplied, taking care of removing any corresponding
3448        // duplicate items in the generic resolve list.
3449        if (specifics != null) {
3450            for (int i=0; i<specifics.length; i++) {
3451                final Intent sintent = specifics[i];
3452                if (sintent == null) {
3453                    continue;
3454                }
3455
3456                if (DEBUG_INTENT_MATCHING) {
3457                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3458                }
3459
3460                String action = sintent.getAction();
3461                if (resultsAction != null && resultsAction.equals(action)) {
3462                    // If this action was explicitly requested, then don't
3463                    // remove things that have it.
3464                    action = null;
3465                }
3466
3467                ResolveInfo ri = null;
3468                ActivityInfo ai = null;
3469
3470                ComponentName comp = sintent.getComponent();
3471                if (comp == null) {
3472                    ri = resolveIntent(
3473                        sintent,
3474                        specificTypes != null ? specificTypes[i] : null,
3475                            flags, userId);
3476                    if (ri == null) {
3477                        continue;
3478                    }
3479                    if (ri == mResolveInfo) {
3480                        // ACK!  Must do something better with this.
3481                    }
3482                    ai = ri.activityInfo;
3483                    comp = new ComponentName(ai.applicationInfo.packageName,
3484                            ai.name);
3485                } else {
3486                    ai = getActivityInfo(comp, flags, userId);
3487                    if (ai == null) {
3488                        continue;
3489                    }
3490                }
3491
3492                // Look for any generic query activities that are duplicates
3493                // of this specific one, and remove them from the results.
3494                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3495                N = results.size();
3496                int j;
3497                for (j=specificsPos; j<N; j++) {
3498                    ResolveInfo sri = results.get(j);
3499                    if ((sri.activityInfo.name.equals(comp.getClassName())
3500                            && sri.activityInfo.applicationInfo.packageName.equals(
3501                                    comp.getPackageName()))
3502                        || (action != null && sri.filter.matchAction(action))) {
3503                        results.remove(j);
3504                        if (DEBUG_INTENT_MATCHING) Log.v(
3505                            TAG, "Removing duplicate item from " + j
3506                            + " due to specific " + specificsPos);
3507                        if (ri == null) {
3508                            ri = sri;
3509                        }
3510                        j--;
3511                        N--;
3512                    }
3513                }
3514
3515                // Add this specific item to its proper place.
3516                if (ri == null) {
3517                    ri = new ResolveInfo();
3518                    ri.activityInfo = ai;
3519                }
3520                results.add(specificsPos, ri);
3521                ri.specificIndex = i;
3522                specificsPos++;
3523            }
3524        }
3525
3526        // Now we go through the remaining generic results and remove any
3527        // duplicate actions that are found here.
3528        N = results.size();
3529        for (int i=specificsPos; i<N-1; i++) {
3530            final ResolveInfo rii = results.get(i);
3531            if (rii.filter == null) {
3532                continue;
3533            }
3534
3535            // Iterate over all of the actions of this result's intent
3536            // filter...  typically this should be just one.
3537            final Iterator<String> it = rii.filter.actionsIterator();
3538            if (it == null) {
3539                continue;
3540            }
3541            while (it.hasNext()) {
3542                final String action = it.next();
3543                if (resultsAction != null && resultsAction.equals(action)) {
3544                    // If this action was explicitly requested, then don't
3545                    // remove things that have it.
3546                    continue;
3547                }
3548                for (int j=i+1; j<N; j++) {
3549                    final ResolveInfo rij = results.get(j);
3550                    if (rij.filter != null && rij.filter.hasAction(action)) {
3551                        results.remove(j);
3552                        if (DEBUG_INTENT_MATCHING) Log.v(
3553                            TAG, "Removing duplicate item from " + j
3554                            + " due to action " + action + " at " + i);
3555                        j--;
3556                        N--;
3557                    }
3558                }
3559            }
3560
3561            // If the caller didn't request filter information, drop it now
3562            // so we don't have to marshall/unmarshall it.
3563            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3564                rii.filter = null;
3565            }
3566        }
3567
3568        // Filter out the caller activity if so requested.
3569        if (caller != null) {
3570            N = results.size();
3571            for (int i=0; i<N; i++) {
3572                ActivityInfo ainfo = results.get(i).activityInfo;
3573                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3574                        && caller.getClassName().equals(ainfo.name)) {
3575                    results.remove(i);
3576                    break;
3577                }
3578            }
3579        }
3580
3581        // If the caller didn't request filter information,
3582        // drop them now so we don't have to
3583        // marshall/unmarshall it.
3584        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3585            N = results.size();
3586            for (int i=0; i<N; i++) {
3587                results.get(i).filter = null;
3588            }
3589        }
3590
3591        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3592        return results;
3593    }
3594
3595    @Override
3596    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3597            int userId) {
3598        if (!sUserManager.exists(userId)) return Collections.emptyList();
3599        ComponentName comp = intent.getComponent();
3600        if (comp == null) {
3601            if (intent.getSelector() != null) {
3602                intent = intent.getSelector();
3603                comp = intent.getComponent();
3604            }
3605        }
3606        if (comp != null) {
3607            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3608            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3609            if (ai != null) {
3610                ResolveInfo ri = new ResolveInfo();
3611                ri.activityInfo = ai;
3612                list.add(ri);
3613            }
3614            return list;
3615        }
3616
3617        // reader
3618        synchronized (mPackages) {
3619            String pkgName = intent.getPackage();
3620            if (pkgName == null) {
3621                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3622            }
3623            final PackageParser.Package pkg = mPackages.get(pkgName);
3624            if (pkg != null) {
3625                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3626                        userId);
3627            }
3628            return null;
3629        }
3630    }
3631
3632    @Override
3633    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3634        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3635        if (!sUserManager.exists(userId)) return null;
3636        if (query != null) {
3637            if (query.size() >= 1) {
3638                // If there is more than one service with the same priority,
3639                // just arbitrarily pick the first one.
3640                return query.get(0);
3641            }
3642        }
3643        return null;
3644    }
3645
3646    @Override
3647    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3648            int userId) {
3649        if (!sUserManager.exists(userId)) return Collections.emptyList();
3650        ComponentName comp = intent.getComponent();
3651        if (comp == null) {
3652            if (intent.getSelector() != null) {
3653                intent = intent.getSelector();
3654                comp = intent.getComponent();
3655            }
3656        }
3657        if (comp != null) {
3658            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3659            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3660            if (si != null) {
3661                final ResolveInfo ri = new ResolveInfo();
3662                ri.serviceInfo = si;
3663                list.add(ri);
3664            }
3665            return list;
3666        }
3667
3668        // reader
3669        synchronized (mPackages) {
3670            String pkgName = intent.getPackage();
3671            if (pkgName == null) {
3672                return mServices.queryIntent(intent, resolvedType, flags, userId);
3673            }
3674            final PackageParser.Package pkg = mPackages.get(pkgName);
3675            if (pkg != null) {
3676                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3677                        userId);
3678            }
3679            return null;
3680        }
3681    }
3682
3683    @Override
3684    public List<ResolveInfo> queryIntentContentProviders(
3685            Intent intent, String resolvedType, int flags, int userId) {
3686        if (!sUserManager.exists(userId)) return Collections.emptyList();
3687        ComponentName comp = intent.getComponent();
3688        if (comp == null) {
3689            if (intent.getSelector() != null) {
3690                intent = intent.getSelector();
3691                comp = intent.getComponent();
3692            }
3693        }
3694        if (comp != null) {
3695            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3696            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3697            if (pi != null) {
3698                final ResolveInfo ri = new ResolveInfo();
3699                ri.providerInfo = pi;
3700                list.add(ri);
3701            }
3702            return list;
3703        }
3704
3705        // reader
3706        synchronized (mPackages) {
3707            String pkgName = intent.getPackage();
3708            if (pkgName == null) {
3709                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3710            }
3711            final PackageParser.Package pkg = mPackages.get(pkgName);
3712            if (pkg != null) {
3713                return mProviders.queryIntentForPackage(
3714                        intent, resolvedType, flags, pkg.providers, userId);
3715            }
3716            return null;
3717        }
3718    }
3719
3720    @Override
3721    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3722        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3723
3724        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3725
3726        // writer
3727        synchronized (mPackages) {
3728            ArrayList<PackageInfo> list;
3729            if (listUninstalled) {
3730                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3731                for (PackageSetting ps : mSettings.mPackages.values()) {
3732                    PackageInfo pi;
3733                    if (ps.pkg != null) {
3734                        pi = generatePackageInfo(ps.pkg, flags, userId);
3735                    } else {
3736                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3737                    }
3738                    if (pi != null) {
3739                        list.add(pi);
3740                    }
3741                }
3742            } else {
3743                list = new ArrayList<PackageInfo>(mPackages.size());
3744                for (PackageParser.Package p : mPackages.values()) {
3745                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3746                    if (pi != null) {
3747                        list.add(pi);
3748                    }
3749                }
3750            }
3751
3752            return new ParceledListSlice<PackageInfo>(list);
3753        }
3754    }
3755
3756    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3757            String[] permissions, boolean[] tmp, int flags, int userId) {
3758        int numMatch = 0;
3759        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3760        for (int i=0; i<permissions.length; i++) {
3761            if (gp.grantedPermissions.contains(permissions[i])) {
3762                tmp[i] = true;
3763                numMatch++;
3764            } else {
3765                tmp[i] = false;
3766            }
3767        }
3768        if (numMatch == 0) {
3769            return;
3770        }
3771        PackageInfo pi;
3772        if (ps.pkg != null) {
3773            pi = generatePackageInfo(ps.pkg, flags, userId);
3774        } else {
3775            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3776        }
3777        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3778            if (numMatch == permissions.length) {
3779                pi.requestedPermissions = permissions;
3780            } else {
3781                pi.requestedPermissions = new String[numMatch];
3782                numMatch = 0;
3783                for (int i=0; i<permissions.length; i++) {
3784                    if (tmp[i]) {
3785                        pi.requestedPermissions[numMatch] = permissions[i];
3786                        numMatch++;
3787                    }
3788                }
3789            }
3790        }
3791        list.add(pi);
3792    }
3793
3794    @Override
3795    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3796            String[] permissions, int flags, int userId) {
3797        if (!sUserManager.exists(userId)) return null;
3798        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3799
3800        // writer
3801        synchronized (mPackages) {
3802            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3803            boolean[] tmpBools = new boolean[permissions.length];
3804            if (listUninstalled) {
3805                for (PackageSetting ps : mSettings.mPackages.values()) {
3806                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3807                }
3808            } else {
3809                for (PackageParser.Package pkg : mPackages.values()) {
3810                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3811                    if (ps != null) {
3812                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3813                                userId);
3814                    }
3815                }
3816            }
3817
3818            return new ParceledListSlice<PackageInfo>(list);
3819        }
3820    }
3821
3822    @Override
3823    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3824        if (!sUserManager.exists(userId)) return null;
3825        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3826
3827        // writer
3828        synchronized (mPackages) {
3829            ArrayList<ApplicationInfo> list;
3830            if (listUninstalled) {
3831                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3832                for (PackageSetting ps : mSettings.mPackages.values()) {
3833                    ApplicationInfo ai;
3834                    if (ps.pkg != null) {
3835                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3836                                ps.readUserState(userId), userId);
3837                    } else {
3838                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3839                    }
3840                    if (ai != null) {
3841                        list.add(ai);
3842                    }
3843                }
3844            } else {
3845                list = new ArrayList<ApplicationInfo>(mPackages.size());
3846                for (PackageParser.Package p : mPackages.values()) {
3847                    if (p.mExtras != null) {
3848                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3849                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3850                        if (ai != null) {
3851                            list.add(ai);
3852                        }
3853                    }
3854                }
3855            }
3856
3857            return new ParceledListSlice<ApplicationInfo>(list);
3858        }
3859    }
3860
3861    public List<ApplicationInfo> getPersistentApplications(int flags) {
3862        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3863
3864        // reader
3865        synchronized (mPackages) {
3866            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3867            final int userId = UserHandle.getCallingUserId();
3868            while (i.hasNext()) {
3869                final PackageParser.Package p = i.next();
3870                if (p.applicationInfo != null
3871                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3872                        && (!mSafeMode || isSystemApp(p))) {
3873                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3874                    if (ps != null) {
3875                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3876                                ps.readUserState(userId), userId);
3877                        if (ai != null) {
3878                            finalList.add(ai);
3879                        }
3880                    }
3881                }
3882            }
3883        }
3884
3885        return finalList;
3886    }
3887
3888    @Override
3889    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3890        if (!sUserManager.exists(userId)) return null;
3891        // reader
3892        synchronized (mPackages) {
3893            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3894            PackageSetting ps = provider != null
3895                    ? mSettings.mPackages.get(provider.owner.packageName)
3896                    : null;
3897            return ps != null
3898                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3899                    && (!mSafeMode || (provider.info.applicationInfo.flags
3900                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3901                    ? PackageParser.generateProviderInfo(provider, flags,
3902                            ps.readUserState(userId), userId)
3903                    : null;
3904        }
3905    }
3906
3907    /**
3908     * @deprecated
3909     */
3910    @Deprecated
3911    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3912        // reader
3913        synchronized (mPackages) {
3914            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3915                    .entrySet().iterator();
3916            final int userId = UserHandle.getCallingUserId();
3917            while (i.hasNext()) {
3918                Map.Entry<String, PackageParser.Provider> entry = i.next();
3919                PackageParser.Provider p = entry.getValue();
3920                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3921
3922                if (ps != null && p.syncable
3923                        && (!mSafeMode || (p.info.applicationInfo.flags
3924                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3925                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3926                            ps.readUserState(userId), userId);
3927                    if (info != null) {
3928                        outNames.add(entry.getKey());
3929                        outInfo.add(info);
3930                    }
3931                }
3932            }
3933        }
3934    }
3935
3936    @Override
3937    public List<ProviderInfo> queryContentProviders(String processName,
3938            int uid, int flags) {
3939        ArrayList<ProviderInfo> finalList = null;
3940        // reader
3941        synchronized (mPackages) {
3942            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3943            final int userId = processName != null ?
3944                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3945            while (i.hasNext()) {
3946                final PackageParser.Provider p = i.next();
3947                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3948                if (ps != null && p.info.authority != null
3949                        && (processName == null
3950                                || (p.info.processName.equals(processName)
3951                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3952                        && mSettings.isEnabledLPr(p.info, flags, userId)
3953                        && (!mSafeMode
3954                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3955                    if (finalList == null) {
3956                        finalList = new ArrayList<ProviderInfo>(3);
3957                    }
3958                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3959                            ps.readUserState(userId), userId);
3960                    if (info != null) {
3961                        finalList.add(info);
3962                    }
3963                }
3964            }
3965        }
3966
3967        if (finalList != null) {
3968            Collections.sort(finalList, mProviderInitOrderSorter);
3969        }
3970
3971        return finalList;
3972    }
3973
3974    @Override
3975    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3976            int flags) {
3977        // reader
3978        synchronized (mPackages) {
3979            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3980            return PackageParser.generateInstrumentationInfo(i, flags);
3981        }
3982    }
3983
3984    @Override
3985    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3986            int flags) {
3987        ArrayList<InstrumentationInfo> finalList =
3988            new ArrayList<InstrumentationInfo>();
3989
3990        // reader
3991        synchronized (mPackages) {
3992            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3993            while (i.hasNext()) {
3994                final PackageParser.Instrumentation p = i.next();
3995                if (targetPackage == null
3996                        || targetPackage.equals(p.info.targetPackage)) {
3997                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3998                            flags);
3999                    if (ii != null) {
4000                        finalList.add(ii);
4001                    }
4002                }
4003            }
4004        }
4005
4006        return finalList;
4007    }
4008
4009    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4010        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4011        if (overlays == null) {
4012            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4013            return;
4014        }
4015        for (PackageParser.Package opkg : overlays.values()) {
4016            // Not much to do if idmap fails: we already logged the error
4017            // and we certainly don't want to abort installation of pkg simply
4018            // because an overlay didn't fit properly. For these reasons,
4019            // ignore the return value of createIdmapForPackagePairLI.
4020            createIdmapForPackagePairLI(pkg, opkg);
4021        }
4022    }
4023
4024    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4025            PackageParser.Package opkg) {
4026        if (!opkg.mTrustedOverlay) {
4027            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4028                    opkg.baseCodePath + ": overlay not trusted");
4029            return false;
4030        }
4031        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4032        if (overlaySet == null) {
4033            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4034                    opkg.baseCodePath + " but target package has no known overlays");
4035            return false;
4036        }
4037        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4038        // TODO: generate idmap for split APKs
4039        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4040            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4041                    + opkg.baseCodePath);
4042            return false;
4043        }
4044        PackageParser.Package[] overlayArray =
4045            overlaySet.values().toArray(new PackageParser.Package[0]);
4046        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4047            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4048                return p1.mOverlayPriority - p2.mOverlayPriority;
4049            }
4050        };
4051        Arrays.sort(overlayArray, cmp);
4052
4053        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4054        int i = 0;
4055        for (PackageParser.Package p : overlayArray) {
4056            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4057        }
4058        return true;
4059    }
4060
4061    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4062        final File[] files = dir.listFiles();
4063        if (ArrayUtils.isEmpty(files)) {
4064            Log.d(TAG, "No files in app dir " + dir);
4065            return;
4066        }
4067
4068        if (DEBUG_PACKAGE_SCANNING) {
4069            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4070                    + " flags=0x" + Integer.toHexString(flags));
4071        }
4072
4073        for (File file : files) {
4074            final boolean isPackage = isApkFile(file) || file.isDirectory();
4075            if (!isPackage) {
4076                // Ignore entries which are not apk's
4077                continue;
4078            }
4079            try {
4080                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime,
4081                        null, null);
4082            } catch (PackageManagerException e) {
4083                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4084
4085                // Don't mess around with apps in system partition.
4086                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4087                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4088                    // Delete the apk
4089                    Slog.w(TAG, "Cleaning up failed install of " + file);
4090                    file.delete();
4091                }
4092            }
4093        }
4094    }
4095
4096    private static File getSettingsProblemFile() {
4097        File dataDir = Environment.getDataDirectory();
4098        File systemDir = new File(dataDir, "system");
4099        File fname = new File(systemDir, "uiderrors.txt");
4100        return fname;
4101    }
4102
4103    static void reportSettingsProblem(int priority, String msg) {
4104        try {
4105            File fname = getSettingsProblemFile();
4106            FileOutputStream out = new FileOutputStream(fname, true);
4107            PrintWriter pw = new FastPrintWriter(out);
4108            SimpleDateFormat formatter = new SimpleDateFormat();
4109            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4110            pw.println(dateString + ": " + msg);
4111            pw.close();
4112            FileUtils.setPermissions(
4113                    fname.toString(),
4114                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4115                    -1, -1);
4116        } catch (java.io.IOException e) {
4117        }
4118        Slog.println(priority, TAG, msg);
4119    }
4120
4121    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4122            PackageParser.Package pkg, File srcFile, int parseFlags)
4123            throws PackageManagerException {
4124        if (ps != null
4125                && ps.codePath.equals(srcFile)
4126                && ps.timeStamp == srcFile.lastModified()
4127                && !isCompatSignatureUpdateNeeded(pkg)) {
4128            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4129            if (ps.signatures.mSignatures != null
4130                    && ps.signatures.mSignatures.length != 0
4131                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4132                // Optimization: reuse the existing cached certificates
4133                // if the package appears to be unchanged.
4134                pkg.mSignatures = ps.signatures.mSignatures;
4135                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4136                synchronized (mPackages) {
4137                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4138                }
4139                return;
4140            }
4141
4142            Slog.w(TAG, "PackageSetting for " + ps.name
4143                    + " is missing signatures.  Collecting certs again to recover them.");
4144        } else {
4145            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4146        }
4147
4148        try {
4149            pp.collectCertificates(pkg, parseFlags);
4150            pp.collectManifestDigest(pkg);
4151        } catch (PackageParserException e) {
4152            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4153                    + pkg.packageName + ": " + e.getMessage());
4154        }
4155    }
4156
4157    /*
4158     *  Scan a package and return the newly parsed package.
4159     *  Returns null in case of errors and the error code is stored in mLastScanError
4160     */
4161    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4162            long currentTime, UserHandle user, String abiOverride) throws PackageManagerException {
4163        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4164        parseFlags |= mDefParseFlags;
4165        PackageParser pp = new PackageParser();
4166        pp.setSeparateProcesses(mSeparateProcesses);
4167        pp.setOnlyCoreApps(mOnlyCore);
4168        pp.setDisplayMetrics(mMetrics);
4169
4170        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4171            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4172        }
4173
4174        final PackageParser.Package pkg;
4175        try {
4176            pkg = pp.parsePackage(scanFile, parseFlags);
4177        } catch (PackageParserException e) {
4178            throw new PackageManagerException(e.error,
4179                    "Failed to scan " + scanFile + ": " + e.getMessage());
4180        }
4181
4182        PackageSetting ps = null;
4183        PackageSetting updatedPkg;
4184        // reader
4185        synchronized (mPackages) {
4186            // Look to see if we already know about this package.
4187            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4188            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4189                // This package has been renamed to its original name.  Let's
4190                // use that.
4191                ps = mSettings.peekPackageLPr(oldName);
4192            }
4193            // If there was no original package, see one for the real package name.
4194            if (ps == null) {
4195                ps = mSettings.peekPackageLPr(pkg.packageName);
4196            }
4197            // Check to see if this package could be hiding/updating a system
4198            // package.  Must look for it either under the original or real
4199            // package name depending on our state.
4200            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4201            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4202        }
4203        boolean updatedPkgBetter = false;
4204        // First check if this is a system package that may involve an update
4205        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4206            if (ps != null && !ps.codePath.equals(scanFile)) {
4207                // The path has changed from what was last scanned...  check the
4208                // version of the new path against what we have stored to determine
4209                // what to do.
4210                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4211                if (pkg.mVersionCode < ps.versionCode) {
4212                    // The system package has been updated and the code path does not match
4213                    // Ignore entry. Skip it.
4214                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4215                            + " ignored: updated version " + ps.versionCode
4216                            + " better than this " + pkg.mVersionCode);
4217                    if (!updatedPkg.codePath.equals(scanFile)) {
4218                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4219                                + ps.name + " changing from " + updatedPkg.codePathString
4220                                + " to " + scanFile);
4221                        updatedPkg.codePath = scanFile;
4222                        updatedPkg.codePathString = scanFile.toString();
4223                        // This is the point at which we know that the system-disk APK
4224                        // for this package has moved during a reboot (e.g. due to an OTA),
4225                        // so we need to reevaluate it for privilege policy.
4226                        if (locationIsPrivileged(scanFile)) {
4227                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4228                        }
4229                    }
4230                    updatedPkg.pkg = pkg;
4231                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4232                } else {
4233                    // The current app on the system partition is better than
4234                    // what we have updated to on the data partition; switch
4235                    // back to the system partition version.
4236                    // At this point, its safely assumed that package installation for
4237                    // apps in system partition will go through. If not there won't be a working
4238                    // version of the app
4239                    // writer
4240                    synchronized (mPackages) {
4241                        // Just remove the loaded entries from package lists.
4242                        mPackages.remove(ps.name);
4243                    }
4244                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4245                            + "reverting from " + ps.codePathString
4246                            + ": new version " + pkg.mVersionCode
4247                            + " better than installed " + ps.versionCode);
4248
4249                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4250                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4251                            getAppDexInstructionSets(ps), isMultiArch(ps));
4252                    synchronized (mInstallLock) {
4253                        args.cleanUpResourcesLI();
4254                    }
4255                    synchronized (mPackages) {
4256                        mSettings.enableSystemPackageLPw(ps.name);
4257                    }
4258                    updatedPkgBetter = true;
4259                }
4260            }
4261        }
4262
4263        if (updatedPkg != null) {
4264            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4265            // initially
4266            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4267
4268            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4269            // flag set initially
4270            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4271                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4272            }
4273        }
4274
4275        // Verify certificates against what was last scanned
4276        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4277
4278        /*
4279         * A new system app appeared, but we already had a non-system one of the
4280         * same name installed earlier.
4281         */
4282        boolean shouldHideSystemApp = false;
4283        if (updatedPkg == null && ps != null
4284                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4285            /*
4286             * Check to make sure the signatures match first. If they don't,
4287             * wipe the installed application and its data.
4288             */
4289            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4290                    != PackageManager.SIGNATURE_MATCH) {
4291                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4292                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4293                ps = null;
4294            } else {
4295                /*
4296                 * If the newly-added system app is an older version than the
4297                 * already installed version, hide it. It will be scanned later
4298                 * and re-added like an update.
4299                 */
4300                if (pkg.mVersionCode < ps.versionCode) {
4301                    shouldHideSystemApp = true;
4302                } else {
4303                    /*
4304                     * The newly found system app is a newer version that the
4305                     * one previously installed. Simply remove the
4306                     * already-installed application and replace it with our own
4307                     * while keeping the application data.
4308                     */
4309                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4310                            + ps.codePathString + ": new version " + pkg.mVersionCode
4311                            + " better than installed " + ps.versionCode);
4312                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4313                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4314                            getAppDexInstructionSets(ps), isMultiArch(ps));
4315                    synchronized (mInstallLock) {
4316                        args.cleanUpResourcesLI();
4317                    }
4318                }
4319            }
4320        }
4321
4322        // The apk is forward locked (not public) if its code and resources
4323        // are kept in different files. (except for app in either system or
4324        // vendor path).
4325        // TODO grab this value from PackageSettings
4326        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4327            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4328                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4329            }
4330        }
4331
4332        // TODO: extend to support forward-locked splits
4333        String resourcePath = null;
4334        String baseResourcePath = null;
4335        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4336            if (ps != null && ps.resourcePathString != null) {
4337                resourcePath = ps.resourcePathString;
4338                baseResourcePath = ps.resourcePathString;
4339            } else {
4340                // Should not happen at all. Just log an error.
4341                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4342            }
4343        } else {
4344            resourcePath = pkg.codePath;
4345            baseResourcePath = pkg.baseCodePath;
4346        }
4347
4348        // Set application objects path explicitly.
4349        pkg.applicationInfo.setCodePath(pkg.codePath);
4350        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4351        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4352        pkg.applicationInfo.setResourcePath(resourcePath);
4353        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4354        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4355
4356        // Note that we invoke the following method only if we are about to unpack an application
4357        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4358                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4359
4360        /*
4361         * If the system app should be overridden by a previously installed
4362         * data, hide the system app now and let the /data/app scan pick it up
4363         * again.
4364         */
4365        if (shouldHideSystemApp) {
4366            synchronized (mPackages) {
4367                /*
4368                 * We have to grant systems permissions before we hide, because
4369                 * grantPermissions will assume the package update is trying to
4370                 * expand its permissions.
4371                 */
4372                grantPermissionsLPw(pkg, true);
4373                mSettings.disableSystemPackageLPw(pkg.packageName);
4374            }
4375        }
4376
4377        return scannedPkg;
4378    }
4379
4380    private static String fixProcessName(String defProcessName,
4381            String processName, int uid) {
4382        if (processName == null) {
4383            return defProcessName;
4384        }
4385        return processName;
4386    }
4387
4388    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4389            throws PackageManagerException {
4390        if (pkgSetting.signatures.mSignatures != null) {
4391            // Already existing package. Make sure signatures match
4392            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4393                    == PackageManager.SIGNATURE_MATCH;
4394            if (!match) {
4395                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4396                        == PackageManager.SIGNATURE_MATCH;
4397            }
4398            if (!match) {
4399                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4400                        + pkg.packageName + " signatures do not match the "
4401                        + "previously installed version; ignoring!");
4402            }
4403        }
4404
4405        // Check for shared user signatures
4406        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4407            // Already existing package. Make sure signatures match
4408            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4409                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4410            if (!match) {
4411                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4412                        == PackageManager.SIGNATURE_MATCH;
4413            }
4414            if (!match) {
4415                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4416                        "Package " + pkg.packageName
4417                        + " has no signatures that match those in shared user "
4418                        + pkgSetting.sharedUser.name + "; ignoring!");
4419            }
4420        }
4421    }
4422
4423    /**
4424     * Enforces that only the system UID or root's UID can call a method exposed
4425     * via Binder.
4426     *
4427     * @param message used as message if SecurityException is thrown
4428     * @throws SecurityException if the caller is not system or root
4429     */
4430    private static final void enforceSystemOrRoot(String message) {
4431        final int uid = Binder.getCallingUid();
4432        if (uid != Process.SYSTEM_UID && uid != 0) {
4433            throw new SecurityException(message);
4434        }
4435    }
4436
4437    @Override
4438    public void performBootDexOpt() {
4439        enforceSystemOrRoot("Only the system can request dexopt be performed");
4440
4441        final HashSet<PackageParser.Package> pkgs;
4442        synchronized (mPackages) {
4443            pkgs = mDeferredDexOpt;
4444            mDeferredDexOpt = null;
4445        }
4446
4447        if (pkgs != null) {
4448            // Filter out packages that aren't recently used.
4449            //
4450            // The exception is first boot of a non-eng device, which
4451            // should do a full dexopt.
4452            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4453            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4454                // TODO: add a property to control this?
4455                long dexOptLRUThresholdInMinutes;
4456                if (eng) {
4457                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4458                } else {
4459                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4460                }
4461                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4462
4463                int total = pkgs.size();
4464                int skipped = 0;
4465                long now = System.currentTimeMillis();
4466                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4467                    PackageParser.Package pkg = i.next();
4468                    long then = pkg.mLastPackageUsageTimeInMills;
4469                    if (then + dexOptLRUThresholdInMills < now) {
4470                        if (DEBUG_DEXOPT) {
4471                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4472                                  ((then == 0) ? "never" : new Date(then)));
4473                        }
4474                        i.remove();
4475                        skipped++;
4476                    }
4477                }
4478                if (DEBUG_DEXOPT) {
4479                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4480                }
4481            }
4482
4483            int i = 0;
4484            for (PackageParser.Package pkg : pkgs) {
4485                i++;
4486                if (DEBUG_DEXOPT) {
4487                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4488                          + ": " + pkg.packageName);
4489                }
4490                if (!isFirstBoot()) {
4491                    try {
4492                        ActivityManagerNative.getDefault().showBootMessage(
4493                                mContext.getResources().getString(
4494                                        R.string.android_upgrading_apk,
4495                                        i, pkgs.size()), true);
4496                    } catch (RemoteException e) {
4497                    }
4498                }
4499                PackageParser.Package p = pkg;
4500                synchronized (mInstallLock) {
4501                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4502                            true /* include dependencies */);
4503                }
4504            }
4505        }
4506    }
4507
4508    @Override
4509    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4510        return performDexOpt(packageName, instructionSet, true);
4511    }
4512
4513    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4514        if (info.primaryCpuAbi == null) {
4515            return getPreferredInstructionSet();
4516        }
4517
4518        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4519    }
4520
4521    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4522        PackageParser.Package p;
4523        final String targetInstructionSet;
4524        synchronized (mPackages) {
4525            p = mPackages.get(packageName);
4526            if (p == null) {
4527                return false;
4528            }
4529            if (updateUsage) {
4530                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4531            }
4532            mPackageUsage.write(false);
4533
4534            targetInstructionSet = instructionSet != null ? instructionSet :
4535                    getPrimaryInstructionSet(p.applicationInfo);
4536            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4537                return false;
4538            }
4539        }
4540
4541        synchronized (mInstallLock) {
4542            final String[] instructionSets = new String[] { targetInstructionSet };
4543            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4544                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4545        }
4546    }
4547
4548    public HashSet<String> getPackagesThatNeedDexOpt() {
4549        HashSet<String> pkgs = null;
4550        synchronized (mPackages) {
4551            for (PackageParser.Package p : mPackages.values()) {
4552                if (DEBUG_DEXOPT) {
4553                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4554                }
4555                if (!p.mDexOptPerformed.isEmpty()) {
4556                    continue;
4557                }
4558                if (pkgs == null) {
4559                    pkgs = new HashSet<String>();
4560                }
4561                pkgs.add(p.packageName);
4562            }
4563        }
4564        return pkgs;
4565    }
4566
4567    public void shutdown() {
4568        mPackageUsage.write(true);
4569    }
4570
4571    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4572             boolean forceDex, boolean defer, HashSet<String> done) {
4573        for (int i=0; i<libs.size(); i++) {
4574            PackageParser.Package libPkg;
4575            String libName;
4576            synchronized (mPackages) {
4577                libName = libs.get(i);
4578                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4579                if (lib != null && lib.apk != null) {
4580                    libPkg = mPackages.get(lib.apk);
4581                } else {
4582                    libPkg = null;
4583                }
4584            }
4585            if (libPkg != null && !done.contains(libName)) {
4586                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4587            }
4588        }
4589    }
4590
4591    static final int DEX_OPT_SKIPPED = 0;
4592    static final int DEX_OPT_PERFORMED = 1;
4593    static final int DEX_OPT_DEFERRED = 2;
4594    static final int DEX_OPT_FAILED = -1;
4595
4596    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4597            boolean forceDex, boolean defer, HashSet<String> done) {
4598        final String[] instructionSets = targetInstructionSets != null ?
4599                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4600
4601        if (done != null) {
4602            done.add(pkg.packageName);
4603            if (pkg.usesLibraries != null) {
4604                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4605            }
4606            if (pkg.usesOptionalLibraries != null) {
4607                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4608            }
4609        }
4610
4611        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4612            return DEX_OPT_SKIPPED;
4613        }
4614
4615        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4616        boolean performedDexOpt = false;
4617        // There are three basic cases here:
4618        // 1.) we need to dexopt, either because we are forced or it is needed
4619        // 2.) we are defering a needed dexopt
4620        // 3.) we are skipping an unneeded dexopt
4621        for (String path : paths) {
4622            for (String instructionSet : instructionSets) {
4623                if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) {
4624                    continue;
4625                }
4626
4627                try {
4628                    final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4629                            pkg.packageName, instructionSet, defer);
4630                    if (forceDex || (!defer && isDexOptNeeded)) {
4631                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4632                                + pkg.applicationInfo.packageName + " isa=" + instructionSet);
4633                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4634                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4635                                pkg.packageName, instructionSet);
4636
4637                        if (ret < 0) {
4638                            // Don't bother running dexopt again if we failed, it will probably
4639                            // just result in an error again. Also, don't bother dexopting for other
4640                            // paths & ISAs.
4641                            return DEX_OPT_FAILED;
4642                        } else {
4643                            performedDexOpt = true;
4644                            pkg.mDexOptPerformed.add(instructionSet);
4645                        }
4646                    }
4647
4648                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4649                    // paths and instruction sets. We'll deal with them all together when we process
4650                    // our list of deferred dexopts.
4651                    if (defer && isDexOptNeeded) {
4652                        if (mDeferredDexOpt == null) {
4653                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4654                        }
4655                        mDeferredDexOpt.add(pkg);
4656                        return DEX_OPT_DEFERRED;
4657                    }
4658                } catch (FileNotFoundException e) {
4659                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4660                    return DEX_OPT_FAILED;
4661                } catch (IOException e) {
4662                    Slog.w(TAG, "IOException reading apk: " + path, e);
4663                    return DEX_OPT_FAILED;
4664                } catch (StaleDexCacheError e) {
4665                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4666                    return DEX_OPT_FAILED;
4667                } catch (Exception e) {
4668                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4669                    return DEX_OPT_FAILED;
4670                }
4671            }
4672        }
4673
4674        // If we've gotten here, we're sure that no error occurred and that we haven't
4675        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4676        // we've skipped all of them because they are up to date. In both cases this
4677        // package doesn't need dexopt any longer.
4678        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4679    }
4680
4681    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4682        if (info.primaryCpuAbi != null) {
4683            if (info.secondaryCpuAbi != null) {
4684                return new String[] {
4685                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4686                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4687            } else {
4688                return new String[] {
4689                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4690            }
4691        }
4692
4693        return new String[] { getPreferredInstructionSet() };
4694    }
4695
4696    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4697        if (ps.primaryCpuAbiString != null) {
4698            if (ps.secondaryCpuAbiString != null) {
4699                return new String[] {
4700                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4701                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4702            } else {
4703                return new String[] {
4704                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4705            }
4706        }
4707
4708        return new String[] { getPreferredInstructionSet() };
4709    }
4710
4711    private static String getPreferredInstructionSet() {
4712        if (sPreferredInstructionSet == null) {
4713            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4714        }
4715
4716        return sPreferredInstructionSet;
4717    }
4718
4719    private static List<String> getAllInstructionSets() {
4720        final String[] allAbis = Build.SUPPORTED_ABIS;
4721        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4722
4723        for (String abi : allAbis) {
4724            final String instructionSet = VMRuntime.getInstructionSet(abi);
4725            if (!allInstructionSets.contains(instructionSet)) {
4726                allInstructionSets.add(instructionSet);
4727            }
4728        }
4729
4730        return allInstructionSets;
4731    }
4732
4733    @Override
4734    public void forceDexOpt(String packageName) {
4735        enforceSystemOrRoot("forceDexOpt");
4736
4737        PackageParser.Package pkg;
4738        synchronized (mPackages) {
4739            pkg = mPackages.get(packageName);
4740            if (pkg == null) {
4741                throw new IllegalArgumentException("Missing package: " + packageName);
4742            }
4743        }
4744
4745        synchronized (mInstallLock) {
4746            final String[] instructionSets = new String[] {
4747                    getPrimaryInstructionSet(pkg.applicationInfo) };
4748            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4749            if (res != DEX_OPT_PERFORMED) {
4750                throw new IllegalStateException("Failed to dexopt: " + res);
4751            }
4752        }
4753    }
4754
4755    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4756                                boolean forceDex, boolean defer, boolean inclDependencies) {
4757        HashSet<String> done;
4758        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4759            done = new HashSet<String>();
4760            done.add(pkg.packageName);
4761        } else {
4762            done = null;
4763        }
4764        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4765    }
4766
4767    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4768        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4769            Slog.w(TAG, "Unable to update from " + oldPkg.name
4770                    + " to " + newPkg.packageName
4771                    + ": old package not in system partition");
4772            return false;
4773        } else if (mPackages.get(oldPkg.name) != null) {
4774            Slog.w(TAG, "Unable to update from " + oldPkg.name
4775                    + " to " + newPkg.packageName
4776                    + ": old package still exists");
4777            return false;
4778        }
4779        return true;
4780    }
4781
4782    File getDataPathForUser(int userId) {
4783        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4784    }
4785
4786    private File getDataPathForPackage(String packageName, int userId) {
4787        /*
4788         * Until we fully support multiple users, return the directory we
4789         * previously would have. The PackageManagerTests will need to be
4790         * revised when this is changed back..
4791         */
4792        if (userId == 0) {
4793            return new File(mAppDataDir, packageName);
4794        } else {
4795            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4796                + File.separator + packageName);
4797        }
4798    }
4799
4800    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4801        int[] users = sUserManager.getUserIds();
4802        int res = mInstaller.install(packageName, uid, uid, seinfo);
4803        if (res < 0) {
4804            return res;
4805        }
4806        for (int user : users) {
4807            if (user != 0) {
4808                res = mInstaller.createUserData(packageName,
4809                        UserHandle.getUid(user, uid), user, seinfo);
4810                if (res < 0) {
4811                    return res;
4812                }
4813            }
4814        }
4815        return res;
4816    }
4817
4818    private int removeDataDirsLI(String packageName) {
4819        int[] users = sUserManager.getUserIds();
4820        int res = 0;
4821        for (int user : users) {
4822            int resInner = mInstaller.remove(packageName, user);
4823            if (resInner < 0) {
4824                res = resInner;
4825            }
4826        }
4827
4828        return res;
4829    }
4830
4831    private int deleteCodeCacheDirsLI(String packageName) {
4832        int[] users = sUserManager.getUserIds();
4833        int res = 0;
4834        for (int user : users) {
4835            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4836            if (resInner < 0) {
4837                res = resInner;
4838            }
4839        }
4840        return res;
4841    }
4842
4843    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4844            PackageParser.Package changingLib) {
4845        if (file.path != null) {
4846            usesLibraryFiles.add(file.path);
4847            return;
4848        }
4849        PackageParser.Package p = mPackages.get(file.apk);
4850        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4851            // If we are doing this while in the middle of updating a library apk,
4852            // then we need to make sure to use that new apk for determining the
4853            // dependencies here.  (We haven't yet finished committing the new apk
4854            // to the package manager state.)
4855            if (p == null || p.packageName.equals(changingLib.packageName)) {
4856                p = changingLib;
4857            }
4858        }
4859        if (p != null) {
4860            usesLibraryFiles.addAll(p.getAllCodePaths());
4861        }
4862    }
4863
4864    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4865            PackageParser.Package changingLib) throws PackageManagerException {
4866        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4867            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4868            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4869            for (int i=0; i<N; i++) {
4870                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4871                if (file == null) {
4872                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4873                            "Package " + pkg.packageName + " requires unavailable shared library "
4874                            + pkg.usesLibraries.get(i) + "; failing!");
4875                }
4876                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4877            }
4878            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4879            for (int i=0; i<N; i++) {
4880                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4881                if (file == null) {
4882                    Slog.w(TAG, "Package " + pkg.packageName
4883                            + " desires unavailable shared library "
4884                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4885                } else {
4886                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4887                }
4888            }
4889            N = usesLibraryFiles.size();
4890            if (N > 0) {
4891                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4892            } else {
4893                pkg.usesLibraryFiles = null;
4894            }
4895        }
4896    }
4897
4898    private static boolean hasString(List<String> list, List<String> which) {
4899        if (list == null) {
4900            return false;
4901        }
4902        for (int i=list.size()-1; i>=0; i--) {
4903            for (int j=which.size()-1; j>=0; j--) {
4904                if (which.get(j).equals(list.get(i))) {
4905                    return true;
4906                }
4907            }
4908        }
4909        return false;
4910    }
4911
4912    private void updateAllSharedLibrariesLPw() {
4913        for (PackageParser.Package pkg : mPackages.values()) {
4914            try {
4915                updateSharedLibrariesLPw(pkg, null);
4916            } catch (PackageManagerException e) {
4917                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4918            }
4919        }
4920    }
4921
4922    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4923            PackageParser.Package changingPkg) {
4924        ArrayList<PackageParser.Package> res = null;
4925        for (PackageParser.Package pkg : mPackages.values()) {
4926            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4927                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4928                if (res == null) {
4929                    res = new ArrayList<PackageParser.Package>();
4930                }
4931                res.add(pkg);
4932                try {
4933                    updateSharedLibrariesLPw(pkg, changingPkg);
4934                } catch (PackageManagerException e) {
4935                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4936                }
4937            }
4938        }
4939        return res;
4940    }
4941
4942    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4943            int scanMode, long currentTime, UserHandle user, String abiOverride)
4944            throws PackageManagerException {
4945        final File scanFile = new File(pkg.codePath);
4946        if (pkg.applicationInfo.getCodePath() == null ||
4947                pkg.applicationInfo.getResourcePath() == null) {
4948            // Bail out. The resource and code paths haven't been set.
4949            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4950                    "Code and resource paths haven't been set correctly");
4951        }
4952
4953        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4954            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4955        }
4956
4957        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4958            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4959        }
4960
4961        if (mCustomResolverComponentName != null &&
4962                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4963            setUpCustomResolverActivity(pkg);
4964        }
4965
4966        if (pkg.packageName.equals("android")) {
4967            synchronized (mPackages) {
4968                if (mAndroidApplication != null) {
4969                    Slog.w(TAG, "*************************************************");
4970                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4971                    Slog.w(TAG, " file=" + scanFile);
4972                    Slog.w(TAG, "*************************************************");
4973                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
4974                            "Core android package being redefined.  Skipping.");
4975                }
4976
4977                // Set up information for our fall-back user intent resolution activity.
4978                mPlatformPackage = pkg;
4979                pkg.mVersionCode = mSdkVersion;
4980                mAndroidApplication = pkg.applicationInfo;
4981
4982                if (!mResolverReplaced) {
4983                    mResolveActivity.applicationInfo = mAndroidApplication;
4984                    mResolveActivity.name = ResolverActivity.class.getName();
4985                    mResolveActivity.packageName = mAndroidApplication.packageName;
4986                    mResolveActivity.processName = "system:ui";
4987                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4988                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4989                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4990                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4991                    mResolveActivity.exported = true;
4992                    mResolveActivity.enabled = true;
4993                    mResolveInfo.activityInfo = mResolveActivity;
4994                    mResolveInfo.priority = 0;
4995                    mResolveInfo.preferredOrder = 0;
4996                    mResolveInfo.match = 0;
4997                    mResolveComponentName = new ComponentName(
4998                            mAndroidApplication.packageName, mResolveActivity.name);
4999                }
5000            }
5001        }
5002
5003        if (DEBUG_PACKAGE_SCANNING) {
5004            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5005                Log.d(TAG, "Scanning package " + pkg.packageName);
5006        }
5007
5008        if (mPackages.containsKey(pkg.packageName)
5009                || mSharedLibraries.containsKey(pkg.packageName)) {
5010            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5011                    "Application package " + pkg.packageName
5012                    + " already installed.  Skipping duplicate.");
5013        }
5014
5015        // Initialize package source and resource directories
5016        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5017        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5018
5019        SharedUserSetting suid = null;
5020        PackageSetting pkgSetting = null;
5021
5022        if (!isSystemApp(pkg)) {
5023            // Only system apps can use these features.
5024            pkg.mOriginalPackages = null;
5025            pkg.mRealPackage = null;
5026            pkg.mAdoptPermissions = null;
5027        }
5028
5029        // writer
5030        synchronized (mPackages) {
5031            if (pkg.mSharedUserId != null) {
5032                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5033                if (suid == null) {
5034                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5035                            "Creating application package " + pkg.packageName
5036                            + " for shared user failed");
5037                }
5038                if (DEBUG_PACKAGE_SCANNING) {
5039                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5040                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5041                                + "): packages=" + suid.packages);
5042                }
5043            }
5044
5045            // Check if we are renaming from an original package name.
5046            PackageSetting origPackage = null;
5047            String realName = null;
5048            if (pkg.mOriginalPackages != null) {
5049                // This package may need to be renamed to a previously
5050                // installed name.  Let's check on that...
5051                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5052                if (pkg.mOriginalPackages.contains(renamed)) {
5053                    // This package had originally been installed as the
5054                    // original name, and we have already taken care of
5055                    // transitioning to the new one.  Just update the new
5056                    // one to continue using the old name.
5057                    realName = pkg.mRealPackage;
5058                    if (!pkg.packageName.equals(renamed)) {
5059                        // Callers into this function may have already taken
5060                        // care of renaming the package; only do it here if
5061                        // it is not already done.
5062                        pkg.setPackageName(renamed);
5063                    }
5064
5065                } else {
5066                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5067                        if ((origPackage = mSettings.peekPackageLPr(
5068                                pkg.mOriginalPackages.get(i))) != null) {
5069                            // We do have the package already installed under its
5070                            // original name...  should we use it?
5071                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5072                                // New package is not compatible with original.
5073                                origPackage = null;
5074                                continue;
5075                            } else if (origPackage.sharedUser != null) {
5076                                // Make sure uid is compatible between packages.
5077                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5078                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5079                                            + " to " + pkg.packageName + ": old uid "
5080                                            + origPackage.sharedUser.name
5081                                            + " differs from " + pkg.mSharedUserId);
5082                                    origPackage = null;
5083                                    continue;
5084                                }
5085                            } else {
5086                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5087                                        + pkg.packageName + " to old name " + origPackage.name);
5088                            }
5089                            break;
5090                        }
5091                    }
5092                }
5093            }
5094
5095            if (mTransferedPackages.contains(pkg.packageName)) {
5096                Slog.w(TAG, "Package " + pkg.packageName
5097                        + " was transferred to another, but its .apk remains");
5098            }
5099
5100            // Just create the setting, don't add it yet. For already existing packages
5101            // the PkgSetting exists already and doesn't have to be created.
5102            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5103                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5104                    pkg.applicationInfo.primaryCpuAbi,
5105                    pkg.applicationInfo.secondaryCpuAbi,
5106                    pkg.applicationInfo.flags, user, false);
5107            if (pkgSetting == null) {
5108                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5109                        "Creating application package " + pkg.packageName + " failed");
5110            }
5111
5112            if (pkgSetting.origPackage != null) {
5113                // If we are first transitioning from an original package,
5114                // fix up the new package's name now.  We need to do this after
5115                // looking up the package under its new name, so getPackageLP
5116                // can take care of fiddling things correctly.
5117                pkg.setPackageName(origPackage.name);
5118
5119                // File a report about this.
5120                String msg = "New package " + pkgSetting.realName
5121                        + " renamed to replace old package " + pkgSetting.name;
5122                reportSettingsProblem(Log.WARN, msg);
5123
5124                // Make a note of it.
5125                mTransferedPackages.add(origPackage.name);
5126
5127                // No longer need to retain this.
5128                pkgSetting.origPackage = null;
5129            }
5130
5131            if (realName != null) {
5132                // Make a note of it.
5133                mTransferedPackages.add(pkg.packageName);
5134            }
5135
5136            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5137                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5138            }
5139
5140            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5141                // Check all shared libraries and map to their actual file path.
5142                // We only do this here for apps not on a system dir, because those
5143                // are the only ones that can fail an install due to this.  We
5144                // will take care of the system apps by updating all of their
5145                // library paths after the scan is done.
5146                updateSharedLibrariesLPw(pkg, null);
5147            }
5148
5149            if (mFoundPolicyFile) {
5150                SELinuxMMAC.assignSeinfoValue(pkg);
5151            }
5152
5153            pkg.applicationInfo.uid = pkgSetting.appId;
5154            pkg.mExtras = pkgSetting;
5155            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5156                try {
5157                    verifySignaturesLP(pkgSetting, pkg);
5158                } catch (PackageManagerException e) {
5159                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5160                        throw e;
5161                    }
5162                    // The signature has changed, but this package is in the system
5163                    // image...  let's recover!
5164                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5165                    // However...  if this package is part of a shared user, but it
5166                    // doesn't match the signature of the shared user, let's fail.
5167                    // What this means is that you can't change the signatures
5168                    // associated with an overall shared user, which doesn't seem all
5169                    // that unreasonable.
5170                    if (pkgSetting.sharedUser != null) {
5171                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5172                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5173                            throw new PackageManagerException(
5174                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5175                                            "Signature mismatch for shared user : "
5176                                            + pkgSetting.sharedUser);
5177                        }
5178                    }
5179                    // File a report about this.
5180                    String msg = "System package " + pkg.packageName
5181                        + " signature changed; retaining data.";
5182                    reportSettingsProblem(Log.WARN, msg);
5183                }
5184            } else {
5185                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5186                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5187                            + pkg.packageName + " upgrade keys do not match the "
5188                            + "previously installed version");
5189                } else {
5190                    // signatures may have changed as result of upgrade
5191                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5192                }
5193            }
5194            // Verify that this new package doesn't have any content providers
5195            // that conflict with existing packages.  Only do this if the
5196            // package isn't already installed, since we don't want to break
5197            // things that are installed.
5198            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5199                final int N = pkg.providers.size();
5200                int i;
5201                for (i=0; i<N; i++) {
5202                    PackageParser.Provider p = pkg.providers.get(i);
5203                    if (p.info.authority != null) {
5204                        String names[] = p.info.authority.split(";");
5205                        for (int j = 0; j < names.length; j++) {
5206                            if (mProvidersByAuthority.containsKey(names[j])) {
5207                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5208                                final String otherPackageName =
5209                                        ((other != null && other.getComponentName() != null) ?
5210                                                other.getComponentName().getPackageName() : "?");
5211                                throw new PackageManagerException(
5212                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5213                                                "Can't install because provider name " + names[j]
5214                                                + " (in package " + pkg.applicationInfo.packageName
5215                                                + ") is already used by " + otherPackageName);
5216                            }
5217                        }
5218                    }
5219                }
5220            }
5221
5222            if (pkg.mAdoptPermissions != null) {
5223                // This package wants to adopt ownership of permissions from
5224                // another package.
5225                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5226                    final String origName = pkg.mAdoptPermissions.get(i);
5227                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5228                    if (orig != null) {
5229                        if (verifyPackageUpdateLPr(orig, pkg)) {
5230                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5231                                    + pkg.packageName);
5232                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5233                        }
5234                    }
5235                }
5236            }
5237        }
5238
5239        final String pkgName = pkg.packageName;
5240
5241        final long scanFileTime = scanFile.lastModified();
5242        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5243        pkg.applicationInfo.processName = fixProcessName(
5244                pkg.applicationInfo.packageName,
5245                pkg.applicationInfo.processName,
5246                pkg.applicationInfo.uid);
5247
5248        File dataPath;
5249        if (mPlatformPackage == pkg) {
5250            // The system package is special.
5251            dataPath = new File (Environment.getDataDirectory(), "system");
5252            pkg.applicationInfo.dataDir = dataPath.getPath();
5253
5254        } else {
5255            // This is a normal package, need to make its data directory.
5256            dataPath = getDataPathForPackage(pkg.packageName, 0);
5257
5258            boolean uidError = false;
5259
5260            if (dataPath.exists()) {
5261                int currentUid = 0;
5262                try {
5263                    StructStat stat = Os.stat(dataPath.getPath());
5264                    currentUid = stat.st_uid;
5265                } catch (ErrnoException e) {
5266                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5267                }
5268
5269                // If we have mismatched owners for the data path, we have a problem.
5270                if (currentUid != pkg.applicationInfo.uid) {
5271                    boolean recovered = false;
5272                    if (currentUid == 0) {
5273                        // The directory somehow became owned by root.  Wow.
5274                        // This is probably because the system was stopped while
5275                        // installd was in the middle of messing with its libs
5276                        // directory.  Ask installd to fix that.
5277                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5278                                pkg.applicationInfo.uid);
5279                        if (ret >= 0) {
5280                            recovered = true;
5281                            String msg = "Package " + pkg.packageName
5282                                    + " unexpectedly changed to uid 0; recovered to " +
5283                                    + pkg.applicationInfo.uid;
5284                            reportSettingsProblem(Log.WARN, msg);
5285                        }
5286                    }
5287                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5288                            || (scanMode&SCAN_BOOTING) != 0)) {
5289                        // If this is a system app, we can at least delete its
5290                        // current data so the application will still work.
5291                        int ret = removeDataDirsLI(pkgName);
5292                        if (ret >= 0) {
5293                            // TODO: Kill the processes first
5294                            // Old data gone!
5295                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5296                                    ? "System package " : "Third party package ";
5297                            String msg = prefix + pkg.packageName
5298                                    + " has changed from uid: "
5299                                    + currentUid + " to "
5300                                    + pkg.applicationInfo.uid + "; old data erased";
5301                            reportSettingsProblem(Log.WARN, msg);
5302                            recovered = true;
5303
5304                            // And now re-install the app.
5305                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5306                                                   pkg.applicationInfo.seinfo);
5307                            if (ret == -1) {
5308                                // Ack should not happen!
5309                                msg = prefix + pkg.packageName
5310                                        + " could not have data directory re-created after delete.";
5311                                reportSettingsProblem(Log.WARN, msg);
5312                                throw new PackageManagerException(
5313                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5314                            }
5315                        }
5316                        if (!recovered) {
5317                            mHasSystemUidErrors = true;
5318                        }
5319                    } else if (!recovered) {
5320                        // If we allow this install to proceed, we will be broken.
5321                        // Abort, abort!
5322                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5323                                "scanPackageLI");
5324                    }
5325                    if (!recovered) {
5326                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5327                            + pkg.applicationInfo.uid + "/fs_"
5328                            + currentUid;
5329                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5330                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5331                        String msg = "Package " + pkg.packageName
5332                                + " has mismatched uid: "
5333                                + currentUid + " on disk, "
5334                                + pkg.applicationInfo.uid + " in settings";
5335                        // writer
5336                        synchronized (mPackages) {
5337                            mSettings.mReadMessages.append(msg);
5338                            mSettings.mReadMessages.append('\n');
5339                            uidError = true;
5340                            if (!pkgSetting.uidError) {
5341                                reportSettingsProblem(Log.ERROR, msg);
5342                            }
5343                        }
5344                    }
5345                }
5346                pkg.applicationInfo.dataDir = dataPath.getPath();
5347                if (mShouldRestoreconData) {
5348                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5349                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5350                                pkg.applicationInfo.uid);
5351                }
5352            } else {
5353                if (DEBUG_PACKAGE_SCANNING) {
5354                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5355                        Log.v(TAG, "Want this data dir: " + dataPath);
5356                }
5357                //invoke installer to do the actual installation
5358                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5359                                           pkg.applicationInfo.seinfo);
5360                if (ret < 0) {
5361                    // Error from installer
5362                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5363                            "Unable to create data dirs [errorCode=" + ret + "]");
5364                }
5365
5366                if (dataPath.exists()) {
5367                    pkg.applicationInfo.dataDir = dataPath.getPath();
5368                } else {
5369                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5370                    pkg.applicationInfo.dataDir = null;
5371                }
5372            }
5373
5374            pkgSetting.uidError = uidError;
5375        }
5376
5377        final String path = scanFile.getPath();
5378        final String codePath = pkg.applicationInfo.getCodePath();
5379        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5380            // For the case where we had previously uninstalled an update, get rid
5381            // of any native binaries we might have unpackaged. Note that this assumes
5382            // that system app updates were not installed via ASEC.
5383            //
5384            // TODO(multiArch): Is this cleanup really necessary ?
5385            NativeLibraryHelper.removeNativeBinariesFromDirLI(
5386                    new File(codePath, LIB_DIR_NAME), false /* delete dirs */);
5387            setBundledAppAbisAndRoots(pkg, pkgSetting);
5388
5389            // If we haven't found any native libraries for the app, check if it has
5390            // renderscript code. We'll need to force the app to 32 bit if it has
5391            // renderscript bitcode.
5392            if (pkg.applicationInfo.primaryCpuAbi == null
5393                    && pkg.applicationInfo.secondaryCpuAbi == null
5394                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5395                NativeLibraryHelper.Handle handle = null;
5396                try {
5397                    handle = NativeLibraryHelper.Handle.create(scanFile);
5398                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5399                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5400                    }
5401                } catch (IOException ioe) {
5402                    Slog.w(TAG, "Error scanning system app : " + ioe);
5403                } finally {
5404                    IoUtils.closeQuietly(handle);
5405                }
5406            }
5407
5408            setNativeLibraryPaths(pkg);
5409        } else {
5410            // TODO: We can probably be smarter about this stuff. For installed apps,
5411            // we can calculate this information at install time once and for all. For
5412            // system apps, we can probably assume that this information doesn't change
5413            // after the first boot scan. As things stand, we do lots of unnecessary work.
5414
5415            // Give ourselves some initial paths; we'll come back for another
5416            // pass once we've determined ABI below.
5417            setNativeLibraryPaths(pkg);
5418
5419            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5420            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5421            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5422
5423            NativeLibraryHelper.Handle handle = null;
5424            try {
5425                handle = NativeLibraryHelper.Handle.create(scanFile);
5426                // TODO(multiArch): This can be null for apps that didn't go through the
5427                // usual installation process. We can calculate it again, like we
5428                // do during install time.
5429                //
5430                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5431                // unnecessary.
5432                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5433
5434                // Null out the abis so that they can be recalculated.
5435                pkg.applicationInfo.primaryCpuAbi = null;
5436                pkg.applicationInfo.secondaryCpuAbi = null;
5437                if (isMultiArch(pkg.applicationInfo)) {
5438                    // Warn if we've set an abiOverride for multi-lib packages..
5439                    // By definition, we need to copy both 32 and 64 bit libraries for
5440                    // such packages.
5441                    if (abiOverride != null) {
5442                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5443                    }
5444
5445                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5446                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5447                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5448                        if (isAsec) {
5449                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5450                        } else {
5451                            abi32 = copyNativeLibrariesForInternalApp(handle,
5452                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5453                        }
5454                    }
5455
5456                    maybeThrowExceptionForMultiArchCopy(
5457                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5458
5459                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5460                        if (isAsec) {
5461                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5462                        } else {
5463                            abi64 = copyNativeLibrariesForInternalApp(handle,
5464                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5465                        }
5466                    }
5467
5468                    maybeThrowExceptionForMultiArchCopy(
5469                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5470
5471                    if (abi64 >= 0) {
5472                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5473                    }
5474
5475                    if (abi32 >= 0) {
5476                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5477                        if (abi64 >= 0) {
5478                            pkg.applicationInfo.secondaryCpuAbi = abi;
5479                        } else {
5480                            pkg.applicationInfo.primaryCpuAbi = abi;
5481                        }
5482                    }
5483                } else {
5484                    String[] abiList = (abiOverride != null) ?
5485                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
5486
5487                    // Enable gross and lame hacks for apps that are built with old
5488                    // SDK tools. We must scan their APKs for renderscript bitcode and
5489                    // not launch them if it's present. Don't bother checking on devices
5490                    // that don't have 64 bit support.
5491                    boolean needsRenderScriptOverride = false;
5492                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
5493                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5494                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5495                        needsRenderScriptOverride = true;
5496                    }
5497
5498                    final int copyRet;
5499                    if (isAsec) {
5500                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5501                    } else {
5502                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5503                                useIsaSpecificSubdirs);
5504                    }
5505
5506                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5507                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5508                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5509                    }
5510
5511                    if (copyRet >= 0) {
5512                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5513                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) {
5514                        pkg.applicationInfo.primaryCpuAbi = abiOverride;
5515                    } else if (needsRenderScriptOverride) {
5516                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5517                    }
5518                }
5519            } catch (IOException ioe) {
5520                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5521            } finally {
5522                IoUtils.closeQuietly(handle);
5523            }
5524
5525            // Now that we've calculated the ABIs and determined if it's an internal app,
5526            // we will go ahead and populate the nativeLibraryPath.
5527            setNativeLibraryPaths(pkg);
5528
5529            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5530            final int[] userIds = sUserManager.getUserIds();
5531            synchronized (mInstallLock) {
5532                // Create a native library symlink only if we have native libraries
5533                // and if the native libraries are 32 bit libraries. We do not provide
5534                // this symlink for 64 bit libraries.
5535                if (pkg.applicationInfo.primaryCpuAbi != null &&
5536                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5537                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5538                    for (int userId : userIds) {
5539                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5540                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5541                                    "Failed linking native library dir (user=" + userId + ")");
5542                        }
5543                    }
5544                }
5545            }
5546        }
5547
5548        // This is a special case for the "system" package, where the ABI is
5549        // dictated by the zygote configuration (and init.rc). We should keep track
5550        // of this ABI so that we can deal with "normal" applications that run under
5551        // the same UID correctly.
5552        if (mPlatformPackage == pkg) {
5553            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5554                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5555        }
5556
5557        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5558        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5559
5560        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5561                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5562                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5563
5564        // Push the derived path down into PackageSettings so we know what to
5565        // clean up at uninstall time.
5566        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5567
5568        if (DEBUG_ABI_SELECTION) {
5569            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5570                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5571                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5572        }
5573
5574        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5575            // We don't do this here during boot because we can do it all
5576            // at once after scanning all existing packages.
5577            //
5578            // We also do this *before* we perform dexopt on this package, so that
5579            // we can avoid redundant dexopts, and also to make sure we've got the
5580            // code and package path correct.
5581            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5582                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5583        }
5584
5585        if ((scanMode&SCAN_NO_DEX) == 0) {
5586            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5587                    == DEX_OPT_FAILED) {
5588                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5589                    removeDataDirsLI(pkg.packageName);
5590                }
5591
5592                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5593            }
5594        }
5595
5596        if (mFactoryTest && pkg.requestedPermissions.contains(
5597                android.Manifest.permission.FACTORY_TEST)) {
5598            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5599        }
5600
5601        ArrayList<PackageParser.Package> clientLibPkgs = null;
5602
5603        // writer
5604        synchronized (mPackages) {
5605            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5606                // Only system apps can add new shared libraries.
5607                if (pkg.libraryNames != null) {
5608                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5609                        String name = pkg.libraryNames.get(i);
5610                        boolean allowed = false;
5611                        if (isUpdatedSystemApp(pkg)) {
5612                            // New library entries can only be added through the
5613                            // system image.  This is important to get rid of a lot
5614                            // of nasty edge cases: for example if we allowed a non-
5615                            // system update of the app to add a library, then uninstalling
5616                            // the update would make the library go away, and assumptions
5617                            // we made such as through app install filtering would now
5618                            // have allowed apps on the device which aren't compatible
5619                            // with it.  Better to just have the restriction here, be
5620                            // conservative, and create many fewer cases that can negatively
5621                            // impact the user experience.
5622                            final PackageSetting sysPs = mSettings
5623                                    .getDisabledSystemPkgLPr(pkg.packageName);
5624                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5625                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5626                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5627                                        allowed = true;
5628                                        allowed = true;
5629                                        break;
5630                                    }
5631                                }
5632                            }
5633                        } else {
5634                            allowed = true;
5635                        }
5636                        if (allowed) {
5637                            if (!mSharedLibraries.containsKey(name)) {
5638                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5639                            } else if (!name.equals(pkg.packageName)) {
5640                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5641                                        + name + " already exists; skipping");
5642                            }
5643                        } else {
5644                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5645                                    + name + " that is not declared on system image; skipping");
5646                        }
5647                    }
5648                    if ((scanMode&SCAN_BOOTING) == 0) {
5649                        // If we are not booting, we need to update any applications
5650                        // that are clients of our shared library.  If we are booting,
5651                        // this will all be done once the scan is complete.
5652                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5653                    }
5654                }
5655            }
5656        }
5657
5658        // We also need to dexopt any apps that are dependent on this library.  Note that
5659        // if these fail, we should abort the install since installing the library will
5660        // result in some apps being broken.
5661        if (clientLibPkgs != null) {
5662            if ((scanMode&SCAN_NO_DEX) == 0) {
5663                for (int i=0; i<clientLibPkgs.size(); i++) {
5664                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5665                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5666                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5667                            == DEX_OPT_FAILED) {
5668                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5669                            removeDataDirsLI(pkg.packageName);
5670                        }
5671
5672                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5673                                "scanPackageLI failed to dexopt clientLibPkgs");
5674                    }
5675                }
5676            }
5677        }
5678
5679        // Request the ActivityManager to kill the process(only for existing packages)
5680        // so that we do not end up in a confused state while the user is still using the older
5681        // version of the application while the new one gets installed.
5682        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5683            // If the package lives in an asec, tell everyone that the container is going
5684            // away so they can clean up any references to its resources (which would prevent
5685            // vold from being able to unmount the asec)
5686            if (isForwardLocked(pkg) || isExternal(pkg)) {
5687                if (DEBUG_INSTALL) {
5688                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5689                }
5690                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5691                final ArrayList<String> pkgList = new ArrayList<String>(1);
5692                pkgList.add(pkg.applicationInfo.packageName);
5693                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5694            }
5695
5696            // Post the request that it be killed now that the going-away broadcast is en route
5697            killApplication(pkg.applicationInfo.packageName,
5698                        pkg.applicationInfo.uid, "update pkg");
5699        }
5700
5701        // Also need to kill any apps that are dependent on the library.
5702        if (clientLibPkgs != null) {
5703            for (int i=0; i<clientLibPkgs.size(); i++) {
5704                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5705                killApplication(clientPkg.applicationInfo.packageName,
5706                        clientPkg.applicationInfo.uid, "update lib");
5707            }
5708        }
5709
5710        // writer
5711        synchronized (mPackages) {
5712            // We don't expect installation to fail beyond this point,
5713            if ((scanMode&SCAN_MONITOR) != 0) {
5714                mAppDirs.put(pkg.codePath, pkg);
5715            }
5716            // Add the new setting to mSettings
5717            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5718            // Add the new setting to mPackages
5719            mPackages.put(pkg.applicationInfo.packageName, pkg);
5720            // Make sure we don't accidentally delete its data.
5721            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5722            while (iter.hasNext()) {
5723                PackageCleanItem item = iter.next();
5724                if (pkgName.equals(item.packageName)) {
5725                    iter.remove();
5726                }
5727            }
5728
5729            // Take care of first install / last update times.
5730            if (currentTime != 0) {
5731                if (pkgSetting.firstInstallTime == 0) {
5732                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5733                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5734                    pkgSetting.lastUpdateTime = currentTime;
5735                }
5736            } else if (pkgSetting.firstInstallTime == 0) {
5737                // We need *something*.  Take time time stamp of the file.
5738                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5739            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5740                if (scanFileTime != pkgSetting.timeStamp) {
5741                    // A package on the system image has changed; consider this
5742                    // to be an update.
5743                    pkgSetting.lastUpdateTime = scanFileTime;
5744                }
5745            }
5746
5747            // Add the package's KeySets to the global KeySetManagerService
5748            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5749            try {
5750                // Old KeySetData no longer valid.
5751                ksms.removeAppKeySetDataLPw(pkg.packageName);
5752                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5753                if (pkg.mKeySetMapping != null) {
5754                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5755                            pkg.mKeySetMapping.entrySet()) {
5756                        if (entry.getValue() != null) {
5757                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5758                                                          entry.getValue(), entry.getKey());
5759                        }
5760                    }
5761                    if (pkg.mUpgradeKeySets != null) {
5762                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5763                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5764                        }
5765                    }
5766                }
5767            } catch (NullPointerException e) {
5768                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5769            } catch (IllegalArgumentException e) {
5770                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5771            }
5772
5773            int N = pkg.providers.size();
5774            StringBuilder r = null;
5775            int i;
5776            for (i=0; i<N; i++) {
5777                PackageParser.Provider p = pkg.providers.get(i);
5778                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5779                        p.info.processName, pkg.applicationInfo.uid);
5780                mProviders.addProvider(p);
5781                p.syncable = p.info.isSyncable;
5782                if (p.info.authority != null) {
5783                    String names[] = p.info.authority.split(";");
5784                    p.info.authority = null;
5785                    for (int j = 0; j < names.length; j++) {
5786                        if (j == 1 && p.syncable) {
5787                            // We only want the first authority for a provider to possibly be
5788                            // syncable, so if we already added this provider using a different
5789                            // authority clear the syncable flag. We copy the provider before
5790                            // changing it because the mProviders object contains a reference
5791                            // to a provider that we don't want to change.
5792                            // Only do this for the second authority since the resulting provider
5793                            // object can be the same for all future authorities for this provider.
5794                            p = new PackageParser.Provider(p);
5795                            p.syncable = false;
5796                        }
5797                        if (!mProvidersByAuthority.containsKey(names[j])) {
5798                            mProvidersByAuthority.put(names[j], p);
5799                            if (p.info.authority == null) {
5800                                p.info.authority = names[j];
5801                            } else {
5802                                p.info.authority = p.info.authority + ";" + names[j];
5803                            }
5804                            if (DEBUG_PACKAGE_SCANNING) {
5805                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5806                                    Log.d(TAG, "Registered content provider: " + names[j]
5807                                            + ", className = " + p.info.name + ", isSyncable = "
5808                                            + p.info.isSyncable);
5809                            }
5810                        } else {
5811                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5812                            Slog.w(TAG, "Skipping provider name " + names[j] +
5813                                    " (in package " + pkg.applicationInfo.packageName +
5814                                    "): name already used by "
5815                                    + ((other != null && other.getComponentName() != null)
5816                                            ? other.getComponentName().getPackageName() : "?"));
5817                        }
5818                    }
5819                }
5820                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5821                    if (r == null) {
5822                        r = new StringBuilder(256);
5823                    } else {
5824                        r.append(' ');
5825                    }
5826                    r.append(p.info.name);
5827                }
5828            }
5829            if (r != null) {
5830                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5831            }
5832
5833            N = pkg.services.size();
5834            r = null;
5835            for (i=0; i<N; i++) {
5836                PackageParser.Service s = pkg.services.get(i);
5837                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5838                        s.info.processName, pkg.applicationInfo.uid);
5839                mServices.addService(s);
5840                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5841                    if (r == null) {
5842                        r = new StringBuilder(256);
5843                    } else {
5844                        r.append(' ');
5845                    }
5846                    r.append(s.info.name);
5847                }
5848            }
5849            if (r != null) {
5850                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5851            }
5852
5853            N = pkg.receivers.size();
5854            r = null;
5855            for (i=0; i<N; i++) {
5856                PackageParser.Activity a = pkg.receivers.get(i);
5857                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5858                        a.info.processName, pkg.applicationInfo.uid);
5859                mReceivers.addActivity(a, "receiver");
5860                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5861                    if (r == null) {
5862                        r = new StringBuilder(256);
5863                    } else {
5864                        r.append(' ');
5865                    }
5866                    r.append(a.info.name);
5867                }
5868            }
5869            if (r != null) {
5870                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5871            }
5872
5873            N = pkg.activities.size();
5874            r = null;
5875            for (i=0; i<N; i++) {
5876                PackageParser.Activity a = pkg.activities.get(i);
5877                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5878                        a.info.processName, pkg.applicationInfo.uid);
5879                mActivities.addActivity(a, "activity");
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(a.info.name);
5887                }
5888            }
5889            if (r != null) {
5890                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5891            }
5892
5893            N = pkg.permissionGroups.size();
5894            r = null;
5895            for (i=0; i<N; i++) {
5896                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5897                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5898                if (cur == null) {
5899                    mPermissionGroups.put(pg.info.name, pg);
5900                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5901                        if (r == null) {
5902                            r = new StringBuilder(256);
5903                        } else {
5904                            r.append(' ');
5905                        }
5906                        r.append(pg.info.name);
5907                    }
5908                } else {
5909                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5910                            + pg.info.packageName + " ignored: original from "
5911                            + cur.info.packageName);
5912                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5913                        if (r == null) {
5914                            r = new StringBuilder(256);
5915                        } else {
5916                            r.append(' ');
5917                        }
5918                        r.append("DUP:");
5919                        r.append(pg.info.name);
5920                    }
5921                }
5922            }
5923            if (r != null) {
5924                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5925            }
5926
5927            N = pkg.permissions.size();
5928            r = null;
5929            for (i=0; i<N; i++) {
5930                PackageParser.Permission p = pkg.permissions.get(i);
5931                HashMap<String, BasePermission> permissionMap =
5932                        p.tree ? mSettings.mPermissionTrees
5933                        : mSettings.mPermissions;
5934                p.group = mPermissionGroups.get(p.info.group);
5935                if (p.info.group == null || p.group != null) {
5936                    BasePermission bp = permissionMap.get(p.info.name);
5937                    if (bp == null) {
5938                        bp = new BasePermission(p.info.name, p.info.packageName,
5939                                BasePermission.TYPE_NORMAL);
5940                        permissionMap.put(p.info.name, bp);
5941                    }
5942                    if (bp.perm == null) {
5943                        if (bp.sourcePackage != null
5944                                && !bp.sourcePackage.equals(p.info.packageName)) {
5945                            // If this is a permission that was formerly defined by a non-system
5946                            // app, but is now defined by a system app (following an upgrade),
5947                            // discard the previous declaration and consider the system's to be
5948                            // canonical.
5949                            if (isSystemApp(p.owner)) {
5950                                String msg = "New decl " + p.owner + " of permission  "
5951                                        + p.info.name + " is system";
5952                                reportSettingsProblem(Log.WARN, msg);
5953                                bp.sourcePackage = null;
5954                            }
5955                        }
5956                        if (bp.sourcePackage == null
5957                                || bp.sourcePackage.equals(p.info.packageName)) {
5958                            BasePermission tree = findPermissionTreeLP(p.info.name);
5959                            if (tree == null
5960                                    || tree.sourcePackage.equals(p.info.packageName)) {
5961                                bp.packageSetting = pkgSetting;
5962                                bp.perm = p;
5963                                bp.uid = pkg.applicationInfo.uid;
5964                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5965                                    if (r == null) {
5966                                        r = new StringBuilder(256);
5967                                    } else {
5968                                        r.append(' ');
5969                                    }
5970                                    r.append(p.info.name);
5971                                }
5972                            } else {
5973                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5974                                        + p.info.packageName + " ignored: base tree "
5975                                        + tree.name + " is from package "
5976                                        + tree.sourcePackage);
5977                            }
5978                        } else {
5979                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5980                                    + p.info.packageName + " ignored: original from "
5981                                    + bp.sourcePackage);
5982                        }
5983                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5984                        if (r == null) {
5985                            r = new StringBuilder(256);
5986                        } else {
5987                            r.append(' ');
5988                        }
5989                        r.append("DUP:");
5990                        r.append(p.info.name);
5991                    }
5992                    if (bp.perm == p) {
5993                        bp.protectionLevel = p.info.protectionLevel;
5994                    }
5995                } else {
5996                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5997                            + p.info.packageName + " ignored: no group "
5998                            + p.group);
5999                }
6000            }
6001            if (r != null) {
6002                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6003            }
6004
6005            N = pkg.instrumentation.size();
6006            r = null;
6007            for (i=0; i<N; i++) {
6008                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6009                a.info.packageName = pkg.applicationInfo.packageName;
6010                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6011                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6012                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6013                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6014                a.info.dataDir = pkg.applicationInfo.dataDir;
6015
6016                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6017                // need other information about the application, like the ABI and what not ?
6018                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6019                mInstrumentation.put(a.getComponentName(), a);
6020                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6021                    if (r == null) {
6022                        r = new StringBuilder(256);
6023                    } else {
6024                        r.append(' ');
6025                    }
6026                    r.append(a.info.name);
6027                }
6028            }
6029            if (r != null) {
6030                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6031            }
6032
6033            if (pkg.protectedBroadcasts != null) {
6034                N = pkg.protectedBroadcasts.size();
6035                for (i=0; i<N; i++) {
6036                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6037                }
6038            }
6039
6040            pkgSetting.setTimeStamp(scanFileTime);
6041
6042            // Create idmap files for pairs of (packages, overlay packages).
6043            // Note: "android", ie framework-res.apk, is handled by native layers.
6044            if (pkg.mOverlayTarget != null) {
6045                // This is an overlay package.
6046                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6047                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6048                        mOverlays.put(pkg.mOverlayTarget,
6049                                new HashMap<String, PackageParser.Package>());
6050                    }
6051                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6052                    map.put(pkg.packageName, pkg);
6053                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6054                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6055                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6056                                "scanPackageLI failed to createIdmap");
6057                    }
6058                }
6059            } else if (mOverlays.containsKey(pkg.packageName) &&
6060                    !pkg.packageName.equals("android")) {
6061                // This is a regular package, with one or more known overlay packages.
6062                createIdmapsForPackageLI(pkg);
6063            }
6064        }
6065
6066        return pkg;
6067    }
6068
6069    /**
6070     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6071     * i.e, so that all packages can be run inside a single process if required.
6072     *
6073     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6074     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6075     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6076     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6077     * updating a package that belongs to a shared user.
6078     *
6079     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6080     * adds unnecessary complexity.
6081     */
6082    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6083            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6084        String requiredInstructionSet = null;
6085        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6086            requiredInstructionSet = VMRuntime.getInstructionSet(
6087                     scannedPackage.applicationInfo.primaryCpuAbi);
6088        }
6089
6090        PackageSetting requirer = null;
6091        for (PackageSetting ps : packagesForUser) {
6092            // If packagesForUser contains scannedPackage, we skip it. This will happen
6093            // when scannedPackage is an update of an existing package. Without this check,
6094            // we will never be able to change the ABI of any package belonging to a shared
6095            // user, even if it's compatible with other packages.
6096            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6097                if (ps.primaryCpuAbiString == null) {
6098                    continue;
6099                }
6100
6101                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6102                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6103                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6104                    // this but there's not much we can do.
6105                    String errorMessage = "Instruction set mismatch, "
6106                            + ((requirer == null) ? "[caller]" : requirer)
6107                            + " requires " + requiredInstructionSet + " whereas " + ps
6108                            + " requires " + instructionSet;
6109                    Slog.w(TAG, errorMessage);
6110                }
6111
6112                if (requiredInstructionSet == null) {
6113                    requiredInstructionSet = instructionSet;
6114                    requirer = ps;
6115                }
6116            }
6117        }
6118
6119        if (requiredInstructionSet != null) {
6120            String adjustedAbi;
6121            if (requirer != null) {
6122                // requirer != null implies that either scannedPackage was null or that scannedPackage
6123                // did not require an ABI, in which case we have to adjust scannedPackage to match
6124                // the ABI of the set (which is the same as requirer's ABI)
6125                adjustedAbi = requirer.primaryCpuAbiString;
6126                if (scannedPackage != null) {
6127                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6128                }
6129            } else {
6130                // requirer == null implies that we're updating all ABIs in the set to
6131                // match scannedPackage.
6132                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6133            }
6134
6135            for (PackageSetting ps : packagesForUser) {
6136                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6137                    if (ps.primaryCpuAbiString != null) {
6138                        continue;
6139                    }
6140
6141                    ps.primaryCpuAbiString = adjustedAbi;
6142                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6143                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6144                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6145
6146                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6147                                deferDexOpt, true) == DEX_OPT_FAILED) {
6148                            ps.primaryCpuAbiString = null;
6149                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6150                            return;
6151                        } else {
6152                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6153                        }
6154                    }
6155                }
6156            }
6157        }
6158    }
6159
6160    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6161        synchronized (mPackages) {
6162            mResolverReplaced = true;
6163            // Set up information for custom user intent resolution activity.
6164            mResolveActivity.applicationInfo = pkg.applicationInfo;
6165            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6166            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6167            mResolveActivity.processName = null;
6168            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6169            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6170                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6171            mResolveActivity.theme = 0;
6172            mResolveActivity.exported = true;
6173            mResolveActivity.enabled = true;
6174            mResolveInfo.activityInfo = mResolveActivity;
6175            mResolveInfo.priority = 0;
6176            mResolveInfo.preferredOrder = 0;
6177            mResolveInfo.match = 0;
6178            mResolveComponentName = mCustomResolverComponentName;
6179            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6180                    mResolveComponentName);
6181        }
6182    }
6183
6184    private static String calculateApkRoot(final String codePathString) {
6185        final File codePath = new File(codePathString);
6186        final File codeRoot;
6187        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6188            codeRoot = Environment.getRootDirectory();
6189        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6190            codeRoot = Environment.getOemDirectory();
6191        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6192            codeRoot = Environment.getVendorDirectory();
6193        } else {
6194            // Unrecognized code path; take its top real segment as the apk root:
6195            // e.g. /something/app/blah.apk => /something
6196            try {
6197                File f = codePath.getCanonicalFile();
6198                File parent = f.getParentFile();    // non-null because codePath is a file
6199                File tmp;
6200                while ((tmp = parent.getParentFile()) != null) {
6201                    f = parent;
6202                    parent = tmp;
6203                }
6204                codeRoot = f;
6205                Slog.w(TAG, "Unrecognized code path "
6206                        + codePath + " - using " + codeRoot);
6207            } catch (IOException e) {
6208                // Can't canonicalize the code path -- shenanigans?
6209                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6210                return Environment.getRootDirectory().getPath();
6211            }
6212        }
6213        return codeRoot.getPath();
6214    }
6215
6216    /**
6217     * Derive and set the location of native libraries for the given package,
6218     * which varies depending on where and how the package was installed.
6219     */
6220    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6221        final ApplicationInfo info = pkg.applicationInfo;
6222        final String codePath = pkg.codePath;
6223        final File codeFile = new File(codePath);
6224        // If "/system/lib64/apkname" exists, assume that is the per-package
6225        // native library directory to use; otherwise use "/system/lib/apkname".
6226        final String apkRoot = calculateApkRoot(info.sourceDir);
6227
6228        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6229        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6230
6231
6232        info.nativeLibraryRootDir = null;
6233        info.nativeLibraryRootRequiresIsa = false;
6234        info.nativeLibraryDir = null;
6235        info.secondaryNativeLibraryDir = null;
6236
6237        if (isApkFile(codeFile)) {
6238            // Monolithic install
6239            if (bundledApp) {
6240                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6241                        getPrimaryInstructionSet(info));
6242
6243                // This is a bundled system app so choose the path based on the ABI.
6244                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6245                // is just the default path.
6246                final String apkName = deriveCodePathName(codePath);
6247                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6248                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6249                        apkName).getAbsolutePath();
6250
6251                if (info.secondaryCpuAbi != null) {
6252                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6253                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6254                            secondaryLibDir, apkName).getAbsolutePath();
6255                }
6256            } else if (asecApp) {
6257                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6258                        .getAbsolutePath();
6259            } else {
6260                final String apkName = deriveCodePathName(codePath);
6261                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6262                        .getAbsolutePath();
6263            }
6264
6265            info.nativeLibraryRootRequiresIsa = false;
6266            info.nativeLibraryDir = info.nativeLibraryRootDir;
6267        } else {
6268            // Cluster install
6269            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6270            info.nativeLibraryRootRequiresIsa = true;
6271
6272            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6273                    getPrimaryInstructionSet(info)).getAbsolutePath();
6274
6275            if (info.secondaryCpuAbi != null) {
6276                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6277                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6278            }
6279        }
6280    }
6281
6282    /**
6283     * Calculate the abis and roots for a bundled app. These can uniquely
6284     * be determined from the contents of the system partition, i.e whether
6285     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6286     * of this information, and instead assume that the system was built
6287     * sensibly.
6288     */
6289    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6290                                           PackageSetting pkgSetting) {
6291        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6292
6293        // If "/system/lib64/apkname" exists, assume that is the per-package
6294        // native library directory to use; otherwise use "/system/lib/apkname".
6295        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6296        setBundledAppAbi(pkg, apkRoot, apkName);
6297        // pkgSetting might be null during rescan following uninstall of updates
6298        // to a bundled app, so accommodate that possibility.  The settings in
6299        // that case will be established later from the parsed package.
6300        //
6301        // If the settings aren't null, sync them up with what we've just derived.
6302        // note that apkRoot isn't stored in the package settings.
6303        if (pkgSetting != null) {
6304            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6305            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6306        }
6307    }
6308
6309    /**
6310     * Deduces the ABI of a bundled app and sets the relevant fields on the
6311     * parsed pkg object.
6312     *
6313     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6314     *        under which system libraries are installed.
6315     * @param apkName the name of the installed package.
6316     */
6317    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6318        final File codeFile = new File(pkg.codePath);
6319
6320        final boolean has64BitLibs;
6321        final boolean has32BitLibs;
6322        if (isApkFile(codeFile)) {
6323            // Monolithic install
6324            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6325            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6326        } else {
6327            // Cluster install
6328            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6329            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6330                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6331                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6332                has64BitLibs = (new File(rootDir, isa)).exists();
6333            } else {
6334                has64BitLibs = false;
6335            }
6336            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6337                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6338                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6339                has32BitLibs = (new File(rootDir, isa)).exists();
6340            } else {
6341                has32BitLibs = false;
6342            }
6343        }
6344
6345        if (has64BitLibs && !has32BitLibs) {
6346            // The package has 64 bit libs, but not 32 bit libs. Its primary
6347            // ABI should be 64 bit. We can safely assume here that the bundled
6348            // native libraries correspond to the most preferred ABI in the list.
6349
6350            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6351            pkg.applicationInfo.secondaryCpuAbi = null;
6352        } else if (has32BitLibs && !has64BitLibs) {
6353            // The package has 32 bit libs but not 64 bit libs. Its primary
6354            // ABI should be 32 bit.
6355
6356            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6357            pkg.applicationInfo.secondaryCpuAbi = null;
6358        } else if (has32BitLibs && has64BitLibs) {
6359            // The application has both 64 and 32 bit bundled libraries. We check
6360            // here that the app declares multiArch support, and warn if it doesn't.
6361            //
6362            // We will be lenient here and record both ABIs. The primary will be the
6363            // ABI that's higher on the list, i.e, a device that's configured to prefer
6364            // 64 bit apps will see a 64 bit primary ABI,
6365
6366            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6367                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6368            }
6369
6370            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6371                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6372                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6373            } else {
6374                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6375                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6376            }
6377        } else {
6378            pkg.applicationInfo.primaryCpuAbi = null;
6379            pkg.applicationInfo.secondaryCpuAbi = null;
6380        }
6381    }
6382
6383    private static void createNativeLibrarySubdir(File path) throws IOException {
6384        if (!path.isDirectory()) {
6385            path.delete();
6386
6387            if (!path.mkdir()) {
6388                throw new IOException("Cannot create " + path.getPath());
6389            }
6390
6391            try {
6392                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6393            } catch (ErrnoException e) {
6394                throw new IOException("Cannot chmod native library directory "
6395                        + path.getPath(), e);
6396            }
6397        } else if (!SELinux.restorecon(path)) {
6398            throw new IOException("Cannot set SELinux context for " + path.getPath());
6399        }
6400    }
6401
6402    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6403            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6404        createNativeLibrarySubdir(nativeLibraryRoot);
6405
6406        /*
6407         * If this is an internal application or our nativeLibraryPath points to
6408         * the app-lib directory, unpack the libraries if necessary.
6409         */
6410        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6411        if (abi >= 0) {
6412            /*
6413             * If we have a matching instruction set, construct a subdir under the native
6414             * library root that corresponds to this instruction set.
6415             */
6416            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6417            final File subDir;
6418            if (useIsaSubdir) {
6419                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6420                createNativeLibrarySubdir(isaSubdir);
6421                subDir = isaSubdir;
6422            } else {
6423                subDir = nativeLibraryRoot;
6424            }
6425
6426            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6427            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6428                return copyRet;
6429            }
6430        }
6431
6432        return abi;
6433    }
6434
6435    private void killApplication(String pkgName, int appId, String reason) {
6436        // Request the ActivityManager to kill the process(only for existing packages)
6437        // so that we do not end up in a confused state while the user is still using the older
6438        // version of the application while the new one gets installed.
6439        IActivityManager am = ActivityManagerNative.getDefault();
6440        if (am != null) {
6441            try {
6442                am.killApplicationWithAppId(pkgName, appId, reason);
6443            } catch (RemoteException e) {
6444            }
6445        }
6446    }
6447
6448    void removePackageLI(PackageSetting ps, boolean chatty) {
6449        if (DEBUG_INSTALL) {
6450            if (chatty)
6451                Log.d(TAG, "Removing package " + ps.name);
6452        }
6453
6454        // writer
6455        synchronized (mPackages) {
6456            mPackages.remove(ps.name);
6457            if (ps.codePathString != null) {
6458                mAppDirs.remove(ps.codePathString);
6459            }
6460
6461            final PackageParser.Package pkg = ps.pkg;
6462            if (pkg != null) {
6463                cleanPackageDataStructuresLILPw(pkg, chatty);
6464            }
6465        }
6466    }
6467
6468    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6469        if (DEBUG_INSTALL) {
6470            if (chatty)
6471                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6472        }
6473
6474        // writer
6475        synchronized (mPackages) {
6476            mPackages.remove(pkg.applicationInfo.packageName);
6477            if (pkg.codePath != null) {
6478                mAppDirs.remove(pkg.codePath);
6479            }
6480            cleanPackageDataStructuresLILPw(pkg, chatty);
6481        }
6482    }
6483
6484    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6485        int N = pkg.providers.size();
6486        StringBuilder r = null;
6487        int i;
6488        for (i=0; i<N; i++) {
6489            PackageParser.Provider p = pkg.providers.get(i);
6490            mProviders.removeProvider(p);
6491            if (p.info.authority == null) {
6492
6493                /* There was another ContentProvider with this authority when
6494                 * this app was installed so this authority is null,
6495                 * Ignore it as we don't have to unregister the provider.
6496                 */
6497                continue;
6498            }
6499            String names[] = p.info.authority.split(";");
6500            for (int j = 0; j < names.length; j++) {
6501                if (mProvidersByAuthority.get(names[j]) == p) {
6502                    mProvidersByAuthority.remove(names[j]);
6503                    if (DEBUG_REMOVE) {
6504                        if (chatty)
6505                            Log.d(TAG, "Unregistered content provider: " + names[j]
6506                                    + ", className = " + p.info.name + ", isSyncable = "
6507                                    + p.info.isSyncable);
6508                    }
6509                }
6510            }
6511            if (DEBUG_REMOVE && chatty) {
6512                if (r == null) {
6513                    r = new StringBuilder(256);
6514                } else {
6515                    r.append(' ');
6516                }
6517                r.append(p.info.name);
6518            }
6519        }
6520        if (r != null) {
6521            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6522        }
6523
6524        N = pkg.services.size();
6525        r = null;
6526        for (i=0; i<N; i++) {
6527            PackageParser.Service s = pkg.services.get(i);
6528            mServices.removeService(s);
6529            if (chatty) {
6530                if (r == null) {
6531                    r = new StringBuilder(256);
6532                } else {
6533                    r.append(' ');
6534                }
6535                r.append(s.info.name);
6536            }
6537        }
6538        if (r != null) {
6539            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6540        }
6541
6542        N = pkg.receivers.size();
6543        r = null;
6544        for (i=0; i<N; i++) {
6545            PackageParser.Activity a = pkg.receivers.get(i);
6546            mReceivers.removeActivity(a, "receiver");
6547            if (DEBUG_REMOVE && chatty) {
6548                if (r == null) {
6549                    r = new StringBuilder(256);
6550                } else {
6551                    r.append(' ');
6552                }
6553                r.append(a.info.name);
6554            }
6555        }
6556        if (r != null) {
6557            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6558        }
6559
6560        N = pkg.activities.size();
6561        r = null;
6562        for (i=0; i<N; i++) {
6563            PackageParser.Activity a = pkg.activities.get(i);
6564            mActivities.removeActivity(a, "activity");
6565            if (DEBUG_REMOVE && chatty) {
6566                if (r == null) {
6567                    r = new StringBuilder(256);
6568                } else {
6569                    r.append(' ');
6570                }
6571                r.append(a.info.name);
6572            }
6573        }
6574        if (r != null) {
6575            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6576        }
6577
6578        N = pkg.permissions.size();
6579        r = null;
6580        for (i=0; i<N; i++) {
6581            PackageParser.Permission p = pkg.permissions.get(i);
6582            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6583            if (bp == null) {
6584                bp = mSettings.mPermissionTrees.get(p.info.name);
6585            }
6586            if (bp != null && bp.perm == p) {
6587                bp.perm = null;
6588                if (DEBUG_REMOVE && chatty) {
6589                    if (r == null) {
6590                        r = new StringBuilder(256);
6591                    } else {
6592                        r.append(' ');
6593                    }
6594                    r.append(p.info.name);
6595                }
6596            }
6597            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6598                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6599                if (appOpPerms != null) {
6600                    appOpPerms.remove(pkg.packageName);
6601                }
6602            }
6603        }
6604        if (r != null) {
6605            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6606        }
6607
6608        N = pkg.requestedPermissions.size();
6609        r = null;
6610        for (i=0; i<N; i++) {
6611            String perm = pkg.requestedPermissions.get(i);
6612            BasePermission bp = mSettings.mPermissions.get(perm);
6613            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6614                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6615                if (appOpPerms != null) {
6616                    appOpPerms.remove(pkg.packageName);
6617                    if (appOpPerms.isEmpty()) {
6618                        mAppOpPermissionPackages.remove(perm);
6619                    }
6620                }
6621            }
6622        }
6623        if (r != null) {
6624            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6625        }
6626
6627        N = pkg.instrumentation.size();
6628        r = null;
6629        for (i=0; i<N; i++) {
6630            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6631            mInstrumentation.remove(a.getComponentName());
6632            if (DEBUG_REMOVE && chatty) {
6633                if (r == null) {
6634                    r = new StringBuilder(256);
6635                } else {
6636                    r.append(' ');
6637                }
6638                r.append(a.info.name);
6639            }
6640        }
6641        if (r != null) {
6642            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6643        }
6644
6645        r = null;
6646        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6647            // Only system apps can hold shared libraries.
6648            if (pkg.libraryNames != null) {
6649                for (i=0; i<pkg.libraryNames.size(); i++) {
6650                    String name = pkg.libraryNames.get(i);
6651                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6652                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6653                        mSharedLibraries.remove(name);
6654                        if (DEBUG_REMOVE && chatty) {
6655                            if (r == null) {
6656                                r = new StringBuilder(256);
6657                            } else {
6658                                r.append(' ');
6659                            }
6660                            r.append(name);
6661                        }
6662                    }
6663                }
6664            }
6665        }
6666        if (r != null) {
6667            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6668        }
6669    }
6670
6671    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6672        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6673            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6674                return true;
6675            }
6676        }
6677        return false;
6678    }
6679
6680    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6681    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6682    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6683
6684    private void updatePermissionsLPw(String changingPkg,
6685            PackageParser.Package pkgInfo, int flags) {
6686        // Make sure there are no dangling permission trees.
6687        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6688        while (it.hasNext()) {
6689            final BasePermission bp = it.next();
6690            if (bp.packageSetting == null) {
6691                // We may not yet have parsed the package, so just see if
6692                // we still know about its settings.
6693                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6694            }
6695            if (bp.packageSetting == null) {
6696                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6697                        + " from package " + bp.sourcePackage);
6698                it.remove();
6699            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6700                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6701                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6702                            + " from package " + bp.sourcePackage);
6703                    flags |= UPDATE_PERMISSIONS_ALL;
6704                    it.remove();
6705                }
6706            }
6707        }
6708
6709        // Make sure all dynamic permissions have been assigned to a package,
6710        // and make sure there are no dangling permissions.
6711        it = mSettings.mPermissions.values().iterator();
6712        while (it.hasNext()) {
6713            final BasePermission bp = it.next();
6714            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6715                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6716                        + bp.name + " pkg=" + bp.sourcePackage
6717                        + " info=" + bp.pendingInfo);
6718                if (bp.packageSetting == null && bp.pendingInfo != null) {
6719                    final BasePermission tree = findPermissionTreeLP(bp.name);
6720                    if (tree != null && tree.perm != null) {
6721                        bp.packageSetting = tree.packageSetting;
6722                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6723                                new PermissionInfo(bp.pendingInfo));
6724                        bp.perm.info.packageName = tree.perm.info.packageName;
6725                        bp.perm.info.name = bp.name;
6726                        bp.uid = tree.uid;
6727                    }
6728                }
6729            }
6730            if (bp.packageSetting == null) {
6731                // We may not yet have parsed the package, so just see if
6732                // we still know about its settings.
6733                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6734            }
6735            if (bp.packageSetting == null) {
6736                Slog.w(TAG, "Removing dangling permission: " + bp.name
6737                        + " from package " + bp.sourcePackage);
6738                it.remove();
6739            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6740                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6741                    Slog.i(TAG, "Removing old permission: " + bp.name
6742                            + " from package " + bp.sourcePackage);
6743                    flags |= UPDATE_PERMISSIONS_ALL;
6744                    it.remove();
6745                }
6746            }
6747        }
6748
6749        // Now update the permissions for all packages, in particular
6750        // replace the granted permissions of the system packages.
6751        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6752            for (PackageParser.Package pkg : mPackages.values()) {
6753                if (pkg != pkgInfo) {
6754                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6755                }
6756            }
6757        }
6758
6759        if (pkgInfo != null) {
6760            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6761        }
6762    }
6763
6764    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6765        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6766        if (ps == null) {
6767            return;
6768        }
6769        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6770        HashSet<String> origPermissions = gp.grantedPermissions;
6771        boolean changedPermission = false;
6772
6773        if (replace) {
6774            ps.permissionsFixed = false;
6775            if (gp == ps) {
6776                origPermissions = new HashSet<String>(gp.grantedPermissions);
6777                gp.grantedPermissions.clear();
6778                gp.gids = mGlobalGids;
6779            }
6780        }
6781
6782        if (gp.gids == null) {
6783            gp.gids = mGlobalGids;
6784        }
6785
6786        final int N = pkg.requestedPermissions.size();
6787        for (int i=0; i<N; i++) {
6788            final String name = pkg.requestedPermissions.get(i);
6789            final boolean required = pkg.requestedPermissionsRequired.get(i);
6790            final BasePermission bp = mSettings.mPermissions.get(name);
6791            if (DEBUG_INSTALL) {
6792                if (gp != ps) {
6793                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6794                }
6795            }
6796
6797            if (bp == null || bp.packageSetting == null) {
6798                Slog.w(TAG, "Unknown permission " + name
6799                        + " in package " + pkg.packageName);
6800                continue;
6801            }
6802
6803            final String perm = bp.name;
6804            boolean allowed;
6805            boolean allowedSig = false;
6806            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6807                // Keep track of app op permissions.
6808                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6809                if (pkgs == null) {
6810                    pkgs = new ArraySet<>();
6811                    mAppOpPermissionPackages.put(bp.name, pkgs);
6812                }
6813                pkgs.add(pkg.packageName);
6814            }
6815            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6816            if (level == PermissionInfo.PROTECTION_NORMAL
6817                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6818                // We grant a normal or dangerous permission if any of the following
6819                // are true:
6820                // 1) The permission is required
6821                // 2) The permission is optional, but was granted in the past
6822                // 3) The permission is optional, but was requested by an
6823                //    app in /system (not /data)
6824                //
6825                // Otherwise, reject the permission.
6826                allowed = (required || origPermissions.contains(perm)
6827                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6828            } else if (bp.packageSetting == null) {
6829                // This permission is invalid; skip it.
6830                allowed = false;
6831            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6832                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6833                if (allowed) {
6834                    allowedSig = true;
6835                }
6836            } else {
6837                allowed = false;
6838            }
6839            if (DEBUG_INSTALL) {
6840                if (gp != ps) {
6841                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6842                }
6843            }
6844            if (allowed) {
6845                if (!isSystemApp(ps) && ps.permissionsFixed) {
6846                    // If this is an existing, non-system package, then
6847                    // we can't add any new permissions to it.
6848                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6849                        // Except...  if this is a permission that was added
6850                        // to the platform (note: need to only do this when
6851                        // updating the platform).
6852                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6853                    }
6854                }
6855                if (allowed) {
6856                    if (!gp.grantedPermissions.contains(perm)) {
6857                        changedPermission = true;
6858                        gp.grantedPermissions.add(perm);
6859                        gp.gids = appendInts(gp.gids, bp.gids);
6860                    } else if (!ps.haveGids) {
6861                        gp.gids = appendInts(gp.gids, bp.gids);
6862                    }
6863                } else {
6864                    Slog.w(TAG, "Not granting permission " + perm
6865                            + " to package " + pkg.packageName
6866                            + " because it was previously installed without");
6867                }
6868            } else {
6869                if (gp.grantedPermissions.remove(perm)) {
6870                    changedPermission = true;
6871                    gp.gids = removeInts(gp.gids, bp.gids);
6872                    Slog.i(TAG, "Un-granting permission " + perm
6873                            + " from package " + pkg.packageName
6874                            + " (protectionLevel=" + bp.protectionLevel
6875                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6876                            + ")");
6877                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6878                    // Don't print warning for app op permissions, since it is fine for them
6879                    // not to be granted, there is a UI for the user to decide.
6880                    Slog.w(TAG, "Not granting permission " + perm
6881                            + " to package " + pkg.packageName
6882                            + " (protectionLevel=" + bp.protectionLevel
6883                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6884                            + ")");
6885                }
6886            }
6887        }
6888
6889        if ((changedPermission || replace) && !ps.permissionsFixed &&
6890                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6891            // This is the first that we have heard about this package, so the
6892            // permissions we have now selected are fixed until explicitly
6893            // changed.
6894            ps.permissionsFixed = true;
6895        }
6896        ps.haveGids = true;
6897    }
6898
6899    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6900        boolean allowed = false;
6901        final int NP = PackageParser.NEW_PERMISSIONS.length;
6902        for (int ip=0; ip<NP; ip++) {
6903            final PackageParser.NewPermissionInfo npi
6904                    = PackageParser.NEW_PERMISSIONS[ip];
6905            if (npi.name.equals(perm)
6906                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6907                allowed = true;
6908                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6909                        + pkg.packageName);
6910                break;
6911            }
6912        }
6913        return allowed;
6914    }
6915
6916    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6917                                          BasePermission bp, HashSet<String> origPermissions) {
6918        boolean allowed;
6919        allowed = (compareSignatures(
6920                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6921                        == PackageManager.SIGNATURE_MATCH)
6922                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6923                        == PackageManager.SIGNATURE_MATCH);
6924        if (!allowed && (bp.protectionLevel
6925                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6926            if (isSystemApp(pkg)) {
6927                // For updated system applications, a system permission
6928                // is granted only if it had been defined by the original application.
6929                if (isUpdatedSystemApp(pkg)) {
6930                    final PackageSetting sysPs = mSettings
6931                            .getDisabledSystemPkgLPr(pkg.packageName);
6932                    final GrantedPermissions origGp = sysPs.sharedUser != null
6933                            ? sysPs.sharedUser : sysPs;
6934
6935                    if (origGp.grantedPermissions.contains(perm)) {
6936                        // If the original was granted this permission, we take
6937                        // that grant decision as read and propagate it to the
6938                        // update.
6939                        allowed = true;
6940                    } else {
6941                        // The system apk may have been updated with an older
6942                        // version of the one on the data partition, but which
6943                        // granted a new system permission that it didn't have
6944                        // before.  In this case we do want to allow the app to
6945                        // now get the new permission if the ancestral apk is
6946                        // privileged to get it.
6947                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6948                            for (int j=0;
6949                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6950                                if (perm.equals(
6951                                        sysPs.pkg.requestedPermissions.get(j))) {
6952                                    allowed = true;
6953                                    break;
6954                                }
6955                            }
6956                        }
6957                    }
6958                } else {
6959                    allowed = isPrivilegedApp(pkg);
6960                }
6961            }
6962        }
6963        if (!allowed && (bp.protectionLevel
6964                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6965            // For development permissions, a development permission
6966            // is granted only if it was already granted.
6967            allowed = origPermissions.contains(perm);
6968        }
6969        return allowed;
6970    }
6971
6972    final class ActivityIntentResolver
6973            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6974        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6975                boolean defaultOnly, int userId) {
6976            if (!sUserManager.exists(userId)) return null;
6977            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6978            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6979        }
6980
6981        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6982                int userId) {
6983            if (!sUserManager.exists(userId)) return null;
6984            mFlags = flags;
6985            return super.queryIntent(intent, resolvedType,
6986                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6987        }
6988
6989        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6990                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6991            if (!sUserManager.exists(userId)) return null;
6992            if (packageActivities == null) {
6993                return null;
6994            }
6995            mFlags = flags;
6996            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6997            final int N = packageActivities.size();
6998            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6999                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7000
7001            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7002            for (int i = 0; i < N; ++i) {
7003                intentFilters = packageActivities.get(i).intents;
7004                if (intentFilters != null && intentFilters.size() > 0) {
7005                    PackageParser.ActivityIntentInfo[] array =
7006                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7007                    intentFilters.toArray(array);
7008                    listCut.add(array);
7009                }
7010            }
7011            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7012        }
7013
7014        public final void addActivity(PackageParser.Activity a, String type) {
7015            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7016            mActivities.put(a.getComponentName(), a);
7017            if (DEBUG_SHOW_INFO)
7018                Log.v(
7019                TAG, "  " + type + " " +
7020                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7021            if (DEBUG_SHOW_INFO)
7022                Log.v(TAG, "    Class=" + a.info.name);
7023            final int NI = a.intents.size();
7024            for (int j=0; j<NI; j++) {
7025                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7026                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7027                    intent.setPriority(0);
7028                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7029                            + a.className + " with priority > 0, forcing to 0");
7030                }
7031                if (DEBUG_SHOW_INFO) {
7032                    Log.v(TAG, "    IntentFilter:");
7033                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7034                }
7035                if (!intent.debugCheck()) {
7036                    Log.w(TAG, "==> For Activity " + a.info.name);
7037                }
7038                addFilter(intent);
7039            }
7040        }
7041
7042        public final void removeActivity(PackageParser.Activity a, String type) {
7043            mActivities.remove(a.getComponentName());
7044            if (DEBUG_SHOW_INFO) {
7045                Log.v(TAG, "  " + type + " "
7046                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7047                                : a.info.name) + ":");
7048                Log.v(TAG, "    Class=" + a.info.name);
7049            }
7050            final int NI = a.intents.size();
7051            for (int j=0; j<NI; j++) {
7052                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7053                if (DEBUG_SHOW_INFO) {
7054                    Log.v(TAG, "    IntentFilter:");
7055                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7056                }
7057                removeFilter(intent);
7058            }
7059        }
7060
7061        @Override
7062        protected boolean allowFilterResult(
7063                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7064            ActivityInfo filterAi = filter.activity.info;
7065            for (int i=dest.size()-1; i>=0; i--) {
7066                ActivityInfo destAi = dest.get(i).activityInfo;
7067                if (destAi.name == filterAi.name
7068                        && destAi.packageName == filterAi.packageName) {
7069                    return false;
7070                }
7071            }
7072            return true;
7073        }
7074
7075        @Override
7076        protected ActivityIntentInfo[] newArray(int size) {
7077            return new ActivityIntentInfo[size];
7078        }
7079
7080        @Override
7081        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7082            if (!sUserManager.exists(userId)) return true;
7083            PackageParser.Package p = filter.activity.owner;
7084            if (p != null) {
7085                PackageSetting ps = (PackageSetting)p.mExtras;
7086                if (ps != null) {
7087                    // System apps are never considered stopped for purposes of
7088                    // filtering, because there may be no way for the user to
7089                    // actually re-launch them.
7090                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7091                            && ps.getStopped(userId);
7092                }
7093            }
7094            return false;
7095        }
7096
7097        @Override
7098        protected boolean isPackageForFilter(String packageName,
7099                PackageParser.ActivityIntentInfo info) {
7100            return packageName.equals(info.activity.owner.packageName);
7101        }
7102
7103        @Override
7104        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7105                int match, int userId) {
7106            if (!sUserManager.exists(userId)) return null;
7107            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7108                return null;
7109            }
7110            final PackageParser.Activity activity = info.activity;
7111            if (mSafeMode && (activity.info.applicationInfo.flags
7112                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7113                return null;
7114            }
7115            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7116            if (ps == null) {
7117                return null;
7118            }
7119            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7120                    ps.readUserState(userId), userId);
7121            if (ai == null) {
7122                return null;
7123            }
7124            final ResolveInfo res = new ResolveInfo();
7125            res.activityInfo = ai;
7126            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7127                res.filter = info;
7128            }
7129            res.priority = info.getPriority();
7130            res.preferredOrder = activity.owner.mPreferredOrder;
7131            //System.out.println("Result: " + res.activityInfo.className +
7132            //                   " = " + res.priority);
7133            res.match = match;
7134            res.isDefault = info.hasDefault;
7135            res.labelRes = info.labelRes;
7136            res.nonLocalizedLabel = info.nonLocalizedLabel;
7137            if (userNeedsBadging(userId)) {
7138                res.noResourceId = true;
7139            } else {
7140                res.icon = info.icon;
7141            }
7142            res.system = isSystemApp(res.activityInfo.applicationInfo);
7143            return res;
7144        }
7145
7146        @Override
7147        protected void sortResults(List<ResolveInfo> results) {
7148            Collections.sort(results, mResolvePrioritySorter);
7149        }
7150
7151        @Override
7152        protected void dumpFilter(PrintWriter out, String prefix,
7153                PackageParser.ActivityIntentInfo filter) {
7154            out.print(prefix); out.print(
7155                    Integer.toHexString(System.identityHashCode(filter.activity)));
7156                    out.print(' ');
7157                    filter.activity.printComponentShortName(out);
7158                    out.print(" filter ");
7159                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7160        }
7161
7162//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7163//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7164//            final List<ResolveInfo> retList = Lists.newArrayList();
7165//            while (i.hasNext()) {
7166//                final ResolveInfo resolveInfo = i.next();
7167//                if (isEnabledLP(resolveInfo.activityInfo)) {
7168//                    retList.add(resolveInfo);
7169//                }
7170//            }
7171//            return retList;
7172//        }
7173
7174        // Keys are String (activity class name), values are Activity.
7175        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7176                = new HashMap<ComponentName, PackageParser.Activity>();
7177        private int mFlags;
7178    }
7179
7180    private final class ServiceIntentResolver
7181            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7182        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7183                boolean defaultOnly, int userId) {
7184            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7185            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7186        }
7187
7188        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7189                int userId) {
7190            if (!sUserManager.exists(userId)) return null;
7191            mFlags = flags;
7192            return super.queryIntent(intent, resolvedType,
7193                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7194        }
7195
7196        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7197                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7198            if (!sUserManager.exists(userId)) return null;
7199            if (packageServices == null) {
7200                return null;
7201            }
7202            mFlags = flags;
7203            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7204            final int N = packageServices.size();
7205            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7206                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7207
7208            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7209            for (int i = 0; i < N; ++i) {
7210                intentFilters = packageServices.get(i).intents;
7211                if (intentFilters != null && intentFilters.size() > 0) {
7212                    PackageParser.ServiceIntentInfo[] array =
7213                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7214                    intentFilters.toArray(array);
7215                    listCut.add(array);
7216                }
7217            }
7218            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7219        }
7220
7221        public final void addService(PackageParser.Service s) {
7222            mServices.put(s.getComponentName(), s);
7223            if (DEBUG_SHOW_INFO) {
7224                Log.v(TAG, "  "
7225                        + (s.info.nonLocalizedLabel != null
7226                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7227                Log.v(TAG, "    Class=" + s.info.name);
7228            }
7229            final int NI = s.intents.size();
7230            int j;
7231            for (j=0; j<NI; j++) {
7232                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7233                if (DEBUG_SHOW_INFO) {
7234                    Log.v(TAG, "    IntentFilter:");
7235                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7236                }
7237                if (!intent.debugCheck()) {
7238                    Log.w(TAG, "==> For Service " + s.info.name);
7239                }
7240                addFilter(intent);
7241            }
7242        }
7243
7244        public final void removeService(PackageParser.Service s) {
7245            mServices.remove(s.getComponentName());
7246            if (DEBUG_SHOW_INFO) {
7247                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7248                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7249                Log.v(TAG, "    Class=" + s.info.name);
7250            }
7251            final int NI = s.intents.size();
7252            int j;
7253            for (j=0; j<NI; j++) {
7254                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7255                if (DEBUG_SHOW_INFO) {
7256                    Log.v(TAG, "    IntentFilter:");
7257                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7258                }
7259                removeFilter(intent);
7260            }
7261        }
7262
7263        @Override
7264        protected boolean allowFilterResult(
7265                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7266            ServiceInfo filterSi = filter.service.info;
7267            for (int i=dest.size()-1; i>=0; i--) {
7268                ServiceInfo destAi = dest.get(i).serviceInfo;
7269                if (destAi.name == filterSi.name
7270                        && destAi.packageName == filterSi.packageName) {
7271                    return false;
7272                }
7273            }
7274            return true;
7275        }
7276
7277        @Override
7278        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7279            return new PackageParser.ServiceIntentInfo[size];
7280        }
7281
7282        @Override
7283        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7284            if (!sUserManager.exists(userId)) return true;
7285            PackageParser.Package p = filter.service.owner;
7286            if (p != null) {
7287                PackageSetting ps = (PackageSetting)p.mExtras;
7288                if (ps != null) {
7289                    // System apps are never considered stopped for purposes of
7290                    // filtering, because there may be no way for the user to
7291                    // actually re-launch them.
7292                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7293                            && ps.getStopped(userId);
7294                }
7295            }
7296            return false;
7297        }
7298
7299        @Override
7300        protected boolean isPackageForFilter(String packageName,
7301                PackageParser.ServiceIntentInfo info) {
7302            return packageName.equals(info.service.owner.packageName);
7303        }
7304
7305        @Override
7306        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7307                int match, int userId) {
7308            if (!sUserManager.exists(userId)) return null;
7309            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7310            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7311                return null;
7312            }
7313            final PackageParser.Service service = info.service;
7314            if (mSafeMode && (service.info.applicationInfo.flags
7315                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7316                return null;
7317            }
7318            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7319            if (ps == null) {
7320                return null;
7321            }
7322            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7323                    ps.readUserState(userId), userId);
7324            if (si == null) {
7325                return null;
7326            }
7327            final ResolveInfo res = new ResolveInfo();
7328            res.serviceInfo = si;
7329            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7330                res.filter = filter;
7331            }
7332            res.priority = info.getPriority();
7333            res.preferredOrder = service.owner.mPreferredOrder;
7334            //System.out.println("Result: " + res.activityInfo.className +
7335            //                   " = " + res.priority);
7336            res.match = match;
7337            res.isDefault = info.hasDefault;
7338            res.labelRes = info.labelRes;
7339            res.nonLocalizedLabel = info.nonLocalizedLabel;
7340            res.icon = info.icon;
7341            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7342            return res;
7343        }
7344
7345        @Override
7346        protected void sortResults(List<ResolveInfo> results) {
7347            Collections.sort(results, mResolvePrioritySorter);
7348        }
7349
7350        @Override
7351        protected void dumpFilter(PrintWriter out, String prefix,
7352                PackageParser.ServiceIntentInfo filter) {
7353            out.print(prefix); out.print(
7354                    Integer.toHexString(System.identityHashCode(filter.service)));
7355                    out.print(' ');
7356                    filter.service.printComponentShortName(out);
7357                    out.print(" filter ");
7358                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7359        }
7360
7361//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7362//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7363//            final List<ResolveInfo> retList = Lists.newArrayList();
7364//            while (i.hasNext()) {
7365//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7366//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7367//                    retList.add(resolveInfo);
7368//                }
7369//            }
7370//            return retList;
7371//        }
7372
7373        // Keys are String (activity class name), values are Activity.
7374        private final HashMap<ComponentName, PackageParser.Service> mServices
7375                = new HashMap<ComponentName, PackageParser.Service>();
7376        private int mFlags;
7377    };
7378
7379    private final class ProviderIntentResolver
7380            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7381        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7382                boolean defaultOnly, int userId) {
7383            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7384            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7385        }
7386
7387        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7388                int userId) {
7389            if (!sUserManager.exists(userId))
7390                return null;
7391            mFlags = flags;
7392            return super.queryIntent(intent, resolvedType,
7393                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7394        }
7395
7396        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7397                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7398            if (!sUserManager.exists(userId))
7399                return null;
7400            if (packageProviders == null) {
7401                return null;
7402            }
7403            mFlags = flags;
7404            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7405            final int N = packageProviders.size();
7406            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7407                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7408
7409            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7410            for (int i = 0; i < N; ++i) {
7411                intentFilters = packageProviders.get(i).intents;
7412                if (intentFilters != null && intentFilters.size() > 0) {
7413                    PackageParser.ProviderIntentInfo[] array =
7414                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7415                    intentFilters.toArray(array);
7416                    listCut.add(array);
7417                }
7418            }
7419            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7420        }
7421
7422        public final void addProvider(PackageParser.Provider p) {
7423            if (mProviders.containsKey(p.getComponentName())) {
7424                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7425                return;
7426            }
7427
7428            mProviders.put(p.getComponentName(), p);
7429            if (DEBUG_SHOW_INFO) {
7430                Log.v(TAG, "  "
7431                        + (p.info.nonLocalizedLabel != null
7432                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7433                Log.v(TAG, "    Class=" + p.info.name);
7434            }
7435            final int NI = p.intents.size();
7436            int j;
7437            for (j = 0; j < NI; j++) {
7438                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7439                if (DEBUG_SHOW_INFO) {
7440                    Log.v(TAG, "    IntentFilter:");
7441                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7442                }
7443                if (!intent.debugCheck()) {
7444                    Log.w(TAG, "==> For Provider " + p.info.name);
7445                }
7446                addFilter(intent);
7447            }
7448        }
7449
7450        public final void removeProvider(PackageParser.Provider p) {
7451            mProviders.remove(p.getComponentName());
7452            if (DEBUG_SHOW_INFO) {
7453                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7454                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7455                Log.v(TAG, "    Class=" + p.info.name);
7456            }
7457            final int NI = p.intents.size();
7458            int j;
7459            for (j = 0; j < NI; j++) {
7460                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7461                if (DEBUG_SHOW_INFO) {
7462                    Log.v(TAG, "    IntentFilter:");
7463                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7464                }
7465                removeFilter(intent);
7466            }
7467        }
7468
7469        @Override
7470        protected boolean allowFilterResult(
7471                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7472            ProviderInfo filterPi = filter.provider.info;
7473            for (int i = dest.size() - 1; i >= 0; i--) {
7474                ProviderInfo destPi = dest.get(i).providerInfo;
7475                if (destPi.name == filterPi.name
7476                        && destPi.packageName == filterPi.packageName) {
7477                    return false;
7478                }
7479            }
7480            return true;
7481        }
7482
7483        @Override
7484        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7485            return new PackageParser.ProviderIntentInfo[size];
7486        }
7487
7488        @Override
7489        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7490            if (!sUserManager.exists(userId))
7491                return true;
7492            PackageParser.Package p = filter.provider.owner;
7493            if (p != null) {
7494                PackageSetting ps = (PackageSetting) p.mExtras;
7495                if (ps != null) {
7496                    // System apps are never considered stopped for purposes of
7497                    // filtering, because there may be no way for the user to
7498                    // actually re-launch them.
7499                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7500                            && ps.getStopped(userId);
7501                }
7502            }
7503            return false;
7504        }
7505
7506        @Override
7507        protected boolean isPackageForFilter(String packageName,
7508                PackageParser.ProviderIntentInfo info) {
7509            return packageName.equals(info.provider.owner.packageName);
7510        }
7511
7512        @Override
7513        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7514                int match, int userId) {
7515            if (!sUserManager.exists(userId))
7516                return null;
7517            final PackageParser.ProviderIntentInfo info = filter;
7518            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7519                return null;
7520            }
7521            final PackageParser.Provider provider = info.provider;
7522            if (mSafeMode && (provider.info.applicationInfo.flags
7523                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7524                return null;
7525            }
7526            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7527            if (ps == null) {
7528                return null;
7529            }
7530            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7531                    ps.readUserState(userId), userId);
7532            if (pi == null) {
7533                return null;
7534            }
7535            final ResolveInfo res = new ResolveInfo();
7536            res.providerInfo = pi;
7537            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7538                res.filter = filter;
7539            }
7540            res.priority = info.getPriority();
7541            res.preferredOrder = provider.owner.mPreferredOrder;
7542            res.match = match;
7543            res.isDefault = info.hasDefault;
7544            res.labelRes = info.labelRes;
7545            res.nonLocalizedLabel = info.nonLocalizedLabel;
7546            res.icon = info.icon;
7547            res.system = isSystemApp(res.providerInfo.applicationInfo);
7548            return res;
7549        }
7550
7551        @Override
7552        protected void sortResults(List<ResolveInfo> results) {
7553            Collections.sort(results, mResolvePrioritySorter);
7554        }
7555
7556        @Override
7557        protected void dumpFilter(PrintWriter out, String prefix,
7558                PackageParser.ProviderIntentInfo filter) {
7559            out.print(prefix);
7560            out.print(
7561                    Integer.toHexString(System.identityHashCode(filter.provider)));
7562            out.print(' ');
7563            filter.provider.printComponentShortName(out);
7564            out.print(" filter ");
7565            out.println(Integer.toHexString(System.identityHashCode(filter)));
7566        }
7567
7568        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7569                = new HashMap<ComponentName, PackageParser.Provider>();
7570        private int mFlags;
7571    };
7572
7573    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7574            new Comparator<ResolveInfo>() {
7575        public int compare(ResolveInfo r1, ResolveInfo r2) {
7576            int v1 = r1.priority;
7577            int v2 = r2.priority;
7578            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7579            if (v1 != v2) {
7580                return (v1 > v2) ? -1 : 1;
7581            }
7582            v1 = r1.preferredOrder;
7583            v2 = r2.preferredOrder;
7584            if (v1 != v2) {
7585                return (v1 > v2) ? -1 : 1;
7586            }
7587            if (r1.isDefault != r2.isDefault) {
7588                return r1.isDefault ? -1 : 1;
7589            }
7590            v1 = r1.match;
7591            v2 = r2.match;
7592            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7593            if (v1 != v2) {
7594                return (v1 > v2) ? -1 : 1;
7595            }
7596            if (r1.system != r2.system) {
7597                return r1.system ? -1 : 1;
7598            }
7599            return 0;
7600        }
7601    };
7602
7603    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7604            new Comparator<ProviderInfo>() {
7605        public int compare(ProviderInfo p1, ProviderInfo p2) {
7606            final int v1 = p1.initOrder;
7607            final int v2 = p2.initOrder;
7608            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7609        }
7610    };
7611
7612    static final void sendPackageBroadcast(String action, String pkg,
7613            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7614            int[] userIds) {
7615        IActivityManager am = ActivityManagerNative.getDefault();
7616        if (am != null) {
7617            try {
7618                if (userIds == null) {
7619                    userIds = am.getRunningUserIds();
7620                }
7621                for (int id : userIds) {
7622                    final Intent intent = new Intent(action,
7623                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7624                    if (extras != null) {
7625                        intent.putExtras(extras);
7626                    }
7627                    if (targetPkg != null) {
7628                        intent.setPackage(targetPkg);
7629                    }
7630                    // Modify the UID when posting to other users
7631                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7632                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7633                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7634                        intent.putExtra(Intent.EXTRA_UID, uid);
7635                    }
7636                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7637                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7638                    if (DEBUG_BROADCASTS) {
7639                        RuntimeException here = new RuntimeException("here");
7640                        here.fillInStackTrace();
7641                        Slog.d(TAG, "Sending to user " + id + ": "
7642                                + intent.toShortString(false, true, false, false)
7643                                + " " + intent.getExtras(), here);
7644                    }
7645                    am.broadcastIntent(null, intent, null, finishedReceiver,
7646                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7647                            finishedReceiver != null, false, id);
7648                }
7649            } catch (RemoteException ex) {
7650            }
7651        }
7652    }
7653
7654    /**
7655     * Check if the external storage media is available. This is true if there
7656     * is a mounted external storage medium or if the external storage is
7657     * emulated.
7658     */
7659    private boolean isExternalMediaAvailable() {
7660        return mMediaMounted || Environment.isExternalStorageEmulated();
7661    }
7662
7663    @Override
7664    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7665        // writer
7666        synchronized (mPackages) {
7667            if (!isExternalMediaAvailable()) {
7668                // If the external storage is no longer mounted at this point,
7669                // the caller may not have been able to delete all of this
7670                // packages files and can not delete any more.  Bail.
7671                return null;
7672            }
7673            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7674            if (lastPackage != null) {
7675                pkgs.remove(lastPackage);
7676            }
7677            if (pkgs.size() > 0) {
7678                return pkgs.get(0);
7679            }
7680        }
7681        return null;
7682    }
7683
7684    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7685        if (false) {
7686            RuntimeException here = new RuntimeException("here");
7687            here.fillInStackTrace();
7688            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7689                    + " andCode=" + andCode, here);
7690        }
7691        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7692                userId, andCode ? 1 : 0, packageName));
7693    }
7694
7695    void startCleaningPackages() {
7696        // reader
7697        synchronized (mPackages) {
7698            if (!isExternalMediaAvailable()) {
7699                return;
7700            }
7701            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7702                return;
7703            }
7704        }
7705        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7706        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7707        IActivityManager am = ActivityManagerNative.getDefault();
7708        if (am != null) {
7709            try {
7710                am.startService(null, intent, null, UserHandle.USER_OWNER);
7711            } catch (RemoteException e) {
7712            }
7713        }
7714    }
7715
7716    @Override
7717    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7718            String installerPackageName, VerificationParams verificationParams,
7719            String packageAbiOverride) {
7720        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7721                null);
7722
7723        final File originFile = new File(originPath);
7724        final int uid = Binder.getCallingUid();
7725        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7726            try {
7727                if (observer != null) {
7728                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7729                }
7730            } catch (RemoteException re) {
7731            }
7732            return;
7733        }
7734
7735        UserHandle user;
7736        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7737            user = UserHandle.ALL;
7738        } else {
7739            user = new UserHandle(UserHandle.getUserId(uid));
7740        }
7741
7742        final int filteredFlags;
7743        if (uid == Process.SHELL_UID || uid == 0) {
7744            if (DEBUG_INSTALL) {
7745                Slog.v(TAG, "Install from ADB");
7746            }
7747            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7748        } else {
7749            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7750        }
7751
7752        verificationParams.setInstallerUid(uid);
7753
7754        final Message msg = mHandler.obtainMessage(INIT_COPY);
7755        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7756                installerPackageName, verificationParams, user, packageAbiOverride);
7757        mHandler.sendMessage(msg);
7758    }
7759
7760    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7761            InstallSessionParams params, String installerPackageName, int installerUid,
7762            UserHandle user) {
7763        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7764                params.referrerUri, installerUid, null);
7765
7766        final Message msg = mHandler.obtainMessage(INIT_COPY);
7767        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7768                installerPackageName, verifParams, user, params.abiOverride);
7769        mHandler.sendMessage(msg);
7770    }
7771
7772    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7773        Bundle extras = new Bundle(1);
7774        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7775
7776        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7777                packageName, extras, null, null, new int[] {userId});
7778        try {
7779            IActivityManager am = ActivityManagerNative.getDefault();
7780            final boolean isSystem =
7781                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7782            if (isSystem && am.isUserRunning(userId, false)) {
7783                // The just-installed/enabled app is bundled on the system, so presumed
7784                // to be able to run automatically without needing an explicit launch.
7785                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7786                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7787                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7788                        .setPackage(packageName);
7789                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7790                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7791            }
7792        } catch (RemoteException e) {
7793            // shouldn't happen
7794            Slog.w(TAG, "Unable to bootstrap installed package", e);
7795        }
7796    }
7797
7798    @Override
7799    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7800            int userId) {
7801        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7802        PackageSetting pkgSetting;
7803        final int uid = Binder.getCallingUid();
7804        if (UserHandle.getUserId(uid) != userId) {
7805            mContext.enforceCallingOrSelfPermission(
7806                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7807                    "setApplicationHiddenSetting for user " + userId);
7808        }
7809
7810        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7811            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7812            return false;
7813        }
7814
7815        long callingId = Binder.clearCallingIdentity();
7816        try {
7817            boolean sendAdded = false;
7818            boolean sendRemoved = false;
7819            // writer
7820            synchronized (mPackages) {
7821                pkgSetting = mSettings.mPackages.get(packageName);
7822                if (pkgSetting == null) {
7823                    return false;
7824                }
7825                if (pkgSetting.getHidden(userId) != hidden) {
7826                    pkgSetting.setHidden(hidden, userId);
7827                    mSettings.writePackageRestrictionsLPr(userId);
7828                    if (hidden) {
7829                        sendRemoved = true;
7830                    } else {
7831                        sendAdded = true;
7832                    }
7833                }
7834            }
7835            if (sendAdded) {
7836                sendPackageAddedForUser(packageName, pkgSetting, userId);
7837                return true;
7838            }
7839            if (sendRemoved) {
7840                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7841                        "hiding pkg");
7842                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7843            }
7844        } finally {
7845            Binder.restoreCallingIdentity(callingId);
7846        }
7847        return false;
7848    }
7849
7850    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7851            int userId) {
7852        final PackageRemovedInfo info = new PackageRemovedInfo();
7853        info.removedPackage = packageName;
7854        info.removedUsers = new int[] {userId};
7855        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7856        info.sendBroadcast(false, false, false);
7857    }
7858
7859    /**
7860     * Returns true if application is not found or there was an error. Otherwise it returns
7861     * the hidden state of the package for the given user.
7862     */
7863    @Override
7864    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7865        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7866        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7867                "getApplicationHidden for user " + userId);
7868        PackageSetting pkgSetting;
7869        long callingId = Binder.clearCallingIdentity();
7870        try {
7871            // writer
7872            synchronized (mPackages) {
7873                pkgSetting = mSettings.mPackages.get(packageName);
7874                if (pkgSetting == null) {
7875                    return true;
7876                }
7877                return pkgSetting.getHidden(userId);
7878            }
7879        } finally {
7880            Binder.restoreCallingIdentity(callingId);
7881        }
7882    }
7883
7884    /**
7885     * @hide
7886     */
7887    @Override
7888    public int installExistingPackageAsUser(String packageName, int userId) {
7889        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7890                null);
7891        PackageSetting pkgSetting;
7892        final int uid = Binder.getCallingUid();
7893        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7894        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7895            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7896        }
7897
7898        long callingId = Binder.clearCallingIdentity();
7899        try {
7900            boolean sendAdded = false;
7901            Bundle extras = new Bundle(1);
7902
7903            // writer
7904            synchronized (mPackages) {
7905                pkgSetting = mSettings.mPackages.get(packageName);
7906                if (pkgSetting == null) {
7907                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7908                }
7909                if (!pkgSetting.getInstalled(userId)) {
7910                    pkgSetting.setInstalled(true, userId);
7911                    pkgSetting.setHidden(false, userId);
7912                    mSettings.writePackageRestrictionsLPr(userId);
7913                    sendAdded = true;
7914                }
7915            }
7916
7917            if (sendAdded) {
7918                sendPackageAddedForUser(packageName, pkgSetting, userId);
7919            }
7920        } finally {
7921            Binder.restoreCallingIdentity(callingId);
7922        }
7923
7924        return PackageManager.INSTALL_SUCCEEDED;
7925    }
7926
7927    boolean isUserRestricted(int userId, String restrictionKey) {
7928        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7929        if (restrictions.getBoolean(restrictionKey, false)) {
7930            Log.w(TAG, "User is restricted: " + restrictionKey);
7931            return true;
7932        }
7933        return false;
7934    }
7935
7936    @Override
7937    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7938        mContext.enforceCallingOrSelfPermission(
7939                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7940                "Only package verification agents can verify applications");
7941
7942        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7943        final PackageVerificationResponse response = new PackageVerificationResponse(
7944                verificationCode, Binder.getCallingUid());
7945        msg.arg1 = id;
7946        msg.obj = response;
7947        mHandler.sendMessage(msg);
7948    }
7949
7950    @Override
7951    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7952            long millisecondsToDelay) {
7953        mContext.enforceCallingOrSelfPermission(
7954                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7955                "Only package verification agents can extend verification timeouts");
7956
7957        final PackageVerificationState state = mPendingVerification.get(id);
7958        final PackageVerificationResponse response = new PackageVerificationResponse(
7959                verificationCodeAtTimeout, Binder.getCallingUid());
7960
7961        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7962            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7963        }
7964        if (millisecondsToDelay < 0) {
7965            millisecondsToDelay = 0;
7966        }
7967        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7968                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7969            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7970        }
7971
7972        if ((state != null) && !state.timeoutExtended()) {
7973            state.extendTimeout();
7974
7975            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7976            msg.arg1 = id;
7977            msg.obj = response;
7978            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7979        }
7980    }
7981
7982    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7983            int verificationCode, UserHandle user) {
7984        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7985        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7986        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7987        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7988        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7989
7990        mContext.sendBroadcastAsUser(intent, user,
7991                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7992    }
7993
7994    private ComponentName matchComponentForVerifier(String packageName,
7995            List<ResolveInfo> receivers) {
7996        ActivityInfo targetReceiver = null;
7997
7998        final int NR = receivers.size();
7999        for (int i = 0; i < NR; i++) {
8000            final ResolveInfo info = receivers.get(i);
8001            if (info.activityInfo == null) {
8002                continue;
8003            }
8004
8005            if (packageName.equals(info.activityInfo.packageName)) {
8006                targetReceiver = info.activityInfo;
8007                break;
8008            }
8009        }
8010
8011        if (targetReceiver == null) {
8012            return null;
8013        }
8014
8015        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8016    }
8017
8018    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8019            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8020        if (pkgInfo.verifiers.length == 0) {
8021            return null;
8022        }
8023
8024        final int N = pkgInfo.verifiers.length;
8025        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8026        for (int i = 0; i < N; i++) {
8027            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8028
8029            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8030                    receivers);
8031            if (comp == null) {
8032                continue;
8033            }
8034
8035            final int verifierUid = getUidForVerifier(verifierInfo);
8036            if (verifierUid == -1) {
8037                continue;
8038            }
8039
8040            if (DEBUG_VERIFY) {
8041                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8042                        + " with the correct signature");
8043            }
8044            sufficientVerifiers.add(comp);
8045            verificationState.addSufficientVerifier(verifierUid);
8046        }
8047
8048        return sufficientVerifiers;
8049    }
8050
8051    private int getUidForVerifier(VerifierInfo verifierInfo) {
8052        synchronized (mPackages) {
8053            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8054            if (pkg == null) {
8055                return -1;
8056            } else if (pkg.mSignatures.length != 1) {
8057                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8058                        + " has more than one signature; ignoring");
8059                return -1;
8060            }
8061
8062            /*
8063             * If the public key of the package's signature does not match
8064             * our expected public key, then this is a different package and
8065             * we should skip.
8066             */
8067
8068            final byte[] expectedPublicKey;
8069            try {
8070                final Signature verifierSig = pkg.mSignatures[0];
8071                final PublicKey publicKey = verifierSig.getPublicKey();
8072                expectedPublicKey = publicKey.getEncoded();
8073            } catch (CertificateException e) {
8074                return -1;
8075            }
8076
8077            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8078
8079            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8080                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8081                        + " does not have the expected public key; ignoring");
8082                return -1;
8083            }
8084
8085            return pkg.applicationInfo.uid;
8086        }
8087    }
8088
8089    @Override
8090    public void finishPackageInstall(int token) {
8091        enforceSystemOrRoot("Only the system is allowed to finish installs");
8092
8093        if (DEBUG_INSTALL) {
8094            Slog.v(TAG, "BM finishing package install for " + token);
8095        }
8096
8097        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8098        mHandler.sendMessage(msg);
8099    }
8100
8101    /**
8102     * Get the verification agent timeout.
8103     *
8104     * @return verification timeout in milliseconds
8105     */
8106    private long getVerificationTimeout() {
8107        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8108                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8109                DEFAULT_VERIFICATION_TIMEOUT);
8110    }
8111
8112    /**
8113     * Get the default verification agent response code.
8114     *
8115     * @return default verification response code
8116     */
8117    private int getDefaultVerificationResponse() {
8118        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8119                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8120                DEFAULT_VERIFICATION_RESPONSE);
8121    }
8122
8123    /**
8124     * Check whether or not package verification has been enabled.
8125     *
8126     * @return true if verification should be performed
8127     */
8128    private boolean isVerificationEnabled(int userId, int flags) {
8129        if (!DEFAULT_VERIFY_ENABLE) {
8130            return false;
8131        }
8132
8133        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8134
8135        // Check if installing from ADB
8136        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8137            // Do not run verification in a test harness environment
8138            if (ActivityManager.isRunningInTestHarness()) {
8139                return false;
8140            }
8141            if (ensureVerifyAppsEnabled) {
8142                return true;
8143            }
8144            // Check if the developer does not want package verification for ADB installs
8145            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8146                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8147                return false;
8148            }
8149        }
8150
8151        if (ensureVerifyAppsEnabled) {
8152            return true;
8153        }
8154
8155        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8156                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8157    }
8158
8159    /**
8160     * Get the "allow unknown sources" setting.
8161     *
8162     * @return the current "allow unknown sources" setting
8163     */
8164    private int getUnknownSourcesSettings() {
8165        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8166                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8167                -1);
8168    }
8169
8170    @Override
8171    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8172        final int uid = Binder.getCallingUid();
8173        // writer
8174        synchronized (mPackages) {
8175            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8176            if (targetPackageSetting == null) {
8177                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8178            }
8179
8180            PackageSetting installerPackageSetting;
8181            if (installerPackageName != null) {
8182                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8183                if (installerPackageSetting == null) {
8184                    throw new IllegalArgumentException("Unknown installer package: "
8185                            + installerPackageName);
8186                }
8187            } else {
8188                installerPackageSetting = null;
8189            }
8190
8191            Signature[] callerSignature;
8192            Object obj = mSettings.getUserIdLPr(uid);
8193            if (obj != null) {
8194                if (obj instanceof SharedUserSetting) {
8195                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8196                } else if (obj instanceof PackageSetting) {
8197                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8198                } else {
8199                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8200                }
8201            } else {
8202                throw new SecurityException("Unknown calling uid " + uid);
8203            }
8204
8205            // Verify: can't set installerPackageName to a package that is
8206            // not signed with the same cert as the caller.
8207            if (installerPackageSetting != null) {
8208                if (compareSignatures(callerSignature,
8209                        installerPackageSetting.signatures.mSignatures)
8210                        != PackageManager.SIGNATURE_MATCH) {
8211                    throw new SecurityException(
8212                            "Caller does not have same cert as new installer package "
8213                            + installerPackageName);
8214                }
8215            }
8216
8217            // Verify: if target already has an installer package, it must
8218            // be signed with the same cert as the caller.
8219            if (targetPackageSetting.installerPackageName != null) {
8220                PackageSetting setting = mSettings.mPackages.get(
8221                        targetPackageSetting.installerPackageName);
8222                // If the currently set package isn't valid, then it's always
8223                // okay to change it.
8224                if (setting != null) {
8225                    if (compareSignatures(callerSignature,
8226                            setting.signatures.mSignatures)
8227                            != PackageManager.SIGNATURE_MATCH) {
8228                        throw new SecurityException(
8229                                "Caller does not have same cert as old installer package "
8230                                + targetPackageSetting.installerPackageName);
8231                    }
8232                }
8233            }
8234
8235            // Okay!
8236            targetPackageSetting.installerPackageName = installerPackageName;
8237            scheduleWriteSettingsLocked();
8238        }
8239    }
8240
8241    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8242        // Queue up an async operation since the package installation may take a little while.
8243        mHandler.post(new Runnable() {
8244            public void run() {
8245                mHandler.removeCallbacks(this);
8246                 // Result object to be returned
8247                PackageInstalledInfo res = new PackageInstalledInfo();
8248                res.returnCode = currentStatus;
8249                res.uid = -1;
8250                res.pkg = null;
8251                res.removedInfo = new PackageRemovedInfo();
8252                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8253                    args.doPreInstall(res.returnCode);
8254                    synchronized (mInstallLock) {
8255                        installPackageLI(args, true, res);
8256                    }
8257                    args.doPostInstall(res.returnCode, res.uid);
8258                }
8259
8260                // A restore should be performed at this point if (a) the install
8261                // succeeded, (b) the operation is not an update, and (c) the new
8262                // package has not opted out of backup participation.
8263                final boolean update = res.removedInfo.removedPackage != null;
8264                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8265                boolean doRestore = !update
8266                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8267
8268                // Set up the post-install work request bookkeeping.  This will be used
8269                // and cleaned up by the post-install event handling regardless of whether
8270                // there's a restore pass performed.  Token values are >= 1.
8271                int token;
8272                if (mNextInstallToken < 0) mNextInstallToken = 1;
8273                token = mNextInstallToken++;
8274
8275                PostInstallData data = new PostInstallData(args, res);
8276                mRunningInstalls.put(token, data);
8277                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8278
8279                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8280                    // Pass responsibility to the Backup Manager.  It will perform a
8281                    // restore if appropriate, then pass responsibility back to the
8282                    // Package Manager to run the post-install observer callbacks
8283                    // and broadcasts.
8284                    IBackupManager bm = IBackupManager.Stub.asInterface(
8285                            ServiceManager.getService(Context.BACKUP_SERVICE));
8286                    if (bm != null) {
8287                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8288                                + " to BM for possible restore");
8289                        try {
8290                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8291                        } catch (RemoteException e) {
8292                            // can't happen; the backup manager is local
8293                        } catch (Exception e) {
8294                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8295                            doRestore = false;
8296                        }
8297                    } else {
8298                        Slog.e(TAG, "Backup Manager not found!");
8299                        doRestore = false;
8300                    }
8301                }
8302
8303                if (!doRestore) {
8304                    // No restore possible, or the Backup Manager was mysteriously not
8305                    // available -- just fire the post-install work request directly.
8306                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8307                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8308                    mHandler.sendMessage(msg);
8309                }
8310            }
8311        });
8312    }
8313
8314    private abstract class HandlerParams {
8315        private static final int MAX_RETRIES = 4;
8316
8317        /**
8318         * Number of times startCopy() has been attempted and had a non-fatal
8319         * error.
8320         */
8321        private int mRetries = 0;
8322
8323        /** User handle for the user requesting the information or installation. */
8324        private final UserHandle mUser;
8325
8326        HandlerParams(UserHandle user) {
8327            mUser = user;
8328        }
8329
8330        UserHandle getUser() {
8331            return mUser;
8332        }
8333
8334        final boolean startCopy() {
8335            boolean res;
8336            try {
8337                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8338
8339                if (++mRetries > MAX_RETRIES) {
8340                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8341                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8342                    handleServiceError();
8343                    return false;
8344                } else {
8345                    handleStartCopy();
8346                    res = true;
8347                }
8348            } catch (RemoteException e) {
8349                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8350                mHandler.sendEmptyMessage(MCS_RECONNECT);
8351                res = false;
8352            }
8353            handleReturnCode();
8354            return res;
8355        }
8356
8357        final void serviceError() {
8358            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8359            handleServiceError();
8360            handleReturnCode();
8361        }
8362
8363        abstract void handleStartCopy() throws RemoteException;
8364        abstract void handleServiceError();
8365        abstract void handleReturnCode();
8366    }
8367
8368    class MeasureParams extends HandlerParams {
8369        private final PackageStats mStats;
8370        private boolean mSuccess;
8371
8372        private final IPackageStatsObserver mObserver;
8373
8374        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8375            super(new UserHandle(stats.userHandle));
8376            mObserver = observer;
8377            mStats = stats;
8378        }
8379
8380        @Override
8381        public String toString() {
8382            return "MeasureParams{"
8383                + Integer.toHexString(System.identityHashCode(this))
8384                + " " + mStats.packageName + "}";
8385        }
8386
8387        @Override
8388        void handleStartCopy() throws RemoteException {
8389            synchronized (mInstallLock) {
8390                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8391            }
8392
8393            if (mSuccess) {
8394                final boolean mounted;
8395                if (Environment.isExternalStorageEmulated()) {
8396                    mounted = true;
8397                } else {
8398                    final String status = Environment.getExternalStorageState();
8399                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8400                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8401                }
8402
8403                if (mounted) {
8404                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8405
8406                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8407                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8408
8409                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8410                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8411
8412                    // Always subtract cache size, since it's a subdirectory
8413                    mStats.externalDataSize -= mStats.externalCacheSize;
8414
8415                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8416                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8417
8418                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8419                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8420                }
8421            }
8422        }
8423
8424        @Override
8425        void handleReturnCode() {
8426            if (mObserver != null) {
8427                try {
8428                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8429                } catch (RemoteException e) {
8430                    Slog.i(TAG, "Observer no longer exists.");
8431                }
8432            }
8433        }
8434
8435        @Override
8436        void handleServiceError() {
8437            Slog.e(TAG, "Could not measure application " + mStats.packageName
8438                            + " external storage");
8439        }
8440    }
8441
8442    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8443            throws RemoteException {
8444        long result = 0;
8445        for (File path : paths) {
8446            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8447        }
8448        return result;
8449    }
8450
8451    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8452        for (File path : paths) {
8453            try {
8454                mcs.clearDirectory(path.getAbsolutePath());
8455            } catch (RemoteException e) {
8456            }
8457        }
8458    }
8459
8460    class InstallParams extends HandlerParams {
8461        /**
8462         * Location where install is coming from, before it has been
8463         * copied/renamed into place. This could be a single monolithic APK
8464         * file, or a cluster directory. This location may be untrusted.
8465         */
8466        final File originFile;
8467
8468        /**
8469         * Flag indicating that {@link #originFile} has already been staged,
8470         * meaning downstream users don't need to defensively copy the contents.
8471         */
8472        boolean originStaged;
8473
8474        final IPackageInstallObserver2 observer;
8475        int flags;
8476        final String installerPackageName;
8477        final VerificationParams verificationParams;
8478        private InstallArgs mArgs;
8479        private int mRet;
8480        final String packageAbiOverride;
8481        boolean multiArch;
8482
8483        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8484                int flags, String installerPackageName, VerificationParams verificationParams,
8485                UserHandle user, String packageAbiOverride) {
8486            super(user);
8487            this.originFile = Preconditions.checkNotNull(originFile);
8488            this.originStaged = originStaged;
8489            this.observer = observer;
8490            this.flags = flags;
8491            this.installerPackageName = installerPackageName;
8492            this.verificationParams = verificationParams;
8493            this.packageAbiOverride = packageAbiOverride;
8494        }
8495
8496        @Override
8497        public String toString() {
8498            return "InstallParams{"
8499                + Integer.toHexString(System.identityHashCode(this))
8500                + " " + originFile + "}";
8501        }
8502
8503        public ManifestDigest getManifestDigest() {
8504            if (verificationParams == null) {
8505                return null;
8506            }
8507            return verificationParams.getManifestDigest();
8508        }
8509
8510        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8511            String packageName = pkgLite.packageName;
8512            int installLocation = pkgLite.installLocation;
8513            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8514            // reader
8515            synchronized (mPackages) {
8516                PackageParser.Package pkg = mPackages.get(packageName);
8517                if (pkg != null) {
8518                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8519                        // Check for downgrading.
8520                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8521                            if (pkgLite.versionCode < pkg.mVersionCode) {
8522                                Slog.w(TAG, "Can't install update of " + packageName
8523                                        + " update version " + pkgLite.versionCode
8524                                        + " is older than installed version "
8525                                        + pkg.mVersionCode);
8526                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8527                            }
8528                        }
8529                        // Check for updated system application.
8530                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8531                            if (onSd) {
8532                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8533                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8534                            }
8535                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8536                        } else {
8537                            if (onSd) {
8538                                // Install flag overrides everything.
8539                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8540                            }
8541                            // If current upgrade specifies particular preference
8542                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8543                                // Application explicitly specified internal.
8544                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8545                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8546                                // App explictly prefers external. Let policy decide
8547                            } else {
8548                                // Prefer previous location
8549                                if (isExternal(pkg)) {
8550                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8551                                }
8552                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8553                            }
8554                        }
8555                    } else {
8556                        // Invalid install. Return error code
8557                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8558                    }
8559                }
8560            }
8561            // All the special cases have been taken care of.
8562            // Return result based on recommended install location.
8563            if (onSd) {
8564                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8565            }
8566            return pkgLite.recommendedInstallLocation;
8567        }
8568
8569        private long getMemoryLowThreshold() {
8570            final DeviceStorageMonitorInternal
8571                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8572            if (dsm == null) {
8573                return 0L;
8574            }
8575            return dsm.getMemoryLowThreshold();
8576        }
8577
8578        /*
8579         * Invoke remote method to get package information and install
8580         * location values. Override install location based on default
8581         * policy if needed and then create install arguments based
8582         * on the install location.
8583         */
8584        public void handleStartCopy() throws RemoteException {
8585            int ret = PackageManager.INSTALL_SUCCEEDED;
8586            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8587            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8588            PackageInfoLite pkgLite = null;
8589
8590            if (onInt && onSd) {
8591                // Check if both bits are set.
8592                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8593                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8594            } else {
8595                final long lowThreshold = getMemoryLowThreshold();
8596                if (lowThreshold == 0L) {
8597                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8598                }
8599
8600                // Remote call to find out default install location
8601                final String originPath = originFile.getAbsolutePath();
8602                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8603                        packageAbiOverride);
8604                // Keep track of whether this package is a multiArch package until
8605                // we perform a full scan of it. We need to do this because we might
8606                // end up extracting the package shared libraries before we perform
8607                // a full scan.
8608                multiArch = pkgLite.multiArch;
8609
8610                /*
8611                 * If we have too little free space, try to free cache
8612                 * before giving up.
8613                 */
8614                if (pkgLite.recommendedInstallLocation
8615                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8616                    final long size = mContainerService.calculateInstalledSize(
8617                            originPath, isForwardLocked(), packageAbiOverride);
8618                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8619                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8620                                lowThreshold, packageAbiOverride);
8621                    }
8622                    /*
8623                     * The cache free must have deleted the file we
8624                     * downloaded to install.
8625                     *
8626                     * TODO: fix the "freeCache" call to not delete
8627                     *       the file we care about.
8628                     */
8629                    if (pkgLite.recommendedInstallLocation
8630                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8631                        pkgLite.recommendedInstallLocation
8632                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8633                    }
8634                }
8635            }
8636
8637            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8638                int loc = pkgLite.recommendedInstallLocation;
8639                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8640                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8641                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8642                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8643                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8644                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8645                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8646                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8647                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8648                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8649                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8650                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8651                } else {
8652                    // Override with defaults if needed.
8653                    loc = installLocationPolicy(pkgLite, flags);
8654                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8655                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8656                    } else if (!onSd && !onInt) {
8657                        // Override install location with flags
8658                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8659                            // Set the flag to install on external media.
8660                            flags |= PackageManager.INSTALL_EXTERNAL;
8661                            flags &= ~PackageManager.INSTALL_INTERNAL;
8662                        } else {
8663                            // Make sure the flag for installing on external
8664                            // media is unset
8665                            flags |= PackageManager.INSTALL_INTERNAL;
8666                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8667                        }
8668                    }
8669                }
8670            }
8671
8672            final InstallArgs args = createInstallArgs(this);
8673            mArgs = args;
8674
8675            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8676                 /*
8677                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8678                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8679                 */
8680                int userIdentifier = getUser().getIdentifier();
8681                if (userIdentifier == UserHandle.USER_ALL
8682                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8683                    userIdentifier = UserHandle.USER_OWNER;
8684                }
8685
8686                /*
8687                 * Determine if we have any installed package verifiers. If we
8688                 * do, then we'll defer to them to verify the packages.
8689                 */
8690                final int requiredUid = mRequiredVerifierPackage == null ? -1
8691                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8692                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8693                    // TODO: send verifier the install session instead of uri
8694                    final Intent verification = new Intent(
8695                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8696                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8697                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8698
8699                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8700                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8701                            0 /* TODO: Which userId? */);
8702
8703                    if (DEBUG_VERIFY) {
8704                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8705                                + verification.toString() + " with " + pkgLite.verifiers.length
8706                                + " optional verifiers");
8707                    }
8708
8709                    final int verificationId = mPendingVerificationToken++;
8710
8711                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8712
8713                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8714                            installerPackageName);
8715
8716                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8717
8718                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8719                            pkgLite.packageName);
8720
8721                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8722                            pkgLite.versionCode);
8723
8724                    if (verificationParams != null) {
8725                        if (verificationParams.getVerificationURI() != null) {
8726                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8727                                 verificationParams.getVerificationURI());
8728                        }
8729                        if (verificationParams.getOriginatingURI() != null) {
8730                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8731                                  verificationParams.getOriginatingURI());
8732                        }
8733                        if (verificationParams.getReferrer() != null) {
8734                            verification.putExtra(Intent.EXTRA_REFERRER,
8735                                  verificationParams.getReferrer());
8736                        }
8737                        if (verificationParams.getOriginatingUid() >= 0) {
8738                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8739                                  verificationParams.getOriginatingUid());
8740                        }
8741                        if (verificationParams.getInstallerUid() >= 0) {
8742                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8743                                  verificationParams.getInstallerUid());
8744                        }
8745                    }
8746
8747                    final PackageVerificationState verificationState = new PackageVerificationState(
8748                            requiredUid, args);
8749
8750                    mPendingVerification.append(verificationId, verificationState);
8751
8752                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8753                            receivers, verificationState);
8754
8755                    /*
8756                     * If any sufficient verifiers were listed in the package
8757                     * manifest, attempt to ask them.
8758                     */
8759                    if (sufficientVerifiers != null) {
8760                        final int N = sufficientVerifiers.size();
8761                        if (N == 0) {
8762                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8763                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8764                        } else {
8765                            for (int i = 0; i < N; i++) {
8766                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8767
8768                                final Intent sufficientIntent = new Intent(verification);
8769                                sufficientIntent.setComponent(verifierComponent);
8770
8771                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8772                            }
8773                        }
8774                    }
8775
8776                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8777                            mRequiredVerifierPackage, receivers);
8778                    if (ret == PackageManager.INSTALL_SUCCEEDED
8779                            && mRequiredVerifierPackage != null) {
8780                        /*
8781                         * Send the intent to the required verification agent,
8782                         * but only start the verification timeout after the
8783                         * target BroadcastReceivers have run.
8784                         */
8785                        verification.setComponent(requiredVerifierComponent);
8786                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8787                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8788                                new BroadcastReceiver() {
8789                                    @Override
8790                                    public void onReceive(Context context, Intent intent) {
8791                                        final Message msg = mHandler
8792                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8793                                        msg.arg1 = verificationId;
8794                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8795                                    }
8796                                }, null, 0, null, null);
8797
8798                        /*
8799                         * We don't want the copy to proceed until verification
8800                         * succeeds, so null out this field.
8801                         */
8802                        mArgs = null;
8803                    }
8804                } else {
8805                    /*
8806                     * No package verification is enabled, so immediately start
8807                     * the remote call to initiate copy using temporary file.
8808                     */
8809                    ret = args.copyApk(mContainerService, true);
8810                }
8811            }
8812
8813            mRet = ret;
8814        }
8815
8816        @Override
8817        void handleReturnCode() {
8818            // If mArgs is null, then MCS couldn't be reached. When it
8819            // reconnects, it will try again to install. At that point, this
8820            // will succeed.
8821            if (mArgs != null) {
8822                processPendingInstall(mArgs, mRet);
8823            }
8824        }
8825
8826        @Override
8827        void handleServiceError() {
8828            mArgs = createInstallArgs(this);
8829            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8830        }
8831
8832        public boolean isForwardLocked() {
8833            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8834        }
8835    }
8836
8837    /*
8838     * Utility class used in movePackage api.
8839     * srcArgs and targetArgs are not set for invalid flags and make
8840     * sure to do null checks when invoking methods on them.
8841     * We probably want to return ErrorPrams for both failed installs
8842     * and moves.
8843     */
8844    class MoveParams extends HandlerParams {
8845        final IPackageMoveObserver observer;
8846        final int flags;
8847        final String packageName;
8848        final InstallArgs srcArgs;
8849        final InstallArgs targetArgs;
8850        int uid;
8851        int mRet;
8852
8853        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8854                String packageName, String[] instructionSets, int uid, UserHandle user,
8855                boolean isMultiArch) {
8856            super(user);
8857            this.srcArgs = srcArgs;
8858            this.observer = observer;
8859            this.flags = flags;
8860            this.packageName = packageName;
8861            this.uid = uid;
8862            if (srcArgs != null) {
8863                final String codePath = srcArgs.getCodePath();
8864                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8865                        instructionSets, isMultiArch);
8866            } else {
8867                targetArgs = null;
8868            }
8869        }
8870
8871        @Override
8872        public String toString() {
8873            return "MoveParams{"
8874                + Integer.toHexString(System.identityHashCode(this))
8875                + " " + packageName + "}";
8876        }
8877
8878        public void handleStartCopy() throws RemoteException {
8879            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8880            // Check for storage space on target medium
8881            if (!targetArgs.checkFreeStorage(mContainerService)) {
8882                Log.w(TAG, "Insufficient storage to install");
8883                return;
8884            }
8885
8886            mRet = srcArgs.doPreCopy();
8887            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8888                return;
8889            }
8890
8891            mRet = targetArgs.copyApk(mContainerService, false);
8892            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8893                srcArgs.doPostCopy(uid);
8894                return;
8895            }
8896
8897            mRet = srcArgs.doPostCopy(uid);
8898            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8899                return;
8900            }
8901
8902            mRet = targetArgs.doPreInstall(mRet);
8903            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8904                return;
8905            }
8906
8907            if (DEBUG_SD_INSTALL) {
8908                StringBuilder builder = new StringBuilder();
8909                if (srcArgs != null) {
8910                    builder.append("src: ");
8911                    builder.append(srcArgs.getCodePath());
8912                }
8913                if (targetArgs != null) {
8914                    builder.append(" target : ");
8915                    builder.append(targetArgs.getCodePath());
8916                }
8917                Log.i(TAG, builder.toString());
8918            }
8919        }
8920
8921        @Override
8922        void handleReturnCode() {
8923            targetArgs.doPostInstall(mRet, uid);
8924            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8925            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8926                currentStatus = PackageManager.MOVE_SUCCEEDED;
8927            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8928                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8929            }
8930            processPendingMove(this, currentStatus);
8931        }
8932
8933        @Override
8934        void handleServiceError() {
8935            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8936        }
8937    }
8938
8939    /**
8940     * Used during creation of InstallArgs
8941     *
8942     * @param flags package installation flags
8943     * @return true if should be installed on external storage
8944     */
8945    private static boolean installOnSd(int flags) {
8946        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8947            return false;
8948        }
8949        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8950            return true;
8951        }
8952        return false;
8953    }
8954
8955    /**
8956     * Used during creation of InstallArgs
8957     *
8958     * @param flags package installation flags
8959     * @return true if should be installed as forward locked
8960     */
8961    private static boolean installForwardLocked(int flags) {
8962        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8963    }
8964
8965    private InstallArgs createInstallArgs(InstallParams params) {
8966        // TODO: extend to support incoming zero-copy locations
8967
8968        if (installOnSd(params.flags) || params.isForwardLocked()) {
8969            return new AsecInstallArgs(params);
8970        } else {
8971            return new FileInstallArgs(params);
8972        }
8973    }
8974
8975    /**
8976     * Create args that describe an existing installed package. Typically used
8977     * when cleaning up old installs, or used as a move source.
8978     */
8979    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
8980            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
8981            boolean isMultiArch) {
8982        final boolean isInAsec;
8983        if (installOnSd(flags)) {
8984            /* Apps on SD card are always in ASEC containers. */
8985            isInAsec = true;
8986        } else if (installForwardLocked(flags)
8987                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8988            /*
8989             * Forward-locked apps are only in ASEC containers if they're the
8990             * new style
8991             */
8992            isInAsec = true;
8993        } else {
8994            isInAsec = false;
8995        }
8996
8997        if (isInAsec) {
8998            return new AsecInstallArgs(codePath, instructionSets,
8999                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9000        } else {
9001            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9002                    instructionSets, isMultiArch);
9003        }
9004    }
9005
9006    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9007            String[] instructionSets, boolean isMultiArch) {
9008        final File codeFile = new File(codePath);
9009        if (installOnSd(flags) || installForwardLocked(flags)) {
9010            String cid = getNextCodePath(codePath, pkgName, "/"
9011                    + AsecInstallArgs.RES_FILE_NAME);
9012            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9013                    installForwardLocked(flags), isMultiArch);
9014        } else {
9015            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9016        }
9017    }
9018
9019    static abstract class InstallArgs {
9020        /** @see InstallParams#originFile */
9021        final File originFile;
9022        /** @see InstallParams#originStaged */
9023        final boolean originStaged;
9024
9025        // TODO: define inherit location
9026
9027        final IPackageInstallObserver2 observer;
9028        // Always refers to PackageManager flags only
9029        final int flags;
9030        final String installerPackageName;
9031        final ManifestDigest manifestDigest;
9032        final UserHandle user;
9033        final String abiOverride;
9034        final boolean multiArch;
9035
9036        // The list of instruction sets supported by this app. This is currently
9037        // only used during the rmdex() phase to clean up resources. We can get rid of this
9038        // if we move dex files under the common app path.
9039        /* nullable */ String[] instructionSets;
9040
9041        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9042                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9043                    UserHandle user, String[] instructionSets,
9044                    String abiOverride, boolean multiArch) {
9045            this.originFile = originFile;
9046            this.originStaged = originStaged;
9047            this.flags = flags;
9048            this.observer = observer;
9049            this.installerPackageName = installerPackageName;
9050            this.manifestDigest = manifestDigest;
9051            this.user = user;
9052            this.instructionSets = instructionSets;
9053            this.abiOverride = abiOverride;
9054            this.multiArch = multiArch;
9055        }
9056
9057        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9058        abstract int doPreInstall(int status);
9059
9060        /**
9061         * Rename package into final resting place. All paths on the given
9062         * scanned package should be updated to reflect the rename.
9063         */
9064        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9065        abstract int doPostInstall(int status, int uid);
9066
9067        /** @see PackageSettingBase#codePathString */
9068        abstract String getCodePath();
9069        /** @see PackageSettingBase#resourcePathString */
9070        abstract String getResourcePath();
9071        abstract String getLegacyNativeLibraryPath();
9072
9073        // Need installer lock especially for dex file removal.
9074        abstract void cleanUpResourcesLI();
9075        abstract boolean doPostDeleteLI(boolean delete);
9076        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9077
9078        /**
9079         * Called before the source arguments are copied. This is used mostly
9080         * for MoveParams when it needs to read the source file to put it in the
9081         * destination.
9082         */
9083        int doPreCopy() {
9084            return PackageManager.INSTALL_SUCCEEDED;
9085        }
9086
9087        /**
9088         * Called after the source arguments are copied. This is used mostly for
9089         * MoveParams when it needs to read the source file to put it in the
9090         * destination.
9091         *
9092         * @return
9093         */
9094        int doPostCopy(int uid) {
9095            return PackageManager.INSTALL_SUCCEEDED;
9096        }
9097
9098        protected boolean isFwdLocked() {
9099            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9100        }
9101
9102        UserHandle getUser() {
9103            return user;
9104        }
9105    }
9106
9107    /**
9108     * Logic to handle installation of non-ASEC applications, including copying
9109     * and renaming logic.
9110     */
9111    class FileInstallArgs extends InstallArgs {
9112        private File codeFile;
9113        private File resourceFile;
9114        private File legacyNativeLibraryPath;
9115
9116        // Example topology:
9117        // /data/app/com.example/base.apk
9118        // /data/app/com.example/split_foo.apk
9119        // /data/app/com.example/lib/arm/libfoo.so
9120        // /data/app/com.example/lib/arm64/libfoo.so
9121        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9122
9123        /** New install */
9124        FileInstallArgs(InstallParams params) {
9125            super(params.originFile, params.originStaged, params.observer, params.flags,
9126                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9127                    null /* instruction sets */, params.packageAbiOverride,
9128                    params.multiArch);
9129            if (isFwdLocked()) {
9130                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9131            }
9132        }
9133
9134        /** Existing install */
9135        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9136                String[] instructionSets, boolean isMultiArch) {
9137            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9138            this.codeFile = (codePath != null) ? new File(codePath) : null;
9139            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9140            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9141                    new File(legacyNativeLibraryPath) : null;
9142        }
9143
9144        /** New install from existing */
9145        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9146            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9147                    isMultiArch);
9148        }
9149
9150        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9151            final long lowThreshold;
9152
9153            final DeviceStorageMonitorInternal
9154                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9155            if (dsm == null) {
9156                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9157                lowThreshold = 0L;
9158            } else {
9159                if (dsm.isMemoryLow()) {
9160                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9161                    return false;
9162                }
9163
9164                lowThreshold = dsm.getMemoryLowThreshold();
9165            }
9166
9167            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9168                    lowThreshold);
9169        }
9170
9171        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9172            int ret = PackageManager.INSTALL_SUCCEEDED;
9173
9174            if (originStaged) {
9175                Slog.d(TAG, originFile + " already staged; skipping copy");
9176                codeFile = originFile;
9177                resourceFile = originFile;
9178            } else {
9179                try {
9180                    final File tempDir = mInstallerService.allocateSessionDir();
9181                    codeFile = tempDir;
9182                    resourceFile = tempDir;
9183                } catch (IOException e) {
9184                    Slog.w(TAG, "Failed to create copy file: " + e);
9185                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9186                }
9187
9188                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9189                    @Override
9190                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9191                        if (!FileUtils.isValidExtFilename(name)) {
9192                            throw new IllegalArgumentException("Invalid filename: " + name);
9193                        }
9194                        try {
9195                            final File file = new File(codeFile, name);
9196                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9197                                    O_RDWR | O_CREAT, 0644);
9198                            Os.chmod(file.getAbsolutePath(), 0644);
9199                            return new ParcelFileDescriptor(fd);
9200                        } catch (ErrnoException e) {
9201                            throw new RemoteException("Failed to open: " + e.getMessage());
9202                        }
9203                    }
9204                };
9205
9206                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9207                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9208                    Slog.e(TAG, "Failed to copy package");
9209                    return ret;
9210                }
9211            }
9212
9213            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9214            NativeLibraryHelper.Handle handle = null;
9215            try {
9216                handle = NativeLibraryHelper.Handle.create(codeFile);
9217                if (multiArch) {
9218                    // Warn if we've set an abiOverride for multi-lib packages..
9219                    // By definition, we need to copy both 32 and 64 bit libraries for
9220                    // such packages.
9221                    if (abiOverride != null) {
9222                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9223                    }
9224
9225                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9226                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9227                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9228                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9229                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9230                    }
9231
9232                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9233                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9234                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9235                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9236                    }
9237                } else {
9238                    String[] abiList = (abiOverride != null) ?
9239                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9240
9241                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
9242                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9243                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9244                    }
9245
9246                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9247                            true /* use isa specific subdirs */);
9248                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9249                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9250                        return copyRet;
9251                    }
9252                }
9253            } catch (IOException e) {
9254                Slog.e(TAG, "Copying native libraries failed", e);
9255                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9256            } catch (PackageManagerException pme) {
9257                Slog.e(TAG, "Copying native libraries failed", pme);
9258                ret = pme.error;
9259            } finally {
9260                IoUtils.closeQuietly(handle);
9261            }
9262
9263            return ret;
9264        }
9265
9266        int doPreInstall(int status) {
9267            if (status != PackageManager.INSTALL_SUCCEEDED) {
9268                cleanUp();
9269            }
9270            return status;
9271        }
9272
9273        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9274            if (status != PackageManager.INSTALL_SUCCEEDED) {
9275                cleanUp();
9276                return false;
9277            } else {
9278                final File beforeCodeFile = codeFile;
9279                final File afterCodeFile = getNextCodePath(pkg.packageName);
9280
9281                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9282                try {
9283                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9284                } catch (ErrnoException e) {
9285                    Slog.d(TAG, "Failed to rename", e);
9286                    return false;
9287                }
9288
9289                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9290                    Slog.d(TAG, "Failed to restorecon");
9291                    return false;
9292                }
9293
9294                // Reflect the rename internally
9295                codeFile = afterCodeFile;
9296                resourceFile = afterCodeFile;
9297
9298                // Reflect the rename in scanned details
9299                pkg.codePath = afterCodeFile.getAbsolutePath();
9300                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9301                        pkg.baseCodePath);
9302                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9303                        pkg.splitCodePaths);
9304
9305                // Reflect the rename in app info
9306                pkg.applicationInfo.setCodePath(pkg.codePath);
9307                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9308                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9309                pkg.applicationInfo.setResourcePath(pkg.codePath);
9310                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9311                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9312
9313                return true;
9314            }
9315        }
9316
9317        int doPostInstall(int status, int uid) {
9318            if (status != PackageManager.INSTALL_SUCCEEDED) {
9319                cleanUp();
9320            }
9321            return status;
9322        }
9323
9324        @Override
9325        String getCodePath() {
9326            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9327        }
9328
9329        @Override
9330        String getResourcePath() {
9331            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9332        }
9333
9334        @Override
9335        String getLegacyNativeLibraryPath() {
9336            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9337        }
9338
9339        private boolean cleanUp() {
9340            if (codeFile == null || !codeFile.exists()) {
9341                return false;
9342            }
9343
9344            if (codeFile.isDirectory()) {
9345                FileUtils.deleteContents(codeFile);
9346            }
9347            codeFile.delete();
9348
9349            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9350                resourceFile.delete();
9351            }
9352
9353            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9354                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9355                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9356                }
9357                legacyNativeLibraryPath.delete();
9358            }
9359
9360            return true;
9361        }
9362
9363        void cleanUpResourcesLI() {
9364            // Try enumerating all code paths before deleting
9365            List<String> allCodePaths = Collections.EMPTY_LIST;
9366            if (codeFile != null && codeFile.exists()) {
9367                try {
9368                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9369                    allCodePaths = pkg.getAllCodePaths();
9370                } catch (PackageParserException e) {
9371                    // Ignored; we tried our best
9372                }
9373            }
9374
9375            cleanUp();
9376
9377            if (!allCodePaths.isEmpty()) {
9378                if (instructionSets == null) {
9379                    throw new IllegalStateException("instructionSet == null");
9380                }
9381
9382                for (String codePath : allCodePaths) {
9383                    for (String instructionSet : instructionSets) {
9384                        int retCode = mInstaller.rmdex(codePath, instructionSet);
9385                        if (retCode < 0) {
9386                            Slog.w(TAG, "Couldn't remove dex file for package: "
9387                                    + " at location " + codePath + ", retcode=" + retCode);
9388                            // we don't consider this to be a failure of the core package deletion
9389                        }
9390                    }
9391                }
9392            }
9393        }
9394
9395        boolean doPostDeleteLI(boolean delete) {
9396            // XXX err, shouldn't we respect the delete flag?
9397            cleanUpResourcesLI();
9398            return true;
9399        }
9400    }
9401
9402    private boolean isAsecExternal(String cid) {
9403        final String asecPath = PackageHelper.getSdFilesystem(cid);
9404        return !asecPath.startsWith(mAsecInternalPath);
9405    }
9406
9407    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9408            PackageManagerException {
9409        if (copyRet < 0) {
9410            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9411                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9412                throw new PackageManagerException(copyRet, message);
9413            }
9414        }
9415    }
9416
9417    /**
9418     * Extract the MountService "container ID" from the full code path of an
9419     * .apk.
9420     */
9421    static String cidFromCodePath(String fullCodePath) {
9422        int eidx = fullCodePath.lastIndexOf("/");
9423        String subStr1 = fullCodePath.substring(0, eidx);
9424        int sidx = subStr1.lastIndexOf("/");
9425        return subStr1.substring(sidx+1, eidx);
9426    }
9427
9428    /**
9429     * Logic to handle installation of ASEC applications, including copying and
9430     * renaming logic.
9431     */
9432    class AsecInstallArgs extends InstallArgs {
9433        // TODO: teach about handling cluster directories
9434
9435        static final String RES_FILE_NAME = "pkg.apk";
9436        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9437
9438        String cid;
9439        String packagePath;
9440        String resourcePath;
9441        String legacyNativeLibraryDir;
9442
9443        /** New install */
9444        AsecInstallArgs(InstallParams params) {
9445            super(params.originFile, params.originStaged, params.observer, params.flags,
9446                    params.installerPackageName, params.getManifestDigest(),
9447                    params.getUser(), null /* instruction sets */,
9448                    params.packageAbiOverride, params.multiArch);
9449        }
9450
9451        /** Existing install */
9452        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9453                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9454            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9455                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9456                    instructionSets, null, isMultiArch);
9457            // Extract cid from fullCodePath
9458            int eidx = fullCodePath.lastIndexOf("/");
9459            String subStr1 = fullCodePath.substring(0, eidx);
9460            int sidx = subStr1.lastIndexOf("/");
9461            cid = subStr1.substring(sidx+1, eidx);
9462            setCachePath(subStr1);
9463        }
9464
9465        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9466                        boolean isMultiArch) {
9467            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9468                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9469                    instructionSets, null, isMultiArch);
9470            this.cid = cid;
9471            setCachePath(PackageHelper.getSdDir(cid));
9472        }
9473
9474        /** New install from existing */
9475        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9476                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9477            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9478                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9479                    instructionSets, null, isMultiArch);
9480            this.cid = cid;
9481        }
9482
9483        void createCopyFile() {
9484            cid = getTempContainerId();
9485        }
9486
9487        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9488            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9489                    abiOverride);
9490        }
9491
9492        private final boolean isExternal() {
9493            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9494        }
9495
9496        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9497            if (temp) {
9498                createCopyFile();
9499            } else {
9500                /*
9501                 * Pre-emptively destroy the container since it's destroyed if
9502                 * copying fails due to it existing anyway.
9503                 */
9504                PackageHelper.destroySdDir(cid);
9505            }
9506
9507            final String newCachePath = imcs.copyPackageToContainer(
9508                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9509                    isFwdLocked(), abiOverride);
9510
9511            if (newCachePath != null) {
9512                setCachePath(newCachePath);
9513                return PackageManager.INSTALL_SUCCEEDED;
9514            } else {
9515                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9516            }
9517        }
9518
9519        @Override
9520        String getCodePath() {
9521            return packagePath;
9522        }
9523
9524        @Override
9525        String getResourcePath() {
9526            return resourcePath;
9527        }
9528
9529        @Override
9530        String getLegacyNativeLibraryPath() {
9531            return legacyNativeLibraryDir;
9532        }
9533
9534        int doPreInstall(int status) {
9535            if (status != PackageManager.INSTALL_SUCCEEDED) {
9536                // Destroy container
9537                PackageHelper.destroySdDir(cid);
9538            } else {
9539                boolean mounted = PackageHelper.isContainerMounted(cid);
9540                if (!mounted) {
9541                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9542                            Process.SYSTEM_UID);
9543                    if (newCachePath != null) {
9544                        setCachePath(newCachePath);
9545                    } else {
9546                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9547                    }
9548                }
9549            }
9550            return status;
9551        }
9552
9553        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9554            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9555            String newCachePath = null;
9556            if (PackageHelper.isContainerMounted(cid)) {
9557                // Unmount the container
9558                if (!PackageHelper.unMountSdDir(cid)) {
9559                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9560                    return false;
9561                }
9562            }
9563            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9564                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9565                        " which might be stale. Will try to clean up.");
9566                // Clean up the stale container and proceed to recreate.
9567                if (!PackageHelper.destroySdDir(newCacheId)) {
9568                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9569                    return false;
9570                }
9571                // Successfully cleaned up stale container. Try to rename again.
9572                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9573                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9574                            + " inspite of cleaning it up.");
9575                    return false;
9576                }
9577            }
9578            if (!PackageHelper.isContainerMounted(newCacheId)) {
9579                Slog.w(TAG, "Mounting container " + newCacheId);
9580                newCachePath = PackageHelper.mountSdDir(newCacheId,
9581                        getEncryptKey(), Process.SYSTEM_UID);
9582            } else {
9583                newCachePath = PackageHelper.getSdDir(newCacheId);
9584            }
9585            if (newCachePath == null) {
9586                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9587                return false;
9588            }
9589            Log.i(TAG, "Succesfully renamed " + cid +
9590                    " to " + newCacheId +
9591                    " at new path: " + newCachePath);
9592            cid = newCacheId;
9593            setCachePath(newCachePath);
9594
9595            // TODO: extend to support split APKs
9596            pkg.codePath = getCodePath();
9597            pkg.baseCodePath = getCodePath();
9598            pkg.splitCodePaths = null;
9599
9600            pkg.applicationInfo.setCodePath(getCodePath());
9601            pkg.applicationInfo.setBaseCodePath(getCodePath());
9602            pkg.applicationInfo.setSplitCodePaths(null);
9603            pkg.applicationInfo.setResourcePath(getResourcePath());
9604            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9605            pkg.applicationInfo.setSplitResourcePaths(null);
9606
9607            return true;
9608        }
9609
9610        private void setCachePath(String newCachePath) {
9611            File cachePath = new File(newCachePath);
9612            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9613            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9614
9615            if (isFwdLocked()) {
9616                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9617            } else {
9618                resourcePath = packagePath;
9619            }
9620        }
9621
9622        int doPostInstall(int status, int uid) {
9623            if (status != PackageManager.INSTALL_SUCCEEDED) {
9624                cleanUp();
9625            } else {
9626                final int groupOwner;
9627                final String protectedFile;
9628                if (isFwdLocked()) {
9629                    groupOwner = UserHandle.getSharedAppGid(uid);
9630                    protectedFile = RES_FILE_NAME;
9631                } else {
9632                    groupOwner = -1;
9633                    protectedFile = null;
9634                }
9635
9636                if (uid < Process.FIRST_APPLICATION_UID
9637                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9638                    Slog.e(TAG, "Failed to finalize " + cid);
9639                    PackageHelper.destroySdDir(cid);
9640                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9641                }
9642
9643                boolean mounted = PackageHelper.isContainerMounted(cid);
9644                if (!mounted) {
9645                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9646                }
9647            }
9648            return status;
9649        }
9650
9651        private void cleanUp() {
9652            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9653
9654            // Destroy secure container
9655            PackageHelper.destroySdDir(cid);
9656        }
9657
9658        void cleanUpResourcesLI() {
9659            String sourceFile = getCodePath();
9660            // Remove dex file
9661            if (instructionSets == null) {
9662                throw new IllegalStateException("instructionSet == null");
9663            }
9664            for (String instructionSet : instructionSets) {
9665                int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9666                if (retCode < 0) {
9667                    Slog.w(TAG, "Couldn't remove dex file for package: "
9668                            + " at location "
9669                            + sourceFile.toString() + ", retcode=" + retCode);
9670                    // we don't consider this to be a failure of the core package deletion
9671                }
9672            }
9673            cleanUp();
9674        }
9675
9676        boolean matchContainer(String app) {
9677            if (cid.startsWith(app)) {
9678                return true;
9679            }
9680            return false;
9681        }
9682
9683        String getPackageName() {
9684            return getAsecPackageName(cid);
9685        }
9686
9687        boolean doPostDeleteLI(boolean delete) {
9688            boolean ret = false;
9689            boolean mounted = PackageHelper.isContainerMounted(cid);
9690            if (mounted) {
9691                // Unmount first
9692                ret = PackageHelper.unMountSdDir(cid);
9693            }
9694            if (ret && delete) {
9695                cleanUpResourcesLI();
9696            }
9697            return ret;
9698        }
9699
9700        @Override
9701        int doPreCopy() {
9702            if (isFwdLocked()) {
9703                if (!PackageHelper.fixSdPermissions(cid,
9704                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9705                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9706                }
9707            }
9708
9709            return PackageManager.INSTALL_SUCCEEDED;
9710        }
9711
9712        @Override
9713        int doPostCopy(int uid) {
9714            if (isFwdLocked()) {
9715                if (uid < Process.FIRST_APPLICATION_UID
9716                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9717                                RES_FILE_NAME)) {
9718                    Slog.e(TAG, "Failed to finalize " + cid);
9719                    PackageHelper.destroySdDir(cid);
9720                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9721                }
9722            }
9723
9724            return PackageManager.INSTALL_SUCCEEDED;
9725        }
9726    }
9727
9728    static String getAsecPackageName(String packageCid) {
9729        int idx = packageCid.lastIndexOf("-");
9730        if (idx == -1) {
9731            return packageCid;
9732        }
9733        return packageCid.substring(0, idx);
9734    }
9735
9736    // Utility method used to create code paths based on package name and available index.
9737    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9738        String idxStr = "";
9739        int idx = 1;
9740        // Fall back to default value of idx=1 if prefix is not
9741        // part of oldCodePath
9742        if (oldCodePath != null) {
9743            String subStr = oldCodePath;
9744            // Drop the suffix right away
9745            if (suffix != null && subStr.endsWith(suffix)) {
9746                subStr = subStr.substring(0, subStr.length() - suffix.length());
9747            }
9748            // If oldCodePath already contains prefix find out the
9749            // ending index to either increment or decrement.
9750            int sidx = subStr.lastIndexOf(prefix);
9751            if (sidx != -1) {
9752                subStr = subStr.substring(sidx + prefix.length());
9753                if (subStr != null) {
9754                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9755                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9756                    }
9757                    try {
9758                        idx = Integer.parseInt(subStr);
9759                        if (idx <= 1) {
9760                            idx++;
9761                        } else {
9762                            idx--;
9763                        }
9764                    } catch(NumberFormatException e) {
9765                    }
9766                }
9767            }
9768        }
9769        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9770        return prefix + idxStr;
9771    }
9772
9773    private File getNextCodePath(String packageName) {
9774        int suffix = 1;
9775        File result;
9776        do {
9777            result = new File(mAppInstallDir, packageName + "-" + suffix);
9778            suffix++;
9779        } while (result.exists());
9780        return result;
9781    }
9782
9783    // Utility method used to ignore ADD/REMOVE events
9784    // by directory observer.
9785    private static boolean ignoreCodePath(String fullPathStr) {
9786        String apkName = deriveCodePathName(fullPathStr);
9787        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9788        if (idx != -1 && ((idx+1) < apkName.length())) {
9789            // Make sure the package ends with a numeral
9790            String version = apkName.substring(idx+1);
9791            try {
9792                Integer.parseInt(version);
9793                return true;
9794            } catch (NumberFormatException e) {}
9795        }
9796        return false;
9797    }
9798
9799    // Utility method that returns the relative package path with respect
9800    // to the installation directory. Like say for /data/data/com.test-1.apk
9801    // string com.test-1 is returned.
9802    static String deriveCodePathName(String codePath) {
9803        if (codePath == null) {
9804            return null;
9805        }
9806        final File codeFile = new File(codePath);
9807        final String name = codeFile.getName();
9808        if (codeFile.isDirectory()) {
9809            return name;
9810        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9811            final int lastDot = name.lastIndexOf('.');
9812            return name.substring(0, lastDot);
9813        } else {
9814            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9815            return null;
9816        }
9817    }
9818
9819    class PackageInstalledInfo {
9820        String name;
9821        int uid;
9822        // The set of users that originally had this package installed.
9823        int[] origUsers;
9824        // The set of users that now have this package installed.
9825        int[] newUsers;
9826        PackageParser.Package pkg;
9827        int returnCode;
9828        String returnMsg;
9829        PackageRemovedInfo removedInfo;
9830
9831        public void setError(int code, String msg) {
9832            returnCode = code;
9833            returnMsg = msg;
9834            Slog.w(TAG, msg);
9835        }
9836
9837        public void setError(String msg, PackageParserException e) {
9838            returnCode = e.error;
9839            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9840            Slog.w(TAG, msg, e);
9841        }
9842
9843        public void setError(String msg, PackageManagerException e) {
9844            returnCode = e.error;
9845            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9846            Slog.w(TAG, msg, e);
9847        }
9848
9849        // In some error cases we want to convey more info back to the observer
9850        String origPackage;
9851        String origPermission;
9852    }
9853
9854    /*
9855     * Install a non-existing package.
9856     */
9857    private void installNewPackageLI(PackageParser.Package pkg,
9858            int parseFlags, int scanMode, UserHandle user,
9859            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9860        // Remember this for later, in case we need to rollback this install
9861        String pkgName = pkg.packageName;
9862
9863        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9864        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9865        synchronized(mPackages) {
9866            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9867                // A package with the same name is already installed, though
9868                // it has been renamed to an older name.  The package we
9869                // are trying to install should be installed as an update to
9870                // the existing one, but that has not been requested, so bail.
9871                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9872                        + " without first uninstalling package running as "
9873                        + mSettings.mRenamedPackages.get(pkgName));
9874                return;
9875            }
9876            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9877                // Don't allow installation over an existing package with the same name.
9878                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9879                        + " without first uninstalling.");
9880                return;
9881            }
9882        }
9883
9884        try {
9885            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9886                    System.currentTimeMillis(), user, abiOverride);
9887
9888            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9889            // delete the partially installed application. the data directory will have to be
9890            // restored if it was already existing
9891            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9892                // remove package from internal structures.  Note that we want deletePackageX to
9893                // delete the package data and cache directories that it created in
9894                // scanPackageLocked, unless those directories existed before we even tried to
9895                // install.
9896                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9897                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9898                                res.removedInfo, true);
9899            }
9900
9901        } catch (PackageManagerException e) {
9902            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9903        }
9904    }
9905
9906    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9907        // Upgrade keysets are being used.  Determine if new package has a superset of the
9908        // required keys.
9909        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9910        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9911        for (int i = 0; i < upgradeKeySets.length; i++) {
9912            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9913            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9914                return true;
9915            }
9916        }
9917        return false;
9918    }
9919
9920    private void replacePackageLI(PackageParser.Package pkg,
9921            int parseFlags, int scanMode, UserHandle user,
9922            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9923        PackageParser.Package oldPackage;
9924        String pkgName = pkg.packageName;
9925        int[] allUsers;
9926        boolean[] perUserInstalled;
9927
9928        // First find the old package info and check signatures
9929        synchronized(mPackages) {
9930            oldPackage = mPackages.get(pkgName);
9931            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9932            PackageSetting ps = mSettings.mPackages.get(pkgName);
9933            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9934                // default to original signature matching
9935                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9936                    != PackageManager.SIGNATURE_MATCH) {
9937                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9938                            "New package has a different signature: " + pkgName);
9939                    return;
9940                }
9941            } else {
9942                if(!checkUpgradeKeySetLP(ps, pkg)) {
9943                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9944                            "New package not signed by keys specified by upgrade-keysets: "
9945                            + pkgName);
9946                    return;
9947                }
9948            }
9949
9950            // In case of rollback, remember per-user/profile install state
9951            allUsers = sUserManager.getUserIds();
9952            perUserInstalled = new boolean[allUsers.length];
9953            for (int i = 0; i < allUsers.length; i++) {
9954                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9955            }
9956        }
9957
9958        boolean sysPkg = (isSystemApp(oldPackage));
9959        if (sysPkg) {
9960            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9961                    user, allUsers, perUserInstalled, installerPackageName, res,
9962                    abiOverride);
9963        } else {
9964            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9965                    user, allUsers, perUserInstalled, installerPackageName, res,
9966                    abiOverride);
9967        }
9968    }
9969
9970    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9971            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9972            int[] allUsers, boolean[] perUserInstalled,
9973            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9974        String pkgName = deletedPackage.packageName;
9975        boolean deletedPkg = true;
9976        boolean updatedSettings = false;
9977
9978        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9979                + deletedPackage);
9980        long origUpdateTime;
9981        if (pkg.mExtras != null) {
9982            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9983        } else {
9984            origUpdateTime = 0;
9985        }
9986
9987        // First delete the existing package while retaining the data directory
9988        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9989                res.removedInfo, true)) {
9990            // If the existing package wasn't successfully deleted
9991            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9992            deletedPkg = false;
9993        } else {
9994            // Successfully deleted the old package. Now proceed with re-installation
9995            deleteCodeCacheDirsLI(pkgName);
9996            try {
9997                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9998                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride);
9999                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10000                updatedSettings = true;
10001            } catch (PackageManagerException e) {
10002                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10003            }
10004        }
10005
10006        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10007            // remove package from internal structures.  Note that we want deletePackageX to
10008            // delete the package data and cache directories that it created in
10009            // scanPackageLocked, unless those directories existed before we even tried to
10010            // install.
10011            if(updatedSettings) {
10012                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10013                deletePackageLI(
10014                        pkgName, null, true, allUsers, perUserInstalled,
10015                        PackageManager.DELETE_KEEP_DATA,
10016                                res.removedInfo, true);
10017            }
10018            // Since we failed to install the new package we need to restore the old
10019            // package that we deleted.
10020            if (deletedPkg) {
10021                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10022                File restoreFile = new File(deletedPackage.codePath);
10023                // Parse old package
10024                boolean oldOnSd = isExternal(deletedPackage);
10025                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10026                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10027                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10028                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10029                        | SCAN_UPDATE_TIME;
10030                try {
10031                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null,
10032                            null);
10033                } catch (PackageManagerException e) {
10034                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10035                            + e.getMessage());
10036                    return;
10037                }
10038                // Restore of old package succeeded. Update permissions.
10039                // writer
10040                synchronized (mPackages) {
10041                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10042                            UPDATE_PERMISSIONS_ALL);
10043                    // can downgrade to reader
10044                    mSettings.writeLPr();
10045                }
10046                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10047            }
10048        }
10049    }
10050
10051    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10052            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10053            int[] allUsers, boolean[] perUserInstalled,
10054            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10055        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10056                + ", old=" + deletedPackage);
10057        boolean updatedSettings = false;
10058        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10059                PackageParser.PARSE_IS_SYSTEM;
10060        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10061            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10062        }
10063        String packageName = deletedPackage.packageName;
10064        if (packageName == null) {
10065            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10066                    "Attempt to delete null packageName.");
10067            return;
10068        }
10069        PackageParser.Package oldPkg;
10070        PackageSetting oldPkgSetting;
10071        // reader
10072        synchronized (mPackages) {
10073            oldPkg = mPackages.get(packageName);
10074            oldPkgSetting = mSettings.mPackages.get(packageName);
10075            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10076                    (oldPkgSetting == null)) {
10077                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10078                        "Couldn't find package:" + packageName + " information");
10079                return;
10080            }
10081        }
10082
10083        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10084
10085        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10086        res.removedInfo.removedPackage = packageName;
10087        // Remove existing system package
10088        removePackageLI(oldPkgSetting, true);
10089        // writer
10090        synchronized (mPackages) {
10091            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10092                // We didn't need to disable the .apk as a current system package,
10093                // which means we are replacing another update that is already
10094                // installed.  We need to make sure to delete the older one's .apk.
10095                res.removedInfo.args = createInstallArgsForExisting(0,
10096                        deletedPackage.applicationInfo.getCodePath(),
10097                        deletedPackage.applicationInfo.getResourcePath(),
10098                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10099                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10100                        isMultiArch(deletedPackage.applicationInfo));
10101            } else {
10102                res.removedInfo.args = null;
10103            }
10104        }
10105
10106        // Successfully disabled the old package. Now proceed with re-installation
10107        deleteCodeCacheDirsLI(packageName);
10108
10109        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10110        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10111
10112        PackageParser.Package newPackage = null;
10113        try {
10114            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10115            if (newPackage.mExtras != null) {
10116                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10117                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10118                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10119
10120                // is the update attempting to change shared user? that isn't going to work...
10121                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10122                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10123                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10124                            + " to " + newPkgSetting.sharedUser);
10125                    updatedSettings = true;
10126                }
10127            }
10128
10129            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10130                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10131                updatedSettings = true;
10132            }
10133
10134        } catch (PackageManagerException e) {
10135            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10136        }
10137
10138        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10139            // Re installation failed. Restore old information
10140            // Remove new pkg information
10141            if (newPackage != null) {
10142                removeInstalledPackageLI(newPackage, true);
10143            }
10144            // Add back the old system package
10145            try {
10146                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user,
10147                        null);
10148            } catch (PackageManagerException e) {
10149                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10150            }
10151            // Restore the old system information in Settings
10152            synchronized(mPackages) {
10153                if (updatedSettings) {
10154                    mSettings.enableSystemPackageLPw(packageName);
10155                    mSettings.setInstallerPackageName(packageName,
10156                            oldPkgSetting.installerPackageName);
10157                }
10158                mSettings.writeLPr();
10159            }
10160        }
10161    }
10162
10163    // Utility method used to move dex files during install.
10164    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10165        // TODO: extend to move split APK dex files
10166        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10167            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10168            for (String instructionSet : instructionSets) {
10169                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10170                        instructionSet);
10171                if (retCode != 0) {
10172                /*
10173                 * Programs may be lazily run through dexopt, so the
10174                 * source may not exist. However, something seems to
10175                 * have gone wrong, so note that dexopt needs to be
10176                 * run again and remove the source file. In addition,
10177                 * remove the target to make sure there isn't a stale
10178                 * file from a previous version of the package.
10179                 */
10180                    newPackage.mDexOptPerformed.clear();
10181                    mInstaller.rmdex(oldCodePath, instructionSet);
10182                    mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10183                }
10184            }
10185        }
10186        return PackageManager.INSTALL_SUCCEEDED;
10187    }
10188
10189    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10190            int[] allUsers, boolean[] perUserInstalled,
10191            PackageInstalledInfo res) {
10192        String pkgName = newPackage.packageName;
10193        synchronized (mPackages) {
10194            //write settings. the installStatus will be incomplete at this stage.
10195            //note that the new package setting would have already been
10196            //added to mPackages. It hasn't been persisted yet.
10197            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10198            mSettings.writeLPr();
10199        }
10200
10201        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10202
10203        synchronized (mPackages) {
10204            updatePermissionsLPw(newPackage.packageName, newPackage,
10205                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10206                            ? UPDATE_PERMISSIONS_ALL : 0));
10207            // For system-bundled packages, we assume that installing an upgraded version
10208            // of the package implies that the user actually wants to run that new code,
10209            // so we enable the package.
10210            if (isSystemApp(newPackage)) {
10211                // NB: implicit assumption that system package upgrades apply to all users
10212                if (DEBUG_INSTALL) {
10213                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10214                }
10215                PackageSetting ps = mSettings.mPackages.get(pkgName);
10216                if (ps != null) {
10217                    if (res.origUsers != null) {
10218                        for (int userHandle : res.origUsers) {
10219                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10220                                    userHandle, installerPackageName);
10221                        }
10222                    }
10223                    // Also convey the prior install/uninstall state
10224                    if (allUsers != null && perUserInstalled != null) {
10225                        for (int i = 0; i < allUsers.length; i++) {
10226                            if (DEBUG_INSTALL) {
10227                                Slog.d(TAG, "    user " + allUsers[i]
10228                                        + " => " + perUserInstalled[i]);
10229                            }
10230                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10231                        }
10232                        // these install state changes will be persisted in the
10233                        // upcoming call to mSettings.writeLPr().
10234                    }
10235                }
10236            }
10237            res.name = pkgName;
10238            res.uid = newPackage.applicationInfo.uid;
10239            res.pkg = newPackage;
10240            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10241            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10242            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10243            //to update install status
10244            mSettings.writeLPr();
10245        }
10246    }
10247
10248    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10249        int pFlags = args.flags;
10250        String installerPackageName = args.installerPackageName;
10251        File tmpPackageFile = new File(args.getCodePath());
10252        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10253        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10254        boolean replace = false;
10255        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10256                | (newInstall ? SCAN_NEW_INSTALL : 0);
10257        // Result object to be returned
10258        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10259
10260        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10261        // Retrieve PackageSettings and parse package
10262        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10263                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10264                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10265        PackageParser pp = new PackageParser();
10266        pp.setSeparateProcesses(mSeparateProcesses);
10267        pp.setDisplayMetrics(mMetrics);
10268
10269        final PackageParser.Package pkg;
10270        try {
10271            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10272        } catch (PackageParserException e) {
10273            res.setError("Failed parse during installPackageLI", e);
10274            return;
10275        }
10276
10277        String pkgName = res.name = pkg.packageName;
10278        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10279            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10280                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10281                return;
10282            }
10283        }
10284
10285        try {
10286            pp.collectCertificates(pkg, parseFlags);
10287            pp.collectManifestDigest(pkg);
10288        } catch (PackageParserException e) {
10289            res.setError("Failed collect during installPackageLI", e);
10290            return;
10291        }
10292
10293        /* If the installer passed in a manifest digest, compare it now. */
10294        if (args.manifestDigest != null) {
10295            if (DEBUG_INSTALL) {
10296                final String parsedManifest = pkg.manifestDigest == null ? "null"
10297                        : pkg.manifestDigest.toString();
10298                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10299                        + parsedManifest);
10300            }
10301
10302            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10303                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10304                return;
10305            }
10306        } else if (DEBUG_INSTALL) {
10307            final String parsedManifest = pkg.manifestDigest == null
10308                    ? "null" : pkg.manifestDigest.toString();
10309            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10310        }
10311
10312        // Get rid of all references to package scan path via parser.
10313        pp = null;
10314        String oldCodePath = null;
10315        boolean systemApp = false;
10316        synchronized (mPackages) {
10317            // Check whether the newly-scanned package wants to define an already-defined perm
10318            int N = pkg.permissions.size();
10319            for (int i = N-1; i >= 0; i--) {
10320                PackageParser.Permission perm = pkg.permissions.get(i);
10321                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10322                if (bp != null) {
10323                    // If the defining package is signed with our cert, it's okay.  This
10324                    // also includes the "updating the same package" case, of course.
10325                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10326                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10327                        // If the owning package is the system itself, we log but allow
10328                        // install to proceed; we fail the install on all other permission
10329                        // redefinitions.
10330                        if (!bp.sourcePackage.equals("android")) {
10331                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10332                                    + pkg.packageName + " attempting to redeclare permission "
10333                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10334                            res.origPermission = perm.info.name;
10335                            res.origPackage = bp.sourcePackage;
10336                            return;
10337                        } else {
10338                            Slog.w(TAG, "Package " + pkg.packageName
10339                                    + " attempting to redeclare system permission "
10340                                    + perm.info.name + "; ignoring new declaration");
10341                            pkg.permissions.remove(i);
10342                        }
10343                    }
10344                }
10345            }
10346
10347            // Check if installing already existing package
10348            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10349                String oldName = mSettings.mRenamedPackages.get(pkgName);
10350                if (pkg.mOriginalPackages != null
10351                        && pkg.mOriginalPackages.contains(oldName)
10352                        && mPackages.containsKey(oldName)) {
10353                    // This package is derived from an original package,
10354                    // and this device has been updating from that original
10355                    // name.  We must continue using the original name, so
10356                    // rename the new package here.
10357                    pkg.setPackageName(oldName);
10358                    pkgName = pkg.packageName;
10359                    replace = true;
10360                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10361                            + oldName + " pkgName=" + pkgName);
10362                } else if (mPackages.containsKey(pkgName)) {
10363                    // This package, under its official name, already exists
10364                    // on the device; we should replace it.
10365                    replace = true;
10366                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10367                }
10368            }
10369            PackageSetting ps = mSettings.mPackages.get(pkgName);
10370            if (ps != null) {
10371                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10372                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10373                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10374                    systemApp = (ps.pkg.applicationInfo.flags &
10375                            ApplicationInfo.FLAG_SYSTEM) != 0;
10376                }
10377                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10378            }
10379        }
10380
10381        if (systemApp && onSd) {
10382            // Disable updates to system apps on sdcard
10383            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10384                    "Cannot install updates to system apps on sdcard");
10385            return;
10386        }
10387
10388        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10389            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10390            return;
10391        }
10392
10393        if (replace) {
10394            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10395                    installerPackageName, res, args.abiOverride);
10396        } else {
10397            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10398                    installerPackageName, res, args.abiOverride);
10399        }
10400        synchronized (mPackages) {
10401            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10402            if (ps != null) {
10403                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10404            }
10405        }
10406    }
10407
10408    private static boolean isForwardLocked(PackageParser.Package pkg) {
10409        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10410    }
10411
10412    private static boolean isForwardLocked(ApplicationInfo info) {
10413        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10414    }
10415
10416    private boolean isForwardLocked(PackageSetting ps) {
10417        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10418    }
10419
10420    private static boolean isMultiArch(PackageSetting ps) {
10421        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10422    }
10423
10424    private static boolean isMultiArch(ApplicationInfo info) {
10425        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10426    }
10427
10428    private static boolean isExternal(PackageParser.Package pkg) {
10429        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10430    }
10431
10432    private static boolean isExternal(PackageSetting ps) {
10433        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10434    }
10435
10436    private static boolean isExternal(ApplicationInfo info) {
10437        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10438    }
10439
10440    private static boolean isSystemApp(PackageParser.Package pkg) {
10441        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10442    }
10443
10444    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10445        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10446    }
10447
10448    private static boolean isSystemApp(ApplicationInfo info) {
10449        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10450    }
10451
10452    private static boolean isSystemApp(PackageSetting ps) {
10453        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10454    }
10455
10456    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10457        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10458    }
10459
10460    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10461        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10462    }
10463
10464    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10465        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10466    }
10467
10468    private int packageFlagsToInstallFlags(PackageSetting ps) {
10469        int installFlags = 0;
10470        if (isExternal(ps)) {
10471            installFlags |= PackageManager.INSTALL_EXTERNAL;
10472        }
10473        if (isForwardLocked(ps)) {
10474            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10475        }
10476        return installFlags;
10477    }
10478
10479    private void deleteTempPackageFiles() {
10480        final FilenameFilter filter = new FilenameFilter() {
10481            public boolean accept(File dir, String name) {
10482                return name.startsWith("vmdl") && name.endsWith(".tmp");
10483            }
10484        };
10485        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10486            file.delete();
10487        }
10488    }
10489
10490    @Override
10491    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10492            int flags) {
10493        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10494                flags);
10495    }
10496
10497    @Override
10498    public void deletePackage(final String packageName,
10499            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10500        mContext.enforceCallingOrSelfPermission(
10501                android.Manifest.permission.DELETE_PACKAGES, null);
10502        final int uid = Binder.getCallingUid();
10503        if (UserHandle.getUserId(uid) != userId) {
10504            mContext.enforceCallingPermission(
10505                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10506                    "deletePackage for user " + userId);
10507        }
10508        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10509            try {
10510                observer.onPackageDeleted(packageName,
10511                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10512            } catch (RemoteException re) {
10513            }
10514            return;
10515        }
10516
10517        boolean uninstallBlocked = false;
10518        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10519            int[] users = sUserManager.getUserIds();
10520            for (int i = 0; i < users.length; ++i) {
10521                if (getBlockUninstallForUser(packageName, users[i])) {
10522                    uninstallBlocked = true;
10523                    break;
10524                }
10525            }
10526        } else {
10527            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10528        }
10529        if (uninstallBlocked) {
10530            try {
10531                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10532                        null);
10533            } catch (RemoteException re) {
10534            }
10535            return;
10536        }
10537
10538        if (DEBUG_REMOVE) {
10539            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10540        }
10541        // Queue up an async operation since the package deletion may take a little while.
10542        mHandler.post(new Runnable() {
10543            public void run() {
10544                mHandler.removeCallbacks(this);
10545                final int returnCode = deletePackageX(packageName, userId, flags);
10546                if (observer != null) {
10547                    try {
10548                        observer.onPackageDeleted(packageName, returnCode, null);
10549                    } catch (RemoteException e) {
10550                        Log.i(TAG, "Observer no longer exists.");
10551                    } //end catch
10552                } //end if
10553            } //end run
10554        });
10555    }
10556
10557    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10558        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10559                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10560        try {
10561            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10562                    || dpm.isDeviceOwner(packageName))) {
10563                return true;
10564            }
10565        } catch (RemoteException e) {
10566        }
10567        return false;
10568    }
10569
10570    /**
10571     *  This method is an internal method that could be get invoked either
10572     *  to delete an installed package or to clean up a failed installation.
10573     *  After deleting an installed package, a broadcast is sent to notify any
10574     *  listeners that the package has been installed. For cleaning up a failed
10575     *  installation, the broadcast is not necessary since the package's
10576     *  installation wouldn't have sent the initial broadcast either
10577     *  The key steps in deleting a package are
10578     *  deleting the package information in internal structures like mPackages,
10579     *  deleting the packages base directories through installd
10580     *  updating mSettings to reflect current status
10581     *  persisting settings for later use
10582     *  sending a broadcast if necessary
10583     */
10584    private int deletePackageX(String packageName, int userId, int flags) {
10585        final PackageRemovedInfo info = new PackageRemovedInfo();
10586        final boolean res;
10587
10588        if (isPackageDeviceAdmin(packageName, userId)) {
10589            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10590            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10591        }
10592
10593        boolean removedForAllUsers = false;
10594        boolean systemUpdate = false;
10595
10596        // for the uninstall-updates case and restricted profiles, remember the per-
10597        // userhandle installed state
10598        int[] allUsers;
10599        boolean[] perUserInstalled;
10600        synchronized (mPackages) {
10601            PackageSetting ps = mSettings.mPackages.get(packageName);
10602            allUsers = sUserManager.getUserIds();
10603            perUserInstalled = new boolean[allUsers.length];
10604            for (int i = 0; i < allUsers.length; i++) {
10605                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10606            }
10607        }
10608
10609        synchronized (mInstallLock) {
10610            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10611            res = deletePackageLI(packageName,
10612                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10613                            ? UserHandle.ALL : new UserHandle(userId),
10614                    true, allUsers, perUserInstalled,
10615                    flags | REMOVE_CHATTY, info, true);
10616            systemUpdate = info.isRemovedPackageSystemUpdate;
10617            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10618                removedForAllUsers = true;
10619            }
10620            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10621                    + " removedForAllUsers=" + removedForAllUsers);
10622        }
10623
10624        if (res) {
10625            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10626
10627            // If the removed package was a system update, the old system package
10628            // was re-enabled; we need to broadcast this information
10629            if (systemUpdate) {
10630                Bundle extras = new Bundle(1);
10631                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10632                        ? info.removedAppId : info.uid);
10633                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10634
10635                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10636                        extras, null, null, null);
10637                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10638                        extras, null, null, null);
10639                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10640                        null, packageName, null, null);
10641            }
10642        }
10643        // Force a gc here.
10644        Runtime.getRuntime().gc();
10645        // Delete the resources here after sending the broadcast to let
10646        // other processes clean up before deleting resources.
10647        if (info.args != null) {
10648            synchronized (mInstallLock) {
10649                info.args.doPostDeleteLI(true);
10650            }
10651        }
10652
10653        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10654    }
10655
10656    static class PackageRemovedInfo {
10657        String removedPackage;
10658        int uid = -1;
10659        int removedAppId = -1;
10660        int[] removedUsers = null;
10661        boolean isRemovedPackageSystemUpdate = false;
10662        // Clean up resources deleted packages.
10663        InstallArgs args = null;
10664
10665        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10666            Bundle extras = new Bundle(1);
10667            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10668            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10669            if (replacing) {
10670                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10671            }
10672            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10673            if (removedPackage != null) {
10674                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10675                        extras, null, null, removedUsers);
10676                if (fullRemove && !replacing) {
10677                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10678                            extras, null, null, removedUsers);
10679                }
10680            }
10681            if (removedAppId >= 0) {
10682                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10683                        removedUsers);
10684            }
10685        }
10686    }
10687
10688    /*
10689     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10690     * flag is not set, the data directory is removed as well.
10691     * make sure this flag is set for partially installed apps. If not its meaningless to
10692     * delete a partially installed application.
10693     */
10694    private void removePackageDataLI(PackageSetting ps,
10695            int[] allUserHandles, boolean[] perUserInstalled,
10696            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10697        String packageName = ps.name;
10698        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10699        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10700        // Retrieve object to delete permissions for shared user later on
10701        final PackageSetting deletedPs;
10702        // reader
10703        synchronized (mPackages) {
10704            deletedPs = mSettings.mPackages.get(packageName);
10705            if (outInfo != null) {
10706                outInfo.removedPackage = packageName;
10707                outInfo.removedUsers = deletedPs != null
10708                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10709                        : null;
10710            }
10711        }
10712        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10713            removeDataDirsLI(packageName);
10714            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10715        }
10716        // writer
10717        synchronized (mPackages) {
10718            if (deletedPs != null) {
10719                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10720                    if (outInfo != null) {
10721                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10722                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10723                    }
10724                    if (deletedPs != null) {
10725                        updatePermissionsLPw(deletedPs.name, null, 0);
10726                        if (deletedPs.sharedUser != null) {
10727                            // remove permissions associated with package
10728                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10729                        }
10730                    }
10731                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10732                }
10733                // make sure to preserve per-user disabled state if this removal was just
10734                // a downgrade of a system app to the factory package
10735                if (allUserHandles != null && perUserInstalled != null) {
10736                    if (DEBUG_REMOVE) {
10737                        Slog.d(TAG, "Propagating install state across downgrade");
10738                    }
10739                    for (int i = 0; i < allUserHandles.length; i++) {
10740                        if (DEBUG_REMOVE) {
10741                            Slog.d(TAG, "    user " + allUserHandles[i]
10742                                    + " => " + perUserInstalled[i]);
10743                        }
10744                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10745                    }
10746                }
10747            }
10748            // can downgrade to reader
10749            if (writeSettings) {
10750                // Save settings now
10751                mSettings.writeLPr();
10752            }
10753        }
10754        if (outInfo != null) {
10755            // A user ID was deleted here. Go through all users and remove it
10756            // from KeyStore.
10757            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10758        }
10759    }
10760
10761    static boolean locationIsPrivileged(File path) {
10762        try {
10763            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10764                    .getCanonicalPath();
10765            return path.getCanonicalPath().startsWith(privilegedAppDir);
10766        } catch (IOException e) {
10767            Slog.e(TAG, "Unable to access code path " + path);
10768        }
10769        return false;
10770    }
10771
10772    /*
10773     * Tries to delete system package.
10774     */
10775    private boolean deleteSystemPackageLI(PackageSetting newPs,
10776            int[] allUserHandles, boolean[] perUserInstalled,
10777            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10778        final boolean applyUserRestrictions
10779                = (allUserHandles != null) && (perUserInstalled != null);
10780        PackageSetting disabledPs = null;
10781        // Confirm if the system package has been updated
10782        // An updated system app can be deleted. This will also have to restore
10783        // the system pkg from system partition
10784        // reader
10785        synchronized (mPackages) {
10786            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10787        }
10788        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10789                + " disabledPs=" + disabledPs);
10790        if (disabledPs == null) {
10791            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10792            return false;
10793        } else if (DEBUG_REMOVE) {
10794            Slog.d(TAG, "Deleting system pkg from data partition");
10795        }
10796        if (DEBUG_REMOVE) {
10797            if (applyUserRestrictions) {
10798                Slog.d(TAG, "Remembering install states:");
10799                for (int i = 0; i < allUserHandles.length; i++) {
10800                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10801                }
10802            }
10803        }
10804        // Delete the updated package
10805        outInfo.isRemovedPackageSystemUpdate = true;
10806        if (disabledPs.versionCode < newPs.versionCode) {
10807            // Delete data for downgrades
10808            flags &= ~PackageManager.DELETE_KEEP_DATA;
10809        } else {
10810            // Preserve data by setting flag
10811            flags |= PackageManager.DELETE_KEEP_DATA;
10812        }
10813        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10814                allUserHandles, perUserInstalled, outInfo, writeSettings);
10815        if (!ret) {
10816            return false;
10817        }
10818        // writer
10819        synchronized (mPackages) {
10820            // Reinstate the old system package
10821            mSettings.enableSystemPackageLPw(newPs.name);
10822            // Remove any native libraries from the upgraded package.
10823            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10824        }
10825        // Install the system package
10826        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10827        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10828        if (locationIsPrivileged(disabledPs.codePath)) {
10829            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10830        }
10831
10832        final PackageParser.Package newPkg;
10833        try {
10834            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0,
10835                    null, null);
10836        } catch (PackageManagerException e) {
10837            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10838            return false;
10839        }
10840
10841        // writer
10842        synchronized (mPackages) {
10843            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10844            updatePermissionsLPw(newPkg.packageName, newPkg,
10845                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10846            if (applyUserRestrictions) {
10847                if (DEBUG_REMOVE) {
10848                    Slog.d(TAG, "Propagating install state across reinstall");
10849                }
10850                for (int i = 0; i < allUserHandles.length; i++) {
10851                    if (DEBUG_REMOVE) {
10852                        Slog.d(TAG, "    user " + allUserHandles[i]
10853                                + " => " + perUserInstalled[i]);
10854                    }
10855                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10856                }
10857                // Regardless of writeSettings we need to ensure that this restriction
10858                // state propagation is persisted
10859                mSettings.writeAllUsersPackageRestrictionsLPr();
10860            }
10861            // can downgrade to reader here
10862            if (writeSettings) {
10863                mSettings.writeLPr();
10864            }
10865        }
10866        return true;
10867    }
10868
10869    private boolean deleteInstalledPackageLI(PackageSetting ps,
10870            boolean deleteCodeAndResources, int flags,
10871            int[] allUserHandles, boolean[] perUserInstalled,
10872            PackageRemovedInfo outInfo, boolean writeSettings) {
10873        if (outInfo != null) {
10874            outInfo.uid = ps.appId;
10875        }
10876
10877        // Delete package data from internal structures and also remove data if flag is set
10878        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10879
10880        // Delete application code and resources
10881        if (deleteCodeAndResources && (outInfo != null)) {
10882            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10883                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10884                    getAppDexInstructionSets(ps), isMultiArch(ps));
10885        }
10886        return true;
10887    }
10888
10889    @Override
10890    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10891            int userId) {
10892        mContext.enforceCallingOrSelfPermission(
10893                android.Manifest.permission.DELETE_PACKAGES, null);
10894        synchronized (mPackages) {
10895            PackageSetting ps = mSettings.mPackages.get(packageName);
10896            if (ps == null) {
10897                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10898                return false;
10899            }
10900            if (!ps.getInstalled(userId)) {
10901                // Can't block uninstall for an app that is not installed or enabled.
10902                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10903                return false;
10904            }
10905            ps.setBlockUninstall(blockUninstall, userId);
10906            mSettings.writePackageRestrictionsLPr(userId);
10907        }
10908        return true;
10909    }
10910
10911    @Override
10912    public boolean getBlockUninstallForUser(String packageName, int userId) {
10913        synchronized (mPackages) {
10914            PackageSetting ps = mSettings.mPackages.get(packageName);
10915            if (ps == null) {
10916                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10917                return false;
10918            }
10919            return ps.getBlockUninstall(userId);
10920        }
10921    }
10922
10923    /*
10924     * This method handles package deletion in general
10925     */
10926    private boolean deletePackageLI(String packageName, UserHandle user,
10927            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10928            int flags, PackageRemovedInfo outInfo,
10929            boolean writeSettings) {
10930        if (packageName == null) {
10931            Slog.w(TAG, "Attempt to delete null packageName.");
10932            return false;
10933        }
10934        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10935        PackageSetting ps;
10936        boolean dataOnly = false;
10937        int removeUser = -1;
10938        int appId = -1;
10939        synchronized (mPackages) {
10940            ps = mSettings.mPackages.get(packageName);
10941            if (ps == null) {
10942                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10943                return false;
10944            }
10945            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10946                    && user.getIdentifier() != UserHandle.USER_ALL) {
10947                // The caller is asking that the package only be deleted for a single
10948                // user.  To do this, we just mark its uninstalled state and delete
10949                // its data.  If this is a system app, we only allow this to happen if
10950                // they have set the special DELETE_SYSTEM_APP which requests different
10951                // semantics than normal for uninstalling system apps.
10952                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10953                ps.setUserState(user.getIdentifier(),
10954                        COMPONENT_ENABLED_STATE_DEFAULT,
10955                        false, //installed
10956                        true,  //stopped
10957                        true,  //notLaunched
10958                        false, //hidden
10959                        null, null, null,
10960                        false // blockUninstall
10961                        );
10962                if (!isSystemApp(ps)) {
10963                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10964                        // Other user still have this package installed, so all
10965                        // we need to do is clear this user's data and save that
10966                        // it is uninstalled.
10967                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10968                        removeUser = user.getIdentifier();
10969                        appId = ps.appId;
10970                        mSettings.writePackageRestrictionsLPr(removeUser);
10971                    } else {
10972                        // We need to set it back to 'installed' so the uninstall
10973                        // broadcasts will be sent correctly.
10974                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10975                        ps.setInstalled(true, user.getIdentifier());
10976                    }
10977                } else {
10978                    // This is a system app, so we assume that the
10979                    // other users still have this package installed, so all
10980                    // we need to do is clear this user's data and save that
10981                    // it is uninstalled.
10982                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10983                    removeUser = user.getIdentifier();
10984                    appId = ps.appId;
10985                    mSettings.writePackageRestrictionsLPr(removeUser);
10986                }
10987            }
10988        }
10989
10990        if (removeUser >= 0) {
10991            // From above, we determined that we are deleting this only
10992            // for a single user.  Continue the work here.
10993            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10994            if (outInfo != null) {
10995                outInfo.removedPackage = packageName;
10996                outInfo.removedAppId = appId;
10997                outInfo.removedUsers = new int[] {removeUser};
10998            }
10999            mInstaller.clearUserData(packageName, removeUser);
11000            removeKeystoreDataIfNeeded(removeUser, appId);
11001            schedulePackageCleaning(packageName, removeUser, false);
11002            return true;
11003        }
11004
11005        if (dataOnly) {
11006            // Delete application data first
11007            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11008            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11009            return true;
11010        }
11011
11012        boolean ret = false;
11013        if (isSystemApp(ps)) {
11014            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11015            // When an updated system application is deleted we delete the existing resources as well and
11016            // fall back to existing code in system partition
11017            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11018                    flags, outInfo, writeSettings);
11019        } else {
11020            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11021            // Kill application pre-emptively especially for apps on sd.
11022            killApplication(packageName, ps.appId, "uninstall pkg");
11023            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11024                    allUserHandles, perUserInstalled,
11025                    outInfo, writeSettings);
11026        }
11027
11028        return ret;
11029    }
11030
11031    private final class ClearStorageConnection implements ServiceConnection {
11032        IMediaContainerService mContainerService;
11033
11034        @Override
11035        public void onServiceConnected(ComponentName name, IBinder service) {
11036            synchronized (this) {
11037                mContainerService = IMediaContainerService.Stub.asInterface(service);
11038                notifyAll();
11039            }
11040        }
11041
11042        @Override
11043        public void onServiceDisconnected(ComponentName name) {
11044        }
11045    }
11046
11047    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11048        final boolean mounted;
11049        if (Environment.isExternalStorageEmulated()) {
11050            mounted = true;
11051        } else {
11052            final String status = Environment.getExternalStorageState();
11053
11054            mounted = status.equals(Environment.MEDIA_MOUNTED)
11055                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11056        }
11057
11058        if (!mounted) {
11059            return;
11060        }
11061
11062        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11063        int[] users;
11064        if (userId == UserHandle.USER_ALL) {
11065            users = sUserManager.getUserIds();
11066        } else {
11067            users = new int[] { userId };
11068        }
11069        final ClearStorageConnection conn = new ClearStorageConnection();
11070        if (mContext.bindServiceAsUser(
11071                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11072            try {
11073                for (int curUser : users) {
11074                    long timeout = SystemClock.uptimeMillis() + 5000;
11075                    synchronized (conn) {
11076                        long now = SystemClock.uptimeMillis();
11077                        while (conn.mContainerService == null && now < timeout) {
11078                            try {
11079                                conn.wait(timeout - now);
11080                            } catch (InterruptedException e) {
11081                            }
11082                        }
11083                    }
11084                    if (conn.mContainerService == null) {
11085                        return;
11086                    }
11087
11088                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11089                    clearDirectory(conn.mContainerService,
11090                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11091                    if (allData) {
11092                        clearDirectory(conn.mContainerService,
11093                                userEnv.buildExternalStorageAppDataDirs(packageName));
11094                        clearDirectory(conn.mContainerService,
11095                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11096                    }
11097                }
11098            } finally {
11099                mContext.unbindService(conn);
11100            }
11101        }
11102    }
11103
11104    @Override
11105    public void clearApplicationUserData(final String packageName,
11106            final IPackageDataObserver observer, final int userId) {
11107        mContext.enforceCallingOrSelfPermission(
11108                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11109        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11110        // Queue up an async operation since the package deletion may take a little while.
11111        mHandler.post(new Runnable() {
11112            public void run() {
11113                mHandler.removeCallbacks(this);
11114                final boolean succeeded;
11115                synchronized (mInstallLock) {
11116                    succeeded = clearApplicationUserDataLI(packageName, userId);
11117                }
11118                clearExternalStorageDataSync(packageName, userId, true);
11119                if (succeeded) {
11120                    // invoke DeviceStorageMonitor's update method to clear any notifications
11121                    DeviceStorageMonitorInternal
11122                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11123                    if (dsm != null) {
11124                        dsm.checkMemory();
11125                    }
11126                }
11127                if(observer != null) {
11128                    try {
11129                        observer.onRemoveCompleted(packageName, succeeded);
11130                    } catch (RemoteException e) {
11131                        Log.i(TAG, "Observer no longer exists.");
11132                    }
11133                } //end if observer
11134            } //end run
11135        });
11136    }
11137
11138    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11139        if (packageName == null) {
11140            Slog.w(TAG, "Attempt to delete null packageName.");
11141            return false;
11142        }
11143        PackageParser.Package p;
11144        boolean dataOnly = false;
11145        final int appId;
11146        synchronized (mPackages) {
11147            p = mPackages.get(packageName);
11148            if (p == null) {
11149                dataOnly = true;
11150                PackageSetting ps = mSettings.mPackages.get(packageName);
11151                if ((ps == null) || (ps.pkg == null)) {
11152                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11153                    return false;
11154                }
11155                p = ps.pkg;
11156            }
11157            if (!dataOnly) {
11158                // need to check this only for fully installed applications
11159                if (p == null) {
11160                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11161                    return false;
11162                }
11163                final ApplicationInfo applicationInfo = p.applicationInfo;
11164                if (applicationInfo == null) {
11165                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11166                    return false;
11167                }
11168            }
11169            if (p != null && p.applicationInfo != null) {
11170                appId = p.applicationInfo.uid;
11171            } else {
11172                appId = -1;
11173            }
11174        }
11175        int retCode = mInstaller.clearUserData(packageName, userId);
11176        if (retCode < 0) {
11177            Slog.w(TAG, "Couldn't remove cache files for package: "
11178                    + packageName);
11179            return false;
11180        }
11181        removeKeystoreDataIfNeeded(userId, appId);
11182        return true;
11183    }
11184
11185    /**
11186     * Remove entries from the keystore daemon. Will only remove it if the
11187     * {@code appId} is valid.
11188     */
11189    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11190        if (appId < 0) {
11191            return;
11192        }
11193
11194        final KeyStore keyStore = KeyStore.getInstance();
11195        if (keyStore != null) {
11196            if (userId == UserHandle.USER_ALL) {
11197                for (final int individual : sUserManager.getUserIds()) {
11198                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11199                }
11200            } else {
11201                keyStore.clearUid(UserHandle.getUid(userId, appId));
11202            }
11203        } else {
11204            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11205        }
11206    }
11207
11208    @Override
11209    public void deleteApplicationCacheFiles(final String packageName,
11210            final IPackageDataObserver observer) {
11211        mContext.enforceCallingOrSelfPermission(
11212                android.Manifest.permission.DELETE_CACHE_FILES, null);
11213        // Queue up an async operation since the package deletion may take a little while.
11214        final int userId = UserHandle.getCallingUserId();
11215        mHandler.post(new Runnable() {
11216            public void run() {
11217                mHandler.removeCallbacks(this);
11218                final boolean succeded;
11219                synchronized (mInstallLock) {
11220                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11221                }
11222                clearExternalStorageDataSync(packageName, userId, false);
11223                if(observer != null) {
11224                    try {
11225                        observer.onRemoveCompleted(packageName, succeded);
11226                    } catch (RemoteException e) {
11227                        Log.i(TAG, "Observer no longer exists.");
11228                    }
11229                } //end if observer
11230            } //end run
11231        });
11232    }
11233
11234    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11235        if (packageName == null) {
11236            Slog.w(TAG, "Attempt to delete null packageName.");
11237            return false;
11238        }
11239        PackageParser.Package p;
11240        synchronized (mPackages) {
11241            p = mPackages.get(packageName);
11242        }
11243        if (p == null) {
11244            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11245            return false;
11246        }
11247        final ApplicationInfo applicationInfo = p.applicationInfo;
11248        if (applicationInfo == null) {
11249            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11250            return false;
11251        }
11252        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11253        if (retCode < 0) {
11254            Slog.w(TAG, "Couldn't remove cache files for package: "
11255                       + packageName + " u" + userId);
11256            return false;
11257        }
11258        return true;
11259    }
11260
11261    @Override
11262    public void getPackageSizeInfo(final String packageName, int userHandle,
11263            final IPackageStatsObserver observer) {
11264        mContext.enforceCallingOrSelfPermission(
11265                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11266        if (packageName == null) {
11267            throw new IllegalArgumentException("Attempt to get size of null packageName");
11268        }
11269
11270        PackageStats stats = new PackageStats(packageName, userHandle);
11271
11272        /*
11273         * Queue up an async operation since the package measurement may take a
11274         * little while.
11275         */
11276        Message msg = mHandler.obtainMessage(INIT_COPY);
11277        msg.obj = new MeasureParams(stats, observer);
11278        mHandler.sendMessage(msg);
11279    }
11280
11281    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11282            PackageStats pStats) {
11283        if (packageName == null) {
11284            Slog.w(TAG, "Attempt to get size of null packageName.");
11285            return false;
11286        }
11287        PackageParser.Package p;
11288        boolean dataOnly = false;
11289        String libDirRoot = null;
11290        String asecPath = null;
11291        PackageSetting ps = null;
11292        synchronized (mPackages) {
11293            p = mPackages.get(packageName);
11294            ps = mSettings.mPackages.get(packageName);
11295            if(p == null) {
11296                dataOnly = true;
11297                if((ps == null) || (ps.pkg == null)) {
11298                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11299                    return false;
11300                }
11301                p = ps.pkg;
11302            }
11303            if (ps != null) {
11304                libDirRoot = ps.legacyNativeLibraryPathString;
11305            }
11306            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11307                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11308                if (secureContainerId != null) {
11309                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11310                }
11311            }
11312        }
11313        String publicSrcDir = null;
11314        if(!dataOnly) {
11315            final ApplicationInfo applicationInfo = p.applicationInfo;
11316            if (applicationInfo == null) {
11317                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11318                return false;
11319            }
11320            if (isForwardLocked(p)) {
11321                publicSrcDir = applicationInfo.getBaseResourcePath();
11322            }
11323        }
11324        // TODO: extend to measure size of split APKs
11325        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11326        // not just the first level.
11327        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11328        // just the primary.
11329        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11330                publicSrcDir, asecPath, getAppDexInstructionSets(ps),
11331                pStats);
11332        if (res < 0) {
11333            return false;
11334        }
11335
11336        // Fix-up for forward-locked applications in ASEC containers.
11337        if (!isExternal(p)) {
11338            pStats.codeSize += pStats.externalCodeSize;
11339            pStats.externalCodeSize = 0L;
11340        }
11341
11342        return true;
11343    }
11344
11345
11346    @Override
11347    public void addPackageToPreferred(String packageName) {
11348        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11349    }
11350
11351    @Override
11352    public void removePackageFromPreferred(String packageName) {
11353        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11354    }
11355
11356    @Override
11357    public List<PackageInfo> getPreferredPackages(int flags) {
11358        return new ArrayList<PackageInfo>();
11359    }
11360
11361    private int getUidTargetSdkVersionLockedLPr(int uid) {
11362        Object obj = mSettings.getUserIdLPr(uid);
11363        if (obj instanceof SharedUserSetting) {
11364            final SharedUserSetting sus = (SharedUserSetting) obj;
11365            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11366            final Iterator<PackageSetting> it = sus.packages.iterator();
11367            while (it.hasNext()) {
11368                final PackageSetting ps = it.next();
11369                if (ps.pkg != null) {
11370                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11371                    if (v < vers) vers = v;
11372                }
11373            }
11374            return vers;
11375        } else if (obj instanceof PackageSetting) {
11376            final PackageSetting ps = (PackageSetting) obj;
11377            if (ps.pkg != null) {
11378                return ps.pkg.applicationInfo.targetSdkVersion;
11379            }
11380        }
11381        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11382    }
11383
11384    @Override
11385    public void addPreferredActivity(IntentFilter filter, int match,
11386            ComponentName[] set, ComponentName activity, int userId) {
11387        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11388    }
11389
11390    private void addPreferredActivityInternal(IntentFilter filter, int match,
11391            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11392        // writer
11393        int callingUid = Binder.getCallingUid();
11394        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11395        if (filter.countActions() == 0) {
11396            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11397            return;
11398        }
11399        synchronized (mPackages) {
11400            if (mContext.checkCallingOrSelfPermission(
11401                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11402                    != PackageManager.PERMISSION_GRANTED) {
11403                if (getUidTargetSdkVersionLockedLPr(callingUid)
11404                        < Build.VERSION_CODES.FROYO) {
11405                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11406                            + callingUid);
11407                    return;
11408                }
11409                mContext.enforceCallingOrSelfPermission(
11410                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11411            }
11412
11413            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11414            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11415            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11416                    new PreferredActivity(filter, match, set, activity, always));
11417            mSettings.writePackageRestrictionsLPr(userId);
11418        }
11419    }
11420
11421    @Override
11422    public void replacePreferredActivity(IntentFilter filter, int match,
11423            ComponentName[] set, ComponentName activity, int userId) {
11424        if (filter.countActions() != 1) {
11425            throw new IllegalArgumentException(
11426                    "replacePreferredActivity expects filter to have only 1 action.");
11427        }
11428        if (filter.countDataAuthorities() != 0
11429                || filter.countDataPaths() != 0
11430                || filter.countDataSchemes() > 1
11431                || filter.countDataTypes() != 0) {
11432            throw new IllegalArgumentException(
11433                    "replacePreferredActivity expects filter to have no data authorities, " +
11434                    "paths, or types; and at most one scheme.");
11435        }
11436
11437        final int callingUid = Binder.getCallingUid();
11438        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11439        final int callingUserId = UserHandle.getUserId(callingUid);
11440        synchronized (mPackages) {
11441            if (mContext.checkCallingOrSelfPermission(
11442                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11443                    != PackageManager.PERMISSION_GRANTED) {
11444                if (getUidTargetSdkVersionLockedLPr(callingUid)
11445                        < Build.VERSION_CODES.FROYO) {
11446                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11447                            + Binder.getCallingUid());
11448                    return;
11449                }
11450                mContext.enforceCallingOrSelfPermission(
11451                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11452            }
11453
11454            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11455            if (pir != null) {
11456                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11457                if (filter.countDataSchemes() == 1) {
11458                    Uri.Builder builder = new Uri.Builder();
11459                    builder.scheme(filter.getDataScheme(0));
11460                    intent.setData(builder.build());
11461                }
11462                List<PreferredActivity> matches = pir.queryIntent(
11463                        intent, null, true, callingUserId);
11464                if (DEBUG_PREFERRED) {
11465                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11466                }
11467                for (int i = 0; i < matches.size(); i++) {
11468                    PreferredActivity pa = matches.get(i);
11469                    if (DEBUG_PREFERRED) {
11470                        Slog.i(TAG, "Removing preferred activity "
11471                                + pa.mPref.mComponent + ":");
11472                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11473                    }
11474                    pir.removeFilter(pa);
11475                }
11476            }
11477            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11478        }
11479    }
11480
11481    @Override
11482    public void clearPackagePreferredActivities(String packageName) {
11483        final int uid = Binder.getCallingUid();
11484        // writer
11485        synchronized (mPackages) {
11486            PackageParser.Package pkg = mPackages.get(packageName);
11487            if (pkg == null || pkg.applicationInfo.uid != uid) {
11488                if (mContext.checkCallingOrSelfPermission(
11489                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11490                        != PackageManager.PERMISSION_GRANTED) {
11491                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11492                            < Build.VERSION_CODES.FROYO) {
11493                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11494                                + Binder.getCallingUid());
11495                        return;
11496                    }
11497                    mContext.enforceCallingOrSelfPermission(
11498                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11499                }
11500            }
11501
11502            int user = UserHandle.getCallingUserId();
11503            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11504                mSettings.writePackageRestrictionsLPr(user);
11505                scheduleWriteSettingsLocked();
11506            }
11507        }
11508    }
11509
11510    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11511    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11512        ArrayList<PreferredActivity> removed = null;
11513        boolean changed = false;
11514        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11515            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11516            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11517            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11518                continue;
11519            }
11520            Iterator<PreferredActivity> it = pir.filterIterator();
11521            while (it.hasNext()) {
11522                PreferredActivity pa = it.next();
11523                // Mark entry for removal only if it matches the package name
11524                // and the entry is of type "always".
11525                if (packageName == null ||
11526                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11527                                && pa.mPref.mAlways)) {
11528                    if (removed == null) {
11529                        removed = new ArrayList<PreferredActivity>();
11530                    }
11531                    removed.add(pa);
11532                }
11533            }
11534            if (removed != null) {
11535                for (int j=0; j<removed.size(); j++) {
11536                    PreferredActivity pa = removed.get(j);
11537                    pir.removeFilter(pa);
11538                }
11539                changed = true;
11540            }
11541        }
11542        return changed;
11543    }
11544
11545    @Override
11546    public void resetPreferredActivities(int userId) {
11547        mContext.enforceCallingOrSelfPermission(
11548                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11549        // writer
11550        synchronized (mPackages) {
11551            int user = UserHandle.getCallingUserId();
11552            clearPackagePreferredActivitiesLPw(null, user);
11553            mSettings.readDefaultPreferredAppsLPw(this, user);
11554            mSettings.writePackageRestrictionsLPr(user);
11555            scheduleWriteSettingsLocked();
11556        }
11557    }
11558
11559    @Override
11560    public int getPreferredActivities(List<IntentFilter> outFilters,
11561            List<ComponentName> outActivities, String packageName) {
11562
11563        int num = 0;
11564        final int userId = UserHandle.getCallingUserId();
11565        // reader
11566        synchronized (mPackages) {
11567            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11568            if (pir != null) {
11569                final Iterator<PreferredActivity> it = pir.filterIterator();
11570                while (it.hasNext()) {
11571                    final PreferredActivity pa = it.next();
11572                    if (packageName == null
11573                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11574                                    && pa.mPref.mAlways)) {
11575                        if (outFilters != null) {
11576                            outFilters.add(new IntentFilter(pa));
11577                        }
11578                        if (outActivities != null) {
11579                            outActivities.add(pa.mPref.mComponent);
11580                        }
11581                    }
11582                }
11583            }
11584        }
11585
11586        return num;
11587    }
11588
11589    @Override
11590    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11591            int userId) {
11592        int callingUid = Binder.getCallingUid();
11593        if (callingUid != Process.SYSTEM_UID) {
11594            throw new SecurityException(
11595                    "addPersistentPreferredActivity can only be run by the system");
11596        }
11597        if (filter.countActions() == 0) {
11598            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11599            return;
11600        }
11601        synchronized (mPackages) {
11602            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11603                    " :");
11604            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11605            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11606                    new PersistentPreferredActivity(filter, activity));
11607            mSettings.writePackageRestrictionsLPr(userId);
11608        }
11609    }
11610
11611    @Override
11612    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11613        int callingUid = Binder.getCallingUid();
11614        if (callingUid != Process.SYSTEM_UID) {
11615            throw new SecurityException(
11616                    "clearPackagePersistentPreferredActivities can only be run by the system");
11617        }
11618        ArrayList<PersistentPreferredActivity> removed = null;
11619        boolean changed = false;
11620        synchronized (mPackages) {
11621            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11622                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11623                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11624                        .valueAt(i);
11625                if (userId != thisUserId) {
11626                    continue;
11627                }
11628                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11629                while (it.hasNext()) {
11630                    PersistentPreferredActivity ppa = it.next();
11631                    // Mark entry for removal only if it matches the package name.
11632                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11633                        if (removed == null) {
11634                            removed = new ArrayList<PersistentPreferredActivity>();
11635                        }
11636                        removed.add(ppa);
11637                    }
11638                }
11639                if (removed != null) {
11640                    for (int j=0; j<removed.size(); j++) {
11641                        PersistentPreferredActivity ppa = removed.get(j);
11642                        ppir.removeFilter(ppa);
11643                    }
11644                    changed = true;
11645                }
11646            }
11647
11648            if (changed) {
11649                mSettings.writePackageRestrictionsLPr(userId);
11650            }
11651        }
11652    }
11653
11654    @Override
11655    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11656            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11657        mContext.enforceCallingOrSelfPermission(
11658                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11659        int callingUid = Binder.getCallingUid();
11660        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11661        if (intentFilter.countActions() == 0) {
11662            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11663            return;
11664        }
11665        synchronized (mPackages) {
11666            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11667                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11668            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11669            mSettings.writePackageRestrictionsLPr(sourceUserId);
11670        }
11671    }
11672
11673    @Override
11674    public void addCrossProfileIntentsForPackage(String packageName,
11675            int sourceUserId, int targetUserId) {
11676        mContext.enforceCallingOrSelfPermission(
11677                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11678        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11679        mSettings.writePackageRestrictionsLPr(sourceUserId);
11680    }
11681
11682    @Override
11683    public void removeCrossProfileIntentsForPackage(String packageName,
11684            int sourceUserId, int targetUserId) {
11685        mContext.enforceCallingOrSelfPermission(
11686                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11687        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11688        mSettings.writePackageRestrictionsLPr(sourceUserId);
11689    }
11690
11691    @Override
11692    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11693            int ownerUserId) {
11694        mContext.enforceCallingOrSelfPermission(
11695                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11696        int callingUid = Binder.getCallingUid();
11697        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11698        int callingUserId = UserHandle.getUserId(callingUid);
11699        synchronized (mPackages) {
11700            CrossProfileIntentResolver resolver =
11701                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11702            HashSet<CrossProfileIntentFilter> set =
11703                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11704            for (CrossProfileIntentFilter filter : set) {
11705                if (filter.getOwnerPackage().equals(ownerPackage)
11706                        && filter.getOwnerUserId() == callingUserId) {
11707                    resolver.removeFilter(filter);
11708                }
11709            }
11710            mSettings.writePackageRestrictionsLPr(sourceUserId);
11711        }
11712    }
11713
11714    // Enforcing that callingUid is owning pkg on userId
11715    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11716        // The system owns everything.
11717        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11718            return;
11719        }
11720        int callingUserId = UserHandle.getUserId(callingUid);
11721        if (callingUserId != userId) {
11722            throw new SecurityException("calling uid " + callingUid
11723                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11724                    + callingUserId);
11725        }
11726        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11727        if (pi == null) {
11728            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11729                    + callingUserId);
11730        }
11731        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11732            throw new SecurityException("Calling uid " + callingUid
11733                    + " does not own package " + pkg);
11734        }
11735    }
11736
11737    @Override
11738    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11739        Intent intent = new Intent(Intent.ACTION_MAIN);
11740        intent.addCategory(Intent.CATEGORY_HOME);
11741
11742        final int callingUserId = UserHandle.getCallingUserId();
11743        List<ResolveInfo> list = queryIntentActivities(intent, null,
11744                PackageManager.GET_META_DATA, callingUserId);
11745        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11746                true, false, false, callingUserId);
11747
11748        allHomeCandidates.clear();
11749        if (list != null) {
11750            for (ResolveInfo ri : list) {
11751                allHomeCandidates.add(ri);
11752            }
11753        }
11754        return (preferred == null || preferred.activityInfo == null)
11755                ? null
11756                : new ComponentName(preferred.activityInfo.packageName,
11757                        preferred.activityInfo.name);
11758    }
11759
11760    /**
11761     * Check if calling UID is the current home app. This handles both the case
11762     * where the user has selected a specific home app, and where there is only
11763     * one home app.
11764     */
11765    public boolean checkCallerIsHomeApp() {
11766        final Intent intent = new Intent(Intent.ACTION_MAIN);
11767        intent.addCategory(Intent.CATEGORY_HOME);
11768
11769        final int callingUid = Binder.getCallingUid();
11770        final int callingUserId = UserHandle.getCallingUserId();
11771        final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId);
11772        final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true,
11773                false, false, callingUserId);
11774
11775        if (preferredHome != null) {
11776            if (callingUid == preferredHome.activityInfo.applicationInfo.uid) {
11777                return true;
11778            }
11779        } else {
11780            for (ResolveInfo info : allHomes) {
11781                if (callingUid == info.activityInfo.applicationInfo.uid) {
11782                    return true;
11783                }
11784            }
11785        }
11786
11787        return false;
11788    }
11789
11790    /**
11791     * Enforce that calling UID is the current home app. This handles both the
11792     * case where the user has selected a specific home app, and where there is
11793     * only one home app.
11794     */
11795    public void enforceCallerIsHomeApp() {
11796        if (!checkCallerIsHomeApp()) {
11797            throw new SecurityException("Caller is not currently selected home app");
11798        }
11799    }
11800
11801    @Override
11802    public void setApplicationEnabledSetting(String appPackageName,
11803            int newState, int flags, int userId, String callingPackage) {
11804        if (!sUserManager.exists(userId)) return;
11805        if (callingPackage == null) {
11806            callingPackage = Integer.toString(Binder.getCallingUid());
11807        }
11808        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11809    }
11810
11811    @Override
11812    public void setComponentEnabledSetting(ComponentName componentName,
11813            int newState, int flags, int userId) {
11814        if (!sUserManager.exists(userId)) return;
11815        setEnabledSetting(componentName.getPackageName(),
11816                componentName.getClassName(), newState, flags, userId, null);
11817    }
11818
11819    private void setEnabledSetting(final String packageName, String className, int newState,
11820            final int flags, int userId, String callingPackage) {
11821        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11822              || newState == COMPONENT_ENABLED_STATE_ENABLED
11823              || newState == COMPONENT_ENABLED_STATE_DISABLED
11824              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11825              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11826            throw new IllegalArgumentException("Invalid new component state: "
11827                    + newState);
11828        }
11829        PackageSetting pkgSetting;
11830        final int uid = Binder.getCallingUid();
11831        final int permission = mContext.checkCallingOrSelfPermission(
11832                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11833        enforceCrossUserPermission(uid, userId, false, "set enabled");
11834        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11835        boolean sendNow = false;
11836        boolean isApp = (className == null);
11837        String componentName = isApp ? packageName : className;
11838        int packageUid = -1;
11839        ArrayList<String> components;
11840
11841        // writer
11842        synchronized (mPackages) {
11843            pkgSetting = mSettings.mPackages.get(packageName);
11844            if (pkgSetting == null) {
11845                if (className == null) {
11846                    throw new IllegalArgumentException(
11847                            "Unknown package: " + packageName);
11848                }
11849                throw new IllegalArgumentException(
11850                        "Unknown component: " + packageName
11851                        + "/" + className);
11852            }
11853            // Allow root and verify that userId is not being specified by a different user
11854            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11855                throw new SecurityException(
11856                        "Permission Denial: attempt to change component state from pid="
11857                        + Binder.getCallingPid()
11858                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11859            }
11860            if (className == null) {
11861                // We're dealing with an application/package level state change
11862                if (pkgSetting.getEnabled(userId) == newState) {
11863                    // Nothing to do
11864                    return;
11865                }
11866                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11867                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11868                    // Don't care about who enables an app.
11869                    callingPackage = null;
11870                }
11871                pkgSetting.setEnabled(newState, userId, callingPackage);
11872                // pkgSetting.pkg.mSetEnabled = newState;
11873            } else {
11874                // We're dealing with a component level state change
11875                // First, verify that this is a valid class name.
11876                PackageParser.Package pkg = pkgSetting.pkg;
11877                if (pkg == null || !pkg.hasComponentClassName(className)) {
11878                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11879                        throw new IllegalArgumentException("Component class " + className
11880                                + " does not exist in " + packageName);
11881                    } else {
11882                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11883                                + className + " does not exist in " + packageName);
11884                    }
11885                }
11886                switch (newState) {
11887                case COMPONENT_ENABLED_STATE_ENABLED:
11888                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11889                        return;
11890                    }
11891                    break;
11892                case COMPONENT_ENABLED_STATE_DISABLED:
11893                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11894                        return;
11895                    }
11896                    break;
11897                case COMPONENT_ENABLED_STATE_DEFAULT:
11898                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11899                        return;
11900                    }
11901                    break;
11902                default:
11903                    Slog.e(TAG, "Invalid new component state: " + newState);
11904                    return;
11905                }
11906            }
11907            mSettings.writePackageRestrictionsLPr(userId);
11908            components = mPendingBroadcasts.get(userId, packageName);
11909            final boolean newPackage = components == null;
11910            if (newPackage) {
11911                components = new ArrayList<String>();
11912            }
11913            if (!components.contains(componentName)) {
11914                components.add(componentName);
11915            }
11916            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11917                sendNow = true;
11918                // Purge entry from pending broadcast list if another one exists already
11919                // since we are sending one right away.
11920                mPendingBroadcasts.remove(userId, packageName);
11921            } else {
11922                if (newPackage) {
11923                    mPendingBroadcasts.put(userId, packageName, components);
11924                }
11925                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11926                    // Schedule a message
11927                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11928                }
11929            }
11930        }
11931
11932        long callingId = Binder.clearCallingIdentity();
11933        try {
11934            if (sendNow) {
11935                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11936                sendPackageChangedBroadcast(packageName,
11937                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11938            }
11939        } finally {
11940            Binder.restoreCallingIdentity(callingId);
11941        }
11942    }
11943
11944    private void sendPackageChangedBroadcast(String packageName,
11945            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11946        if (DEBUG_INSTALL)
11947            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11948                    + componentNames);
11949        Bundle extras = new Bundle(4);
11950        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11951        String nameList[] = new String[componentNames.size()];
11952        componentNames.toArray(nameList);
11953        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11954        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11955        extras.putInt(Intent.EXTRA_UID, packageUid);
11956        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11957                new int[] {UserHandle.getUserId(packageUid)});
11958    }
11959
11960    @Override
11961    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11962        if (!sUserManager.exists(userId)) return;
11963        final int uid = Binder.getCallingUid();
11964        final int permission = mContext.checkCallingOrSelfPermission(
11965                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11966        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11967        enforceCrossUserPermission(uid, userId, true, "stop package");
11968        // writer
11969        synchronized (mPackages) {
11970            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11971                    uid, userId)) {
11972                scheduleWritePackageRestrictionsLocked(userId);
11973            }
11974        }
11975    }
11976
11977    @Override
11978    public String getInstallerPackageName(String packageName) {
11979        // reader
11980        synchronized (mPackages) {
11981            return mSettings.getInstallerPackageNameLPr(packageName);
11982        }
11983    }
11984
11985    @Override
11986    public int getApplicationEnabledSetting(String packageName, int userId) {
11987        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11988        int uid = Binder.getCallingUid();
11989        enforceCrossUserPermission(uid, userId, false, "get enabled");
11990        // reader
11991        synchronized (mPackages) {
11992            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11993        }
11994    }
11995
11996    @Override
11997    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11998        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11999        int uid = Binder.getCallingUid();
12000        enforceCrossUserPermission(uid, userId, false, "get component enabled");
12001        // reader
12002        synchronized (mPackages) {
12003            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12004        }
12005    }
12006
12007    @Override
12008    public void enterSafeMode() {
12009        enforceSystemOrRoot("Only the system can request entering safe mode");
12010
12011        if (!mSystemReady) {
12012            mSafeMode = true;
12013        }
12014    }
12015
12016    @Override
12017    public void systemReady() {
12018        mSystemReady = true;
12019
12020        // Read the compatibilty setting when the system is ready.
12021        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12022                mContext.getContentResolver(),
12023                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12024        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12025        if (DEBUG_SETTINGS) {
12026            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12027        }
12028
12029        synchronized (mPackages) {
12030            // Verify that all of the preferred activity components actually
12031            // exist.  It is possible for applications to be updated and at
12032            // that point remove a previously declared activity component that
12033            // had been set as a preferred activity.  We try to clean this up
12034            // the next time we encounter that preferred activity, but it is
12035            // possible for the user flow to never be able to return to that
12036            // situation so here we do a sanity check to make sure we haven't
12037            // left any junk around.
12038            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12039            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12040                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12041                removed.clear();
12042                for (PreferredActivity pa : pir.filterSet()) {
12043                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12044                        removed.add(pa);
12045                    }
12046                }
12047                if (removed.size() > 0) {
12048                    for (int r=0; r<removed.size(); r++) {
12049                        PreferredActivity pa = removed.get(r);
12050                        Slog.w(TAG, "Removing dangling preferred activity: "
12051                                + pa.mPref.mComponent);
12052                        pir.removeFilter(pa);
12053                    }
12054                    mSettings.writePackageRestrictionsLPr(
12055                            mSettings.mPreferredActivities.keyAt(i));
12056                }
12057            }
12058        }
12059        sUserManager.systemReady();
12060    }
12061
12062    @Override
12063    public boolean isSafeMode() {
12064        return mSafeMode;
12065    }
12066
12067    @Override
12068    public boolean hasSystemUidErrors() {
12069        return mHasSystemUidErrors;
12070    }
12071
12072    static String arrayToString(int[] array) {
12073        StringBuffer buf = new StringBuffer(128);
12074        buf.append('[');
12075        if (array != null) {
12076            for (int i=0; i<array.length; i++) {
12077                if (i > 0) buf.append(", ");
12078                buf.append(array[i]);
12079            }
12080        }
12081        buf.append(']');
12082        return buf.toString();
12083    }
12084
12085    static class DumpState {
12086        public static final int DUMP_LIBS = 1 << 0;
12087        public static final int DUMP_FEATURES = 1 << 1;
12088        public static final int DUMP_RESOLVERS = 1 << 2;
12089        public static final int DUMP_PERMISSIONS = 1 << 3;
12090        public static final int DUMP_PACKAGES = 1 << 4;
12091        public static final int DUMP_SHARED_USERS = 1 << 5;
12092        public static final int DUMP_MESSAGES = 1 << 6;
12093        public static final int DUMP_PROVIDERS = 1 << 7;
12094        public static final int DUMP_VERIFIERS = 1 << 8;
12095        public static final int DUMP_PREFERRED = 1 << 9;
12096        public static final int DUMP_PREFERRED_XML = 1 << 10;
12097        public static final int DUMP_KEYSETS = 1 << 11;
12098        public static final int DUMP_VERSION = 1 << 12;
12099        public static final int DUMP_INSTALLS = 1 << 13;
12100
12101        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12102
12103        private int mTypes;
12104
12105        private int mOptions;
12106
12107        private boolean mTitlePrinted;
12108
12109        private SharedUserSetting mSharedUser;
12110
12111        public boolean isDumping(int type) {
12112            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12113                return true;
12114            }
12115
12116            return (mTypes & type) != 0;
12117        }
12118
12119        public void setDump(int type) {
12120            mTypes |= type;
12121        }
12122
12123        public boolean isOptionEnabled(int option) {
12124            return (mOptions & option) != 0;
12125        }
12126
12127        public void setOptionEnabled(int option) {
12128            mOptions |= option;
12129        }
12130
12131        public boolean onTitlePrinted() {
12132            final boolean printed = mTitlePrinted;
12133            mTitlePrinted = true;
12134            return printed;
12135        }
12136
12137        public boolean getTitlePrinted() {
12138            return mTitlePrinted;
12139        }
12140
12141        public void setTitlePrinted(boolean enabled) {
12142            mTitlePrinted = enabled;
12143        }
12144
12145        public SharedUserSetting getSharedUser() {
12146            return mSharedUser;
12147        }
12148
12149        public void setSharedUser(SharedUserSetting user) {
12150            mSharedUser = user;
12151        }
12152    }
12153
12154    @Override
12155    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12156        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12157                != PackageManager.PERMISSION_GRANTED) {
12158            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12159                    + Binder.getCallingPid()
12160                    + ", uid=" + Binder.getCallingUid()
12161                    + " without permission "
12162                    + android.Manifest.permission.DUMP);
12163            return;
12164        }
12165
12166        DumpState dumpState = new DumpState();
12167        boolean fullPreferred = false;
12168        boolean checkin = false;
12169
12170        String packageName = null;
12171
12172        int opti = 0;
12173        while (opti < args.length) {
12174            String opt = args[opti];
12175            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12176                break;
12177            }
12178            opti++;
12179            if ("-a".equals(opt)) {
12180                // Right now we only know how to print all.
12181            } else if ("-h".equals(opt)) {
12182                pw.println("Package manager dump options:");
12183                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12184                pw.println("    --checkin: dump for a checkin");
12185                pw.println("    -f: print details of intent filters");
12186                pw.println("    -h: print this help");
12187                pw.println("  cmd may be one of:");
12188                pw.println("    l[ibraries]: list known shared libraries");
12189                pw.println("    f[ibraries]: list device features");
12190                pw.println("    k[eysets]: print known keysets");
12191                pw.println("    r[esolvers]: dump intent resolvers");
12192                pw.println("    perm[issions]: dump permissions");
12193                pw.println("    pref[erred]: print preferred package settings");
12194                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12195                pw.println("    prov[iders]: dump content providers");
12196                pw.println("    p[ackages]: dump installed packages");
12197                pw.println("    s[hared-users]: dump shared user IDs");
12198                pw.println("    m[essages]: print collected runtime messages");
12199                pw.println("    v[erifiers]: print package verifier info");
12200                pw.println("    version: print database version info");
12201                pw.println("    write: write current settings now");
12202                pw.println("    <package.name>: info about given package");
12203                pw.println("    installs: details about install sessions");
12204                return;
12205            } else if ("--checkin".equals(opt)) {
12206                checkin = true;
12207            } else if ("-f".equals(opt)) {
12208                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12209            } else {
12210                pw.println("Unknown argument: " + opt + "; use -h for help");
12211            }
12212        }
12213
12214        // Is the caller requesting to dump a particular piece of data?
12215        if (opti < args.length) {
12216            String cmd = args[opti];
12217            opti++;
12218            // Is this a package name?
12219            if ("android".equals(cmd) || cmd.contains(".")) {
12220                packageName = cmd;
12221                // When dumping a single package, we always dump all of its
12222                // filter information since the amount of data will be reasonable.
12223                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12224            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12225                dumpState.setDump(DumpState.DUMP_LIBS);
12226            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12227                dumpState.setDump(DumpState.DUMP_FEATURES);
12228            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12229                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12230            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12231                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12232            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12233                dumpState.setDump(DumpState.DUMP_PREFERRED);
12234            } else if ("preferred-xml".equals(cmd)) {
12235                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12236                if (opti < args.length && "--full".equals(args[opti])) {
12237                    fullPreferred = true;
12238                    opti++;
12239                }
12240            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12241                dumpState.setDump(DumpState.DUMP_PACKAGES);
12242            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12243                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12244            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12245                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12246            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12247                dumpState.setDump(DumpState.DUMP_MESSAGES);
12248            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12249                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12250            } else if ("version".equals(cmd)) {
12251                dumpState.setDump(DumpState.DUMP_VERSION);
12252            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12253                dumpState.setDump(DumpState.DUMP_KEYSETS);
12254            } else if ("write".equals(cmd)) {
12255                synchronized (mPackages) {
12256                    mSettings.writeLPr();
12257                    pw.println("Settings written.");
12258                    return;
12259                }
12260            } else if ("installs".equals(cmd)) {
12261                dumpState.setDump(DumpState.DUMP_INSTALLS);
12262            }
12263        }
12264
12265        if (checkin) {
12266            pw.println("vers,1");
12267        }
12268
12269        // reader
12270        synchronized (mPackages) {
12271            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12272                if (!checkin) {
12273                    if (dumpState.onTitlePrinted())
12274                        pw.println();
12275                    pw.println("Database versions:");
12276                    pw.print("  SDK Version:");
12277                    pw.print(" internal=");
12278                    pw.print(mSettings.mInternalSdkPlatform);
12279                    pw.print(" external=");
12280                    pw.println(mSettings.mExternalSdkPlatform);
12281                    pw.print("  DB Version:");
12282                    pw.print(" internal=");
12283                    pw.print(mSettings.mInternalDatabaseVersion);
12284                    pw.print(" external=");
12285                    pw.println(mSettings.mExternalDatabaseVersion);
12286                }
12287            }
12288
12289            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12290                if (!checkin) {
12291                    if (dumpState.onTitlePrinted())
12292                        pw.println();
12293                    pw.println("Verifiers:");
12294                    pw.print("  Required: ");
12295                    pw.print(mRequiredVerifierPackage);
12296                    pw.print(" (uid=");
12297                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12298                    pw.println(")");
12299                } else if (mRequiredVerifierPackage != null) {
12300                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12301                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12302                }
12303            }
12304
12305            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12306                boolean printedHeader = false;
12307                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12308                while (it.hasNext()) {
12309                    String name = it.next();
12310                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12311                    if (!checkin) {
12312                        if (!printedHeader) {
12313                            if (dumpState.onTitlePrinted())
12314                                pw.println();
12315                            pw.println("Libraries:");
12316                            printedHeader = true;
12317                        }
12318                        pw.print("  ");
12319                    } else {
12320                        pw.print("lib,");
12321                    }
12322                    pw.print(name);
12323                    if (!checkin) {
12324                        pw.print(" -> ");
12325                    }
12326                    if (ent.path != null) {
12327                        if (!checkin) {
12328                            pw.print("(jar) ");
12329                            pw.print(ent.path);
12330                        } else {
12331                            pw.print(",jar,");
12332                            pw.print(ent.path);
12333                        }
12334                    } else {
12335                        if (!checkin) {
12336                            pw.print("(apk) ");
12337                            pw.print(ent.apk);
12338                        } else {
12339                            pw.print(",apk,");
12340                            pw.print(ent.apk);
12341                        }
12342                    }
12343                    pw.println();
12344                }
12345            }
12346
12347            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12348                if (dumpState.onTitlePrinted())
12349                    pw.println();
12350                if (!checkin) {
12351                    pw.println("Features:");
12352                }
12353                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12354                while (it.hasNext()) {
12355                    String name = it.next();
12356                    if (!checkin) {
12357                        pw.print("  ");
12358                    } else {
12359                        pw.print("feat,");
12360                    }
12361                    pw.println(name);
12362                }
12363            }
12364
12365            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12366                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12367                        : "Activity Resolver Table:", "  ", packageName,
12368                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12369                    dumpState.setTitlePrinted(true);
12370                }
12371                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12372                        : "Receiver Resolver Table:", "  ", packageName,
12373                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12374                    dumpState.setTitlePrinted(true);
12375                }
12376                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12377                        : "Service Resolver Table:", "  ", packageName,
12378                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12379                    dumpState.setTitlePrinted(true);
12380                }
12381                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12382                        : "Provider Resolver Table:", "  ", packageName,
12383                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12384                    dumpState.setTitlePrinted(true);
12385                }
12386            }
12387
12388            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12389                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12390                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12391                    int user = mSettings.mPreferredActivities.keyAt(i);
12392                    if (pir.dump(pw,
12393                            dumpState.getTitlePrinted()
12394                                ? "\nPreferred Activities User " + user + ":"
12395                                : "Preferred Activities User " + user + ":", "  ",
12396                            packageName, true)) {
12397                        dumpState.setTitlePrinted(true);
12398                    }
12399                }
12400            }
12401
12402            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12403                pw.flush();
12404                FileOutputStream fout = new FileOutputStream(fd);
12405                BufferedOutputStream str = new BufferedOutputStream(fout);
12406                XmlSerializer serializer = new FastXmlSerializer();
12407                try {
12408                    serializer.setOutput(str, "utf-8");
12409                    serializer.startDocument(null, true);
12410                    serializer.setFeature(
12411                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12412                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12413                    serializer.endDocument();
12414                    serializer.flush();
12415                } catch (IllegalArgumentException e) {
12416                    pw.println("Failed writing: " + e);
12417                } catch (IllegalStateException e) {
12418                    pw.println("Failed writing: " + e);
12419                } catch (IOException e) {
12420                    pw.println("Failed writing: " + e);
12421                }
12422            }
12423
12424            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12425                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12426                if (packageName == null) {
12427                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12428                        if (iperm == 0) {
12429                            if (dumpState.onTitlePrinted())
12430                                pw.println();
12431                            pw.println("AppOp Permissions:");
12432                        }
12433                        pw.print("  AppOp Permission ");
12434                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12435                        pw.println(":");
12436                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12437                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12438                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12439                        }
12440                    }
12441                }
12442            }
12443
12444            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12445                boolean printedSomething = false;
12446                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12447                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12448                        continue;
12449                    }
12450                    if (!printedSomething) {
12451                        if (dumpState.onTitlePrinted())
12452                            pw.println();
12453                        pw.println("Registered ContentProviders:");
12454                        printedSomething = true;
12455                    }
12456                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12457                    pw.print("    "); pw.println(p.toString());
12458                }
12459                printedSomething = false;
12460                for (Map.Entry<String, PackageParser.Provider> entry :
12461                        mProvidersByAuthority.entrySet()) {
12462                    PackageParser.Provider p = entry.getValue();
12463                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12464                        continue;
12465                    }
12466                    if (!printedSomething) {
12467                        if (dumpState.onTitlePrinted())
12468                            pw.println();
12469                        pw.println("ContentProvider Authorities:");
12470                        printedSomething = true;
12471                    }
12472                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12473                    pw.print("    "); pw.println(p.toString());
12474                    if (p.info != null && p.info.applicationInfo != null) {
12475                        final String appInfo = p.info.applicationInfo.toString();
12476                        pw.print("      applicationInfo="); pw.println(appInfo);
12477                    }
12478                }
12479            }
12480
12481            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12482                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12483            }
12484
12485            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12486                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12487            }
12488
12489            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12490                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12491            }
12492
12493            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12494                if (dumpState.onTitlePrinted()) pw.println();
12495                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12496            }
12497
12498            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12499                if (dumpState.onTitlePrinted()) pw.println();
12500                mSettings.dumpReadMessagesLPr(pw, dumpState);
12501
12502                pw.println();
12503                pw.println("Package warning messages:");
12504                final File fname = getSettingsProblemFile();
12505                FileInputStream in = null;
12506                try {
12507                    in = new FileInputStream(fname);
12508                    final int avail = in.available();
12509                    final byte[] data = new byte[avail];
12510                    in.read(data);
12511                    pw.print(new String(data));
12512                } catch (FileNotFoundException e) {
12513                } catch (IOException e) {
12514                } finally {
12515                    if (in != null) {
12516                        try {
12517                            in.close();
12518                        } catch (IOException e) {
12519                        }
12520                    }
12521                }
12522            }
12523        }
12524    }
12525
12526    // ------- apps on sdcard specific code -------
12527    static final boolean DEBUG_SD_INSTALL = false;
12528
12529    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12530
12531    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12532
12533    private boolean mMediaMounted = false;
12534
12535    private String getEncryptKey() {
12536        try {
12537            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12538                    SD_ENCRYPTION_KEYSTORE_NAME);
12539            if (sdEncKey == null) {
12540                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12541                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12542                if (sdEncKey == null) {
12543                    Slog.e(TAG, "Failed to create encryption keys");
12544                    return null;
12545                }
12546            }
12547            return sdEncKey;
12548        } catch (NoSuchAlgorithmException nsae) {
12549            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12550            return null;
12551        } catch (IOException ioe) {
12552            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12553            return null;
12554        }
12555
12556    }
12557
12558    /* package */static String getTempContainerId() {
12559        int tmpIdx = 1;
12560        String list[] = PackageHelper.getSecureContainerList();
12561        if (list != null) {
12562            for (final String name : list) {
12563                // Ignore null and non-temporary container entries
12564                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12565                    continue;
12566                }
12567
12568                String subStr = name.substring(mTempContainerPrefix.length());
12569                try {
12570                    int cid = Integer.parseInt(subStr);
12571                    if (cid >= tmpIdx) {
12572                        tmpIdx = cid + 1;
12573                    }
12574                } catch (NumberFormatException e) {
12575                }
12576            }
12577        }
12578        return mTempContainerPrefix + tmpIdx;
12579    }
12580
12581    /*
12582     * Update media status on PackageManager.
12583     */
12584    @Override
12585    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12586        int callingUid = Binder.getCallingUid();
12587        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12588            throw new SecurityException("Media status can only be updated by the system");
12589        }
12590        // reader; this apparently protects mMediaMounted, but should probably
12591        // be a different lock in that case.
12592        synchronized (mPackages) {
12593            Log.i(TAG, "Updating external media status from "
12594                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12595                    + (mediaStatus ? "mounted" : "unmounted"));
12596            if (DEBUG_SD_INSTALL)
12597                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12598                        + ", mMediaMounted=" + mMediaMounted);
12599            if (mediaStatus == mMediaMounted) {
12600                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12601                        : 0, -1);
12602                mHandler.sendMessage(msg);
12603                return;
12604            }
12605            mMediaMounted = mediaStatus;
12606        }
12607        // Queue up an async operation since the package installation may take a
12608        // little while.
12609        mHandler.post(new Runnable() {
12610            public void run() {
12611                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12612            }
12613        });
12614    }
12615
12616    /**
12617     * Called by MountService when the initial ASECs to scan are available.
12618     * Should block until all the ASEC containers are finished being scanned.
12619     */
12620    public void scanAvailableAsecs() {
12621        updateExternalMediaStatusInner(true, false, false);
12622        if (mShouldRestoreconData) {
12623            SELinuxMMAC.setRestoreconDone();
12624            mShouldRestoreconData = false;
12625        }
12626    }
12627
12628    /*
12629     * Collect information of applications on external media, map them against
12630     * existing containers and update information based on current mount status.
12631     * Please note that we always have to report status if reportStatus has been
12632     * set to true especially when unloading packages.
12633     */
12634    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12635            boolean externalStorage) {
12636        // Collection of uids
12637        int uidArr[] = null;
12638        // Collection of stale containers
12639        HashSet<String> removeCids = new HashSet<String>();
12640        // Collection of packages on external media with valid containers.
12641        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12642        // Get list of secure containers.
12643        final String list[] = PackageHelper.getSecureContainerList();
12644        if (list == null || list.length == 0) {
12645            Log.i(TAG, "No secure containers on sdcard");
12646        } else {
12647            // Process list of secure containers and categorize them
12648            // as active or stale based on their package internal state.
12649            int uidList[] = new int[list.length];
12650            int num = 0;
12651            // reader
12652            synchronized (mPackages) {
12653                for (String cid : list) {
12654                    if (DEBUG_SD_INSTALL)
12655                        Log.i(TAG, "Processing container " + cid);
12656                    String pkgName = getAsecPackageName(cid);
12657                    if (pkgName == null) {
12658                        if (DEBUG_SD_INSTALL)
12659                            Log.i(TAG, "Container : " + cid + " stale");
12660                        removeCids.add(cid);
12661                        continue;
12662                    }
12663                    if (DEBUG_SD_INSTALL)
12664                        Log.i(TAG, "Looking for pkg : " + pkgName);
12665
12666                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12667                    if (ps == null) {
12668                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12669                        removeCids.add(cid);
12670                        continue;
12671                    }
12672
12673                    /*
12674                     * Skip packages that are not external if we're unmounting
12675                     * external storage.
12676                     */
12677                    if (externalStorage && !isMounted && !isExternal(ps)) {
12678                        continue;
12679                    }
12680
12681                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12682                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12683                    // The package status is changed only if the code path
12684                    // matches between settings and the container id.
12685                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12686                        if (DEBUG_SD_INSTALL) {
12687                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12688                                    + " at code path: " + ps.codePathString);
12689                        }
12690
12691                        // We do have a valid package installed on sdcard
12692                        processCids.put(args, ps.codePathString);
12693                        final int uid = ps.appId;
12694                        if (uid != -1) {
12695                            uidList[num++] = uid;
12696                        }
12697                    } else {
12698                        Log.i(TAG, "Deleting stale container for " + cid);
12699                        removeCids.add(cid);
12700                    }
12701                }
12702            }
12703
12704            if (num > 0) {
12705                // Sort uid list
12706                Arrays.sort(uidList, 0, num);
12707                // Throw away duplicates
12708                uidArr = new int[num];
12709                uidArr[0] = uidList[0];
12710                int di = 0;
12711                for (int i = 1; i < num; i++) {
12712                    if (uidList[i - 1] != uidList[i]) {
12713                        uidArr[di++] = uidList[i];
12714                    }
12715                }
12716            }
12717        }
12718        // Process packages with valid entries.
12719        if (isMounted) {
12720            if (DEBUG_SD_INSTALL)
12721                Log.i(TAG, "Loading packages");
12722            loadMediaPackages(processCids, uidArr, removeCids);
12723            startCleaningPackages();
12724        } else {
12725            if (DEBUG_SD_INSTALL)
12726                Log.i(TAG, "Unloading packages");
12727            unloadMediaPackages(processCids, uidArr, reportStatus);
12728        }
12729    }
12730
12731   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12732           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12733        int size = pkgList.size();
12734        if (size > 0) {
12735            // Send broadcasts here
12736            Bundle extras = new Bundle();
12737            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12738                    .toArray(new String[size]));
12739            if (uidArr != null) {
12740                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12741            }
12742            if (replacing) {
12743                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12744            }
12745            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12746                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12747            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12748        }
12749    }
12750
12751   /*
12752     * Look at potentially valid container ids from processCids If package
12753     * information doesn't match the one on record or package scanning fails,
12754     * the cid is added to list of removeCids. We currently don't delete stale
12755     * containers.
12756     */
12757   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12758            HashSet<String> removeCids) {
12759        ArrayList<String> pkgList = new ArrayList<String>();
12760        Set<AsecInstallArgs> keys = processCids.keySet();
12761        boolean doGc = false;
12762        for (AsecInstallArgs args : keys) {
12763            String codePath = processCids.get(args);
12764            if (DEBUG_SD_INSTALL)
12765                Log.i(TAG, "Loading container : " + args.cid);
12766            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12767            try {
12768                // Make sure there are no container errors first.
12769                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12770                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12771                            + " when installing from sdcard");
12772                    continue;
12773                }
12774                // Check code path here.
12775                if (codePath == null || !codePath.equals(args.getCodePath())) {
12776                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12777                            + " does not match one in settings " + codePath);
12778                    continue;
12779                }
12780                // Parse package
12781                int parseFlags = mDefParseFlags;
12782                if (args.isExternal()) {
12783                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12784                }
12785                if (args.isFwdLocked()) {
12786                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12787                }
12788
12789                doGc = true;
12790                synchronized (mInstallLock) {
12791                    PackageParser.Package pkg = null;
12792                    try {
12793                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null);
12794                    } catch (PackageManagerException e) {
12795                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12796                    }
12797                    // Scan the package
12798                    if (pkg != null) {
12799                        /*
12800                         * TODO why is the lock being held? doPostInstall is
12801                         * called in other places without the lock. This needs
12802                         * to be straightened out.
12803                         */
12804                        // writer
12805                        synchronized (mPackages) {
12806                            retCode = PackageManager.INSTALL_SUCCEEDED;
12807                            pkgList.add(pkg.packageName);
12808                            // Post process args
12809                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12810                                    pkg.applicationInfo.uid);
12811                        }
12812                    } else {
12813                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12814                    }
12815                }
12816
12817            } finally {
12818                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12819                    // Don't destroy container here. Wait till gc clears things
12820                    // up.
12821                    removeCids.add(args.cid);
12822                }
12823            }
12824        }
12825        // writer
12826        synchronized (mPackages) {
12827            // If the platform SDK has changed since the last time we booted,
12828            // we need to re-grant app permission to catch any new ones that
12829            // appear. This is really a hack, and means that apps can in some
12830            // cases get permissions that the user didn't initially explicitly
12831            // allow... it would be nice to have some better way to handle
12832            // this situation.
12833            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12834            if (regrantPermissions)
12835                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12836                        + mSdkVersion + "; regranting permissions for external storage");
12837            mSettings.mExternalSdkPlatform = mSdkVersion;
12838
12839            // Make sure group IDs have been assigned, and any permission
12840            // changes in other apps are accounted for
12841            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12842                    | (regrantPermissions
12843                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12844                            : 0));
12845
12846            mSettings.updateExternalDatabaseVersion();
12847
12848            // can downgrade to reader
12849            // Persist settings
12850            mSettings.writeLPr();
12851        }
12852        // Send a broadcast to let everyone know we are done processing
12853        if (pkgList.size() > 0) {
12854            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12855        }
12856        // Force gc to avoid any stale parser references that we might have.
12857        if (doGc) {
12858            Runtime.getRuntime().gc();
12859        }
12860        // List stale containers and destroy stale temporary containers.
12861        if (removeCids != null) {
12862            for (String cid : removeCids) {
12863                if (cid.startsWith(mTempContainerPrefix)) {
12864                    Log.i(TAG, "Destroying stale temporary container " + cid);
12865                    PackageHelper.destroySdDir(cid);
12866                } else {
12867                    Log.w(TAG, "Container " + cid + " is stale");
12868               }
12869           }
12870        }
12871    }
12872
12873   /*
12874     * Utility method to unload a list of specified containers
12875     */
12876    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12877        // Just unmount all valid containers.
12878        for (AsecInstallArgs arg : cidArgs) {
12879            synchronized (mInstallLock) {
12880                arg.doPostDeleteLI(false);
12881           }
12882       }
12883   }
12884
12885    /*
12886     * Unload packages mounted on external media. This involves deleting package
12887     * data from internal structures, sending broadcasts about diabled packages,
12888     * gc'ing to free up references, unmounting all secure containers
12889     * corresponding to packages on external media, and posting a
12890     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12891     * that we always have to post this message if status has been requested no
12892     * matter what.
12893     */
12894    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12895            final boolean reportStatus) {
12896        if (DEBUG_SD_INSTALL)
12897            Log.i(TAG, "unloading media packages");
12898        ArrayList<String> pkgList = new ArrayList<String>();
12899        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12900        final Set<AsecInstallArgs> keys = processCids.keySet();
12901        for (AsecInstallArgs args : keys) {
12902            String pkgName = args.getPackageName();
12903            if (DEBUG_SD_INSTALL)
12904                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12905            // Delete package internally
12906            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12907            synchronized (mInstallLock) {
12908                boolean res = deletePackageLI(pkgName, null, false, null, null,
12909                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12910                if (res) {
12911                    pkgList.add(pkgName);
12912                } else {
12913                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12914                    failedList.add(args);
12915                }
12916            }
12917        }
12918
12919        // reader
12920        synchronized (mPackages) {
12921            // We didn't update the settings after removing each package;
12922            // write them now for all packages.
12923            mSettings.writeLPr();
12924        }
12925
12926        // We have to absolutely send UPDATED_MEDIA_STATUS only
12927        // after confirming that all the receivers processed the ordered
12928        // broadcast when packages get disabled, force a gc to clean things up.
12929        // and unload all the containers.
12930        if (pkgList.size() > 0) {
12931            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12932                    new IIntentReceiver.Stub() {
12933                public void performReceive(Intent intent, int resultCode, String data,
12934                        Bundle extras, boolean ordered, boolean sticky,
12935                        int sendingUser) throws RemoteException {
12936                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12937                            reportStatus ? 1 : 0, 1, keys);
12938                    mHandler.sendMessage(msg);
12939                }
12940            });
12941        } else {
12942            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12943                    keys);
12944            mHandler.sendMessage(msg);
12945        }
12946    }
12947
12948    /** Binder call */
12949    @Override
12950    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12951            final int flags) {
12952        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12953        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12954        int returnCode = PackageManager.MOVE_SUCCEEDED;
12955        int currFlags = 0;
12956        int newFlags = 0;
12957        // reader
12958        synchronized (mPackages) {
12959            PackageParser.Package pkg = mPackages.get(packageName);
12960            if (pkg == null) {
12961                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12962            } else {
12963                // Disable moving fwd locked apps and system packages
12964                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12965                    Slog.w(TAG, "Cannot move system application");
12966                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12967                } else if (pkg.mOperationPending) {
12968                    Slog.w(TAG, "Attempt to move package which has pending operations");
12969                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12970                } else {
12971                    // Find install location first
12972                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12973                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12974                        Slog.w(TAG, "Ambigous flags specified for move location.");
12975                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12976                    } else {
12977                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12978                                : PackageManager.INSTALL_INTERNAL;
12979                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12980                                : PackageManager.INSTALL_INTERNAL;
12981
12982                        if (newFlags == currFlags) {
12983                            Slog.w(TAG, "No move required. Trying to move to same location");
12984                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12985                        } else {
12986                            if (isForwardLocked(pkg)) {
12987                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12988                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12989                            }
12990                        }
12991                    }
12992                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12993                        pkg.mOperationPending = true;
12994                    }
12995                }
12996            }
12997
12998            /*
12999             * TODO this next block probably shouldn't be inside the lock. We
13000             * can't guarantee these won't change after this is fired off
13001             * anyway.
13002             */
13003            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13004                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
13005                        returnCode);
13006            } else {
13007                Message msg = mHandler.obtainMessage(INIT_COPY);
13008                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
13009                final boolean multiArch = isMultiArch(pkg.applicationInfo);
13010                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
13011                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
13012                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
13013                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
13014                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
13015                msg.obj = mp;
13016                mHandler.sendMessage(msg);
13017            }
13018        }
13019    }
13020
13021    private void processPendingMove(final MoveParams mp, final int currentStatus) {
13022        // Queue up an async operation since the package deletion may take a
13023        // little while.
13024        mHandler.post(new Runnable() {
13025            public void run() {
13026                // TODO fix this; this does nothing.
13027                mHandler.removeCallbacks(this);
13028                int returnCode = currentStatus;
13029                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
13030                    int uidArr[] = null;
13031                    ArrayList<String> pkgList = null;
13032                    synchronized (mPackages) {
13033                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13034                        if (pkg == null) {
13035                            Slog.w(TAG, " Package " + mp.packageName
13036                                    + " doesn't exist. Aborting move");
13037                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13038                        } else if (!mp.srcArgs.getCodePath().equals(
13039                                pkg.applicationInfo.getCodePath())) {
13040                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
13041                                    + mp.srcArgs.getCodePath() + " to "
13042                                    + pkg.applicationInfo.getCodePath()
13043                                    + " Aborting move and returning error");
13044                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13045                        } else {
13046                            uidArr = new int[] {
13047                                pkg.applicationInfo.uid
13048                            };
13049                            pkgList = new ArrayList<String>();
13050                            pkgList.add(mp.packageName);
13051                        }
13052                    }
13053                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13054                        // Send resources unavailable broadcast
13055                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
13056                        // Update package code and resource paths
13057                        synchronized (mInstallLock) {
13058                            synchronized (mPackages) {
13059                                PackageParser.Package pkg = mPackages.get(mp.packageName);
13060                                // Recheck for package again.
13061                                if (pkg == null) {
13062                                    Slog.w(TAG, " Package " + mp.packageName
13063                                            + " doesn't exist. Aborting move");
13064                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13065                                } else if (!mp.srcArgs.getCodePath().equals(
13066                                        pkg.applicationInfo.getCodePath())) {
13067                                    Slog.w(TAG, "Package " + mp.packageName
13068                                            + " code path changed from " + mp.srcArgs.getCodePath()
13069                                            + " to " + pkg.applicationInfo.getCodePath()
13070                                            + " Aborting move and returning error");
13071                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13072                                } else {
13073                                    final String oldCodePath = pkg.codePath;
13074                                    final String newCodePath = mp.targetArgs.getCodePath();
13075                                    final String newResPath = mp.targetArgs.getResourcePath();
13076                                    // TODO: This assumes the new style of installation.
13077                                    // should we look at legacyNativeLibraryPath ?
13078                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
13079                                    final File newNativeDir = new File(newNativeRoot);
13080
13081                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
13082                                        // TODO(multiArch): Fix this so that it looks at the existing
13083                                        // recorded CPU abis from the package. There's no need for a separate
13084                                        // round of ABI scanning here.
13085                                        NativeLibraryHelper.Handle handle = null;
13086                                        try {
13087                                            handle = NativeLibraryHelper.Handle.create(
13088                                                    new File(newCodePath));
13089                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13090                                                    handle, Build.SUPPORTED_ABIS);
13091                                            if (abi >= 0) {
13092                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13093                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13094                                            }
13095                                        } catch (IOException ioe) {
13096                                            Slog.w(TAG, "Unable to extract native libs for package :"
13097                                                    + mp.packageName, ioe);
13098                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13099                                        } finally {
13100                                            IoUtils.closeQuietly(handle);
13101                                        }
13102                                    }
13103
13104                                    final int[] users = sUserManager.getUserIds();
13105                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13106                                        for (int user : users) {
13107                                            // TODO(multiArch): Fix this so that it links to the
13108                                            // correct directory. We're currently pointing to root. but we
13109                                            // must point to the arch specific subdirectory (if applicable).
13110                                            //
13111                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13112                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13113                                                    newNativeRoot, user) < 0) {
13114                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13115                                            }
13116                                        }
13117                                    }
13118
13119                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13120                                        pkg.codePath = newCodePath;
13121                                        pkg.baseCodePath = newCodePath;
13122                                        // Move dex files around
13123                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13124                                            // Moving of dex files failed. Set
13125                                            // error code and abort move.
13126                                            pkg.codePath = oldCodePath;
13127                                            pkg.baseCodePath = oldCodePath;
13128                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13129                                        }
13130                                    }
13131
13132                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13133                                        pkg.applicationInfo.setCodePath(newCodePath);
13134                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13135                                        pkg.applicationInfo.setSplitCodePaths(null);
13136                                        pkg.applicationInfo.setResourcePath(newResPath);
13137                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13138                                        pkg.applicationInfo.setSplitResourcePaths(null);
13139
13140                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13141                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13142                                        ps.codePathString = ps.codePath.getPath();
13143                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13144                                        ps.resourcePathString = ps.resourcePath.getPath();
13145
13146                                        // Note that we don't have to recalculate the primary and secondary
13147                                        // CPU ABIs because they must already have been calculated during the
13148                                        // initial install of the app.
13149                                        ps.legacyNativeLibraryPathString = null;
13150
13151                                        // Set the application info flag
13152                                        // correctly.
13153                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13154                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13155                                        } else {
13156                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13157                                        }
13158                                        ps.setFlags(pkg.applicationInfo.flags);
13159                                        mAppDirs.remove(oldCodePath);
13160                                        mAppDirs.put(newCodePath, pkg);
13161                                        // Persist settings
13162                                        mSettings.writeLPr();
13163                                    }
13164                                }
13165                            }
13166                        }
13167                        // Send resources available broadcast
13168                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13169                    }
13170                }
13171                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13172                    // Clean up failed installation
13173                    if (mp.targetArgs != null) {
13174                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13175                                -1);
13176                    }
13177                } else {
13178                    // Force a gc to clear things up.
13179                    Runtime.getRuntime().gc();
13180                    // Delete older code
13181                    synchronized (mInstallLock) {
13182                        mp.srcArgs.doPostDeleteLI(true);
13183                    }
13184                }
13185
13186                // Allow more operations on this file if we didn't fail because
13187                // an operation was already pending for this package.
13188                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13189                    synchronized (mPackages) {
13190                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13191                        if (pkg != null) {
13192                            pkg.mOperationPending = false;
13193                       }
13194                   }
13195                }
13196
13197                IPackageMoveObserver observer = mp.observer;
13198                if (observer != null) {
13199                    try {
13200                        observer.packageMoved(mp.packageName, returnCode);
13201                    } catch (RemoteException e) {
13202                        Log.i(TAG, "Observer no longer exists.");
13203                    }
13204                }
13205            }
13206        });
13207    }
13208
13209    @Override
13210    public boolean setInstallLocation(int loc) {
13211        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13212                null);
13213        if (getInstallLocation() == loc) {
13214            return true;
13215        }
13216        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13217                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13218            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13219                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13220            return true;
13221        }
13222        return false;
13223   }
13224
13225    @Override
13226    public int getInstallLocation() {
13227        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13228                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13229                PackageHelper.APP_INSTALL_AUTO);
13230    }
13231
13232    /** Called by UserManagerService */
13233    void cleanUpUserLILPw(int userHandle) {
13234        mDirtyUsers.remove(userHandle);
13235        mSettings.removeUserLPw(userHandle);
13236        mPendingBroadcasts.remove(userHandle);
13237        if (mInstaller != null) {
13238            // Technically, we shouldn't be doing this with the package lock
13239            // held.  However, this is very rare, and there is already so much
13240            // other disk I/O going on, that we'll let it slide for now.
13241            mInstaller.removeUserDataDirs(userHandle);
13242        }
13243        mUserNeedsBadging.delete(userHandle);
13244    }
13245
13246    /** Called by UserManagerService */
13247    void createNewUserLILPw(int userHandle, File path) {
13248        if (mInstaller != null) {
13249            mInstaller.createUserConfig(userHandle);
13250            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13251        }
13252    }
13253
13254    @Override
13255    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13256        mContext.enforceCallingOrSelfPermission(
13257                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13258                "Only package verification agents can read the verifier device identity");
13259
13260        synchronized (mPackages) {
13261            return mSettings.getVerifierDeviceIdentityLPw();
13262        }
13263    }
13264
13265    @Override
13266    public void setPermissionEnforced(String permission, boolean enforced) {
13267        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13268        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13269            synchronized (mPackages) {
13270                if (mSettings.mReadExternalStorageEnforced == null
13271                        || mSettings.mReadExternalStorageEnforced != enforced) {
13272                    mSettings.mReadExternalStorageEnforced = enforced;
13273                    mSettings.writeLPr();
13274                }
13275            }
13276            // kill any non-foreground processes so we restart them and
13277            // grant/revoke the GID.
13278            final IActivityManager am = ActivityManagerNative.getDefault();
13279            if (am != null) {
13280                final long token = Binder.clearCallingIdentity();
13281                try {
13282                    am.killProcessesBelowForeground("setPermissionEnforcement");
13283                } catch (RemoteException e) {
13284                } finally {
13285                    Binder.restoreCallingIdentity(token);
13286                }
13287            }
13288        } else {
13289            throw new IllegalArgumentException("No selective enforcement for " + permission);
13290        }
13291    }
13292
13293    @Override
13294    @Deprecated
13295    public boolean isPermissionEnforced(String permission) {
13296        return true;
13297    }
13298
13299    @Override
13300    public boolean isStorageLow() {
13301        final long token = Binder.clearCallingIdentity();
13302        try {
13303            final DeviceStorageMonitorInternal
13304                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13305            if (dsm != null) {
13306                return dsm.isMemoryLow();
13307            } else {
13308                return false;
13309            }
13310        } finally {
13311            Binder.restoreCallingIdentity(token);
13312        }
13313    }
13314
13315    @Override
13316    public IPackageInstaller getPackageInstaller() {
13317        return mInstallerService;
13318    }
13319
13320    private boolean userNeedsBadging(int userId) {
13321        int index = mUserNeedsBadging.indexOfKey(userId);
13322        if (index < 0) {
13323            final UserInfo userInfo;
13324            final long token = Binder.clearCallingIdentity();
13325            try {
13326                userInfo = sUserManager.getUserInfo(userId);
13327            } finally {
13328                Binder.restoreCallingIdentity(token);
13329            }
13330            final boolean b;
13331            if (userInfo != null && userInfo.isManagedProfile()) {
13332                b = true;
13333            } else {
13334                b = false;
13335            }
13336            mUserNeedsBadging.put(userId, b);
13337            return b;
13338        }
13339        return mUserNeedsBadging.valueAt(index);
13340    }
13341
13342    @Override
13343    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13344        if (packageName == null || alias == null) {
13345            return null;
13346        }
13347        synchronized(mPackages) {
13348            final PackageParser.Package pkg = mPackages.get(packageName);
13349            if (pkg == null) {
13350                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13351                throw new IllegalArgumentException("Unknown package: " + packageName);
13352            }
13353            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13354                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13355                throw new SecurityException("May not access KeySets defined by"
13356                        + " aliases in other applications.");
13357            }
13358            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13359            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13360        }
13361    }
13362
13363    @Override
13364    public KeySetHandle getSigningKeySet(String packageName) {
13365        if (packageName == null) {
13366            return null;
13367        }
13368        synchronized(mPackages) {
13369            final PackageParser.Package pkg = mPackages.get(packageName);
13370            if (pkg == null) {
13371                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13372                throw new IllegalArgumentException("Unknown package: " + packageName);
13373            }
13374            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13375                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13376                throw new SecurityException("May not access signing KeySet of other apps.");
13377            }
13378            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13379            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13380        }
13381    }
13382
13383    @Override
13384    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13385        if (packageName == null || ks == null) {
13386            return false;
13387        }
13388        synchronized(mPackages) {
13389            final PackageParser.Package pkg = mPackages.get(packageName);
13390            if (pkg == null) {
13391                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13392                throw new IllegalArgumentException("Unknown package: " + packageName);
13393            }
13394            if (ks instanceof KeySetHandle) {
13395                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13396                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13397            }
13398            return false;
13399        }
13400    }
13401
13402    @Override
13403    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13404        if (packageName == null || ks == null) {
13405            return false;
13406        }
13407        synchronized(mPackages) {
13408            final PackageParser.Package pkg = mPackages.get(packageName);
13409            if (pkg == null) {
13410                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13411                throw new IllegalArgumentException("Unknown package: " + packageName);
13412            }
13413            if (ks instanceof KeySetHandle) {
13414                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13415                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13416            }
13417            return false;
13418        }
13419    }
13420
13421    private static class LegacyPackageDeleteObserver extends PackageDeleteObserver {
13422        private final IPackageDeleteObserver mLegacy;
13423
13424        public LegacyPackageDeleteObserver(IPackageDeleteObserver legacy) {
13425            mLegacy = legacy;
13426        }
13427
13428        @Override
13429        public void onPackageDeleted(String basePackageName, int returnCode, String msg) {
13430            try {
13431                mLegacy.packageDeleted(basePackageName, returnCode);
13432            } catch (RemoteException ignored) {
13433            }
13434        }
13435    }
13436}
13437